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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.779   ! albertel    4: # $Id: lonnet.pm,v 1.778 2006/09/05 20:42:15 albertel Exp $
1.178     www         5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.169     harris41   28: ###
                     29: 
1.1       albertel   30: package Apache::lonnet;
                     31: 
                     32: use strict;
1.8       www        33: use LWP::UserAgent();
1.15      www        34: use HTTP::Headers;
1.486     www        35: use HTTP::Date;
                     36: # use Date::Parse;
1.11      www        37: use vars 
1.599     albertel   38: qw(%perlvar %hostname %badServerCache %iphost %spareid %hostdom 
                     39:    %libserv %pr %prp $memcache %packagetab 
1.662     raeburn    40:    %courselogs %accesshash %userrolehash %domainrolehash $processmarker $dumpcount 
1.741     raeburn    41:    %coursedombuf %coursenumbuf %coursehombuf %coursedescrbuf %courseinstcodebuf %courseownerbuf %coursetypebuf
1.599     albertel   42:    %domaindescription %domain_auth_def %domain_auth_arg_def 
1.685     raeburn    43:    %domain_lang_def %domain_city %domain_longi %domain_lati %domain_primary
                     44:    $tmpdir $_64bit %env);
1.403     www        45: 
1.1       albertel   46: use IO::Socket;
1.31      www        47: use GDBM_File;
1.208     albertel   48: use HTML::LCParser;
1.637     raeburn    49: use HTML::Parser;
1.88      www        50: use Fcntl qw(:flock);
1.557     albertel   51: use Storable qw(lock_store lock_nstore lock_retrieve freeze thaw nfreeze);
1.539     albertel   52: use Time::HiRes qw( gettimeofday tv_interval );
1.599     albertel   53: use Cache::Memcached;
1.676     albertel   54: use Digest::MD5;
1.740     www        55: use lib '/home/httpd/lib/perl';
                     56: use LONCAPA;
                     57: use LONCAPA::Configuration;
1.676     albertel   58: 
1.195     www        59: my $readit;
1.550     foxr       60: my $max_connection_retries = 10;     # Or some such value.
1.1       albertel   61: 
1.619     albertel   62: require Exporter;
                     63: 
                     64: our @ISA = qw (Exporter);
                     65: our @EXPORT = qw(%env);
                     66: 
1.449     matthew    67: =pod
                     68: 
                     69: =head1 Package Variables
                     70: 
                     71: These are largely undocumented, so if you decipher one please note it here.
                     72: 
                     73: =over 4
                     74: 
                     75: =item $processmarker
                     76: 
                     77: Contains the time this process was started and this servers host id.
                     78: 
                     79: =item $dumpcount
                     80: 
                     81: Counts the number of times a message log flush has been attempted (regardless
                     82: of success) by this process.  Used as part of the filename when messages are
                     83: delayed.
                     84: 
                     85: =back
                     86: 
                     87: =cut
                     88: 
                     89: 
1.1       albertel   90: # --------------------------------------------------------------------- Logging
1.729     www        91: {
                     92:     my $logid;
                     93:     sub instructor_log {
                     94: 	my ($hash_name,$storehash,$delflag,$uname,$udom)=@_;
                     95: 	$logid++;
                     96: 	my $id=time().'00000'.$$.'00000'.$logid;
                     97: 	return &Apache::lonnet::put('nohist_'.$hash_name,
1.730     www        98: 				    { $id => {
                     99: 					'exe_uname' => $env{'user.name'},
                    100: 					'exe_udom'  => $env{'user.domain'},
                    101: 					'exe_time'  => time(),
                    102: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    103: 					'delflag'   => $delflag,
                    104: 					'logentry'  => $storehash,
                    105: 					'uname'     => $uname,
                    106: 					'udom'      => $udom,
                    107: 				    }
                    108: 				  },
1.729     www       109: 				    $env{'course.'.$env{'request.course.id'}.'.domain'},
                    110: 				    $env{'course.'.$env{'request.course.id'}.'.num'}
                    111: 				    );
                    112:     }
                    113: }
1.1       albertel  114: 
1.163     harris41  115: sub logtouch {
                    116:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  117:     unless (-e "$execdir/logs/lonnet.log") {	
                    118: 	open(my $fh,">>$execdir/logs/lonnet.log");
1.163     harris41  119: 	close $fh;
                    120:     }
                    121:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    122:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    123: }
                    124: 
1.1       albertel  125: sub logthis {
                    126:     my $message=shift;
                    127:     my $execdir=$perlvar{'lonDaemons'};
                    128:     my $now=time;
                    129:     my $local=localtime($now);
1.448     albertel  130:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
                    131: 	print $fh "$local ($$): $message\n";
                    132: 	close($fh);
                    133:     }
1.1       albertel  134:     return 1;
                    135: }
                    136: 
                    137: sub logperm {
                    138:     my $message=shift;
                    139:     my $execdir=$perlvar{'lonDaemons'};
                    140:     my $now=time;
                    141:     my $local=localtime($now);
1.448     albertel  142:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
                    143: 	print $fh "$now:$message:$local\n";
                    144: 	close($fh);
                    145:     }
1.1       albertel  146:     return 1;
                    147: }
                    148: 
                    149: # -------------------------------------------------- Non-critical communication
                    150: sub subreply {
                    151:     my ($cmd,$server)=@_;
1.704     albertel  152:     my $peerfile="$perlvar{'lonSockDir'}/".$hostname{$server};
1.549     foxr      153:     #
                    154:     #  With loncnew process trimming, there's a timing hole between lonc server
                    155:     #  process exit and the master server picking up the listen on the AF_UNIX
                    156:     #  socket.  In that time interval, a lock file will exist:
                    157: 
                    158:     my $lockfile=$peerfile.".lock";
                    159:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
                    160: 	sleep(1);
                    161:     }
                    162:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      163:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      164:     #
1.550     foxr      165:     #   We'll give the connection a few tries before abandoning it.  If
                    166:     #   connection is not possible, we'll con_lost back to the client.
                    167:     #   
                    168:     my $client;
                    169:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    170: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    171: 				      Type    => SOCK_STREAM,
                    172: 				      Timeout => 10);
                    173: 	if($client) {
                    174: 	    last;		# Connected!
                    175: 	}
                    176: 	sleep(1);		# Try again later if failed connection.
                    177:     }
                    178:     my $answer;
                    179:     if ($client) {
1.704     albertel  180: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      181: 	$answer=<$client>;
                    182: 	if (!$answer) { $answer="con_lost"; }
                    183: 	chomp($answer);
                    184:     } else {
                    185: 	$answer = 'con_lost';	# Failed connection.
                    186:     }
1.1       albertel  187:     return $answer;
                    188: }
                    189: 
                    190: sub reply {
                    191:     my ($cmd,$server)=@_;
1.205     www       192:     unless (defined($hostname{$server})) { return 'no_such_host'; }
1.1       albertel  193:     my $answer=subreply($cmd,$server);
1.65      www       194:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  195:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       196:                 " $cmd to $server returned $answer</font>");
                    197:     }
1.1       albertel  198:     return $answer;
                    199: }
                    200: 
                    201: # ----------------------------------------------------------- Send USR1 to lonc
                    202: 
                    203: sub reconlonc {
                    204:     my $peerfile=shift;
                    205:     &logthis("Trying to reconnect for $peerfile");
                    206:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  207:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  208: 	my $loncpid=<$fh>;
                    209:         chomp($loncpid);
                    210:         if (kill 0 => $loncpid) {
                    211: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    212:             kill USR1 => $loncpid;
                    213:             sleep 1;
                    214:             if (-e "$peerfile") { return; }
                    215:             &logthis("$peerfile still not there, give it another try");
                    216:             sleep 5;
                    217:             if (-e "$peerfile") { return; }
1.12      www       218:             &logthis(
1.672     albertel  219:   "<font color=\"blue\">WARNING: $peerfile still not there, giving up</font>");
1.1       albertel  220:         } else {
1.12      www       221: 	    &logthis(
1.672     albertel  222:                "<font color=\"blue\">WARNING:".
1.12      www       223:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  224:         }
                    225:     } else {
1.672     albertel  226:      &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  227:     }
                    228: }
                    229: 
                    230: # ------------------------------------------------------ Critical communication
1.12      www       231: 
1.1       albertel  232: sub critical {
                    233:     my ($cmd,$server)=@_;
1.89      www       234:     unless ($hostname{$server}) {
1.672     albertel  235:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       236:                " Critical message to unknown server ($server)</font>");
                    237:         return 'no_such_host';
                    238:     }
1.1       albertel  239:     my $answer=reply($cmd,$server);
                    240:     if ($answer eq 'con_lost') {
                    241: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
1.589     albertel  242: 	my $answer=reply($cmd,$server);
1.1       albertel  243:         if ($answer eq 'con_lost') {
                    244:             my $now=time;
                    245:             my $middlename=$cmd;
1.5       www       246:             $middlename=substr($middlename,0,16);
1.1       albertel  247:             $middlename=~s/\W//g;
                    248:             my $dfilename=
1.305     www       249:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    250:             $dumpcount++;
1.1       albertel  251:             {
1.448     albertel  252: 		my $dfh;
                    253: 		if (open($dfh,">$dfilename")) {
                    254: 		    print $dfh "$cmd\n"; 
                    255: 		    close($dfh);
                    256: 		}
1.1       albertel  257:             }
                    258:             sleep 2;
                    259:             my $wcmd='';
                    260:             {
1.448     albertel  261: 		my $dfh;
                    262: 		if (open($dfh,"<$dfilename")) {
                    263: 		    $wcmd=<$dfh>; 
                    264: 		    close($dfh);
                    265: 		}
1.1       albertel  266:             }
                    267:             chomp($wcmd);
1.7       www       268:             if ($wcmd eq $cmd) {
1.672     albertel  269: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       270:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  271:                 &logperm("D:$server:$cmd");
                    272: 	        return 'con_delayed';
                    273:             } else {
1.672     albertel  274:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       275:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  276:                 &logperm("F:$server:$cmd");
                    277:                 return 'con_failed';
                    278:             }
                    279:         }
                    280:     }
                    281:     return $answer;
1.405     albertel  282: }
                    283: 
1.755     albertel  284: # ------------------------------------------- check if return value is an error
                    285: 
                    286: sub error {
                    287:     my ($result) = @_;
1.756     albertel  288:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  289: 	if ($2 == 2) { return undef; }
                    290: 	return $1;
                    291:     }
                    292:     return undef;
                    293: }
                    294: 
1.374     www       295: # ------------------------------------------- Transfer profile into environment
                    296: 
                    297: sub transfer_profile_to_env {
                    298:     my ($lonidsdir,$handle)=@_;
1.720     albertel  299:     if (!defined($lonidsdir)) {
                    300: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    301:     }
                    302:     if (!defined($handle)) {
                    303:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    304:     }
                    305: 
1.374     www       306:     my @profile;
                    307:     {
1.448     albertel  308: 	open(my $idf,"$lonidsdir/$handle.id");
1.374     www       309: 	flock($idf,LOCK_SH);
                    310: 	@profile=<$idf>;
1.448     albertel  311: 	close($idf);
1.374     www       312:     }
                    313:     my $envi;
1.433     matthew   314:     my %Remove;
1.374     www       315:     for ($envi=0;$envi<=$#profile;$envi++) {
                    316: 	chomp($profile[$envi]);
1.690     albertel  317: 	my ($envname,$envvalue)=split(/=/,$profile[$envi],2);
1.726     albertel  318: 	$envname=&unescape($envname);
                    319: 	$envvalue=&unescape($envvalue);
1.619     albertel  320: 	$env{$envname} = $envvalue;
1.433     matthew   321:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    322:             if ($time < time-300) {
                    323:                 $Remove{$key}++;
                    324:             }
                    325:         }
                    326:     }
1.619     albertel  327:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.433     matthew   328:     foreach my $expired_key (keys(%Remove)) {
                    329:         &delenv($expired_key);
1.374     www       330:     }
1.1       albertel  331: }
                    332: 
1.5       www       333: # ---------------------------------------------------------- Append Environment
                    334: 
                    335: sub appenv {
1.6       www       336:     my %newenv=@_;
1.692     albertel  337:     foreach my $key (keys(%newenv)) {
                    338: 	if (($newenv{$key}=~/^user\.role/) || ($newenv{$key}=~/^user\.priv/)) {
1.672     albertel  339:             &logthis("<font color=\"blue\">WARNING: ".
1.692     albertel  340:                 "Attempt to modify environment ".$key." to ".$newenv{$key}
1.151     www       341:                 .'</font>');
1.692     albertel  342: 	    delete($newenv{$key});
1.35      www       343:         } else {
1.692     albertel  344:             $env{$key}=$newenv{$key};
1.35      www       345:         }
1.191     harris41  346:     }
1.779   ! albertel  347:     foreach my $key (keys(%newenv)) {
        !           348: 	my $value = &escape($newenv{$key});
        !           349: 	delete($newenv{$key});
        !           350: 	$newenv{&escape($key)}=$value;
        !           351:     }
1.95      www       352: 
                    353:     my $lockfh;
1.620     albertel  354:     unless (open($lockfh,"$env{'user.environment'}")) {
1.448     albertel  355: 	return 'error: '.$!;
1.95      www       356:     }
                    357:     unless (flock($lockfh,LOCK_EX)) {
1.672     albertel  358:          &logthis("<font color=\"blue\">WARNING: ".
1.95      www       359:                   'Could not obtain exclusive lock in appenv: '.$!);
1.448     albertel  360:          close($lockfh);
1.95      www       361:          return 'error: '.$!;
                    362:     }
                    363: 
1.6       www       364:     my @oldenv;
                    365:     {
1.448     albertel  366: 	my $fh;
1.620     albertel  367: 	unless (open($fh,"$env{'user.environment'}")) {
1.448     albertel  368: 	    return 'error: '.$!;
                    369: 	}
                    370: 	@oldenv=<$fh>;
                    371: 	close($fh);
1.6       www       372:     }
                    373:     for (my $i=0; $i<=$#oldenv; $i++) {
                    374:         chomp($oldenv[$i]);
1.9       www       375:         if ($oldenv[$i] ne '') {
1.690     albertel  376: 	    my ($name,$value)=split(/=/,$oldenv[$i],2);
1.448     albertel  377: 	    unless (defined($newenv{$name})) {
                    378: 		$newenv{$name}=$value;
                    379: 	    }
1.9       www       380:         }
1.6       www       381:     }
                    382:     {
1.448     albertel  383: 	my $fh;
1.620     albertel  384: 	unless (open($fh,">$env{'user.environment'}")) {
1.448     albertel  385: 	    return 'error';
                    386: 	}
                    387: 	my $newname;
                    388: 	foreach $newname (keys %newenv) {
1.779   ! albertel  389: 	    print $fh $newname.'='.$newenv{$newname}."\n";
1.448     albertel  390: 	}
                    391: 	close($fh);
1.56      www       392:     }
1.448     albertel  393: 	
                    394:     close($lockfh);
1.56      www       395:     return 'ok';
                    396: }
                    397: # ----------------------------------------------------- Delete from Environment
                    398: 
                    399: sub delenv {
                    400:     my $delthis=shift;
                    401:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
1.672     albertel  402:         &logthis("<font color=\"blue\">WARNING: ".
1.56      www       403:                 "Attempt to delete from environment ".$delthis);
                    404:         return 'error';
                    405:     }
                    406:     my @oldenv;
                    407:     {
1.448     albertel  408: 	my $fh;
1.620     albertel  409: 	unless (open($fh,"$env{'user.environment'}")) {
1.448     albertel  410: 	    return 'error';
                    411: 	}
                    412: 	unless (flock($fh,LOCK_SH)) {
1.672     albertel  413: 	    &logthis("<font color=\"blue\">WARNING: ".
1.448     albertel  414: 		     'Could not obtain shared lock in delenv: '.$!);
                    415: 	    close($fh);
                    416: 	    return 'error: '.$!;
                    417: 	}
                    418: 	@oldenv=<$fh>;
                    419: 	close($fh);
1.56      www       420:     }
                    421:     {
1.448     albertel  422: 	my $fh;
1.620     albertel  423: 	unless (open($fh,">$env{'user.environment'}")) {
1.448     albertel  424: 	    return 'error';
                    425: 	}
                    426: 	unless (flock($fh,LOCK_EX)) {
1.672     albertel  427: 	    &logthis("<font color=\"blue\">WARNING: ".
1.448     albertel  428: 		     'Could not obtain exclusive lock in delenv: '.$!);
                    429: 	    close($fh);
                    430: 	    return 'error: '.$!;
                    431: 	}
1.692     albertel  432: 	foreach my $cur_key (@oldenv) {
1.726     albertel  433: 	    my $unescaped_cur_key = &unescape($cur_key);
                    434: 	    if ($unescaped_cur_key=~/^$delthis/) { 
                    435:                 my ($key) = split('=',$cur_key,2);
                    436: 		$key = &unescape($key);
1.619     albertel  437:                 delete($env{$key});
1.473     matthew   438:             } else {
1.692     albertel  439:                 print $fh $cur_key; 
1.473     matthew   440:             }
1.448     albertel  441: 	}
                    442: 	close($fh);
1.5       www       443:     }
                    444:     return 'ok';
1.369     albertel  445: }
                    446: 
                    447: # ------------------------------------------ Find out current server userload
                    448: # there is a copy in lond
                    449: sub userload {
                    450:     my $numusers=0;
                    451:     {
                    452: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    453: 	my $filename;
                    454: 	my $curtime=time;
                    455: 	while ($filename=readdir(LONIDS)) {
                    456: 	    if ($filename eq '.' || $filename eq '..') {next;}
1.404     albertel  457: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  458: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  459: 	}
                    460: 	closedir(LONIDS);
                    461:     }
                    462:     my $userloadpercent=0;
                    463:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    464:     if ($maxuserload) {
1.371     albertel  465: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  466:     }
1.372     albertel  467:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  468:     return $userloadpercent;
1.283     www       469: }
                    470: 
                    471: # ------------------------------------------ Fight off request when overloaded
                    472: 
                    473: sub overloaderror {
                    474:     my ($r,$checkserver)=@_;
                    475:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
                    476:     my $loadavg;
                    477:     if ($checkserver eq $perlvar{'lonHostID'}) {
1.448     albertel  478:        open(my $loadfile,'/proc/loadavg');
1.283     www       479:        $loadavg=<$loadfile>;
                    480:        $loadavg =~ s/\s.*//g;
1.285     matthew   481:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
1.448     albertel  482:        close($loadfile);
1.283     www       483:     } else {
                    484:        $loadavg=&reply('load',$checkserver);
                    485:     }
1.285     matthew   486:     my $overload=$loadavg-100;
1.283     www       487:     if ($overload>0) {
1.285     matthew   488: 	$r->err_headers_out->{'Retry-After'}=$overload;
1.283     www       489:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
1.554     www       490:         return 413;
1.283     www       491:     }    
                    492:     return '';
1.5       www       493: }
1.1       albertel  494: 
                    495: # ------------------------------ Find server with least workload from spare.tab
1.11      www       496: 
1.1       albertel  497: sub spareserver {
1.670     albertel  498:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
1.1       albertel  499:     my $tryserver;
                    500:     my $spareserver='';
1.370     albertel  501:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
                    502:     my $lowestserver=$loadpercent > $userloadpercent?
                    503: 	             $loadpercent :  $userloadpercent;
1.670     albertel  504:     foreach $tryserver (keys(%spareid)) {
                    505: 	my $loadans=&reply('load',$tryserver);
                    506: 	my $userloadans=&reply('userload',$tryserver);
1.411     albertel  507: 	if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
                    508: 	    next; #didn't get a number from the server
                    509: 	}
                    510: 	my $answer;
                    511: 	if ($loadans =~ /\d/) {
                    512: 	    if ($userloadans =~ /\d/) {
                    513: 		#both are numbers, pick the bigger one
                    514: 		$answer=$loadans > $userloadans?
                    515: 		    $loadans :  $userloadans;
                    516: 	    } else {
                    517: 		$answer = $loadans;
                    518: 	    }
                    519: 	} else {
                    520: 	    $answer = $userloadans;
                    521: 	}
                    522: 	if (($answer =~ /\d/) && ($answer<$lowestserver)) {
1.670     albertel  523: 	    if ($want_server_name) {
                    524: 		$spareserver=$tryserver;
                    525: 	    } else {
                    526: 		$spareserver="http://$hostname{$tryserver}";
                    527: 	    }
1.411     albertel  528: 	    $lowestserver=$answer;
                    529: 	}
1.370     albertel  530:     }
1.1       albertel  531:     return $spareserver;
1.202     matthew   532: }
                    533: 
                    534: # --------------------------------------------- Try to change a user's password
                    535: 
                    536: sub changepass {
                    537:     my ($uname,$udom,$currentpass,$newpass,$server)=@_;
                    538:     $currentpass = &escape($currentpass);
                    539:     $newpass     = &escape($newpass);
                    540:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass",
                    541: 		       $server);
                    542:     if (! $answer) {
                    543: 	&logthis("No reply on password change request to $server ".
                    544: 		 "by $uname in domain $udom.");
                    545:     } elsif ($answer =~ "^ok") {
                    546:         &logthis("$uname in $udom successfully changed their password ".
                    547: 		 "on $server.");
                    548:     } elsif ($answer =~ "^pwchange_failure") {
                    549: 	&logthis("$uname in $udom was unable to change their password ".
                    550: 		 "on $server.  The action was blocked by either lcpasswd ".
                    551: 		 "or pwchange");
                    552:     } elsif ($answer =~ "^non_authorized") {
                    553:         &logthis("$uname in $udom did not get their password correct when ".
                    554: 		 "attempting to change it on $server.");
                    555:     } elsif ($answer =~ "^auth_mode_error") {
                    556:         &logthis("$uname in $udom attempted to change their password despite ".
                    557: 		 "not being locally or internally authenticated on $server.");
                    558:     } elsif ($answer =~ "^unknown_user") {
                    559:         &logthis("$uname in $udom attempted to change their password ".
                    560: 		 "on $server but were unable to because $server is not ".
                    561: 		 "their home server.");
                    562:     } elsif ($answer =~ "^refused") {
                    563: 	&logthis("$server refused to change $uname in $udom password because ".
                    564: 		 "it was sent an unencrypted request to change the password.");
                    565:     }
                    566:     return $answer;
1.1       albertel  567: }
                    568: 
1.169     harris41  569: # ----------------------- Try to determine user's current authentication scheme
                    570: 
                    571: sub queryauthenticate {
                    572:     my ($uname,$udom)=@_;
1.456     albertel  573:     my $uhome=&homeserver($uname,$udom);
                    574:     if (!$uhome) {
                    575: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                    576: 	return 'no_host';
                    577:     }
                    578:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                    579:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                    580: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41  581:     }
1.456     albertel  582:     return $answer;
1.169     harris41  583: }
                    584: 
1.1       albertel  585: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www       586: 
1.1       albertel  587: sub authenticate {
                    588:     my ($uname,$upass,$udom)=@_;
1.12      www       589:     $upass=escape($upass);
1.199     www       590:     $uname=~s/\W//g;
1.471     albertel  591:     my $uhome=&homeserver($uname,$udom);
                    592:     if (!$uhome) {
                    593: 	&logthis("User $uname at $udom is unknown in authenticate");
                    594: 	return 'no_host';
1.1       albertel  595:     }
1.471     albertel  596:     my $answer=reply("encrypt:auth:$udom:$uname:$upass",$uhome);
                    597:     if ($answer eq 'authorized') {
                    598: 	&logthis("User $uname at $udom authorized by $uhome"); 
                    599: 	return $uhome; 
                    600:     }
                    601:     if ($answer eq 'non_authorized') {
                    602: 	&logthis("User $uname at $udom rejected by $uhome");
                    603: 	return 'no_host'; 
1.9       www       604:     }
1.471     albertel  605:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel  606:     return 'no_host';
                    607: }
                    608: 
                    609: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www       610: 
1.599     albertel  611: my %homecache;
1.1       albertel  612: sub homeserver {
1.230     stredwic  613:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel  614:     my $index="$uname:$udom";
1.426     albertel  615: 
1.599     albertel  616:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.1       albertel  617:     my $tryserver;
                    618:     foreach $tryserver (keys %libserv) {
1.230     stredwic  619:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic  620: 		 exists($badServerCache{$tryserver}));
1.1       albertel  621: 	if ($hostdom{$tryserver} eq $udom) {
                    622:            my $answer=reply("home:$udom:$uname",$tryserver);
                    623:            if ($answer eq 'found') { 
1.599     albertel  624: 	       return $homecache{$index}=$tryserver;
1.231     stredwic  625:            } elsif ($answer eq 'no_host') {
                    626: 	       $badServerCache{$tryserver}=1;
1.221     matthew   627:            }
1.1       albertel  628:        }
                    629:     }    
                    630:     return 'no_host';
1.70      www       631: }
                    632: 
                    633: # ------------------------------------- Find the usernames behind a list of IDs
                    634: 
                    635: sub idget {
                    636:     my ($udom,@ids)=@_;
                    637:     my %returnhash=();
                    638:     
                    639:     my $tryserver;
                    640:     foreach $tryserver (keys %libserv) {
                    641:        if ($hostdom{$tryserver} eq $udom) {
                    642: 	  my $idlist=join('&',@ids);
                    643:           $idlist=~tr/A-Z/a-z/; 
                    644: 	  my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                    645:           my @answer=();
1.76      www       646:           if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1.70      www       647: 	      @answer=split(/\&/,$reply);
                    648:           }                    ;
                    649:           my $i;
                    650:           for ($i=0;$i<=$#ids;$i++) {
                    651:               if ($answer[$i]) {
                    652: 		  $returnhash{$ids[$i]}=$answer[$i];
                    653:               } 
                    654:           }
                    655:        }
                    656:     }    
                    657:     return %returnhash;
                    658: }
                    659: 
                    660: # ------------------------------------- Find the IDs behind a list of usernames
                    661: 
                    662: sub idrget {
                    663:     my ($udom,@unames)=@_;
                    664:     my %returnhash=();
1.191     harris41  665:     foreach (@unames) {
1.70      www       666:         $returnhash{$_}=(&userenvironment($udom,$_,'id'))[1];
1.191     harris41  667:     }
1.70      www       668:     return %returnhash;
                    669: }
                    670: 
                    671: # ------------------------------- Store away a list of names and associated IDs
                    672: 
                    673: sub idput {
                    674:     my ($udom,%ids)=@_;
                    675:     my %servers=();
1.191     harris41  676:     foreach (keys %ids) {
1.487     albertel  677: 	&cput('environment',{'id'=>$ids{$_}},$udom,$_);
1.70      www       678:         my $uhom=&homeserver($_,$udom);
                    679:         if ($uhom ne 'no_host') {
                    680:             my $id=&escape($ids{$_});
                    681:             $id=~tr/A-Z/a-z/;
                    682:             my $unam=&escape($_);
                    683: 	    if ($servers{$uhom}) {
                    684: 		$servers{$uhom}.='&'.$id.'='.$unam;
                    685:             } else {
                    686:                 $servers{$uhom}=$id.'='.$unam;
                    687:             }
                    688:         }
1.191     harris41  689:     }
                    690:     foreach (keys %servers) {
1.70      www       691:         &critical('idput:'.$udom.':'.$servers{$_},$_);
1.191     harris41  692:     }
1.344     www       693: }
                    694: 
                    695: # --------------------------------------------------- Assign a key to a student
                    696: 
                    697: sub assign_access_key {
1.364     www       698: #
                    699: # a valid key looks like uname:udom#comments
                    700: # comments are being appended
                    701: #
1.498     www       702:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                    703:     $kdom=
1.620     albertel  704:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www       705:     $knum=
1.620     albertel  706:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www       707:     $cdom=
1.620     albertel  708:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       709:     $cnum=
1.620     albertel  710:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                    711:     $udom=$env{'user.name'} unless (defined($udom));
                    712:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www       713:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www       714:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel  715:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www       716:                                                   # assigned to this person
                    717:                                                   # - this should not happen,
1.345     www       718:                                                   # unless something went wrong
                    719:                                                   # the first time around
                    720: # ready to assign
1.364     www       721:         $logentry=$1.'; '.$logentry;
1.496     www       722:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www       723:                                                  $kdom,$knum) eq 'ok') {
1.345     www       724: # key now belongs to user
1.346     www       725: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www       726:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
                    727:                 &appenv('environment.'.$envkey => $ckey);
                    728:                 return 'ok';
                    729:             } else {
                    730:                 return 
                    731:   'error: Count not permanently assign key, will need to be re-entered later.';
                    732: 	    }
                    733:         } else {
                    734:             return 'error: Could not assign key, try again later.';
                    735:         }
1.364     www       736:     } elsif (!$existing{$ckey}) {
1.345     www       737: # the key does not exist
                    738: 	return 'error: The key does not exist';
                    739:     } else {
                    740: # the key is somebody else's
                    741: 	return 'error: The key is already in use';
                    742:     }
1.344     www       743: }
                    744: 
1.364     www       745: # ------------------------------------------ put an additional comment on a key
                    746: 
                    747: sub comment_access_key {
                    748: #
                    749: # a valid key looks like uname:udom#comments
                    750: # comments are being appended
                    751: #
                    752:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                    753:     $cdom=
1.620     albertel  754:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www       755:     $cnum=
1.620     albertel  756:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www       757:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                    758:     if ($existing{$ckey}) {
                    759:         $existing{$ckey}.='; '.$logentry;
                    760: # ready to assign
1.367     www       761:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www       762:                                                  $cdom,$cnum) eq 'ok') {
                    763: 	    return 'ok';
                    764:         } else {
                    765: 	    return 'error: Count not store comment.';
                    766:         }
                    767:     } else {
                    768: # the key does not exist
                    769: 	return 'error: The key does not exist';
                    770:     }
                    771: }
                    772: 
1.344     www       773: # ------------------------------------------------------ Generate a set of keys
                    774: 
                    775: sub generate_access_keys {
1.364     www       776:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www       777:     $cdom=
1.620     albertel  778:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       779:     $cnum=
1.620     albertel  780:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www       781:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www       782:     unless (($cdom) && ($cnum)) { return 0; }
                    783:     if ($number>10000) { return 0; }
                    784:     sleep(2); # make sure don't get same seed twice
                    785:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                    786:     my $total=0;
                    787:     for (my $i=1;$i<=$number;$i++) {
                    788:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                    789:                   sprintf("%lx",int(100000*rand)).'-'.
                    790:                   sprintf("%lx",int(100000*rand));
                    791:        $newkey=~s/1/g/g; # folks mix up 1 and l
                    792:        $newkey=~s/0/h/g; # and also 0 and O
                    793:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                    794:        if ($existing{$newkey}) {
                    795:            $i--;
                    796:        } else {
1.364     www       797: 	  if (&put('accesskeys',
                    798:               { $newkey => '# generated '.localtime().
1.620     albertel  799:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www       800:                            '; '.$logentry },
                    801: 		   $cdom,$cnum) eq 'ok') {
1.344     www       802:               $total++;
                    803: 	  }
                    804:        }
                    805:     }
1.620     albertel  806:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www       807:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                    808:     return $total;
                    809: }
                    810: 
                    811: # ------------------------------------------------------- Validate an accesskey
                    812: 
                    813: sub validate_access_key {
                    814:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                    815:     $cdom=
1.620     albertel  816:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       817:     $cnum=
1.620     albertel  818:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                    819:     $udom=$env{'user.domain'} unless (defined($udom));
                    820:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www       821:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel  822:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www       823: }
                    824: 
                    825: # ------------------------------------- Find the section of student in a course
1.652     albertel  826: sub devalidate_getsection_cache {
                    827:     my ($udom,$unam,$courseid)=@_;
                    828:     $courseid=~s/\_/\//g;
                    829:     $courseid=~s/^(\w)/\/$1/;
                    830:     my $hashid="$udom:$unam:$courseid";
                    831:     &devalidate_cache_new('getsection',$hashid);
                    832: }
1.298     matthew   833: 
                    834: sub getsection {
                    835:     my ($udom,$unam,$courseid)=@_;
1.599     albertel  836:     my $cachetime=1800;
1.298     matthew   837:     $courseid=~s/\_/\//g;
                    838:     $courseid=~s/^(\w)/\/$1/;
1.551     albertel  839: 
                    840:     my $hashid="$udom:$unam:$courseid";
1.599     albertel  841:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel  842:     if (defined($cached)) { return $result; }
                    843: 
1.298     matthew   844:     my %Pending; 
                    845:     my %Expired;
                    846:     #
                    847:     # Each role can either have not started yet (pending), be active, 
                    848:     #    or have expired.
                    849:     #
                    850:     # If there is an active role, we are done.
                    851:     #
                    852:     # If there is more than one role which has not started yet, 
                    853:     #     choose the one which will start sooner
                    854:     # If there is one role which has not started yet, return it.
                    855:     #
                    856:     # If there is more than one expired role, choose the one which ended last.
                    857:     # If there is a role which has expired, return it.
                    858:     #
                    859:     foreach (split(/\&/,&reply('dump:'.$udom.':'.$unam.':roles',
                    860:                         &homeserver($unam,$udom)))) {
                    861:         my ($key,$value)=split(/\=/,$_);
                    862:         $key=&unescape($key);
1.479     albertel  863:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew   864:         my $section=$1;
                    865:         if ($key eq $courseid.'_st') { $section=''; }
                    866:         my ($dummy,$end,$start)=split(/\_/,&unescape($value));
                    867:         my $now=time;
1.548     albertel  868:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew   869:             $Expired{$end}=$section;
                    870:             next;
                    871:         }
1.548     albertel  872:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew   873:             $Pending{$start}=$section;
                    874:             next;
                    875:         }
1.599     albertel  876:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew   877:     }
                    878:     #
                    879:     # Presumedly there will be few matching roles from the above
                    880:     # loop and the sorting time will be negligible.
                    881:     if (scalar(keys(%Pending))) {
                    882:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel  883:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew   884:     } 
                    885:     if (scalar(keys(%Expired))) {
                    886:         my @sorted = sort {$a <=> $b} keys(%Expired);
                    887:         my $time = pop(@sorted);
1.599     albertel  888:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew   889:     }
1.599     albertel  890:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew   891: }
1.70      www       892: 
1.599     albertel  893: sub save_cache {
                    894:     &purge_remembered();
1.722     albertel  895:     #&Apache::loncommon::validate_page();
1.620     albertel  896:     undef(%env);
1.599     albertel  897: }
1.452     albertel  898: 
1.599     albertel  899: my $to_remember=-1;
                    900: my %remembered;
                    901: my %accessed;
                    902: my $kicks=0;
                    903: my $hits=0;
                    904: sub devalidate_cache_new {
                    905:     my ($name,$id,$debug) = @_;
                    906:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
                    907:     $id=&escape($name.':'.$id);
                    908:     $memcache->delete($id);
                    909:     delete($remembered{$id});
                    910:     delete($accessed{$id});
                    911: }
                    912: 
                    913: sub is_cached_new {
                    914:     my ($name,$id,$debug) = @_;
                    915:     $id=&escape($name.':'.$id);
                    916:     if (exists($remembered{$id})) {
                    917: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                    918: 	$accessed{$id}=[&gettimeofday()];
                    919: 	$hits++;
                    920: 	return ($remembered{$id},1);
                    921:     }
                    922:     my $value = $memcache->get($id);
                    923:     if (!(defined($value))) {
                    924: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel  925: 	return (undef,undef);
1.416     albertel  926:     }
1.599     albertel  927:     if ($value eq '__undef__') {
                    928: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                    929: 	$value=undef;
                    930:     }
                    931:     &make_room($id,$value,$debug);
                    932:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                    933:     return ($value,1);
                    934: }
                    935: 
                    936: sub do_cache_new {
                    937:     my ($name,$id,$value,$time,$debug) = @_;
                    938:     $id=&escape($name.':'.$id);
                    939:     my $setvalue=$value;
                    940:     if (!defined($setvalue)) {
                    941: 	$setvalue='__undef__';
                    942:     }
1.623     albertel  943:     if (!defined($time) ) {
                    944: 	$time=600;
                    945:     }
1.599     albertel  946:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.600     albertel  947:     $memcache->set($id,$setvalue,$time);
                    948:     # need to make a copy of $value
                    949:     #&make_room($id,$value,$debug);
1.599     albertel  950:     return $value;
                    951: }
                    952: 
                    953: sub make_room {
                    954:     my ($id,$value,$debug)=@_;
                    955:     $remembered{$id}=$value;
                    956:     if ($to_remember<0) { return; }
                    957:     $accessed{$id}=[&gettimeofday()];
                    958:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                    959:     my $to_kick;
                    960:     my $max_time=0;
                    961:     foreach my $other (keys(%accessed)) {
                    962: 	if (&tv_interval($accessed{$other}) > $max_time) {
                    963: 	    $to_kick=$other;
                    964: 	    $max_time=&tv_interval($accessed{$other});
                    965: 	}
                    966:     }
                    967:     delete($remembered{$to_kick});
                    968:     delete($accessed{$to_kick});
                    969:     $kicks++;
                    970:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel  971:     return;
                    972: }
                    973: 
1.599     albertel  974: sub purge_remembered {
1.604     albertel  975:     #&logthis("Tossing ".scalar(keys(%remembered)));
                    976:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel  977:     undef(%remembered);
                    978:     undef(%accessed);
1.428     albertel  979: }
1.70      www       980: # ------------------------------------- Read an entry from a user's environment
                    981: 
                    982: sub userenvironment {
                    983:     my ($udom,$unam,@what)=@_;
                    984:     my %returnhash=();
                    985:     my @answer=split(/\&/,
                    986:                 &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
                    987:                       &homeserver($unam,$udom)));
                    988:     my $i;
                    989:     for ($i=0;$i<=$#what;$i++) {
                    990: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
                    991:     }
                    992:     return %returnhash;
1.1       albertel  993: }
                    994: 
1.617     albertel  995: # ---------------------------------------------------------- Get a studentphoto
                    996: sub studentphoto {
                    997:     my ($udom,$unam,$ext) = @_;
                    998:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn   999:     if (defined($env{'request.course.id'})) {
1.708     raeburn  1000:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  1001:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   1002:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   1003:             } else {
                   1004:                 my ($result,$perm_reqd)=
1.707     albertel 1005: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1006:                 if ($result eq 'ok') {
                   1007:                     if (!($perm_reqd eq 'yes')) {
                   1008:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   1009:                     }
                   1010:                 }
                   1011:             }
                   1012:         }
                   1013:     } else {
                   1014:         my ($result,$perm_reqd) = 
1.707     albertel 1015: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1016:         if ($result eq 'ok') {
                   1017:             if (!($perm_reqd eq 'yes')) {
                   1018:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   1019:             }
                   1020:         }
                   1021:     }
                   1022:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   1023: }
                   1024: 
                   1025: sub retrievestudentphoto {
                   1026:     my ($udom,$unam,$ext,$type) = @_;
                   1027:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   1028:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   1029:     if ($ret eq 'ok') {
                   1030:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   1031:         if ($type eq 'thumbnail') {
                   1032:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   1033:         }
                   1034:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   1035:         return $tokenurl;
                   1036:     } else {
                   1037:         if ($type eq 'thumbnail') {
                   1038:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   1039:         } else { 
                   1040:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   1041:         }
1.617     albertel 1042:     }
                   1043: }
                   1044: 
1.263     www      1045: # -------------------------------------------------------------------- New chat
                   1046: 
                   1047: sub chatsend {
1.724     raeburn  1048:     my ($newentry,$anon,$group)=@_;
1.620     albertel 1049:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1050:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1051:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      1052:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 1053: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  1054: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      1055: }
                   1056: 
                   1057: # ------------------------------------------ Find current version of a resource
                   1058: 
                   1059: sub getversion {
                   1060:     my $fname=&clutter(shift);
                   1061:     unless ($fname=~/^\/res\//) { return -1; }
                   1062:     return &currentversion(&filelocation('',$fname));
                   1063: }
                   1064: 
                   1065: sub currentversion {
                   1066:     my $fname=shift;
1.599     albertel 1067:     my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440     www      1068:     if (defined($cached)) { return $result; }
1.292     www      1069:     my $author=$fname;
                   1070:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1071:     my ($udom,$uname)=split(/\//,$author);
                   1072:     my $home=homeserver($uname,$udom);
                   1073:     if ($home eq 'no_host') { 
                   1074:         return -1; 
                   1075:     }
                   1076:     my $answer=reply("currentversion:$fname",$home);
                   1077:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1078: 	return -1;
                   1079:     }
1.599     albertel 1080:     return &do_cache_new('resversion',$fname,$answer,600);
1.263     www      1081: }
                   1082: 
1.1       albertel 1083: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      1084: 
1.1       albertel 1085: sub subscribe {
                   1086:     my $fname=shift;
1.761     raeburn  1087:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 1088:     $fname=~s/[\n\r]//g;
1.1       albertel 1089:     my $author=$fname;
                   1090:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1091:     my ($udom,$uname)=split(/\//,$author);
                   1092:     my $home=homeserver($uname,$udom);
1.335     albertel 1093:     if ($home eq 'no_host') {
                   1094:         return 'not_found';
1.1       albertel 1095:     }
                   1096:     my $answer=reply("sub:$fname",$home);
1.64      www      1097:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1098: 	$answer.=' by '.$home;
                   1099:     }
1.1       albertel 1100:     return $answer;
                   1101: }
                   1102:     
1.8       www      1103: # -------------------------------------------------------------- Replicate file
                   1104: 
                   1105: sub repcopy {
                   1106:     my $filename=shift;
1.23      www      1107:     $filename=~s/\/+/\//g;
1.607     raeburn  1108:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   1109:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 1110:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 1111: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 1112: 	return &repcopy_userfile($filename);
                   1113:     }
1.532     albertel 1114:     $filename=~s/[\n\r]//g;
1.8       www      1115:     my $transname="$filename.in.transfer";
1.607     raeburn  1116:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      1117:     my $remoteurl=subscribe($filename);
1.64      www      1118:     if ($remoteurl =~ /^con_lost by/) {
                   1119: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1120:            return 'unavailable';
1.8       www      1121:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 1122: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  1123: 	   return 'not_found';
1.64      www      1124:     } elsif ($remoteurl =~ /^rejected by/) {
                   1125: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1126:            return 'forbidden';
1.20      www      1127:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  1128:            return 'ok';
1.8       www      1129:     } else {
1.290     www      1130:         my $author=$filename;
                   1131:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1132:         my ($udom,$uname)=split(/\//,$author);
                   1133:         my $home=homeserver($uname,$udom);
                   1134:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      1135:            my @parts=split(/\//,$filename);
                   1136:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   1137:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   1138:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  1139: 	       return 'bad_request';
1.8       www      1140:            }
                   1141:            my $count;
                   1142:            for ($count=5;$count<$#parts;$count++) {
                   1143:                $path.="/$parts[$count]";
                   1144:                if ((-e $path)!=1) {
                   1145: 		   mkdir($path,0777);
                   1146:                }
                   1147:            }
                   1148:            my $ua=new LWP::UserAgent;
                   1149:            my $request=new HTTP::Request('GET',"$remoteurl");
                   1150:            my $response=$ua->request($request,$transname);
                   1151:            if ($response->is_error()) {
                   1152: 	       unlink($transname);
                   1153:                my $message=$response->status_line;
1.672     albertel 1154:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      1155:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  1156:                return 'unavailable';
1.8       www      1157:            } else {
1.16      www      1158: 	       if ($remoteurl!~/\.meta$/) {
                   1159:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   1160:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   1161:                   if ($mresponse->is_error()) {
                   1162: 		      unlink($filename.'.meta');
                   1163:                       &logthis(
1.672     albertel 1164:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      1165:                   }
                   1166: 	       }
1.8       www      1167:                rename($transname,$filename);
1.607     raeburn  1168:                return 'ok';
1.8       www      1169:            }
1.290     www      1170:        }
1.8       www      1171:     }
1.330     www      1172: }
                   1173: 
                   1174: # ------------------------------------------------ Get server side include body
                   1175: sub ssi_body {
1.381     albertel 1176:     my ($filelink,%form)=@_;
1.606     matthew  1177:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   1178:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   1179:     }
1.330     www      1180:     my $output=($filelink=~/^http\:/?&externalssi($filelink):
1.381     albertel 1181:                                      &ssi($filelink,%form));
1.778     albertel 1182:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 1183:     $output=~s/^.*?\<body[^\>]*\>//si;
                   1184:     $output=~s/(.*)\<\/body\s*\>.*?$/$1/si;
1.330     www      1185:     return $output;
1.8       www      1186: }
                   1187: 
1.15      www      1188: # --------------------------------------------------------- Server Side Include
                   1189: 
                   1190: sub ssi {
                   1191: 
1.23      www      1192:     my ($fn,%form)=@_;
1.15      www      1193: 
                   1194:     my $ua=new LWP::UserAgent;
1.23      www      1195:     
                   1196:     my $request;
1.711     albertel 1197: 
                   1198:     $form{'no_update_last_known'}=1;
                   1199: 
1.23      www      1200:     if (%form) {
                   1201:       $request=new HTTP::Request('POST',"http://".$ENV{'HTTP_HOST'}.$fn);
1.201     albertel 1202:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1.23      www      1203:     } else {
                   1204:       $request=new HTTP::Request('GET',"http://".$ENV{'HTTP_HOST'}.$fn);
                   1205:     }
                   1206: 
1.15      www      1207:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   1208:     my $response=$ua->request($request);
                   1209: 
1.324     www      1210:     return $response->content;
                   1211: }
                   1212: 
                   1213: sub externalssi {
                   1214:     my ($url)=@_;
                   1215:     my $ua=new LWP::UserAgent;
                   1216:     my $request=new HTTP::Request('GET',$url);
                   1217:     my $response=$ua->request($request);
1.15      www      1218:     return $response->content;
                   1219: }
1.254     www      1220: 
1.492     albertel 1221: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   1222: 
                   1223: sub allowuploaded {
                   1224:     my ($srcurl,$url)=@_;
                   1225:     $url=&clutter(&declutter($url));
                   1226:     my $dir=$url;
                   1227:     $dir=~s/\/[^\/]+$//;
                   1228:     my %httpref=();
                   1229:     my $httpurl=&hreflocation('',$url);
                   1230:     $httpref{'httpref.'.$httpurl}=$srcurl;
                   1231:     &Apache::lonnet::appenv(%httpref);
1.254     www      1232: }
1.477     raeburn  1233: 
1.478     albertel 1234: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 1235: # input: action, courseID, current domain, intended
1.637     raeburn  1236: #        path to file, source of file, instruction to parse file for objects,
                   1237: #        ref to hash for embedded objects,
                   1238: #        ref to hash for codebase of java objects.
                   1239: #
1.485     raeburn  1240: # output: url to file (if action was uploaddoc), 
                   1241: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  1242: #
1.478     albertel 1243: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   1244: # course.
1.477     raeburn  1245: #
1.478     albertel 1246: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1247: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   1248: #          course's home server.
1.477     raeburn  1249: #
1.478     albertel 1250: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   1251: #          be copied from $source (current location) to 
                   1252: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1253: #         and will then be copied to
                   1254: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   1255: #         course's home server.
1.485     raeburn  1256: #
1.481     raeburn  1257: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 1258: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  1259: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1260: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   1261: #         in course's home server.
1.637     raeburn  1262: #
1.477     raeburn  1263: 
                   1264: sub process_coursefile {
1.638     albertel 1265:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477     raeburn  1266:     my $fetchresult;
1.638     albertel 1267:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  1268:     if ($action eq 'propagate') {
1.638     albertel 1269:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   1270: 			     $home);
1.481     raeburn  1271:     } else {
1.477     raeburn  1272:         my $fpath = '';
                   1273:         my $fname = $file;
1.478     albertel 1274:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  1275:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  1276:         my $filepath = &build_filepath($fpath);
1.481     raeburn  1277:         if ($action eq 'copy') {
                   1278:             if ($source eq '') {
                   1279:                 $fetchresult = 'no source file';
                   1280:                 return $fetchresult;
                   1281:             } else {
                   1282:                 my $destination = $filepath.'/'.$fname;
                   1283:                 rename($source,$destination);
                   1284:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1285:                                  $home);
1.481     raeburn  1286:             }
                   1287:         } elsif ($action eq 'uploaddoc') {
                   1288:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 1289:             print $fh $env{'form.'.$source};
1.481     raeburn  1290:             close($fh);
1.637     raeburn  1291:             if ($parser eq 'parse') {
                   1292:                 my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
                   1293:                 unless ($parse_result eq 'ok') {
                   1294:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   1295:                 }
                   1296:             }
1.477     raeburn  1297:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1298:                                  $home);
1.481     raeburn  1299:             if ($fetchresult eq 'ok') {
                   1300:                 return '/uploaded/'.$fpath.'/'.$fname;
                   1301:             } else {
                   1302:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1303:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  1304:                 return '/adm/notfound.html';
                   1305:             }
1.477     raeburn  1306:         }
                   1307:     }
1.485     raeburn  1308:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  1309:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1310:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  1311:     }
                   1312:     return $fetchresult;
                   1313: }
                   1314: 
1.637     raeburn  1315: sub build_filepath {
                   1316:     my ($fpath) = @_;
                   1317:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   1318:     unless ($fpath eq '') {
                   1319:         my @parts=split('/',$fpath);
                   1320:         foreach my $part (@parts) {
                   1321:             $filepath.= '/'.$part;
                   1322:             if ((-e $filepath)!=1) {
                   1323:                 mkdir($filepath,0777);
                   1324:             }
                   1325:         }
                   1326:     }
                   1327:     return $filepath;
                   1328: }
                   1329: 
                   1330: sub store_edited_file {
1.638     albertel 1331:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  1332:     my $file = $primary_url;
                   1333:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   1334:     my $fpath = '';
                   1335:     my $fname = $file;
                   1336:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   1337:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   1338:     my $filepath = &build_filepath($fpath);
                   1339:     open(my $fh,'>'.$filepath.'/'.$fname);
                   1340:     print $fh $content;
                   1341:     close($fh);
1.638     albertel 1342:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  1343:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1344: 			  $home);
1.637     raeburn  1345:     if ($$fetchresult eq 'ok') {
                   1346:         return '/uploaded/'.$fpath.'/'.$fname;
                   1347:     } else {
1.638     albertel 1348:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   1349: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  1350:         return '/adm/notfound.html';
                   1351:     }
                   1352: }
                   1353: 
1.531     albertel 1354: sub clean_filename {
                   1355:     my ($fname)=@_;
1.315     www      1356: # Replace Windows backslashes by forward slashes
1.257     www      1357:     $fname=~s/\\/\//g;
1.315     www      1358: # Get rid of everything but the actual filename
1.257     www      1359:     $fname=~s/^.*\/([^\/]+)$/$1/;
1.315     www      1360: # Replace spaces by underscores
                   1361:     $fname=~s/\s+/\_/g;
                   1362: # Replace all other weird characters by nothing
1.317     www      1363:     $fname=~s/[^\w\.\-]//g;
1.540     albertel 1364: # Replace all .\d. sequences with _\d. so they no longer look like version
                   1365: # numbers
                   1366:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 1367:     return $fname;
                   1368: }
                   1369: 
1.608     albertel 1370: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 1371: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719     banghart 1372: #                    the desired filenam is in $env{"form.$formname.filename"}
1.686     albertel 1373: #        $coursedoc - if true up to the current course
                   1374: #                     if false
                   1375: #        $subdir - directory in userfile to store the file into
                   1376: #        $parser, $allfiles, $codebase - unknown
                   1377: #
                   1378: # output: url of file in userspace, or error: <message> 
                   1379: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 1380: 
                   1381: 
1.531     albertel 1382: sub userfileupload {
1.719     banghart 1383:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,$destudom)=@_;
1.531     albertel 1384:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 1385:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 1386:     $fname=&clean_filename($fname);
1.315     www      1387: # See if there is anything left
1.257     www      1388:     unless ($fname) { return 'error: no uploaded file'; }
1.620     albertel 1389:     chop($env{'form.'.$formname});
1.523     raeburn  1390:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
                   1391:         my $now = time;
                   1392:         my $filepath = 'tmp/helprequests/'.$now;
                   1393:         my @parts=split(/\//,$filepath);
                   1394:         my $fullpath = $perlvar{'lonDaemons'};
                   1395:         for (my $i=0;$i<@parts;$i++) {
                   1396:             $fullpath .= '/'.$parts[$i];
                   1397:             if ((-e $fullpath)!=1) {
                   1398:                 mkdir($fullpath,0777);
                   1399:             }
                   1400:         }
                   1401:         open(my $fh,'>'.$fullpath.'/'.$fname);
1.620     albertel 1402:         print $fh $env{'form.'.$formname};
1.523     raeburn  1403:         close($fh);
1.741     raeburn  1404:         return $fullpath.'/'.$fname;
                   1405:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
                   1406:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   1407:                        '_'.$env{'user.domain'}.'/pending';
                   1408:         my @parts=split(/\//,$filepath);
                   1409:         my $fullpath = $perlvar{'lonDaemons'};
                   1410:         for (my $i=0;$i<@parts;$i++) {
                   1411:             $fullpath .= '/'.$parts[$i];
                   1412:             if ((-e $fullpath)!=1) {
                   1413:                 mkdir($fullpath,0777);
                   1414:             }
                   1415:         }
                   1416:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   1417:         print $fh $env{'form.'.$formname};
                   1418:         close($fh);
                   1419:         return $fullpath.'/'.$fname;
1.523     raeburn  1420:     }
1.719     banghart 1421:     
1.258     www      1422: # Create the directory if not present
1.493     albertel 1423:     $fname="$subdir/$fname";
1.259     www      1424:     if ($coursedoc) {
1.638     albertel 1425: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1426: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  1427:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 1428:             return &finishuserfileupload($docuname,$docudom,
                   1429: 					 $formname,$fname,$parser,$allfiles,
                   1430: 					 $codebase);
1.481     raeburn  1431:         } else {
1.620     albertel 1432:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 1433:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   1434: 				       $fname,$formname,$parser,
                   1435: 				       $allfiles,$codebase);
1.481     raeburn  1436:         }
1.719     banghart 1437:     } elsif (defined($destuname)) {
                   1438:         my $docuname=$destuname;
                   1439:         my $docudom=$destudom;
                   1440: 	return &finishuserfileupload($docuname,$docudom,$formname,
                   1441: 				     $fname,$parser,$allfiles,$codebase);
                   1442:         
1.259     www      1443:     } else {
1.638     albertel 1444:         my $docuname=$env{'user.name'};
                   1445:         my $docudom=$env{'user.domain'};
1.714     raeburn  1446:         if (exists($env{'form.group'})) {
                   1447:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1448:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1449:         }
1.638     albertel 1450: 	return &finishuserfileupload($docuname,$docudom,$formname,
                   1451: 				     $fname,$parser,$allfiles,$codebase);
1.259     www      1452:     }
1.271     www      1453: }
                   1454: 
                   1455: sub finishuserfileupload {
1.638     albertel 1456:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase) = @_;
1.477     raeburn  1457:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      1458:     my $filepath=$perlvar{'lonDocRoot'};
1.494     albertel 1459:     my ($fnamepath,$file);
                   1460:     $file=$fname;
                   1461:     if ($fname=~m|/|) {
                   1462:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   1463: 	$path.=$fnamepath.'/';
                   1464:     }
1.259     www      1465:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      1466:     my $count;
                   1467:     for ($count=4;$count<=$#parts;$count++) {
                   1468:         $filepath.="/$parts[$count]";
                   1469:         if ((-e $filepath)!=1) {
                   1470: 	    mkdir($filepath,0777);
                   1471:         }
                   1472:     }
                   1473: # Save the file
                   1474:     {
1.701     albertel 1475: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   1476: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   1477: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   1478: 	    return '/adm/notfound.html';
                   1479: 	}
                   1480: 	if (!print FH ($env{'form.'.$formname})) {
                   1481: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   1482: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   1483: 	    return '/adm/notfound.html';
                   1484: 	}
1.570     albertel 1485: 	close(FH);
1.258     www      1486:     }
1.637     raeburn  1487:     if ($parser eq 'parse') {
1.638     albertel 1488:         my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
                   1489: 						   $codebase);
1.637     raeburn  1490:         unless ($parse_result eq 'ok') {
1.638     albertel 1491:             &logthis('Failed to parse '.$filepath.$file.
                   1492: 		     ' for embedded media: '.$parse_result); 
1.637     raeburn  1493:         }
                   1494:     }
1.259     www      1495: # Notify homeserver to grep it
                   1496: #
1.638     albertel 1497:     my $docuhome=&homeserver($docuname,$docudom);
1.494     albertel 1498:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      1499:     if ($fetchresult eq 'ok') {
1.259     www      1500: #
1.258     www      1501: # Return the URL to it
1.494     albertel 1502:         return '/uploaded/'.$path.$file;
1.263     www      1503:     } else {
1.494     albertel 1504:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   1505: 		 ': '.$fetchresult);
1.263     www      1506:         return '/adm/notfound.html';
                   1507:     }    
1.493     albertel 1508: }
                   1509: 
1.637     raeburn  1510: sub extract_embedded_items {
1.648     raeburn  1511:     my ($filepath,$file,$allfiles,$codebase,$content) = @_;
1.637     raeburn  1512:     my @state = ();
                   1513:     my %javafiles = (
                   1514:                       codebase => '',
                   1515:                       code => '',
                   1516:                       archive => ''
                   1517:                     );
                   1518:     my %mediafiles = (
                   1519:                       src => '',
                   1520:                       movie => '',
                   1521:                      );
1.648     raeburn  1522:     my $p;
                   1523:     if ($content) {
                   1524:         $p = HTML::LCParser->new($content);
                   1525:     } else {
                   1526:         $p = HTML::LCParser->new($filepath.'/'.$file);
                   1527:     }
1.641     albertel 1528:     while (my $t=$p->get_token()) {
1.640     albertel 1529: 	if ($t->[0] eq 'S') {
                   1530: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
                   1531: 	    push (@state, $tagname);
1.648     raeburn  1532:             if (lc($tagname) eq 'allow') {
                   1533:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   1534:             }
1.640     albertel 1535: 	    if (lc($tagname) eq 'img') {
                   1536: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   1537: 	    }
1.645     raeburn  1538:             if (lc($tagname) eq 'script') {
                   1539:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   1540:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   1541:                 } else {
                   1542:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   1543:                 }
                   1544:             }
                   1545:             if (lc($tagname) eq 'link') {
                   1546:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   1547:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   1548:                 }
                   1549:             }
1.640     albertel 1550: 	    if (lc($tagname) eq 'object' ||
                   1551: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   1552: 		foreach my $item (keys(%javafiles)) {
                   1553: 		    $javafiles{$item} = '';
                   1554: 		}
                   1555: 	    }
                   1556: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   1557: 		my $name = lc($attr->{'name'});
                   1558: 		foreach my $item (keys(%javafiles)) {
                   1559: 		    if ($name eq $item) {
                   1560: 			$javafiles{$item} = $attr->{'value'};
                   1561: 			last;
                   1562: 		    }
                   1563: 		}
                   1564: 		foreach my $item (keys(%mediafiles)) {
                   1565: 		    if ($name eq $item) {
                   1566: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   1567: 			last;
                   1568: 		    }
                   1569: 		}
                   1570: 	    }
                   1571: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   1572: 		foreach my $item (keys(%javafiles)) {
                   1573: 		    if ($attr->{$item}) {
                   1574: 			$javafiles{$item} = $attr->{$item};
                   1575: 			last;
                   1576: 		    }
                   1577: 		}
                   1578: 		foreach my $item (keys(%mediafiles)) {
                   1579: 		    if ($attr->{$item}) {
                   1580: 			&add_filetype($allfiles,$attr->{$item},$item);
                   1581: 			last;
                   1582: 		    }
                   1583: 		}
                   1584: 	    }
                   1585: 	} elsif ($t->[0] eq 'E') {
                   1586: 	    my ($tagname) = ($t->[1]);
                   1587: 	    if ($javafiles{'codebase'} ne '') {
                   1588: 		$javafiles{'codebase'} .= '/';
                   1589: 	    }  
                   1590: 	    if (lc($tagname) eq 'applet' ||
                   1591: 		lc($tagname) eq 'object' ||
                   1592: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   1593: 		) {
                   1594: 		foreach my $item (keys(%javafiles)) {
                   1595: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   1596: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   1597: 			&add_filetype($allfiles,$file,$item);
                   1598: 		    }
                   1599: 		}
                   1600: 	    } 
                   1601: 	    pop @state;
                   1602: 	}
                   1603:     }
1.637     raeburn  1604:     return 'ok';
                   1605: }
                   1606: 
1.639     albertel 1607: sub add_filetype {
                   1608:     my ($allfiles,$file,$type)=@_;
                   1609:     if (exists($allfiles->{$file})) {
                   1610: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   1611: 	    push(@{$allfiles->{$file}}, &escape($type));
                   1612: 	}
                   1613:     } else {
                   1614: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  1615:     }
                   1616: }
                   1617: 
1.493     albertel 1618: sub removeuploadedurl {
                   1619:     my ($url)=@_;
                   1620:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613     albertel 1621:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 1622: }
                   1623: 
                   1624: sub removeuserfile {
                   1625:     my ($docuname,$docudom,$fname)=@_;
                   1626:     my $home=&homeserver($docuname,$docudom);
                   1627:     return &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.257     www      1628: }
1.15      www      1629: 
1.530     albertel 1630: sub mkdiruserfile {
                   1631:     my ($docuname,$docudom,$dir)=@_;
                   1632:     my $home=&homeserver($docuname,$docudom);
                   1633:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   1634: }
                   1635: 
1.531     albertel 1636: sub renameuserfile {
                   1637:     my ($docuname,$docudom,$old,$new)=@_;
                   1638:     my $home=&homeserver($docuname,$docudom);
                   1639:     return &reply("renameuserfile:$docudom:$docuname:".&escape("$old").':'.
                   1640: 		  &escape("$new"),$home);
                   1641: }
                   1642: 
1.14      www      1643: # ------------------------------------------------------------------------- Log
                   1644: 
                   1645: sub log {
                   1646:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      1647:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      1648: }
                   1649: 
                   1650: # ------------------------------------------------------------------ Course Log
1.352     www      1651: #
                   1652: # This routine flushes several buffers of non-mission-critical nature
                   1653: #
1.157     www      1654: 
                   1655: sub flushcourselogs {
1.352     www      1656:     &logthis('Flushing log buffers');
                   1657: #
                   1658: # course logs
                   1659: # This is a log of all transactions in a course, which can be used
                   1660: # for data mining purposes
                   1661: #
                   1662: # It also collects the courseid database, which lists last transaction
                   1663: # times and course titles for all courseids
                   1664: #
                   1665:     my %courseidbuffer=();
1.191     harris41 1666:     foreach (keys %courselogs) {
1.157     www      1667:         my $crsid=$_;
1.352     www      1668:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      1669: 		          &escape($courselogs{$crsid}),
                   1670: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      1671: 	    delete $courselogs{$crsid};
                   1672:         } else {
                   1673:             &logthis('Failed to flush log buffer for '.$crsid);
                   1674:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 1675:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      1676:                         " exceeded maximum size, deleting.</font>");
                   1677:                delete $courselogs{$crsid};
                   1678:             }
1.352     www      1679:         }
                   1680:         if ($courseidbuffer{$coursehombuf{$crsid}}) {
                   1681:            $courseidbuffer{$coursehombuf{$crsid}}.='&'.
1.516     raeburn  1682: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.741     raeburn  1683:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1.352     www      1684:         } else {
                   1685:            $courseidbuffer{$coursehombuf{$crsid}}=
1.516     raeburn  1686: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.741     raeburn  1687:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1.571     raeburn  1688:         }
1.191     harris41 1689:     }
1.352     www      1690: #
                   1691: # Write course id database (reverse lookup) to homeserver of courses 
                   1692: # Is used in pickcourse
                   1693: #
                   1694:     foreach (keys %courseidbuffer) {
1.353     www      1695:         &courseidput($hostdom{$_},$courseidbuffer{$_},$_);
1.352     www      1696:     }
                   1697: #
                   1698: # File accesses
                   1699: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   1700: #
1.449     matthew  1701:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  1702:         if ($entry =~ /___count$/) {
                   1703:             my ($dom,$name);
                   1704:             ($dom,$name,undef)=($entry=~m:___(\w+)/(\w+)/(.*)___count$:);
                   1705:             if (! defined($dom) || $dom eq '' || 
                   1706:                 ! defined($name) || $name eq '') {
1.620     albertel 1707:                 my $cid = $env{'request.course.id'};
                   1708:                 $dom  = $env{'request.'.$cid.'.domain'};
                   1709:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  1710:             }
1.450     matthew  1711:             my $value = $accesshash{$entry};
                   1712:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   1713:             my %temphash=($url => $value);
1.449     matthew  1714:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   1715:             if ($result eq 'ok') {
                   1716:                 delete $accesshash{$entry};
                   1717:             } elsif ($result eq 'unknown_cmd') {
                   1718:                 # Target server has old code running on it.
1.450     matthew  1719:                 my %temphash=($entry => $value);
1.449     matthew  1720:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   1721:                     delete $accesshash{$entry};
                   1722:                 }
                   1723:             }
                   1724:         } else {
1.458     matthew  1725:             my ($dom,$name) = ($entry=~m:___(\w+)/(\w+)/(.*)___(\w+)$:);
1.450     matthew  1726:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  1727:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   1728:                 delete $accesshash{$entry};
                   1729:             }
1.185     www      1730:         }
1.191     harris41 1731:     }
1.352     www      1732: #
                   1733: # Roles
                   1734: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   1735: #
1.349     www      1736:     foreach (keys %userrolehash) {
                   1737:         my $entry=$_;
1.351     www      1738:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      1739: 	    split(/\:/,$entry);
                   1740:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      1741:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      1742:                 $rudom,$runame) eq 'ok') {
                   1743: 	    delete $userrolehash{$entry};
                   1744:         }
                   1745:     }
1.662     raeburn  1746: #
                   1747: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   1748: #
                   1749:     my %domrolebuffer = ();
                   1750:     foreach my $entry (keys %domainrolehash) {
                   1751:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split/:/,$entry;
                   1752:         if ($domrolebuffer{$rudom}) {
                   1753:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   1754:                       '='.&escape($domainrolehash{$entry});
                   1755:         } else {
                   1756:             $domrolebuffer{$rudom}.=&escape($entry).
                   1757:                       '='.&escape($domainrolehash{$entry});
                   1758:         }
                   1759:         delete $domainrolehash{$entry};
                   1760:     }
                   1761:     foreach my $dom (keys(%domrolebuffer)) {
                   1762:         foreach my $tryserver (keys %libserv) {
                   1763:             if ($hostdom{$tryserver} eq $dom) {
                   1764:                 unless (&reply('domroleput:'.$dom.':'.
                   1765:                   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   1766:                     &logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   1767:                 }
                   1768:             }
                   1769:         }
                   1770:     }
1.186     www      1771:     $dumpcount++;
1.157     www      1772: }
                   1773: 
                   1774: sub courselog {
                   1775:     my $what=shift;
1.158     www      1776:     $what=time.':'.$what;
1.620     albertel 1777:     unless ($env{'request.course.id'}) { return ''; }
                   1778:     $coursedombuf{$env{'request.course.id'}}=
                   1779:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   1780:     $coursenumbuf{$env{'request.course.id'}}=
                   1781:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   1782:     $coursehombuf{$env{'request.course.id'}}=
                   1783:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   1784:     $coursedescrbuf{$env{'request.course.id'}}=
                   1785:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   1786:     $courseinstcodebuf{$env{'request.course.id'}}=
                   1787:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   1788:     $courseownerbuf{$env{'request.course.id'}}=
                   1789:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  1790:     $coursetypebuf{$env{'request.course.id'}}=
                   1791:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 1792:     if (defined $courselogs{$env{'request.course.id'}}) {
                   1793: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      1794:     } else {
1.620     albertel 1795: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      1796:     }
1.620     albertel 1797:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      1798: 	&flushcourselogs();
                   1799:     }
1.158     www      1800: }
                   1801: 
                   1802: sub courseacclog {
                   1803:     my $fnsymb=shift;
1.620     albertel 1804:     unless ($env{'request.course.id'}) { return ''; }
                   1805:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 1806:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      1807:         $what.=':POST';
1.583     matthew  1808:         # FIXME: Probably ought to escape things....
1.620     albertel 1809: 	foreach (keys %env) {
1.158     www      1810:             if ($_=~/^form\.(.*)/) {
1.620     albertel 1811: 		$what.=':'.$1.'='.$env{$_};
1.158     www      1812:             }
1.191     harris41 1813:         }
1.583     matthew  1814:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   1815:         # FIXME: We should not be depending on a form parameter that someone
                   1816:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 1817:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  1818:             $what.= ':POST';
                   1819:             # FIXME: Probably ought to escape things....
                   1820:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   1821:                                  'crsdiscuss') {
1.620     albertel 1822:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  1823:             }
                   1824:         }
1.158     www      1825:     }
                   1826:     &courselog($what);
1.149     www      1827: }
                   1828: 
1.185     www      1829: sub countacc {
                   1830:     my $url=&declutter(shift);
1.458     matthew  1831:     return if (! defined($url) || $url eq '');
1.620     albertel 1832:     unless ($env{'request.course.id'}) { return ''; }
                   1833:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      1834:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  1835:     $accesshash{$key}++;
1.185     www      1836: }
1.349     www      1837: 
1.361     www      1838: sub linklog {
                   1839:     my ($from,$to)=@_;
                   1840:     $from=&declutter($from);
                   1841:     $to=&declutter($to);
                   1842:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   1843:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   1844: }
                   1845:   
1.349     www      1846: sub userrolelog {
                   1847:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  1848:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  1849:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  1850:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
                   1851:         ($trole=~/^ta/)) {
1.350     www      1852:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   1853:        $userrolehash
                   1854:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      1855:                     =$tend.':'.$tstart;
1.662     raeburn  1856:     }
                   1857:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   1858:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   1859:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   1860:         ($trole=~/^sc/)) {
                   1861:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   1862:        $domainrolehash
                   1863:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   1864:                     = $tend.':'.$tstart;
                   1865:     }
1.351     www      1866: }
                   1867: 
                   1868: sub get_course_adv_roles {
                   1869:     my $cid=shift;
1.620     albertel 1870:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      1871:     my %coursehash=&coursedescription($cid);
1.470     www      1872:     my %nothide=();
                   1873:     foreach (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   1874: 	$nothide{join(':',split(/[\@\:]/,$_))}=1;
                   1875:     }
1.351     www      1876:     my %returnhash=();
                   1877:     my %dumphash=
                   1878:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   1879:     my $now=time;
                   1880:     foreach (keys %dumphash) {
                   1881: 	my ($tend,$tstart)=split(/\:/,$dumphash{$_});
                   1882:         if (($tstart) && ($tstart<0)) { next; }
                   1883:         if (($tend) && ($tend<$now)) { next; }
                   1884:         if (($tstart) && ($now<$tstart)) { next; }
                   1885:         my ($role,$username,$domain,$section)=split(/\:/,$_);
1.576     albertel 1886: 	if ($username eq '' || $domain eq '') { next; }
1.470     www      1887: 	if ((&privileged($username,$domain)) && 
                   1888: 	    (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 1889: 	if ($role eq 'cr') { next; }
1.351     www      1890:         my $key=&plaintext($role);
                   1891:         if ($section) { $key.=' (Sec/Grp '.$section.')'; }
                   1892:         if ($returnhash{$key}) {
                   1893: 	    $returnhash{$key}.=','.$username.':'.$domain;
                   1894:         } else {
                   1895:             $returnhash{$key}=$username.':'.$domain;
                   1896:         }
1.400     www      1897:      }
                   1898:     return %returnhash;
                   1899: }
                   1900: 
                   1901: sub get_my_roles {
                   1902:     my ($uname,$udom)=@_;
1.620     albertel 1903:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   1904:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.400     www      1905:     my %dumphash=
                   1906:             &dump('nohist_userroles',$udom,$uname);
                   1907:     my %returnhash=();
                   1908:     my $now=time;
                   1909:     foreach (keys %dumphash) {
                   1910: 	my ($tend,$tstart)=split(/\:/,$dumphash{$_});
                   1911:         if (($tstart) && ($tstart<0)) { next; }
                   1912:         if (($tend) && ($tend<$now)) { next; }
                   1913:         if (($tstart) && ($now<$tstart)) { next; }
                   1914:         my ($role,$username,$domain,$section)=split(/\:/,$_);
                   1915: 	$returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
1.373     www      1916:      }
                   1917:     return %returnhash;
1.399     www      1918: }
                   1919: 
                   1920: # ----------------------------------------------------- Frontpage Announcements
                   1921: #
                   1922: #
                   1923: 
                   1924: sub postannounce {
                   1925:     my ($server,$text)=@_;
                   1926:     unless (&allowed('psa',$hostdom{$server})) { return 'refused'; }
                   1927:     unless ($text=~/\w/) { $text=''; }
                   1928:     return &reply('setannounce:'.&escape($text),$server);
                   1929: }
                   1930: 
                   1931: sub getannounce {
1.448     albertel 1932: 
                   1933:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      1934: 	my $announcement='';
                   1935: 	while (<$fh>) { $announcement .=$_; }
1.448     albertel 1936: 	close($fh);
1.399     www      1937: 	if ($announcement=~/\w/) { 
                   1938: 	    return 
                   1939:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 1940:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      1941: 	} else {
                   1942: 	    return '';
                   1943: 	}
                   1944:     } else {
                   1945: 	return '';
                   1946:     }
1.351     www      1947: }
1.353     www      1948: 
                   1949: # ---------------------------------------------------------- Course ID routines
                   1950: # Deal with domain's nohist_courseid.db files
                   1951: #
                   1952: 
                   1953: sub courseidput {
                   1954:     my ($domain,$what,$coursehome)=@_;
                   1955:     return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   1956: }
                   1957: 
                   1958: sub courseiddump {
1.741     raeburn  1959:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,$coursefilter,$hostidflag,$hostidref,$typefilter)=@_;
1.353     www      1960:     my %returnhash=();
1.355     www      1961:     unless ($domfilter) { $domfilter=''; }
1.353     www      1962:     foreach my $tryserver (keys %libserv) {
1.511     raeburn  1963:         if ( ($hostidflag == 1 && grep/^$tryserver$/,@{$hostidref}) || (!defined($hostidflag)) ) {
1.506     raeburn  1964: 	    if ((!$domfilter) || ($hostdom{$tryserver} eq $domfilter)) {
                   1965: 	        foreach (
                   1966:                  split(/\&/,&reply('courseiddump:'.$hostdom{$tryserver}.':'.
1.571     raeburn  1967: 			       $sincefilter.':'.&escape($descfilter).':'.
1.741     raeburn  1968:                                &escape($instcodefilter).':'.&escape($ownerfilter).':'.&escape($coursefilter).':'.&escape($typefilter),
1.354     www      1969:                                $tryserver))) {
1.506     raeburn  1970: 		    my ($key,$value)=split(/\=/,$_);
                   1971:                     if (($key) && ($value)) {
1.516     raeburn  1972: 		        $returnhash{&unescape($key)}=$value;
1.506     raeburn  1973:                     }
1.353     www      1974:                 }
                   1975:             }
                   1976:         }
                   1977:     }
                   1978:     return %returnhash;
                   1979: }
                   1980: 
1.658     raeburn  1981: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  1982: 
                   1983: sub dcmailput {
1.685     raeburn  1984:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  1985:     my $status = &Apache::lonnet::critical(
1.740     www      1986:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   1987:        &escape($message),$server);
1.662     raeburn  1988:     return $status;
                   1989: }
                   1990: 
1.658     raeburn  1991: sub dcmaildump {
                   1992:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  1993:     my %returnhash=();
                   1994:     if (exists($domain_primary{$dom})) {
                   1995:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   1996:                                                          &escape($enddate).':';
                   1997: 	my @esc_senders=map { &escape($_)} @$senders;
                   1998: 	$cmd.=&escape(join('&',@esc_senders));
                   1999: 	foreach (split(/\&/,&reply($cmd,$domain_primary{$dom}))) {
                   2000:             my ($key,$value) = split(/\=/,$_);
                   2001:             if (($key) && ($value)) {
                   2002:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  2003:             }
                   2004:         }
                   2005:     }
                   2006:     return %returnhash;
                   2007: }
1.662     raeburn  2008: # ---------------------------------------------------------- Domain roles
                   2009: 
                   2010: sub get_domain_roles {
                   2011:     my ($dom,$roles,$startdate,$enddate)=@_;
                   2012:     if (undef($startdate) || $startdate eq '') {
                   2013:         $startdate = '.';
                   2014:     }
                   2015:     if (undef($enddate) || $enddate eq '') {
                   2016:         $enddate = '.';
                   2017:     }
                   2018:     my $rolelist = join(':',@{$roles});
                   2019:     my %personnel = ();
                   2020:     foreach my $tryserver (keys(%libserv)) {
                   2021:         if ($hostdom{$tryserver} eq $dom) {
                   2022:             %{$personnel{$tryserver}}=();
                   2023:             foreach (
                   2024:                 split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   2025:                    &escape($startdate).':'.&escape($enddate).':'.
                   2026:                    &escape($rolelist), $tryserver))) {
                   2027:                 my($key,$value) = split(/\=/,$_);
                   2028:                 if (($key) && ($value)) {
                   2029:                     $personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   2030:                 }
                   2031:             }
                   2032:         }
                   2033:     }
                   2034:     return %personnel;
                   2035: }
1.658     raeburn  2036: 
1.149     www      2037: # ----------------------------------------------------------- Check out an item
                   2038: 
1.504     albertel 2039: sub get_first_access {
                   2040:     my ($type,$argsymb)=@_;
                   2041:     my ($symb,$courseid,$udom,$uname)=&Apache::lonxml::whichuser();
                   2042:     if ($argsymb) { $symb=$argsymb; }
                   2043:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 2044:     if ($type eq 'map') {
                   2045: 	$res=&symbread($map);
                   2046:     } else {
                   2047: 	$res=$symb;
                   2048:     }
                   2049:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   2050:     return $times{"$courseid\0$res"};
1.504     albertel 2051: }
                   2052: 
                   2053: sub set_first_access {
                   2054:     my ($type)=@_;
                   2055:     my ($symb,$courseid,$udom,$uname)=&Apache::lonxml::whichuser();
                   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 $firstaccess=&get_first_access($type,$symb);
1.505     albertel 2063:     if (!$firstaccess) {
1.588     albertel 2064: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 2065:     }
                   2066:     return 'already_set';
1.504     albertel 2067: }
                   2068: 
1.149     www      2069: sub checkout {
                   2070:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   2071:     my $now=time;
                   2072:     my $lonhost=$perlvar{'lonHostID'};
                   2073:     my $infostr=&escape(
1.234     www      2074:                  'CHECKOUTTOKEN&'.
1.149     www      2075:                  $tuname.'&'.
                   2076:                  $tudom.'&'.
                   2077:                  $tcrsid.'&'.
                   2078:                  $symb.'&'.
                   2079: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                   2080:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www      2081:     if ($token=~/^error\:/) { 
1.672     albertel 2082:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2083:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2084:                  "</font>");
                   2085:         return ''; 
                   2086:     }
                   2087: 
1.149     www      2088:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   2089:     $token=~tr/a-z/A-Z/;
                   2090: 
1.153     www      2091:     my %infohash=('resource.0.outtoken' => $token,
                   2092:                   'resource.0.checkouttime' => $now,
                   2093:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www      2094: 
                   2095:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2096:        return '';
1.151     www      2097:     } else {
1.672     albertel 2098:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2099:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2100:                  "</font>");
1.149     www      2101:     }    
                   2102: 
                   2103:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2104:                          &escape('Checkout '.$infostr.' - '.
                   2105:                                                  $token)) ne 'ok') {
                   2106: 	return '';
1.151     www      2107:     } else {
1.672     albertel 2108:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2109:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2110:                  "</font>");
1.149     www      2111:     }
1.151     www      2112:     return $token;
1.149     www      2113: }
                   2114: 
                   2115: # ------------------------------------------------------------ Check in an item
                   2116: 
                   2117: sub checkin {
                   2118:     my $token=shift;
1.150     www      2119:     my $now=time;
                   2120:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   2121:     $lonhost=~tr/A-Z/a-z/;
1.595     albertel 2122:     my $dtoken=$ta.'_'.$hostname{$lonhost}.'_'.$tb;
1.150     www      2123:     $dtoken=~s/\W/\_/g;
1.234     www      2124:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www      2125:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   2126: 
1.154     www      2127:     unless (($tuname) && ($tudom)) {
                   2128:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   2129:         return '';
                   2130:     }
                   2131:     
                   2132:     unless (&allowed('mgr',$tcrsid)) {
                   2133:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620     albertel 2134:                  $env{'user.name'}.' - '.$env{'user.domain'});
1.154     www      2135:         return '';
                   2136:     }
                   2137: 
1.153     www      2138:     my %infohash=('resource.0.intoken' => $token,
                   2139:                   'resource.0.checkintime' => $now,
                   2140:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      2141: 
                   2142:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2143:        return '';
                   2144:     }    
                   2145: 
                   2146:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2147:                          &escape('Checkin - '.$token)) ne 'ok') {
                   2148: 	return '';
                   2149:     }
                   2150: 
                   2151:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      2152: }
                   2153: 
                   2154: # --------------------------------------------- Set Expire Date for Spreadsheet
                   2155: 
                   2156: sub expirespread {
                   2157:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 2158:     my $cid=$env{'request.course.id'}; 
1.110     www      2159:     if ($cid) {
                   2160:        my $now=time;
                   2161:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 2162:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   2163:                             $env{'course.'.$cid.'.num'}.
1.110     www      2164: 	        	    ':nohist_expirationdates:'.
                   2165:                             &escape($key).'='.$now,
1.620     albertel 2166:                             $env{'course.'.$cid.'.home'})
1.110     www      2167:     }
                   2168:     return 'ok';
1.14      www      2169: }
                   2170: 
1.109     www      2171: # ----------------------------------------------------- Devalidate Spreadsheets
                   2172: 
                   2173: sub devalidate {
1.325     www      2174:     my ($symb,$uname,$udom)=@_;
1.620     albertel 2175:     my $cid=$env{'request.course.id'}; 
1.109     www      2176:     if ($cid) {
1.391     matthew  2177:         # delete the stored spreadsheets for
                   2178:         # - the student level sheet of this user in course's homespace
                   2179:         # - the assessment level sheet for this resource 
                   2180:         #   for this user in user's homespace
1.553     albertel 2181: 	# - current conditional state info
1.325     www      2182: 	my $key=$uname.':'.$udom.':';
1.109     www      2183:         my $status=
1.299     matthew  2184: 	    &del('nohist_calculatedsheets',
1.391     matthew  2185: 		 [$key.'studentcalc:'],
1.620     albertel 2186: 		 $env{'course.'.$cid.'.domain'},
                   2187: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 2188: 		.' '.
                   2189: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  2190: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      2191:         unless ($status eq 'ok ok') {
                   2192:            &logthis('Could not devalidate spreadsheet '.
1.325     www      2193:                     $uname.' at '.$udom.' for '.
1.109     www      2194: 		    $symb.': '.$status);
1.133     albertel 2195:         }
1.553     albertel 2196: 	&delenv('user.state.'.$cid);
1.109     www      2197:     }
                   2198: }
                   2199: 
1.265     albertel 2200: sub get_scalar {
                   2201:     my ($string,$end) = @_;
                   2202:     my $value;
                   2203:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   2204: 	$value = $1;
                   2205:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   2206: 	$value = $1;
                   2207:     }
                   2208:     return &unescape($value);
                   2209: }
                   2210: 
                   2211: sub array2str {
                   2212:   my (@array) = @_;
                   2213:   my $result=&arrayref2str(\@array);
                   2214:   $result=~s/^__ARRAY_REF__//;
                   2215:   $result=~s/__END_ARRAY_REF__$//;
                   2216:   return $result;
                   2217: }
                   2218: 
1.204     albertel 2219: sub arrayref2str {
                   2220:   my ($arrayref) = @_;
1.265     albertel 2221:   my $result='__ARRAY_REF__';
1.204     albertel 2222:   foreach my $elem (@$arrayref) {
1.265     albertel 2223:     if(ref($elem) eq 'ARRAY') {
                   2224:       $result.=&arrayref2str($elem).'&';
                   2225:     } elsif(ref($elem) eq 'HASH') {
                   2226:       $result.=&hashref2str($elem).'&';
                   2227:     } elsif(ref($elem)) {
                   2228:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 2229:     } else {
                   2230:       $result.=&escape($elem).'&';
                   2231:     }
                   2232:   }
                   2233:   $result=~s/\&$//;
1.265     albertel 2234:   $result .= '__END_ARRAY_REF__';
1.204     albertel 2235:   return $result;
                   2236: }
                   2237: 
1.168     albertel 2238: sub hash2str {
1.204     albertel 2239:   my (%hash) = @_;
                   2240:   my $result=&hashref2str(\%hash);
1.265     albertel 2241:   $result=~s/^__HASH_REF__//;
                   2242:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 2243:   return $result;
                   2244: }
                   2245: 
                   2246: sub hashref2str {
                   2247:   my ($hashref)=@_;
1.265     albertel 2248:   my $result='__HASH_REF__';
1.495     albertel 2249:   foreach (sort(keys(%$hashref))) {
1.204     albertel 2250:     if (ref($_) eq 'ARRAY') {
1.265     albertel 2251:       $result.=&arrayref2str($_).'=';
1.204     albertel 2252:     } elsif (ref($_) eq 'HASH') {
1.265     albertel 2253:       $result.=&hashref2str($_).'=';
1.204     albertel 2254:     } elsif (ref($_)) {
1.265     albertel 2255:       $result.='=';
                   2256:       #print("Got a ref of ".(ref($_))." skipping.");
1.204     albertel 2257:     } else {
1.265     albertel 2258: 	if ($_) {$result.=&escape($_).'=';} else { last; }
1.204     albertel 2259:     }
                   2260: 
1.265     albertel 2261:     if(ref($hashref->{$_}) eq 'ARRAY') {
                   2262:       $result.=&arrayref2str($hashref->{$_}).'&';
                   2263:     } elsif(ref($hashref->{$_}) eq 'HASH') {
                   2264:       $result.=&hashref2str($hashref->{$_}).'&';
                   2265:     } elsif(ref($hashref->{$_})) {
                   2266:        $result.='&';
                   2267:       #print("Got a ref of ".(ref($hashref->{$_}))." skipping.");
1.204     albertel 2268:     } else {
1.265     albertel 2269:       $result.=&escape($hashref->{$_}).'&';
1.204     albertel 2270:     }
                   2271:   }
1.168     albertel 2272:   $result=~s/\&$//;
1.265     albertel 2273:   $result .= '__END_HASH_REF__';
1.168     albertel 2274:   return $result;
                   2275: }
                   2276: 
                   2277: sub str2hash {
1.265     albertel 2278:     my ($string)=@_;
                   2279:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   2280:     return %$hash;
                   2281: }
                   2282: 
                   2283: sub str2hashref {
1.168     albertel 2284:   my ($string) = @_;
1.265     albertel 2285: 
                   2286:   my %hash;
                   2287: 
                   2288:   if($string !~ /^__HASH_REF__/) {
                   2289:       if (! ($string eq '' || !defined($string))) {
                   2290: 	  $hash{'error'}='Not hash reference';
                   2291:       }
                   2292:       return (\%hash, $string);
                   2293:   }
                   2294: 
                   2295:   $string =~ s/^__HASH_REF__//;
                   2296: 
                   2297:   while($string !~ /^__END_HASH_REF__/) {
                   2298:       #key
                   2299:       my $key='';
                   2300:       if($string =~ /^__HASH_REF__/) {
                   2301:           ($key, $string)=&str2hashref($string);
                   2302:           if(defined($key->{'error'})) {
                   2303:               $hash{'error'}='Bad data';
                   2304:               return (\%hash, $string);
                   2305:           }
                   2306:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2307:           ($key, $string)=&str2arrayref($string);
                   2308:           if($key->[0] eq 'Array reference error') {
                   2309:               $hash{'error'}='Bad data';
                   2310:               return (\%hash, $string);
                   2311:           }
                   2312:       } else {
                   2313:           $string =~ s/^(.*?)=//;
1.267     albertel 2314: 	  $key=&unescape($1);
1.265     albertel 2315:       }
                   2316:       $string =~ s/^=//;
                   2317: 
                   2318:       #value
                   2319:       my $value='';
                   2320:       if($string =~ /^__HASH_REF__/) {
                   2321:           ($value, $string)=&str2hashref($string);
                   2322:           if(defined($value->{'error'})) {
                   2323:               $hash{'error'}='Bad data';
                   2324:               return (\%hash, $string);
                   2325:           }
                   2326:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2327:           ($value, $string)=&str2arrayref($string);
                   2328:           if($value->[0] eq 'Array reference error') {
                   2329:               $hash{'error'}='Bad data';
                   2330:               return (\%hash, $string);
                   2331:           }
                   2332:       } else {
                   2333: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   2334:       }
                   2335:       $string =~ s/^&//;
                   2336: 
                   2337:       $hash{$key}=$value;
1.204     albertel 2338:   }
1.265     albertel 2339: 
                   2340:   $string =~ s/^__END_HASH_REF__//;
                   2341: 
                   2342:   return (\%hash, $string);
1.204     albertel 2343: }
                   2344: 
                   2345: sub str2array {
1.265     albertel 2346:     my ($string)=@_;
                   2347:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   2348:     return @$array;
                   2349: }
                   2350: 
                   2351: sub str2arrayref {
1.204     albertel 2352:   my ($string) = @_;
1.265     albertel 2353:   my @array;
                   2354: 
                   2355:   if($string !~ /^__ARRAY_REF__/) {
                   2356:       if (! ($string eq '' || !defined($string))) {
                   2357: 	  $array[0]='Array reference error';
                   2358:       }
                   2359:       return (\@array, $string);
                   2360:   }
                   2361: 
                   2362:   $string =~ s/^__ARRAY_REF__//;
                   2363: 
                   2364:   while($string !~ /^__END_ARRAY_REF__/) {
                   2365:       my $value='';
                   2366:       if($string =~ /^__HASH_REF__/) {
                   2367:           ($value, $string)=&str2hashref($string);
                   2368:           if(defined($value->{'error'})) {
                   2369:               $array[0] ='Array reference error';
                   2370:               return (\@array, $string);
                   2371:           }
                   2372:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2373:           ($value, $string)=&str2arrayref($string);
                   2374:           if($value->[0] eq 'Array reference error') {
                   2375:               $array[0] ='Array reference error';
                   2376:               return (\@array, $string);
                   2377:           }
                   2378:       } else {
                   2379: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   2380:       }
                   2381:       $string =~ s/^&//;
                   2382: 
                   2383:       push(@array, $value);
1.191     harris41 2384:   }
1.265     albertel 2385: 
                   2386:   $string =~ s/^__END_ARRAY_REF__//;
                   2387: 
                   2388:   return (\@array, $string);
1.168     albertel 2389: }
                   2390: 
1.167     albertel 2391: # -------------------------------------------------------------------Temp Store
                   2392: 
1.168     albertel 2393: sub tmpreset {
                   2394:   my ($symb,$namespace,$domain,$stuname) = @_;
                   2395:   if (!$symb) {
                   2396:     $symb=&symbread();
1.620     albertel 2397:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2398:   }
                   2399:   $symb=escape($symb);
                   2400: 
1.620     albertel 2401:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 2402:   $namespace=~s/\//\_/g;
                   2403:   $namespace=~s/\W//g;
                   2404: 
1.620     albertel 2405:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2406:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2407:   if ($domain eq 'public' && $stuname eq 'public') {
                   2408:       $stuname=$ENV{'REMOTE_ADDR'};
                   2409:   }
1.168     albertel 2410:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2411:   my %hash;
                   2412:   if (tie(%hash,'GDBM_File',
                   2413: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2414: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2415:     foreach my $key (keys %hash) {
1.180     albertel 2416:       if ($key=~ /:$symb/) {
1.168     albertel 2417: 	delete($hash{$key});
                   2418:       }
                   2419:     }
                   2420:   }
                   2421: }
                   2422: 
1.167     albertel 2423: sub tmpstore {
1.168     albertel 2424:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2425: 
                   2426:   if (!$symb) {
                   2427:     $symb=&symbread();
1.620     albertel 2428:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2429:   }
                   2430:   $symb=escape($symb);
                   2431: 
                   2432:   if (!$namespace) {
                   2433:     # I don't think we would ever want to store this for a course.
                   2434:     # it seems this will only be used if we don't have a course.
1.620     albertel 2435:     #$namespace=$env{'request.course.id'};
1.168     albertel 2436:     #if (!$namespace) {
1.620     albertel 2437:       $namespace=$env{'request.state'};
1.168     albertel 2438:     #}
                   2439:   }
                   2440:   $namespace=~s/\//\_/g;
                   2441:   $namespace=~s/\W//g;
1.620     albertel 2442:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2443:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2444:   if ($domain eq 'public' && $stuname eq 'public') {
                   2445:       $stuname=$ENV{'REMOTE_ADDR'};
                   2446:   }
1.168     albertel 2447:   my $now=time;
                   2448:   my %hash;
                   2449:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2450:   if (tie(%hash,'GDBM_File',
                   2451: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2452: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2453:     $hash{"version:$symb"}++;
                   2454:     my $version=$hash{"version:$symb"};
                   2455:     my $allkeys=''; 
                   2456:     foreach my $key (keys(%$storehash)) {
                   2457:       $allkeys.=$key.':';
1.591     albertel 2458:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 2459:     }
                   2460:     $hash{"$version:$symb:timestamp"}=$now;
                   2461:     $allkeys.='timestamp';
                   2462:     $hash{"$version:keys:$symb"}=$allkeys;
                   2463:     if (untie(%hash)) {
                   2464:       return 'ok';
                   2465:     } else {
                   2466:       return "error:$!";
                   2467:     }
                   2468:   } else {
                   2469:     return "error:$!";
                   2470:   }
                   2471: }
1.167     albertel 2472: 
1.168     albertel 2473: # -----------------------------------------------------------------Temp Restore
1.167     albertel 2474: 
1.168     albertel 2475: sub tmprestore {
                   2476:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 2477: 
1.168     albertel 2478:   if (!$symb) {
                   2479:     $symb=&symbread();
1.620     albertel 2480:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2481:   }
                   2482:   $symb=escape($symb);
                   2483: 
1.620     albertel 2484:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 2485: 
1.620     albertel 2486:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2487:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2488:   if ($domain eq 'public' && $stuname eq 'public') {
                   2489:       $stuname=$ENV{'REMOTE_ADDR'};
                   2490:   }
1.168     albertel 2491:   my %returnhash;
                   2492:   $namespace=~s/\//\_/g;
                   2493:   $namespace=~s/\W//g;
                   2494:   my %hash;
                   2495:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2496:   if (tie(%hash,'GDBM_File',
                   2497: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2498: 	  &GDBM_READER(),0640)) {
1.168     albertel 2499:     my $version=$hash{"version:$symb"};
                   2500:     $returnhash{'version'}=$version;
                   2501:     my $scope;
                   2502:     for ($scope=1;$scope<=$version;$scope++) {
                   2503:       my $vkeys=$hash{"$scope:keys:$symb"};
                   2504:       my @keys=split(/:/,$vkeys);
                   2505:       my $key;
                   2506:       $returnhash{"$scope:keys"}=$vkeys;
                   2507:       foreach $key (@keys) {
1.591     albertel 2508: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   2509: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 2510:       }
                   2511:     }
1.168     albertel 2512:     if (!(untie(%hash))) {
                   2513:       return "error:$!";
                   2514:     }
                   2515:   } else {
                   2516:     return "error:$!";
                   2517:   }
                   2518:   return %returnhash;
1.167     albertel 2519: }
                   2520: 
1.9       www      2521: # ----------------------------------------------------------------------- Store
                   2522: 
                   2523: sub store {
1.124     www      2524:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2525:     my $home='';
                   2526: 
1.168     albertel 2527:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2528: 
1.213     www      2529:     $symb=&symbclean($symb);
1.122     albertel 2530:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      2531: 
1.620     albertel 2532:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2533:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      2534: 
                   2535:     &devalidate($symb,$stuname,$domain);
1.109     www      2536: 
                   2537:     $symb=escape($symb);
1.187     www      2538:     if (!$namespace) { 
1.620     albertel 2539:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      2540:           return ''; 
                   2541:        } 
                   2542:     }
1.620     albertel 2543:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      2544: 
                   2545:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   2546:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   2547: 
1.12      www      2548:     my $namevalue='';
1.191     harris41 2549:     foreach (keys %$storehash) {
1.591     albertel 2550:         $namevalue.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
1.191     harris41 2551:     }
1.12      www      2552:     $namevalue=~s/\&$//;
1.187     www      2553:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      2554:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      2555: }
                   2556: 
1.47      www      2557: # -------------------------------------------------------------- Critical Store
                   2558: 
                   2559: sub cstore {
1.124     www      2560:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2561:     my $home='';
                   2562: 
1.168     albertel 2563:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2564: 
1.213     www      2565:     $symb=&symbclean($symb);
1.122     albertel 2566:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      2567: 
1.620     albertel 2568:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2569:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      2570: 
                   2571:     &devalidate($symb,$stuname,$domain);
1.109     www      2572: 
                   2573:     $symb=escape($symb);
1.187     www      2574:     if (!$namespace) { 
1.620     albertel 2575:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      2576:           return ''; 
                   2577:        } 
                   2578:     }
1.620     albertel 2579:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      2580: 
                   2581:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   2582:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 2583: 
1.47      www      2584:     my $namevalue='';
1.191     harris41 2585:     foreach (keys %$storehash) {
1.591     albertel 2586:         $namevalue.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
1.191     harris41 2587:     }
1.47      www      2588:     $namevalue=~s/\&$//;
1.187     www      2589:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      2590:     return critical
                   2591:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      2592: }
                   2593: 
1.9       www      2594: # --------------------------------------------------------------------- Restore
                   2595: 
                   2596: sub restore {
1.124     www      2597:     my ($symb,$namespace,$domain,$stuname) = @_;
                   2598:     my $home='';
                   2599: 
1.168     albertel 2600:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2601: 
1.122     albertel 2602:     if (!$symb) {
                   2603:       unless ($symb=escape(&symbread())) { return ''; }
                   2604:     } else {
1.213     www      2605:       $symb=&escape(&symbclean($symb));
1.122     albertel 2606:     }
1.188     www      2607:     if (!$namespace) { 
1.620     albertel 2608:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      2609:           return ''; 
                   2610:        } 
                   2611:     }
1.620     albertel 2612:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2613:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   2614:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 2615:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   2616: 
1.12      www      2617:     my %returnhash=();
1.191     harris41 2618:     foreach (split(/\&/,$answer)) {
1.12      www      2619: 	my ($name,$value)=split(/\=/,$_);
1.591     albertel 2620:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 2621:     }
1.75      www      2622:     my $version;
                   2623:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.191     harris41 2624:        foreach (split(/\:/,$returnhash{$version.':keys'})) {
1.75      www      2625:           $returnhash{$_}=$returnhash{$version.':'.$_};
1.191     harris41 2626:        }
1.75      www      2627:     }
1.13      www      2628:     return %returnhash;
1.34      www      2629: }
                   2630: 
                   2631: # ---------------------------------------------------------- Course Description
                   2632: 
                   2633: sub coursedescription {
1.731     albertel 2634:     my ($courseid,$args)=@_;
1.34      www      2635:     $courseid=~s/^\///;
1.49      www      2636:     $courseid=~s/\_/\//g;
1.34      www      2637:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 2638:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 2639:     my $normalid=$cdomain.'_'.$cnum;
                   2640:     # need to always cache even if we get errors otherwise we keep 
                   2641:     # trying and trying and trying to get the course description.
                   2642:     my %envhash=();
                   2643:     my %returnhash=();
1.731     albertel 2644:     
                   2645:     my $expiretime=600;
                   2646:     if ($env{'request.course.id'} eq $normalid) {
                   2647: 	$expiretime=120;
                   2648:     }
                   2649: 
                   2650:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   2651:     if (!$args->{'freshen_cache'}
                   2652: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   2653: 	foreach my $key (keys(%env)) {
                   2654: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   2655: 	    my ($setting) = $1;
                   2656: 	    $returnhash{$setting} = $env{$key};
                   2657: 	}
                   2658: 	return %returnhash;
                   2659:     }
                   2660: 
                   2661:     # get the data agin
                   2662:     if (!$args->{'one_time'}) {
                   2663: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   2664:     }
1.34      www      2665:     if ($chome ne 'no_host') {
1.302     albertel 2666:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 2667:        if (!exists($returnhash{'con_lost'})) {
                   2668:            $returnhash{'home'}= $chome;
                   2669: 	   $returnhash{'domain'} = $cdomain;
                   2670: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  2671:            if (!defined($returnhash{'type'})) {
                   2672:                $returnhash{'type'} = 'Course';
                   2673:            }
1.130     albertel 2674:            while (my ($name,$value) = each %returnhash) {
1.53      www      2675:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 2676:            }
1.270     www      2677:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      2678:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 2679: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      2680:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   2681:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   2682:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      2683:        }
                   2684:     }
1.731     albertel 2685:     if (!$args->{'one_time'}) {
                   2686: 	&appenv(%envhash);
                   2687:     }
1.302     albertel 2688:     return %returnhash;
1.461     www      2689: }
                   2690: 
                   2691: # -------------------------------------------------See if a user is privileged
                   2692: 
                   2693: sub privileged {
                   2694:     my ($username,$domain)=@_;
                   2695:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   2696: 			&homeserver($username,$domain));
                   2697:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
                   2698:     my $now=time;
                   2699:     if ($rolesdump ne '') {
                   2700:         foreach (split(/&/,$rolesdump)) {
1.586     albertel 2701: 	    if ($_!~/^rolesdef_/) {
1.461     www      2702: 		my ($area,$role)=split(/=/,$_);
                   2703: 		$area=~s/\_\w\w$//;
                   2704: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   2705: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   2706: 		    my $active=1;
                   2707: 		    if ($tend) {
                   2708: 			if ($tend<$now) { $active=0; }
                   2709: 		    }
                   2710: 		    if ($tstart) {
                   2711: 			if ($tstart>$now) { $active=0; }
                   2712: 		    }
                   2713: 		    if ($active) { return 1; }
                   2714: 		}
                   2715: 	    }
                   2716: 	}
                   2717:     }
                   2718:     return 0;
1.9       www      2719: }
1.1       albertel 2720: 
1.103     harris41 2721: # -------------------------------------------------------- Get user privileges
1.11      www      2722: 
                   2723: sub rolesinit {
                   2724:     my ($domain,$username,$authhost)=@_;
                   2725:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.12      www      2726:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
1.11      www      2727:     my %allroles=();
1.678     raeburn  2728:     my %allgroups=();   
1.11      www      2729:     my $now=time;
1.743     albertel 2730:     my %userroles = ('user.login.time' => $now);
1.678     raeburn  2731:     my $group_privs;
1.11      www      2732: 
                   2733:     if ($rolesdump ne '') {
1.191     harris41 2734:         foreach (split(/&/,$rolesdump)) {
1.586     albertel 2735: 	  if ($_!~/^rolesdef_/) {
1.11      www      2736:             my ($area,$role)=split(/=/,$_);
1.587     albertel 2737: 	    $area=~s/\_\w\w$//;
1.678     raeburn  2738:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 2739: 	    if ($role=~/^cr/) { 
1.655     albertel 2740: 		if ($role=~m|^(cr/\w+/\w+/[a-zA-Z0-9]+)_(.*)$|) {
                   2741: 		    ($trole,my $trest)=($role=~m|^(cr/\w+/\w+/[a-zA-Z0-9]+)_(.*)$|);
                   2742: 		    ($tend,$tstart)=split('_',$trest);
                   2743: 		} else {
                   2744: 		    $trole=$role;
                   2745: 		}
1.678     raeburn  2746:             } elsif ($role =~ m|^gr/|) {
                   2747:                 ($trole,$tend,$tstart) = split(/_/,$role);
                   2748:                 ($trole,$group_privs) = split(/\//,$trole);
                   2749:                 $group_privs = &unescape($group_privs);
1.587     albertel 2750: 	    } else {
                   2751: 		($trole,$tend,$tstart)=split(/_/,$role);
                   2752: 	    }
1.743     albertel 2753: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   2754: 					 $username);
                   2755: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  2756:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   2757:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      2758:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 2759: 		my $spec=$trole.'.'.$area;
                   2760: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   2761: 		if ($trole =~ /^cr\//) {
1.567     raeburn  2762:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  2763:                 } elsif ($trole eq 'gr') {
                   2764:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 2765: 		} else {
1.567     raeburn  2766:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 2767: 		}
1.12      www      2768:             }
1.662     raeburn  2769:           }
1.191     harris41 2770:         }
1.743     albertel 2771:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   2772:         $userroles{'user.adv'}    = $adv;
                   2773: 	$userroles{'user.author'} = $author;
1.620     albertel 2774:         $env{'user.adv'}=$adv;
1.11      www      2775:     }
1.743     albertel 2776:     return \%userroles;  
1.11      www      2777: }
                   2778: 
1.567     raeburn  2779: sub set_arearole {
                   2780:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   2781: # log the associated role with the area
                   2782:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 2783:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  2784: }
                   2785: 
                   2786: sub custom_roleprivs {
                   2787:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   2788:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   2789:     my $homsvr=homeserver($rauthor,$rdomain);
                   2790:     if ($hostname{$homsvr} ne '') {
                   2791:         my ($rdummy,$roledef)=
                   2792:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   2793:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   2794:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   2795:             if (defined($syspriv)) {
                   2796:                 $$allroles{'cm./'}.=':'.$syspriv;
                   2797:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   2798:             }
                   2799:             if ($tdomain ne '') {
                   2800:                 if (defined($dompriv)) {
                   2801:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   2802:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   2803:                 }
                   2804:                 if (($trest ne '') && (defined($coursepriv))) {
                   2805:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   2806:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   2807:                 }
                   2808:             }
                   2809:         }
                   2810:     }
                   2811: }
                   2812: 
1.678     raeburn  2813: sub group_roleprivs {
                   2814:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   2815:     my $access = 1;
                   2816:     my $now = time;
                   2817:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   2818:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   2819:     if ($access) {
                   2820:         my ($course,$group) = ($area =~ m|(/\w+/\w+)/([^/]+)$|);
                   2821:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   2822:     }
                   2823: }
1.567     raeburn  2824: 
                   2825: sub standard_roleprivs {
                   2826:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   2827:     if (defined($pr{$trole.':s'})) {
                   2828:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   2829:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   2830:     }
                   2831:     if ($tdomain ne '') {
                   2832:         if (defined($pr{$trole.':d'})) {
                   2833:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   2834:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   2835:         }
                   2836:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   2837:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   2838:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   2839:         }
                   2840:     }
                   2841: }
                   2842: 
                   2843: sub set_userprivs {
1.678     raeburn  2844:     my ($userroles,$allroles,$allgroups) = @_; 
1.567     raeburn  2845:     my $author=0;
                   2846:     my $adv=0;
1.678     raeburn  2847:     my %grouproles = ();
                   2848:     if (keys(%{$allgroups}) > 0) {
                   2849:         foreach my $role (keys %{$allroles}) {
1.681     raeburn  2850:             my ($trole,$area,$sec,$extendedarea);
1.771     raeburn  2851:             if ($role =~ m-^(\w+|cr/\w+/\w+/\w+)\.(/\w+/\w+)(/?\w*)-) {
1.678     raeburn  2852:                 $trole = $1;
                   2853:                 $area = $2;
1.681     raeburn  2854:                 $sec = $3;
                   2855:                 $extendedarea = $area.$sec;
                   2856:                 if (exists($$allgroups{$area})) {
                   2857:                     foreach my $group (keys(%{$$allgroups{$area}})) {
                   2858:                         my $spec = $trole.'.'.$extendedarea;
                   2859:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
                   2860:                                                 $$allgroups{$area}{$group};
1.678     raeburn  2861:                     }
                   2862:                 }
                   2863:             }
                   2864:         }
                   2865:     }
                   2866:     foreach (keys(%grouproles)) {
                   2867:         $$allroles{$_} = $grouproles{$_};
                   2868:     }
1.567     raeburn  2869:     foreach (keys %{$allroles}) {
                   2870:         my %thesepriv=();
                   2871:         if (($_=~/^au/) || ($_=~/^ca/)) { $author=1; }
                   2872:         foreach (split(/:/,$$allroles{$_})) {
                   2873:             if ($_ ne '') {
                   2874:                 my ($privilege,$restrictions)=split(/&/,$_);
                   2875:                 if ($restrictions eq '') {
                   2876:                     $thesepriv{$privilege}='F';
                   2877:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   2878:                     $thesepriv{$privilege}.=$restrictions;
                   2879:                 }
                   2880:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   2881:             }
                   2882:         }
                   2883:         my $thesestr='';
                   2884:         foreach (keys %thesepriv) { $thesestr.=':'.$_.'&'.$thesepriv{$_}; }
1.743     albertel 2885:         $userroles->{'user.priv.'.$_} = $thesestr;
1.567     raeburn  2886:     }
                   2887:     return ($author,$adv);
                   2888: }
                   2889: 
1.12      www      2890: # --------------------------------------------------------------- get interface
                   2891: 
                   2892: sub get {
1.131     albertel 2893:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      2894:    my $items='';
1.191     harris41 2895:    foreach (@$storearr) {
1.12      www      2896:        $items.=escape($_).'&';
1.191     harris41 2897:    }
1.12      www      2898:    $items=~s/\&$//;
1.620     albertel 2899:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2900:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 2901:    my $uhome=&homeserver($uname,$udomain);
                   2902: 
1.133     albertel 2903:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      2904:    my @pairs=split(/\&/,$rep);
1.273     albertel 2905:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   2906:      return @pairs;
                   2907:    }
1.15      www      2908:    my %returnhash=();
1.42      www      2909:    my $i=0;
1.191     harris41 2910:    foreach (@$storearr) {
1.557     albertel 2911:       $returnhash{$_}=&thaw_unescape($pairs[$i]);
1.42      www      2912:       $i++;
1.191     harris41 2913:    }
1.15      www      2914:    return %returnhash;
1.27      www      2915: }
                   2916: 
                   2917: # --------------------------------------------------------------- del interface
                   2918: 
                   2919: sub del {
1.133     albertel 2920:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      2921:    my $items='';
1.191     harris41 2922:    foreach (@$storearr) {
1.27      www      2923:        $items.=escape($_).'&';
1.191     harris41 2924:    }
1.27      www      2925:    $items=~s/\&$//;
1.620     albertel 2926:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2927:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 2928:    my $uhome=&homeserver($uname,$udomain);
                   2929: 
                   2930:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      2931: }
                   2932: 
                   2933: # -------------------------------------------------------------- dump interface
                   2934: 
                   2935: sub dump {
1.755     albertel 2936:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   2937:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2938:     if (!$uname) { $uname=$env{'user.name'}; }
                   2939:     my $uhome=&homeserver($uname,$udomain);
                   2940:     if ($regexp) {
                   2941: 	$regexp=&escape($regexp);
                   2942:     } else {
                   2943: 	$regexp='.';
                   2944:     }
                   2945:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   2946:     my @pairs=split(/\&/,$rep);
                   2947:     my %returnhash=();
                   2948:     foreach my $item (@pairs) {
                   2949: 	my ($key,$value)=split(/=/,$item,2);
                   2950: 	$key = &unescape($key);
                   2951: 	next if ($key =~ /^error: 2 /);
                   2952: 	$returnhash{$key}=&thaw_unescape($value);
                   2953:     }
                   2954:     return %returnhash;
1.407     www      2955: }
                   2956: 
1.717     albertel 2957: # --------------------------------------------------------- dumpstore interface
                   2958: 
                   2959: sub dumpstore {
                   2960:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   2961:    return &dump($namespace,$udomain,$uname,$regexp,$range);
                   2962: }
                   2963: 
1.407     www      2964: # -------------------------------------------------------------- keys interface
                   2965: 
                   2966: sub getkeys {
                   2967:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 2968:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2969:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      2970:    my $uhome=&homeserver($uname,$udomain);
                   2971:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   2972:    my @keyarray=();
                   2973:    foreach (split(/\&/,$rep)) {
                   2974:       push (@keyarray,&unescape($_));
                   2975:    }
                   2976:    return @keyarray;
1.318     matthew  2977: }
                   2978: 
1.319     matthew  2979: # --------------------------------------------------------------- currentdump
                   2980: sub currentdump {
1.328     matthew  2981:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 2982:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   2983:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   2984:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  2985:    my $uhome = &homeserver($sname,$sdom);
                   2986:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  2987:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  2988:    #
1.318     matthew  2989:    my %returnhash=();
1.319     matthew  2990:    #
                   2991:    if ($rep eq "unknown_cmd") { 
                   2992:        # an old lond will not know currentdump
                   2993:        # Do a dump and make it look like a currentdump
1.326     matthew  2994:        my @tmp = &dump($courseid,$sdom,$sname,'.');
1.319     matthew  2995:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   2996:        my %hash = @tmp;
                   2997:        @tmp=();
1.424     matthew  2998:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  2999:    } else {
                   3000:        my @pairs=split(/\&/,$rep);
                   3001:        foreach (@pairs) {
                   3002:            my ($key,$value)=split(/=/,$_);
                   3003:            my ($symb,$param) = split(/:/,$key);
                   3004:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 3005:                                                         &thaw_unescape($value);
1.319     matthew  3006:        }
1.191     harris41 3007:    }
1.12      www      3008:    return %returnhash;
1.424     matthew  3009: }
                   3010: 
                   3011: sub convert_dump_to_currentdump{
                   3012:     my %hash = %{shift()};
                   3013:     my %returnhash;
                   3014:     # Code ripped from lond, essentially.  The only difference
                   3015:     # here is the unescaping done by lonnet::dump().  Conceivably
                   3016:     # we might run in to problems with parameter names =~ /^v\./
                   3017:     while (my ($key,$value) = each(%hash)) {
                   3018:         my ($v,$symb,$param) = split(/:/,$key);
                   3019:         next if ($v eq 'version' || $symb eq 'keys');
                   3020:         next if (exists($returnhash{$symb}) &&
                   3021:                  exists($returnhash{$symb}->{$param}) &&
                   3022:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   3023:         $returnhash{$symb}->{$param}=$value;
                   3024:         $returnhash{$symb}->{'v.'.$param}=$v;
                   3025:     }
                   3026:     #
                   3027:     # Remove all of the keys in the hashes which keep track of
                   3028:     # the version of the parameter.
                   3029:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   3030:         # use a foreach because we are going to delete from the hash.
                   3031:         foreach my $key (keys(%$param_hash)) {
                   3032:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   3033:         }
                   3034:     }
                   3035:     return \%returnhash;
1.12      www      3036: }
                   3037: 
1.627     albertel 3038: # ------------------------------------------------------ critical inc interface
                   3039: 
                   3040: sub cinc {
                   3041:     return &inc(@_,'critical');
                   3042: }
                   3043: 
1.449     matthew  3044: # --------------------------------------------------------------- inc interface
                   3045: 
                   3046: sub inc {
1.627     albertel 3047:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 3048:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3049:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  3050:     my $uhome=&homeserver($uname,$udomain);
                   3051:     my $items='';
                   3052:     if (! ref($store)) {
                   3053:         # got a single value, so use that instead
                   3054:         $items = &escape($store).'=&';
                   3055:     } elsif (ref($store) eq 'SCALAR') {
                   3056:         $items = &escape($$store).'=&';        
                   3057:     } elsif (ref($store) eq 'ARRAY') {
                   3058:         $items = join('=&',map {&escape($_);} @{$store});
                   3059:     } elsif (ref($store) eq 'HASH') {
                   3060:         while (my($key,$value) = each(%{$store})) {
                   3061:             $items.= &escape($key).'='.&escape($value).'&';
                   3062:         }
                   3063:     }
                   3064:     $items=~s/\&$//;
1.627     albertel 3065:     if ($critical) {
                   3066: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3067:     } else {
                   3068: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3069:     }
1.449     matthew  3070: }
                   3071: 
1.12      www      3072: # --------------------------------------------------------------- put interface
                   3073: 
                   3074: sub put {
1.134     albertel 3075:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3076:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3077:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3078:    my $uhome=&homeserver($uname,$udomain);
1.12      www      3079:    my $items='';
1.191     harris41 3080:    foreach (keys %$storehash) {
1.557     albertel 3081:        $items.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
1.191     harris41 3082:    }
1.12      www      3083:    $items=~s/\&$//;
1.134     albertel 3084:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      3085: }
                   3086: 
1.631     albertel 3087: # ------------------------------------------------------------ newput interface
                   3088: 
                   3089: sub newput {
                   3090:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   3091:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3092:    if (!$uname) { $uname=$env{'user.name'}; }
                   3093:    my $uhome=&homeserver($uname,$udomain);
                   3094:    my $items='';
                   3095:    foreach my $key (keys(%$storehash)) {
                   3096:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   3097:    }
                   3098:    $items=~s/\&$//;
                   3099:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   3100: }
                   3101: 
                   3102: # ---------------------------------------------------------  putstore interface
                   3103: 
1.524     raeburn  3104: sub putstore {
1.715     albertel 3105:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 3106:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3107:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  3108:    my $uhome=&homeserver($uname,$udomain);
                   3109:    my $items='';
1.715     albertel 3110:    foreach my $key (keys(%$storehash)) {
                   3111:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  3112:    }
1.715     albertel 3113:    $items=~s/\&$//;
1.716     albertel 3114:    my $esc_symb=&escape($symb);
                   3115:    my $esc_v=&escape($version);
1.715     albertel 3116:    my $reply =
1.716     albertel 3117:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 3118: 	      $uhome);
                   3119:    if ($reply eq 'unknown_cmd') {
1.716     albertel 3120:        # gfall back to way things use to be done
1.715     albertel 3121:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   3122: 			    $uname);
1.524     raeburn  3123:    }
1.715     albertel 3124:    return $reply;
                   3125: }
                   3126: 
                   3127: sub old_putstore {
1.716     albertel 3128:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   3129:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3130:     if (!$uname) { $uname=$env{'user.name'}; }
                   3131:     my $uhome=&homeserver($uname,$udomain);
                   3132:     my %newstorehash;
                   3133:     foreach (keys %$storehash) {
                   3134: 	my $key = $version.':'.&escape($symb).':'.$_;
                   3135: 	$newstorehash{$key} = $storehash->{$_};
                   3136:     }
                   3137:     my $items='';
                   3138:     my %allitems = ();
                   3139:     foreach (keys %newstorehash) {
                   3140: 	if ($_ =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
                   3141: 	    my $key = $1.':keys:'.$2;
                   3142: 	    $allitems{$key} .= $3.':';
                   3143: 	}
                   3144: 	$items.=$_.'='.&freeze_escape($newstorehash{$_}).'&';
                   3145:     }
                   3146:     foreach (keys %allitems) {
                   3147: 	$allitems{$_} =~ s/\:$//;
                   3148: 	$items.= $_.'='.$allitems{$_}.'&';
                   3149:     }
                   3150:     $items=~s/\&$//;
                   3151:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  3152: }
                   3153: 
1.47      www      3154: # ------------------------------------------------------ critical put interface
                   3155: 
                   3156: sub cput {
1.134     albertel 3157:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3158:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3159:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3160:    my $uhome=&homeserver($uname,$udomain);
1.47      www      3161:    my $items='';
1.191     harris41 3162:    foreach (keys %$storehash) {
1.715     albertel 3163:        $items.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
1.191     harris41 3164:    }
1.47      www      3165:    $items=~s/\&$//;
1.134     albertel 3166:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3167: }
                   3168: 
                   3169: # -------------------------------------------------------------- eget interface
                   3170: 
                   3171: sub eget {
1.133     albertel 3172:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3173:    my $items='';
1.191     harris41 3174:    foreach (@$storearr) {
1.12      www      3175:        $items.=escape($_).'&';
1.191     harris41 3176:    }
1.12      www      3177:    $items=~s/\&$//;
1.620     albertel 3178:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3179:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3180:    my $uhome=&homeserver($uname,$udomain);
                   3181:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3182:    my @pairs=split(/\&/,$rep);
                   3183:    my %returnhash=();
1.42      www      3184:    my $i=0;
1.191     harris41 3185:    foreach (@$storearr) {
1.557     albertel 3186:       $returnhash{$_}=&thaw_unescape($pairs[$i]);
1.42      www      3187:       $i++;
1.191     harris41 3188:    }
1.12      www      3189:    return %returnhash;
                   3190: }
                   3191: 
1.667     albertel 3192: # ------------------------------------------------------------ tmpput interface
                   3193: sub tmpput {
                   3194:     my ($storehash,$server)=@_;
                   3195:     my $items='';
                   3196:     foreach (keys(%$storehash)) {
                   3197: 	$items.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
                   3198:     }
                   3199:     $items=~s/\&$//;
                   3200:     return &reply("tmpput:$items",$server);
                   3201: }
                   3202: 
                   3203: # ------------------------------------------------------------ tmpget interface
                   3204: sub tmpget {
1.688     albertel 3205:     my ($token,$server)=@_;
                   3206:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3207:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 3208:     my %returnhash;
                   3209:     foreach my $item (split(/\&/,$rep)) {
                   3210: 	my ($key,$value)=split(/=/,$item);
                   3211: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   3212:     }
                   3213:     return %returnhash;
                   3214: }
                   3215: 
1.688     albertel 3216: # ------------------------------------------------------------ tmpget interface
                   3217: sub tmpdel {
                   3218:     my ($token,$server)=@_;
                   3219:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3220:     return &reply("tmpdel:$token",$server);
                   3221: }
                   3222: 
1.765     albertel 3223: # -------------------------------------------------- portfolio access checking
                   3224: 
                   3225: sub portfolio_access {
1.766     albertel 3226:     my ($requrl) = @_;
1.765     albertel 3227:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   3228:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
                   3229:     if ($result eq 'ok') {
1.766     albertel 3230:        return 'F';
1.765     albertel 3231:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 3232:        return 'A';
1.765     albertel 3233:     }
1.766     albertel 3234:     return '';
1.765     albertel 3235: }
                   3236: 
                   3237: sub get_portfolio_access {
1.767     albertel 3238:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   3239: 
                   3240:     if (!ref($access_hash)) {
                   3241: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   3242: 	my %access_controls = &get_access_controls($current_perms,$group,
                   3243: 						   $file_name);
                   3244: 	$access_hash = $access_controls{$file_name};
                   3245:     }
                   3246: 
1.765     albertel 3247:     my ($public,$guest,@domains,@users,@courses,@groups);
                   3248:     my $now = time;
                   3249:     if (ref($access_hash) eq 'HASH') {
                   3250:         foreach my $key (keys(%{$access_hash})) {
                   3251:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   3252:             if ($start > $now) {
                   3253:                 next;
                   3254:             }
                   3255:             if ($end && $end<$now) {
                   3256:                 next;
                   3257:             }
                   3258:             if ($scope eq 'public') {
                   3259:                 $public = $key;
                   3260:                 last;
                   3261:             } elsif ($scope eq 'guest') {
                   3262:                 $guest = $key;
                   3263:             } elsif ($scope eq 'domains') {
                   3264:                 push(@domains,$key);
                   3265:             } elsif ($scope eq 'users') {
                   3266:                 push(@users,$key);
                   3267:             } elsif ($scope eq 'course') {
                   3268:                 push(@courses,$key);
                   3269:             } elsif ($scope eq 'group') {
                   3270:                 push(@groups,$key);
                   3271:             }
                   3272:         }
                   3273:         if ($public) {
                   3274:             return 'ok';
                   3275:         }
                   3276:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   3277:             if ($guest) {
                   3278:                 return $guest;
                   3279:             }
                   3280:         } else {
                   3281:             if (@domains > 0) {
                   3282:                 foreach my $domkey (@domains) {
                   3283:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   3284:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   3285:                             return 'ok';
                   3286:                         }
                   3287:                     }
                   3288:                 }
                   3289:             }
                   3290:             if (@users > 0) {
                   3291:                 foreach my $userkey (@users) {
                   3292:                     if (exists($access_hash->{$userkey}{'users'}{$env{'user.name'}.':'.$env{'user.domain'}})) {
                   3293:                         return 'ok';
                   3294:                     }
                   3295:                 }
                   3296:             }
                   3297:             my %roleshash;
                   3298:             my @courses_and_groups = @courses;
                   3299:             push(@courses_and_groups,@groups); 
                   3300:             if (@courses_and_groups > 0) {
                   3301:                 my (%allgroups,%allroles); 
                   3302:                 my ($start,$end,$role,$sec,$group);
                   3303:                 foreach my $envkey (%env) {
                   3304:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./([^/]+)/([^/]+)/?([^/]*)$-) {
                   3305:                         my $cid = $2.'_'.$3; 
                   3306:                         if ($1 eq 'gr') {
                   3307:                             $group = $4;
                   3308:                             $allgroups{$cid}{$group} = $env{$envkey};
                   3309:                         } else {
                   3310:                             if ($4 eq '') {
                   3311:                                 $sec = 'none';
                   3312:                             } else {
                   3313:                                 $sec = $4;
                   3314:                             }
                   3315:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   3316:                         }
                   3317:                     } elsif ($envkey =~ m-^user\.role\./cr/(\w+/\w+/\w*)./([^/]+)/([^/]+)/?([^/]*)$-) {
                   3318:                         my $cid = $2.'_'.$3;
                   3319:                         if ($4 eq '') {
                   3320:                             $sec = 'none';
                   3321:                         } else {
                   3322:                             $sec = $4;
                   3323:                         }
                   3324:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   3325:                     }
                   3326:                 }
                   3327:                 if (keys(%allroles) == 0) {
                   3328:                     return;
                   3329:                 }
                   3330:                 foreach my $key (@courses_and_groups) {
                   3331:                     my %content = %{$$access_hash{$key}};
                   3332:                     my $cnum = $content{'number'};
                   3333:                     my $cdom = $content{'domain'};
                   3334:                     my $cid = $cdom.'_'.$cnum;
                   3335:                     if (!exists($allroles{$cid})) {
                   3336:                         next;
                   3337:                     }    
                   3338:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   3339:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   3340:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   3341:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   3342:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   3343:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   3344:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   3345:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   3346:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   3347:                                         if (grep/^all$/,@sections) {
                   3348:                                             return 'ok';
                   3349:                                         } else {
                   3350:                                             if (grep/^$sec$/,@sections) {
                   3351:                                                 return 'ok';
                   3352:                                             }
                   3353:                                         }
                   3354:                                     }
                   3355:                                 }
                   3356:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   3357:                                     if (grep/^none$/,@groups) {
                   3358:                                         return 'ok';
                   3359:                                     }
                   3360:                                 } else {
                   3361:                                     if (grep/^all$/,@groups) {
                   3362:                                         return 'ok';
                   3363:                                     } 
                   3364:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   3365:                                         if (grep/^$group$/,@groups) {
                   3366:                                             return 'ok';
                   3367:                                         }
                   3368:                                     }
                   3369:                                 } 
                   3370:                             }
                   3371:                         }
                   3372:                     }
                   3373:                 }
                   3374:             }
                   3375:             if ($guest) {
                   3376:                 return $guest;
                   3377:             }
                   3378:         }
                   3379:     }
                   3380:     return;
                   3381: }
                   3382: 
                   3383: sub course_group_datechecker {
                   3384:     my ($dates,$now,$status) = @_;
                   3385:     my ($start,$end) = split(/\./,$dates);
                   3386:     if (!$start && !$end) {
                   3387:         return 'ok';
                   3388:     }
                   3389:     if (grep/^active$/,@{$status}) {
                   3390:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   3391:             return 'ok';
                   3392:         }
                   3393:     }
                   3394:     if (grep/^previous$/,@{$status}) {
                   3395:         if ($end > $now ) {
                   3396:             return 'ok';
                   3397:         }
                   3398:     }
                   3399:     if (grep/^future$/,@{$status}) {
                   3400:         if ($start > $now) {
                   3401:             return 'ok';
                   3402:         }
                   3403:     }
                   3404:     return; 
                   3405: }
                   3406: 
                   3407: sub parse_portfolio_url {
                   3408:     my ($url) = @_;
                   3409: 
                   3410:     my ($type,$udom,$unum,$group,$file_name);
                   3411:     
                   3412:     if ($url =~  m-^/*uploaded/([^/]+)/([^/]+)/portfolio(/.+)$-) {
                   3413: 	$type = 1;
                   3414:         $udom = $1;
                   3415:         $unum = $2;
                   3416:         $file_name = $3;
                   3417:     } elsif ($url =~ m-^/*uploaded/([^/]+)/([^/]+)/groups/([^/]+)/portfolio/(.+)$-) {
                   3418: 	$type = 2;
                   3419:         $udom = $1;
                   3420:         $unum = $2;
                   3421:         $group = $3;
                   3422:         $file_name = $3.'/'.$4;
                   3423:     }
                   3424:     if (wantarray) {
                   3425: 	return ($type,$udom,$unum,$file_name,$group);
                   3426:     }
                   3427:     return $type;
                   3428: }
                   3429: 
                   3430: sub is_portfolio_url {
                   3431:     my ($url) = @_;
                   3432:     return scalar(&parse_portfolio_url($url));
                   3433: }
                   3434: 
1.341     www      3435: # ---------------------------------------------- Custom access rule evaluation
                   3436: 
                   3437: sub customaccess {
                   3438:     my ($priv,$uri)=@_;
1.620     albertel 3439:     my ($urole,$urealm)=split(/\./,$env{'request.role'});
1.343     www      3440:     $urealm=~s/^\W//;
                   3441:     my ($udom,$ucrs,$usec)=split(/\//,$urealm);
1.341     www      3442:     my $access=0;
                   3443:     foreach (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.342     www      3444: 	my ($effect,$realm,$role)=split(/\:/,$_);
1.343     www      3445:         if ($role) {
                   3446: 	   if ($role ne $urole) { next; }
                   3447:         }
                   3448:         foreach (split(/\s*\,\s*/,$realm)) {
                   3449:             my ($tdom,$tcrs,$tsec)=split(/\_/,$_);
                   3450:             if ($tdom) {
                   3451: 		if ($tdom ne $udom) { next; }
                   3452:             }
                   3453:             if ($tcrs) {
                   3454: 		if ($tcrs ne $ucrs) { next; }
                   3455:             }
                   3456:             if ($tsec) {
                   3457: 		if ($tsec ne $usec) { next; }
                   3458:             }
                   3459:             $access=($effect eq 'allow');
                   3460:             last;
1.342     www      3461:         }
1.402     bowersj2 3462: 	if ($realm eq '' && $role eq '') {
                   3463:             $access=($effect eq 'allow');
                   3464: 	}
1.341     www      3465:     }
                   3466:     return $access;
                   3467: }
                   3468: 
1.103     harris41 3469: # ------------------------------------------------- Check for a user privilege
1.12      www      3470: 
                   3471: sub allowed {
1.579     albertel 3472:     my ($priv,$uri,$symb)=@_;
1.705     albertel 3473:     my $ver_orguri=$uri;
1.439     www      3474:     $uri=&deversion($uri);
1.152     www      3475:     my $orguri=$uri;
1.52      www      3476:     $uri=&declutter($uri);
1.545     banghart 3477:     
1.620     albertel 3478:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      3479: # Free bre access to adm and meta resources
1.775     albertel 3480:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 3481: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   3482: 	&& ($priv eq 'bre')) {
1.14      www      3483: 	return 'F';
1.159     www      3484:     }
                   3485: 
1.545     banghart 3486: # Free bre access to user's own portfolio contents
1.714     raeburn  3487:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  3488:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  3489: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.545     banghart 3490:         return 'F';
                   3491:     }
                   3492: 
1.762     raeburn  3493: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  3494:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   3495:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   3496:         if (exists($env{'request.course.id'})) {
                   3497:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3498:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3499:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   3500:                 my $courseprivid=$env{'request.course.id'};
                   3501:                 $courseprivid=~s/\_/\//;
                   3502:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   3503:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   3504:                     return $1; 
1.762     raeburn  3505:                 } else {
                   3506:                     if ($env{'request.course.sec'}) {
                   3507:                         $courseprivid.='/'.$env{'request.course.sec'};
                   3508:                     }
                   3509:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   3510:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   3511:                         return $2;
                   3512:                     }
1.714     raeburn  3513:                 }
                   3514:             }
                   3515:         }
                   3516:     }
                   3517: 
1.159     www      3518: # Free bre to public access
                   3519: 
                   3520:     if ($priv eq 'bre') {
1.238     www      3521:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 3522: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      3523:            return 'F'; 
                   3524:         }
1.238     www      3525:         if ($copyright eq 'priv') {
                   3526:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 3527: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      3528: 		return '';
                   3529:             }
                   3530:         }
                   3531:         if ($copyright eq 'domain') {
                   3532:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 3533: 	    unless (($env{'user.domain'} eq $1) ||
                   3534:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      3535: 		return '';
                   3536:             }
1.262     matthew  3537:         }
1.620     albertel 3538:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  3539:             # Library role, so allow browsing of resources in this domain.
                   3540:             return 'F';
1.238     www      3541:         }
1.341     www      3542:         if ($copyright eq 'custom') {
                   3543: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   3544:         }
1.14      www      3545:     }
1.264     matthew  3546:     # Domain coordinator is trying to create a course
1.620     albertel 3547:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  3548:         # uri is the requested domain in this case.
                   3549:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  3550:         # a role of dc for the domain in question.
1.620     albertel 3551:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  3552:     }
1.29      www      3553: 
1.52      www      3554:     my $thisallowed='';
                   3555:     my $statecond=0;
                   3556:     my $courseprivid='';
                   3557: 
                   3558: # Course
                   3559: 
1.620     albertel 3560:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3561:        $thisallowed.=$1;
                   3562:     }
1.29      www      3563: 
1.52      www      3564: # Domain
                   3565: 
1.620     albertel 3566:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 3567:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      3568:        $thisallowed.=$1;
                   3569:     }
1.52      www      3570: 
                   3571: # Course: uri itself is a course
1.66      www      3572:     my $courseuri=$uri;
                   3573:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      3574:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      3575: 
1.620     albertel 3576:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 3577:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      3578:        $thisallowed.=$1;
                   3579:     }
1.29      www      3580: 
1.665     albertel 3581: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 3582: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 3583:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 3584: 	$thisallowed='';
1.671     raeburn  3585:         my ($match)=&is_on_map($uri);
                   3586:         if ($match) {
                   3587:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   3588:                   =~/\Q$priv\E\&([^\:]*)/) {
                   3589:                 $thisallowed.=$1;
                   3590:             }
                   3591:         } else {
1.705     albertel 3592:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  3593:             if ($refuri) {
                   3594:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  3595:                     $thisallowed='F';
1.671     raeburn  3596:                 } else {
                   3597:                     $refuri=&declutter($refuri);
                   3598:                     my ($match) = &is_on_map($refuri);
                   3599:                     if ($match) {
                   3600:                         $thisallowed='F';
                   3601:                     }
1.669     raeburn  3602:                 }
1.671     raeburn  3603:             }
                   3604:         }
1.314     www      3605:     }
1.492     albertel 3606: 
1.766     albertel 3607:     if ($priv eq 'bre'
                   3608: 	&& $thisallowed ne 'F' 
                   3609: 	&& $thisallowed ne '2'
                   3610: 	&& &is_portfolio_url($uri)) {
                   3611: 	$thisallowed = &portfolio_access($uri);
                   3612:     }
                   3613:     
1.52      www      3614: # Full access at system, domain or course-wide level? Exit.
1.29      www      3615: 
                   3616:     if ($thisallowed=~/F/) {
                   3617: 	return 'F';
                   3618:     }
                   3619: 
1.52      www      3620: # If this is generating or modifying users, exit with special codes
1.29      www      3621: 
1.643     www      3622:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   3623: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 3624: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      3625: # no author name given, so this just checks on the general right to make a co-author in this domain
                   3626: 	    unless ($auname) { return $thisallowed; }
                   3627: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 3628: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   3629: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   3630: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   3631: 	}
1.52      www      3632: 	return $thisallowed;
                   3633:     }
                   3634: #
1.103     harris41 3635: # Gathered so far: system, domain and course wide privileges
1.52      www      3636: #
                   3637: # Course: See if uri or referer is an individual resource that is part of 
                   3638: # the course
                   3639: 
1.620     albertel 3640:     if ($env{'request.course.id'}) {
1.232     www      3641: 
1.620     albertel 3642:        $courseprivid=$env{'request.course.id'};
                   3643:        if ($env{'request.course.sec'}) {
                   3644:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      3645:        }
                   3646:        $courseprivid=~s/\_/\//;
                   3647:        my $checkreferer=1;
1.232     www      3648:        my ($match,$cond)=&is_on_map($uri);
                   3649:        if ($match) {
                   3650:            $statecond=$cond;
1.620     albertel 3651:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 3652:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3653:                $thisallowed.=$1;
                   3654:                $checkreferer=0;
                   3655:            }
1.29      www      3656:        }
1.83      www      3657:        
1.148     www      3658:        if ($checkreferer) {
1.620     albertel 3659: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      3660:             unless ($refuri) {
1.620     albertel 3661:                 foreach (keys %env) {
1.148     www      3662: 		    if ($_=~/^httpref\..*\*/) {
                   3663: 			my $pattern=$_;
1.156     www      3664:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      3665:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   3666:                         $pattern=~s/\//\\\//g;
1.152     www      3667:                         if ($orguri=~/$pattern/) {
1.620     albertel 3668: 			    $refuri=$env{$_};
1.148     www      3669:                         }
                   3670:                     }
1.191     harris41 3671:                 }
1.148     www      3672:             }
1.232     www      3673: 
1.148     www      3674:          if ($refuri) { 
1.152     www      3675: 	  $refuri=&declutter($refuri);
1.232     www      3676:           my ($match,$cond)=&is_on_map($refuri);
                   3677:             if ($match) {
                   3678:               my $refstatecond=$cond;
1.620     albertel 3679:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 3680:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3681:                   $thisallowed.=$1;
1.53      www      3682:                   $uri=$refuri;
                   3683:                   $statecond=$refstatecond;
1.52      www      3684:               }
                   3685:           }
1.148     www      3686:         }
1.29      www      3687:        }
1.52      www      3688:    }
1.29      www      3689: 
1.52      www      3690: #
1.103     harris41 3691: # Gathered now: all privileges that could apply, and condition number
1.52      www      3692: # 
                   3693: #
                   3694: # Full or no access?
                   3695: #
1.29      www      3696: 
1.52      www      3697:     if ($thisallowed=~/F/) {
                   3698: 	return 'F';
                   3699:     }
1.29      www      3700: 
1.52      www      3701:     unless ($thisallowed) {
                   3702:         return '';
                   3703:     }
1.29      www      3704: 
1.52      www      3705: # Restrictions exist, deal with them
                   3706: #
                   3707: #   C:according to course preferences
                   3708: #   R:according to resource settings
                   3709: #   L:unless locked
                   3710: #   X:according to user session state
                   3711: #
                   3712: 
                   3713: # Possibly locked functionality, check all courses
1.54      www      3714: # Locks might take effect only after 10 minutes cache expiration for other
                   3715: # courses, and 2 minutes for current course
1.52      www      3716: 
                   3717:     my $envkey;
                   3718:     if ($thisallowed=~/L/) {
1.620     albertel 3719:         foreach $envkey (keys %env) {
1.54      www      3720:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   3721:                my $courseid=$2;
                   3722:                my $roleid=$1.'.'.$2;
1.92      www      3723:                $courseid=~s/^\///;
1.54      www      3724:                my $expiretime=600;
1.620     albertel 3725:                if ($env{'request.role'} eq $roleid) {
1.54      www      3726: 		  $expiretime=120;
                   3727:                }
                   3728: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   3729:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 3730:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 3731: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      3732:                }
1.620     albertel 3733:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   3734:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   3735: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   3736:                        &log($env{'user.domain'},$env{'user.name'},
                   3737:                             $env{'user.home'},
1.57      www      3738:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      3739:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 3740:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      3741: 		       return '';
                   3742:                    }
                   3743:                }
1.620     albertel 3744:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   3745:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   3746: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   3747:                        &log($env{'user.domain'},$env{'user.name'},
                   3748:                             $env{'user.home'},
1.57      www      3749:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      3750:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 3751:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      3752: 		       return '';
                   3753:                    }
                   3754:                }
                   3755: 	   }
1.29      www      3756:        }
1.52      www      3757:     }
                   3758:    
                   3759: #
                   3760: # Rest of the restrictions depend on selected course
                   3761: #
                   3762: 
1.620     albertel 3763:     unless ($env{'request.course.id'}) {
1.766     albertel 3764: 	if ($thisallowed eq 'A') {
                   3765: 	    return 'A';
                   3766: 	} else {
                   3767: 	    return '1';
                   3768: 	}
1.52      www      3769:     }
1.29      www      3770: 
1.52      www      3771: #
                   3772: # Now user is definitely in a course
                   3773: #
1.53      www      3774: 
                   3775: 
                   3776: # Course preferences
                   3777: 
                   3778:    if ($thisallowed=~/C/) {
1.620     albertel 3779:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   3780:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   3781:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 3782: 	   =~/\Q$rolecode\E/) {
1.689     albertel 3783: 	   if ($priv ne 'pch') { 
                   3784: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   3785: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   3786: 			$env{'request.course.id'});
                   3787: 	   }
1.237     www      3788:            return '';
                   3789:        }
                   3790: 
1.620     albertel 3791:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 3792: 	   =~/\Q$unamedom\E/) {
1.689     albertel 3793: 	   if ($priv ne 'pch') { 
                   3794: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   3795: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   3796: 			$env{'request.course.id'});
                   3797: 	   }
1.54      www      3798:            return '';
                   3799:        }
1.53      www      3800:    }
                   3801: 
                   3802: # Resource preferences
                   3803: 
                   3804:    if ($thisallowed=~/R/) {
1.620     albertel 3805:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 3806:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689     albertel 3807: 	   if ($priv ne 'pch') { 
                   3808: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   3809: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   3810: 	   }
                   3811: 	   return '';
1.54      www      3812:        }
1.53      www      3813:    }
1.30      www      3814: 
1.246     www      3815: # Restricted by state or randomout?
1.30      www      3816: 
1.52      www      3817:    if ($thisallowed=~/X/) {
1.620     albertel 3818:       if ($env{'acc.randomout'}) {
1.579     albertel 3819: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 3820:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      3821:             return ''; 
                   3822:          }
1.247     www      3823:       }
                   3824:       if (&condval($statecond)) {
1.52      www      3825: 	 return '2';
                   3826:       } else {
                   3827:          return '';
                   3828:       }
                   3829:    }
1.30      www      3830: 
1.766     albertel 3831:     if ($thisallowed eq 'A') {
                   3832: 	return 'A';
                   3833:     }
1.52      www      3834:    return 'F';
1.232     www      3835: }
                   3836: 
1.710     albertel 3837: sub split_uri_for_cond {
                   3838:     my $uri=&deversion(&declutter(shift));
                   3839:     my @uriparts=split(/\//,$uri);
                   3840:     my $filename=pop(@uriparts);
                   3841:     my $pathname=join('/',@uriparts);
                   3842:     return ($pathname,$filename);
                   3843: }
1.232     www      3844: # --------------------------------------------------- Is a resource on the map?
                   3845: 
                   3846: sub is_on_map {
1.710     albertel 3847:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 3848:     #Trying to find the conditional for the file
1.620     albertel 3849:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 3850: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      3851:     if ($match) {
1.289     bowersj2 3852: 	return (1,$1);
                   3853:     } else {
1.434     www      3854: 	return (0,0);
1.289     bowersj2 3855:     }
1.12      www      3856: }
                   3857: 
1.427     www      3858: # --------------------------------------------------------- Get symb from alias
                   3859: 
                   3860: sub get_symb_from_alias {
                   3861:     my $symb=shift;
                   3862:     my ($map,$resid,$url)=&decode_symb($symb);
                   3863: # Already is a symb
                   3864:     if ($url) { return $symb; }
                   3865: # Must be an alias
                   3866:     my $aliassymb='';
                   3867:     my %bighash;
1.620     albertel 3868:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      3869:                             &GDBM_READER(),0640)) {
                   3870:         my $rid=$bighash{'mapalias_'.$symb};
                   3871: 	if ($rid) {
                   3872: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 3873: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   3874: 				    $resid,$bighash{'src_'.$rid});
1.427     www      3875: 	}
                   3876:         untie %bighash;
                   3877:     }
                   3878:     return $aliassymb;
                   3879: }
                   3880: 
1.12      www      3881: # ----------------------------------------------------------------- Define Role
                   3882: 
                   3883: sub definerole {
                   3884:   if (allowed('mcr','/')) {
                   3885:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.392     www      3886:     foreach (split(':',$sysrole)) {
1.21      www      3887: 	my ($crole,$cqual)=split(/\&/,$_);
1.479     albertel 3888:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   3889:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   3890: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      3891:                return "refused:s:$crole&$cqual"; 
                   3892:             }
                   3893:         }
1.191     harris41 3894:     }
1.392     www      3895:     foreach (split(':',$domrole)) {
1.21      www      3896: 	my ($crole,$cqual)=split(/\&/,$_);
1.479     albertel 3897:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   3898:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   3899: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      3900:                return "refused:d:$crole&$cqual"; 
                   3901:             }
                   3902:         }
1.191     harris41 3903:     }
1.392     www      3904:     foreach (split(':',$courole)) {
1.21      www      3905: 	my ($crole,$cqual)=split(/\&/,$_);
1.479     albertel 3906:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   3907:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   3908: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      3909:                return "refused:c:$crole&$cqual"; 
                   3910:             }
                   3911:         }
1.191     harris41 3912:     }
1.620     albertel 3913:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   3914:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      3915: 	        "rolesdef_$rolename=".
                   3916:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 3917:     return reply($command,$env{'user.home'});
1.12      www      3918:   } else {
                   3919:     return 'refused';
                   3920:   }
1.105     harris41 3921: }
                   3922: 
                   3923: # ---------------- Make a metadata query against the network of library servers
                   3924: 
                   3925: sub metadata_query {
1.244     matthew  3926:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 3927:     my %rhash;
1.244     matthew  3928:     my @server_list = (defined($server_array) ? @$server_array
                   3929:                                               : keys(%libserv) );
                   3930:     for my $server (@server_list) {
1.118     harris41 3931: 	unless ($custom or $customshow) {
                   3932: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   3933: 	    $rhash{$server}=$reply;
                   3934: 	}
                   3935: 	else {
                   3936: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   3937: 			     &escape($custom).':'.&escape($customshow),
                   3938: 			     $server);
                   3939: 	    $rhash{$server}=$reply;
                   3940: 	}
1.112     harris41 3941:     }
1.118     harris41 3942:     return \%rhash;
1.240     www      3943: }
                   3944: 
                   3945: # ----------------------------------------- Send log queries and wait for reply
                   3946: 
                   3947: sub log_query {
                   3948:     my ($uname,$udom,$query,%filters)=@_;
                   3949:     my $uhome=&homeserver($uname,$udom);
                   3950:     if ($uhome eq 'no_host') { return 'error: no_host'; }
                   3951:     my $uhost=$hostname{$uhome};
1.241     www      3952:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys %filters));
1.240     www      3953:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   3954:                        $uhome);
1.479     albertel 3955:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      3956:     return get_query_reply($queryid);
                   3957: }
                   3958: 
1.508     raeburn  3959: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  3960: 
                   3961: sub fetch_enrollment_query {
1.511     raeburn  3962:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  3963:     my $homeserver;
1.547     raeburn  3964:     my $maxtries = 1;
1.508     raeburn  3965:     if ($context eq 'automated') {
                   3966:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  3967:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  3968:     } else {
                   3969:         $homeserver = &homeserver($cnum,$dom);
                   3970:     }
1.506     raeburn  3971:     my $host=$hostname{$homeserver};
                   3972:     my $cmd = '';
                   3973:     foreach (keys %{$affiliatesref}) {
1.508     raeburn  3974:         $cmd .= $_.'='.join(",",@{$$affiliatesref{$_}}).'%%';
1.506     raeburn  3975:     }
                   3976:     $cmd =~ s/%%$//;
                   3977:     $cmd = &escape($cmd);
                   3978:     my $query = 'fetchenrollment';
1.620     albertel 3979:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  3980:     unless ($queryid=~/^\Q$host\E\_/) { 
                   3981:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   3982:         return 'error: '.$queryid;
                   3983:     }
1.506     raeburn  3984:     my $reply = &get_query_reply($queryid);
1.547     raeburn  3985:     my $tries = 1;
                   3986:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   3987:         $reply = &get_query_reply($queryid);
                   3988:         $tries ++;
                   3989:     }
1.526     raeburn  3990:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 3991:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  3992:     } else {
1.515     raeburn  3993:         my @responses = split/:/,$reply;
                   3994:         if ($homeserver eq $perlvar{'lonHostID'}) {
                   3995:             foreach (@responses) {
                   3996:                 my ($key,$value) = split/=/,$_;
                   3997:                 $$replyref{$key} = $value;
                   3998:             }
                   3999:         } else {
1.506     raeburn  4000:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
                   4001:             foreach (@responses) {
                   4002:                 my ($key,$value) = split/=/,$_;
                   4003:                 $$replyref{$key} = $value;
                   4004:                 if ($value > 0) {
                   4005:                     foreach (@{$$affiliatesref{$key}}) {
                   4006:                         my $filename = $dom.'_'.$key.'_'.$_.'_classlist.xml';
                   4007:                         my $destname = $pathname.'/'.$filename;
                   4008:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  4009:                         if ($xml_classlist =~ /^error/) {
                   4010:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   4011:                         } else {
1.506     raeburn  4012:                             if ( open(FILE,">$destname") ) {
                   4013:                                 print FILE &unescape($xml_classlist);
                   4014:                                 close(FILE);
1.526     raeburn  4015:                             } else {
                   4016:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  4017:                             }
                   4018:                         }
                   4019:                     }
                   4020:                 }
                   4021:             }
                   4022:         }
                   4023:         return 'ok';
                   4024:     }
                   4025:     return 'error';
                   4026: }
                   4027: 
1.242     www      4028: sub get_query_reply {
                   4029:     my $queryid=shift;
1.240     www      4030:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   4031:     my $reply='';
                   4032:     for (1..100) {
                   4033: 	sleep 2;
                   4034:         if (-e $replyfile.'.end') {
1.448     albertel 4035: 	    if (open(my $fh,$replyfile)) {
1.240     www      4036:                $reply.=<$fh>;
1.448     albertel 4037:                close($fh);
1.240     www      4038: 	   } else { return 'error: reply_file_error'; }
1.242     www      4039:            return &unescape($reply);
                   4040: 	}
1.240     www      4041:     }
1.242     www      4042:     return 'timeout:'.$queryid;
1.240     www      4043: }
                   4044: 
                   4045: sub courselog_query {
1.241     www      4046: #
                   4047: # possible filters:
                   4048: # url: url or symb
                   4049: # username
                   4050: # domain
                   4051: # action: view, submit, grade
                   4052: # start: timestamp
                   4053: # end: timestamp
                   4054: #
1.240     www      4055:     my (%filters)=@_;
1.620     albertel 4056:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      4057:     if ($filters{'url'}) {
                   4058: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   4059:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   4060:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   4061:     }
1.620     albertel 4062:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4063:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      4064:     return &log_query($cname,$cdom,'courselog',%filters);
                   4065: }
                   4066: 
                   4067: sub userlog_query {
                   4068:     my ($uname,$udom,%filters)=@_;
                   4069:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      4070: }
                   4071: 
1.506     raeburn  4072: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   4073: 
                   4074: sub auto_run {
1.508     raeburn  4075:     my ($cnum,$cdom) = @_;
                   4076:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  4077:     my $response = &reply('autorun:'.$cdom,$homeserver);
1.506     raeburn  4078:     return $response;
                   4079: }
1.776     albertel 4080: 
1.506     raeburn  4081: sub auto_get_sections {
1.508     raeburn  4082:     my ($cnum,$cdom,$inst_coursecode) = @_;
                   4083:     my $homeserver = &homeserver($cnum,$cdom);
1.506     raeburn  4084:     my @secs = ();
1.511     raeburn  4085:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506     raeburn  4086:     unless ($response eq 'refused') {
                   4087:         @secs = split/:/,$response;
                   4088:     }
                   4089:     return @secs;
                   4090: }
1.776     albertel 4091: 
1.506     raeburn  4092: sub auto_new_course {
1.508     raeburn  4093:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
                   4094:     my $homeserver = &homeserver($cnum,$cdom);
1.515     raeburn  4095:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506     raeburn  4096:     return $response;
                   4097: }
1.776     albertel 4098: 
1.506     raeburn  4099: sub auto_validate_courseID {
1.508     raeburn  4100:     my ($cnum,$cdom,$inst_course_id) = @_;
                   4101:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  4102:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  4103:     return $response;
                   4104: }
1.776     albertel 4105: 
1.506     raeburn  4106: sub auto_create_password {
1.508     raeburn  4107:     my ($cnum,$cdom,$authparam) = @_;
                   4108:     my $homeserver = &homeserver($cnum,$cdom); 
1.506     raeburn  4109:     my $create_passwd = 0;
                   4110:     my $authchk = '';
1.511     raeburn  4111:     my $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
1.506     raeburn  4112:     if ($response eq 'refused') {
                   4113:         $authchk = 'refused';
                   4114:     } else {
                   4115:         ($authparam,$create_passwd,$authchk) = split/:/,$response;
                   4116:     }
                   4117:     return ($authparam,$create_passwd,$authchk);
                   4118: }
                   4119: 
1.706     raeburn  4120: sub auto_photo_permission {
                   4121:     my ($cnum,$cdom,$students) = @_;
                   4122:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 4123:     my ($outcome,$perm_reqd,$conditions) = 
                   4124: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 4125:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4126: 	return (undef,undef);
                   4127:     }
1.706     raeburn  4128:     return ($outcome,$perm_reqd,$conditions);
                   4129: }
                   4130: 
                   4131: sub auto_checkphotos {
                   4132:     my ($uname,$udom,$pid) = @_;
                   4133:     my $homeserver = &homeserver($uname,$udom);
                   4134:     my ($result,$resulttype);
                   4135:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 4136: 				   &escape($uname).':'.&escape($pid),
                   4137: 				   $homeserver));
1.709     albertel 4138:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4139: 	return (undef,undef);
                   4140:     }
1.706     raeburn  4141:     if ($outcome) {
                   4142:         ($result,$resulttype) = split(/:/,$outcome);
                   4143:     } 
                   4144:     return ($result,$resulttype);
                   4145: }
                   4146: 
                   4147: sub auto_photochoice {
                   4148:     my ($cnum,$cdom) = @_;
                   4149:     my $homeserver = &homeserver($cnum,$cdom);
                   4150:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 4151: 						       &escape($cdom),
                   4152: 						       $homeserver)));
1.709     albertel 4153:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4154: 	return (undef,undef);
                   4155:     }
1.706     raeburn  4156:     return ($update,$comment);
                   4157: }
                   4158: 
                   4159: sub auto_photoupdate {
                   4160:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   4161:     my $homeserver = &homeserver($cnum,$dom);
                   4162:     my $host=$hostname{$homeserver};
                   4163:     my $cmd = '';
                   4164:     my $maxtries = 1;
                   4165:     foreach (keys %{$affiliatesref}) {
                   4166:         $cmd .= $_.'='.join(",",@{$$affiliatesref{$_}}).'%%';
                   4167:     }
                   4168:     $cmd =~ s/%%$//;
                   4169:     $cmd = &escape($cmd);
                   4170:     my $query = 'institutionalphotos';
                   4171:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   4172:     unless ($queryid=~/^\Q$host\E\_/) {
                   4173:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   4174:         return 'error: '.$queryid;
                   4175:     }
                   4176:     my $reply = &get_query_reply($queryid);
                   4177:     my $tries = 1;
                   4178:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   4179:         $reply = &get_query_reply($queryid);
                   4180:         $tries ++;
                   4181:     }
                   4182:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   4183:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   4184:     } else {
                   4185:         my @responses = split(/:/,$reply);
                   4186:         my $outcome = shift(@responses); 
                   4187:         foreach my $item (@responses) {
                   4188:             my ($key,$value) = split(/=/,$item);
                   4189:             $$photo{$key} = $value;
                   4190:         }
                   4191:         return $outcome;
                   4192:     }
                   4193:     return 'error';
                   4194: }
                   4195: 
1.521     raeburn  4196: sub auto_instcode_format {
                   4197:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,$cat_order) = @_;
                   4198:     my $courses = '';
1.772     raeburn  4199:     my @homeservers;
1.521     raeburn  4200:     if ($caller eq 'global') {
1.584     raeburn  4201:         foreach my $tryserver (keys %libserv) {
                   4202:             if ($hostdom{$tryserver} eq $codedom) {
1.772     raeburn  4203:                 if (!grep/^\Q$tryserver\E$/,@homeservers) {
                   4204:                     push(@homeservers,$tryserver);
                   4205:                 }
1.584     raeburn  4206:             }
                   4207:         }
1.521     raeburn  4208:     } else {
1.772     raeburn  4209:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  4210:     }
                   4211:     foreach (keys %{$instcodes}) {
                   4212:         $courses .= &escape($_).'='.&escape($$instcodes{$_}).'&';
                   4213:     }
                   4214:     chop($courses);
1.772     raeburn  4215:     my $ok_response = 0;
                   4216:     my $response;
                   4217:     while (@homeservers > 0 && $ok_response == 0) {
                   4218:         my $server = shift(@homeservers); 
                   4219:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   4220:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   4221:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
                   4222:                                                             split/:/,$response;
                   4223:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   4224:             push(@{$codetitles},&str2array($codetitles_str));
                   4225:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   4226:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   4227:             $ok_response = 1;
                   4228:         }
                   4229:     }
                   4230:     if ($ok_response) {
1.521     raeburn  4231:         return 'ok';
1.772     raeburn  4232:     } else {
                   4233:         return $response;
1.521     raeburn  4234:     }
                   4235: }
                   4236: 
1.777     albertel 4237: sub auto_validate_class_sec {
1.773     raeburn  4238:     my ($cdom,$cnum,$owner,$inst_class) = @_;
                   4239:     my $homeserver = &homeserver($cnum,$cdom);
                   4240:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.774     banghart 4241:                         &escape($owner).':'.$cdom,$homeserver);
1.773     raeburn  4242:     return $response;
                   4243: }
                   4244: 
1.679     raeburn  4245: # ------------------------------------------------------- Course Group routines
                   4246: 
                   4247: sub get_coursegroups {
1.683     raeburn  4248:     my ($cdom,$cnum,$group) = @_;
                   4249:     return(&dump('coursegroups',$cdom,$cnum,$group));
1.679     raeburn  4250: }
                   4251: 
                   4252: sub modify_coursegroup {
                   4253:     my ($cdom,$cnum,$groupsettings) = @_;
                   4254:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   4255: }
                   4256: 
                   4257: sub modify_group_roles {
                   4258:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
                   4259:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   4260:     my $role = 'gr/'.&escape($userprivs);
                   4261:     my ($uname,$udom) = split(/:/,$user);
                   4262:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
1.684     raeburn  4263:     if ($result eq 'ok') {
                   4264:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   4265:     }
1.679     raeburn  4266:     return $result;
                   4267: }
                   4268: 
                   4269: sub modify_coursegroup_membership {
                   4270:     my ($cdom,$cnum,$membership) = @_;
                   4271:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   4272:     return $result;
                   4273: }
                   4274: 
1.682     raeburn  4275: sub get_active_groups {
                   4276:     my ($udom,$uname,$cdom,$cnum) = @_;
                   4277:     my $now = time;
                   4278:     my %groups = ();
                   4279:     foreach my $key (keys(%env)) {
                   4280:         if ($key =~ m-user\.role\.gr\./([^/]+)/([^/]+)/(\w+)$-) {
                   4281:             my ($start,$end) = split(/\./,$env{$key});
                   4282:             if (($end!=0) && ($end<$now)) { next; }
                   4283:             if (($start!=0) && ($start>$now)) { next; }
                   4284:             if ($1 eq $cdom && $2 eq $cnum) {
                   4285:                 $groups{$3} = $env{$key} ;
                   4286:             }
                   4287:         }
                   4288:     }
                   4289:     return %groups;
                   4290: }
                   4291: 
1.683     raeburn  4292: sub get_group_membership {
                   4293:     my ($cdom,$cnum,$group) = @_;
                   4294:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   4295: }
                   4296: 
                   4297: sub get_users_groups {
                   4298:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  4299:     my @usersgroups;
1.683     raeburn  4300:     my $cachetime=1800;
                   4301:     $courseid=~s/\_/\//g;
                   4302:     $courseid=~s/^(\w)/\/$1/;
                   4303: 
                   4304:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  4305:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   4306:     if (defined($cached)) {
1.734     albertel 4307:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  4308:     } else {  
                   4309:         $grouplist = '';
                   4310:         my %roleshash = &dump('roles',$udom,$uname,$courseid);
                   4311:         my ($tmp) = keys(%roleshash);
                   4312:         if ($tmp=~/^error:/) {
                   4313:             &logthis('Error retrieving roles: '.$tmp.' for '.$uname.':'.$udom);
                   4314:         } else {
                   4315:             my $access_end = $env{'course.'.$courseid.
                   4316:                                   '.default_enrollment_end_date'};
                   4317:             my $now = time;
1.734     albertel 4318:             foreach my $key (keys(%roleshash)) {
1.733     raeburn  4319:                 if ($key =~ /^\Q$courseid\E\/(\w+)\_gr$/) {
                   4320:                     my $group = $1;
                   4321:                     if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   4322:                         my $start = $2;
                   4323:                         my $end = $1;
                   4324:                         if ($start == -1) { next; } # deleted from group
                   4325:                         if (($start!=0) && ($start>$now)) { next; }
                   4326:                         if (($end!=0) && ($end<$now)) {
                   4327:                             if ($access_end && $access_end < $now) {
                   4328:                                 if ($access_end - $end < 86400) {
                   4329:                                     push(@usersgroups,$group);
                   4330:                                 }
                   4331:                             }
                   4332:                             next;
                   4333:                         }
                   4334:                         push(@usersgroups,$group);
                   4335:                     }
1.683     raeburn  4336:                 }
                   4337:             }
1.733     raeburn  4338:             @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   4339:             $grouplist = join(':',@usersgroups);
                   4340:             &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  4341:         }
                   4342:     }
1.733     raeburn  4343:     return @usersgroups;
1.683     raeburn  4344: }
                   4345: 
                   4346: sub devalidate_getgroups_cache {
                   4347:     my ($udom,$uname,$cdom,$cnum)=@_;
                   4348:     my $courseid = $cdom.'_'.$cnum;
                   4349:     $courseid=~s/\_/\//g;
                   4350:     $courseid=~s/^(\w)/\/$1/;
                   4351:     my $hashid="$udom:$uname:$courseid";
                   4352:     &devalidate_cache_new('getgroups',$hashid);
                   4353: }
                   4354: 
1.12      www      4355: # ------------------------------------------------------------------ Plain Text
                   4356: 
                   4357: sub plaintext {
1.742     raeburn  4358:     my ($short,$type,$cid) = @_;
1.758     albertel 4359:     if ($short =~ /^cr/) {
                   4360: 	return (split('/',$short))[-1];
                   4361:     }
1.742     raeburn  4362:     if (!defined($cid)) {
                   4363:         $cid = $env{'request.course.id'};
                   4364:     }
                   4365:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
                   4366:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
                   4367:                                           '.plaintext'});
                   4368:     }
                   4369:     my %rolenames = (
                   4370:                       Course => 'std',
                   4371:                       Group => 'alt1',
                   4372:                     );
                   4373:     if (defined($type) && 
                   4374:          defined($rolenames{$type}) && 
                   4375:          defined($prp{$short}{$rolenames{$type}})) {
                   4376:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
                   4377:     } else {
                   4378:         return &Apache::lonlocal::mt($prp{$short}{'std'});
                   4379:     }
1.12      www      4380: }
                   4381: 
                   4382: # ----------------------------------------------------------------- Assign Role
                   4383: 
                   4384: sub assignrole {
1.357     www      4385:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
1.21      www      4386:     my $mrole;
                   4387:     if ($role =~ /^cr\//) {
1.393     www      4388:         my $cwosec=$url;
                   4389:         $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
                   4390: 	unless (&allowed('ccr',$cwosec)) {
1.104     www      4391:            &logthis('Refused custom assignrole: '.
                   4392:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 4393: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      4394:            return 'refused'; 
                   4395:         }
1.21      www      4396:         $mrole='cr';
1.678     raeburn  4397:     } elsif ($role =~ /^gr\//) {
                   4398:         my $cwogrp=$url;
                   4399:         $cwogrp=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
                   4400:         unless (&allowed('mdg',$cwogrp)) {
                   4401:             &logthis('Refused group assignrole: '.
                   4402:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   4403:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   4404:             return 'refused';
                   4405:         }
                   4406:         $mrole='gr';
1.21      www      4407:     } else {
1.82      www      4408:         my $cwosec=$url;
1.83      www      4409:         $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
1.373     www      4410:         unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) { 
1.104     www      4411:            &logthis('Refused assignrole: '.
                   4412:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 4413: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      4414:            return 'refused'; 
                   4415:         }
1.21      www      4416:         $mrole=$role;
                   4417:     }
1.620     albertel 4418:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      4419:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      4420:     if ($end) { $command.='_'.$end; }
1.21      www      4421:     if ($start) {
                   4422: 	if ($end) { 
1.81      www      4423:            $command.='_'.$start; 
1.21      www      4424:         } else {
1.81      www      4425:            $command.='_0_'.$start;
1.21      www      4426:         }
                   4427:     }
1.739     raeburn  4428:     my $origstart = $start;
                   4429:     my $origend = $end;
1.357     www      4430: # actually delete
                   4431:     if ($deleteflag) {
1.373     www      4432: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      4433: # modify command to delete the role
1.620     albertel 4434:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      4435:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 4436: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      4437: # set start and finish to negative values for userrolelog
                   4438:            $start=-1;
                   4439:            $end=-1;
                   4440:         }
                   4441:     }
                   4442: # send command
1.349     www      4443:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      4444: # log new user role if status is ok
1.349     www      4445:     if ($answer eq 'ok') {
1.663     raeburn  4446: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  4447: # for course roles, perform group memberships changes triggered by role change.
                   4448:         unless ($role =~ /^gr/) {
                   4449:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   4450:                                              $origstart);
                   4451:         }
1.349     www      4452:     }
                   4453:     return $answer;
1.169     harris41 4454: }
                   4455: 
                   4456: # -------------------------------------------------- Modify user authentication
1.197     www      4457: # Overrides without validation
                   4458: 
1.169     harris41 4459: sub modifyuserauth {
                   4460:     my ($udom,$uname,$umode,$upass)=@_;
                   4461:     my $uhome=&homeserver($uname,$udom);
1.197     www      4462:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   4463:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 4464:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   4465:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 4466:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   4467: 		     &escape($upass),$uhome);
1.620     albertel 4468:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      4469:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   4470:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   4471:     &log($udom,,$uname,$uhome,
1.620     albertel 4472:         'Authentication changed by '.$env{'user.domain'}.', '.
                   4473:                                      $env{'user.name'}.', '.$umode.
1.197     www      4474:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 4475:     unless ($reply eq 'ok') {
1.197     www      4476:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 4477: 	return 'error: '.$reply;
                   4478:     }   
1.170     harris41 4479:     return 'ok';
1.80      www      4480: }
                   4481: 
1.81      www      4482: # --------------------------------------------------------------- Modify a user
1.80      www      4483: 
1.81      www      4484: sub modifyuser {
1.206     matthew  4485:     my ($udom,    $uname, $uid,
                   4486:         $umode,   $upass, $first,
                   4487:         $middle,  $last,  $gene,
1.387     www      4488:         $forceid, $desiredhome, $email)=@_;
1.198     www      4489:     $udom=~s/\W//g;
                   4490:     $uname=~s/\W//g;
1.81      www      4491:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      4492:              $umode.', '.$first.', '.$middle.', '.
1.206     matthew  4493: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
                   4494:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   4495:                                      ' desiredhome not specified'). 
1.620     albertel 4496:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   4497:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 4498:     my $uhome=&homeserver($uname,$udom,'true');
1.80      www      4499: # ----------------------------------------------------------------- Create User
1.406     albertel 4500:     if (($uhome eq 'no_host') && 
                   4501: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      4502:         my $unhome='';
1.209     matthew  4503:         if (defined($desiredhome) && $hostdom{$desiredhome} eq $udom) { 
                   4504:             $unhome = $desiredhome;
1.620     albertel 4505: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   4506: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  4507:         } else { # load balancing routine for determining $unhome
1.80      www      4508:             my $tryserver;
1.81      www      4509:             my $loadm=10000000;
1.80      www      4510:             foreach $tryserver (keys %libserv) {
                   4511: 	       if ($hostdom{$tryserver} eq $udom) {
                   4512:                   my $answer=reply('load',$tryserver);
                   4513:                   if (($answer=~/\d+/) && ($answer<$loadm)) {
                   4514: 		      $loadm=$answer;
                   4515:                       $unhome=$tryserver;
                   4516:                   }
                   4517: 	       }
                   4518: 	    }
                   4519:         }
                   4520:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  4521: 	    return 'error: unable to find a home server for '.$uname.
                   4522:                    ' in domain '.$udom;
1.80      www      4523:         }
                   4524:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   4525:                          &escape($upass),$unhome);
                   4526: 	unless ($reply eq 'ok') {
                   4527:             return 'error: '.$reply;
                   4528:         }   
1.230     stredwic 4529:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      4530:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  4531: 	    return 'error: unable verify users home machine.';
1.80      www      4532:         }
1.209     matthew  4533:     }   # End of creation of new user
1.80      www      4534: # ---------------------------------------------------------------------- Add ID
                   4535:     if ($uid) {
                   4536:        $uid=~tr/A-Z/a-z/;
                   4537:        my %uidhash=&idrget($udom,$uname);
1.196     www      4538:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   4539:          && (!$forceid)) {
1.80      www      4540: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  4541: 	      return 'error: user id "'.$uid.'" does not match '.
                   4542:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      4543:           }
                   4544:        } else {
                   4545: 	  &idput($udom,($uname => $uid));
                   4546:        }
                   4547:     }
                   4548: # -------------------------------------------------------------- Add names, etc
1.313     matthew  4549:     my @tmp=&get('environment',
1.134     albertel 4550: 		   ['firstname','middlename','lastname','generation'],
                   4551: 		   $udom,$uname);
1.313     matthew  4552:     my %names;
                   4553:     if ($tmp[0] =~ m/^error:.*/) { 
                   4554:         %names=(); 
                   4555:     } else {
                   4556:         %names = @tmp;
                   4557:     }
1.388     www      4558: #
                   4559: # Make sure to not trash student environment if instructor does not bother
                   4560: # to supply name and email information
                   4561: #
                   4562:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  4563:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      4564:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  4565:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      4566:     if ($email) {
                   4567:        $email=~s/[^\w\@\.\-\,]//gs;
                   4568:        if ($email=~/\@/) { $names{'notification'} = $email;
                   4569: 			   $names{'critnotification'} = $email;
                   4570: 			   $names{'permanentemail'} = $email; }
                   4571:     }
1.134     albertel 4572:     my $reply = &put('environment', \%names, $udom,$uname);
                   4573:     if ($reply ne 'ok') { return 'error: '.$reply; }
1.680     www      4574:     &devalidate_cache_new('namescache',$uname.':'.$udom);
1.81      www      4575:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      4576:              $umode.', '.$first.', '.$middle.', '.
                   4577: 	     $last.', '.$gene.' by '.
1.620     albertel 4578:              $env{'user.name'}.' at '.$env{'user.domain'});
1.134     albertel 4579:     return 'ok';
1.80      www      4580: }
                   4581: 
1.81      www      4582: # -------------------------------------------------------------- Modify student
1.80      www      4583: 
1.81      www      4584: sub modifystudent {
                   4585:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.515     raeburn  4586:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
1.455     albertel 4587:     if (!$cid) {
1.620     albertel 4588: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 4589: 	    return 'not_in_class';
                   4590: 	}
1.80      www      4591:     }
                   4592: # --------------------------------------------------------------- Make the user
1.81      www      4593:     my $reply=&modifyuser
1.209     matthew  4594: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387     www      4595:          $desiredhome,$email);
1.80      www      4596:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  4597:     # This will cause &modify_student_enrollment to get the uid from the
                   4598:     # students environment
                   4599:     $uid = undef if (!$forceid);
1.455     albertel 4600:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.515     raeburn  4601: 					$gene,$usec,$end,$start,$type,$locktype,$cid);
1.297     matthew  4602:     return $reply;
                   4603: }
                   4604: 
                   4605: sub modify_student_enrollment {
1.515     raeburn  4606:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
1.455     albertel 4607:     my ($cdom,$cnum,$chome);
                   4608:     if (!$cid) {
1.620     albertel 4609: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 4610: 	    return 'not_in_class';
                   4611: 	}
1.620     albertel 4612: 	$cdom=$env{'course.'.$cid.'.domain'};
                   4613: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 4614:     } else {
                   4615: 	($cdom,$cnum)=split(/_/,$cid);
                   4616:     }
1.620     albertel 4617:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 4618:     if (!$chome) {
1.457     raeburn  4619: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  4620:     }
1.455     albertel 4621:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  4622:     # Make sure the user exists
1.81      www      4623:     my $uhome=&homeserver($uname,$udom);
                   4624:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   4625: 	return 'error: no such user';
                   4626:     }
1.297     matthew  4627:     # Get student data if we were not given enough information
                   4628:     if (!defined($first)  || $first  eq '' || 
                   4629:         !defined($last)   || $last   eq '' || 
                   4630:         !defined($uid)    || $uid    eq '' || 
                   4631:         !defined($middle) || $middle eq '' || 
                   4632:         !defined($gene)   || $gene   eq '') {
1.294     matthew  4633:         # They did not supply us with enough data to enroll the student, so
                   4634:         # we need to pick up more information.
1.297     matthew  4635:         my %tmp = &get('environment',
1.294     matthew  4636:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  4637:                        ,$udom,$uname);
                   4638: 
1.455     albertel 4639:         #foreach (keys(%tmp)) {
                   4640:         #    &logthis("key $_ = ".$tmp{$_});
                   4641:         #}
1.294     matthew  4642:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   4643:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   4644:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  4645:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  4646:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   4647:     }
1.556     albertel 4648:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 4649:     my $reply=cput('classlist',
                   4650: 		   {"$uname:$udom" => 
1.515     raeburn  4651: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 4652: 		   $cdom,$cnum);
1.81      www      4653:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   4654: 	return 'error: '.$reply;
1.652     albertel 4655:     } else {
                   4656: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      4657:     }
1.297     matthew  4658:     # Add student role to user
1.83      www      4659:     my $uurl='/'.$cid;
1.81      www      4660:     $uurl=~s/\_/\//g;
                   4661:     if ($usec) {
                   4662: 	$uurl.='/'.$usec;
                   4663:     }
                   4664:     return &assignrole($udom,$uname,$uurl,'st',$end,$start);
1.21      www      4665: }
                   4666: 
1.556     albertel 4667: sub format_name {
                   4668:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   4669:     my $name;
                   4670:     if ($first ne 'lastname') {
                   4671: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   4672:     } else {
                   4673: 	if ($lastname=~/\S/) {
                   4674: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   4675: 	    $name=~s/\s+,/,/;
                   4676: 	} else {
                   4677: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   4678: 	}
                   4679:     }
                   4680:     $name=~s/^\s+//;
                   4681:     $name=~s/\s+$//;
                   4682:     $name=~s/\s+/ /g;
                   4683:     return $name;
                   4684: }
                   4685: 
1.84      www      4686: # ------------------------------------------------- Write to course preferences
                   4687: 
                   4688: sub writecoursepref {
                   4689:     my ($courseid,%prefs)=@_;
                   4690:     $courseid=~s/^\///;
                   4691:     $courseid=~s/\_/\//g;
                   4692:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   4693:     my $chome=homeserver($cnum,$cdomain);
                   4694:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   4695: 	return 'error: no such course';
                   4696:     }
                   4697:     my $cstring='';
1.191     harris41 4698:     foreach (keys %prefs) {
1.84      www      4699: 	$cstring.=escape($_).'='.escape($prefs{$_}).'&';
1.191     harris41 4700:     }
1.84      www      4701:     $cstring=~s/\&$//;
                   4702:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   4703: }
                   4704: 
                   4705: # ---------------------------------------------------------- Make/modify course
                   4706: 
                   4707: sub createcourse {
1.741     raeburn  4708:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
                   4709:         $course_owner,$crstype)=@_;
1.84      www      4710:     $url=&declutter($url);
                   4711:     my $cid='';
1.264     matthew  4712:     unless (&allowed('ccc',$udom)) {
1.84      www      4713:         return 'refused';
                   4714:     }
                   4715: # ------------------------------------------------------------------- Create ID
1.674     www      4716:    my $uname=int(1+rand(9)).
                   4717:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   4718:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
1.84      www      4719:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   4720: # ----------------------------------------------- Make sure that does not exist
1.230     stredwic 4721:    my $uhome=&homeserver($uname,$udom,'true');
1.84      www      4722:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   4723:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   4724:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230     stredwic 4725:        $uhome=&homeserver($uname,$udom,'true');       
1.84      www      4726:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   4727:            return 'error: unable to generate unique course-ID';
                   4728:        } 
                   4729:    }
1.264     matthew  4730: # ------------------------------------------------ Check supplied server name
1.620     albertel 4731:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.264     matthew  4732:     if (! exists($libserv{$course_server})) {
                   4733:         return 'error:bad server name '.$course_server;
                   4734:     }
1.84      www      4735: # ------------------------------------------------------------- Make the course
                   4736:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  4737:                       $course_server);
1.84      www      4738:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230     stredwic 4739:     $uhome=&homeserver($uname,$udom,'true');
1.84      www      4740:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   4741: 	return 'error: no such course';
                   4742:     }
1.271     www      4743: # ----------------------------------------------------------------- Course made
1.516     raeburn  4744: # log existence
                   4745:     &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description).
1.741     raeburn  4746:                  ':'.&escape($inst_code).':'.&escape($course_owner).':'.
                   4747:                   &escape($crstype),$uhome);
1.358     www      4748:     &flushcourselogs();
                   4749: # set toplevel url
1.271     www      4750:     my $topurl=$url;
                   4751:     unless ($nonstandard) {
                   4752: # ------------------------------------------ For standard courses, make top url
                   4753:         my $mapurl=&clutter($url);
1.278     www      4754:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 4755:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      4756: <map>
                   4757: <resource id="1" type="start"></resource>
                   4758: <resource id="2" src="$mapurl"></resource>
                   4759: <resource id="3" type="finish"></resource>
                   4760: <link index="1" from="1" to="2"></link>
                   4761: <link index="2" from="2" to="3"></link>
                   4762: </map>
                   4763: ENDINITMAP
                   4764:         $topurl=&declutter(
1.638     albertel 4765:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      4766:                           );
                   4767:     }
                   4768: # ----------------------------------------------------------- Write preferences
1.84      www      4769:     &writecoursepref($udom.'_'.$uname,
                   4770:                      ('description' => $description,
1.271     www      4771:                       'url'         => $topurl));
1.84      www      4772:     return '/'.$udom.'/'.$uname;
                   4773: }
                   4774: 
1.21      www      4775: # ---------------------------------------------------------- Assign Custom Role
                   4776: 
                   4777: sub assigncustomrole {
1.357     www      4778:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
1.21      www      4779:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.357     www      4780:                        $end,$start,$deleteflag);
1.21      www      4781: }
                   4782: 
                   4783: # ----------------------------------------------------------------- Revoke Role
                   4784: 
                   4785: sub revokerole {
1.357     www      4786:     my ($udom,$uname,$url,$role,$deleteflag)=@_;
1.21      www      4787:     my $now=time;
1.357     www      4788:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
1.21      www      4789: }
                   4790: 
                   4791: # ---------------------------------------------------------- Revoke Custom Role
                   4792: 
                   4793: sub revokecustomrole {
1.357     www      4794:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
1.21      www      4795:     my $now=time;
1.357     www      4796:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
                   4797:            $deleteflag);
1.17      www      4798: }
                   4799: 
1.533     banghart 4800: # ------------------------------------------------------------ Disk usage
1.535     albertel 4801: sub diskusage {
1.533     banghart 4802:     my ($udom,$uname,$directoryRoot)=@_;
                   4803:     $directoryRoot =~ s/\/$//;
1.535     albertel 4804:     my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
1.514     albertel 4805:     return $listing;
1.512     banghart 4806: }
                   4807: 
1.566     banghart 4808: sub is_locked {
                   4809:     my ($file_name, $domain, $user) = @_;
                   4810:     my @check;
                   4811:     my $is_locked;
                   4812:     push @check, $file_name;
1.613     albertel 4813:     my %locked = &get('file_permissions',\@check,
1.620     albertel 4814: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 4815:     my ($tmp)=keys(%locked);
                   4816:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  4817:     
1.566     banghart 4818:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  4819:         $is_locked = 'false';
                   4820:         foreach my $entry (@{$locked{$file_name}}) {
                   4821:            if (ref($entry) eq 'ARRAY') { 
1.746     raeburn  4822:                $is_locked = 'true';
                   4823:                last;
1.745     raeburn  4824:            }
                   4825:        }
1.566     banghart 4826:     } else {
                   4827:         $is_locked = 'false';
                   4828:     }
                   4829: }
                   4830: 
1.759     albertel 4831: sub declutter_portfile {
                   4832:     my ($file) = @_;
                   4833:     &logthis("got $file");
                   4834:     $file =~ s-^(/portfolio/|portfolio/)-/-;
                   4835:     &logthis("ret $file");
                   4836:     return $file;
                   4837: }
                   4838: 
1.559     banghart 4839: # ------------------------------------------------------------- Mark as Read Only
                   4840: 
                   4841: sub mark_as_readonly {
                   4842:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 4843:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 4844:     my ($tmp)=keys(%current_permissions);
                   4845:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 4846:     foreach my $file (@{$files}) {
1.759     albertel 4847: 	$file = &declutter_portfile($file);
1.561     banghart 4848:         push(@{$current_permissions{$file}},$what);
1.559     banghart 4849:     }
1.613     albertel 4850:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 4851:     return;
                   4852: }
                   4853: 
1.572     banghart 4854: # ------------------------------------------------------------Save Selected Files
                   4855: 
                   4856: sub save_selected_files {
                   4857:     my ($user, $path, @files) = @_;
                   4858:     my $filename = $user."savedfiles";
1.573     banghart 4859:     my @other_files = &files_not_in_path($user, $path);
1.574     banghart 4860:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 4861:     foreach my $file (@files) {
1.620     albertel 4862:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 4863:     }
                   4864:     foreach my $file (@other_files) {
1.574     banghart 4865:         print (OUT $file."\n");
1.572     banghart 4866:     }
1.574     banghart 4867:     close (OUT);
1.572     banghart 4868:     return 'ok';
                   4869: }
                   4870: 
1.574     banghart 4871: sub clear_selected_files {
                   4872:     my ($user) = @_;
                   4873:     my $filename = $user."savedfiles";
                   4874:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   4875:     print (OUT undef);
                   4876:     close (OUT);
                   4877:     return ("ok");    
                   4878: }
                   4879: 
1.572     banghart 4880: sub files_in_path {
                   4881:     my ($user, $path) = @_;
                   4882:     my $filename = $user."savedfiles";
                   4883:     my %return_files;
1.574     banghart 4884:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 4885:     while (my $line_in = <IN>) {
1.574     banghart 4886:         chomp ($line_in);
                   4887:         my @paths_and_file = split (m!/!, $line_in);
                   4888:         my $file_part = pop (@paths_and_file);
                   4889:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 4890:         $path_part.='/';
                   4891:         my $path_and_file = $path_part.$file_part;
                   4892:         if ($path_part eq $path) {
                   4893:             $return_files{$file_part}= 'selected';
                   4894:         }
                   4895:     }
1.574     banghart 4896:     close (IN);
                   4897:     return (\%return_files);
1.572     banghart 4898: }
                   4899: 
                   4900: # called in portfolio select mode, to show files selected NOT in current directory
                   4901: sub files_not_in_path {
                   4902:     my ($user, $path) = @_;
                   4903:     my $filename = $user."savedfiles";
                   4904:     my @return_files;
                   4905:     my $path_part;
1.574     banghart 4906:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.572     banghart 4907:     while (<IN>) {
                   4908:         #ok, I know it's clunky, but I want it to work
                   4909:         my @paths_and_file = split m!/!, $_;
1.574     banghart 4910:         my $file_part = pop (@paths_and_file);
                   4911:         chomp ($file_part);
                   4912:         my $path_part = join ('/', @paths_and_file);
1.572     banghart 4913:         $path_part .= '/';
                   4914:         my $path_and_file = $path_part.$file_part;
                   4915:         if ($path_part ne $path) {
1.574     banghart 4916:             push (@return_files, ($path_and_file));
1.572     banghart 4917:         }
                   4918:     }
1.574     banghart 4919:     close (OUT);
                   4920:     return (@return_files);
1.572     banghart 4921: }
                   4922: 
1.745     raeburn  4923: #----------------------------------------------Get portfolio file permissions
1.629     banghart 4924: 
1.745     raeburn  4925: sub get_portfile_permissions {
                   4926:     my ($domain,$user) = @_;
1.613     albertel 4927:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 4928:     my ($tmp)=keys(%current_permissions);
                   4929:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  4930:     return \%current_permissions;
                   4931: }
                   4932: 
                   4933: #---------------------------------------------Get portfolio file access controls
                   4934: 
1.749     raeburn  4935: sub get_access_controls {
1.745     raeburn  4936:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 4937:     my %access;
                   4938:     my $real_file = $file;
                   4939:     $file =~ s/\.meta$//;
1.745     raeburn  4940:     if (defined($file)) {
1.749     raeburn  4941:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   4942:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 4943:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  4944:             }
                   4945:         }
1.745     raeburn  4946:     } else {
1.749     raeburn  4947:         foreach my $key (keys(%{$current_permissions})) {
                   4948:             if ($key =~ /\0accesscontrol$/) {
                   4949:                 if (defined($group)) {
                   4950:                     if ($key !~ m-^\Q$group\E/-) {
                   4951:                         next;
                   4952:                     }
                   4953:                 }
                   4954:                 my ($fullpath) = split(/\0/,$key);
                   4955:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   4956:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   4957:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   4958:                     }
                   4959:                 }
                   4960:             }
                   4961:         }
                   4962:     }
                   4963:     return %access;
                   4964: }
                   4965: 
                   4966: sub modify_access_controls {
                   4967:     my ($file_name,$changes,$domain,$user)=@_;
                   4968:     my ($outcome,$deloutcome);
                   4969:     my %store_permissions;
                   4970:     my %new_values;
                   4971:     my %new_control;
                   4972:     my %translation;
                   4973:     my @deletions = ();
                   4974:     my $now = time;
                   4975:     if (exists($$changes{'activate'})) {
                   4976:         if (ref($$changes{'activate'}) eq 'HASH') {
                   4977:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   4978:             my $numnew = scalar(@newitems);
                   4979:             for (my $i=0; $i<$numnew; $i++) {
                   4980:                 my $newkey = $newitems[$i];
                   4981:                 my $newid = &Apache::loncommon::get_cgi_id();
                   4982:                 $newkey =~ s/^(\d+)/$newid/;
                   4983:                 $translation{$1} = $newid;
                   4984:                 $new_values{$file_name."\0".$newkey} = 
                   4985:                                           $$changes{'activate'}{$newitems[$i]};
                   4986:                 $new_control{$newkey} = $now;
                   4987:             }
                   4988:         }
                   4989:     }
                   4990:     my %todelete;
                   4991:     my %changed_items;
                   4992:     foreach my $action ('delete','update') {
                   4993:         if (exists($$changes{$action})) {
                   4994:             if (ref($$changes{$action}) eq 'HASH') {
                   4995:                 foreach my $key (keys(%{$$changes{$action}})) {
                   4996:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   4997:                     if ($action eq 'delete') { 
                   4998:                         $todelete{$itemnum} = 1;
                   4999:                     } else {
                   5000:                         $changed_items{$itemnum} = $key;
                   5001:                     }
                   5002:                 }
1.745     raeburn  5003:             }
                   5004:         }
1.749     raeburn  5005:     }
                   5006:     # get lock on access controls for file.
                   5007:     my $lockhash = {
                   5008:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   5009:                                                        ':'.$env{'user.domain'},
                   5010:                    }; 
                   5011:     my $tries = 0;
                   5012:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   5013:    
                   5014:     while (($gotlock ne 'ok') && $tries <3) {
                   5015:         $tries ++;
                   5016:         sleep 1;
                   5017:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   5018:     }
                   5019:     if ($gotlock eq 'ok') {
                   5020:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   5021:         my ($tmp)=keys(%curr_permissions);
                   5022:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   5023:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   5024:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   5025:             if (ref($curr_controls) eq 'HASH') {
                   5026:                 foreach my $control_item (keys(%{$curr_controls})) {
                   5027:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   5028:                     if (defined($todelete{$itemnum})) {
                   5029:                         push(@deletions,$file_name."\0".$control_item);
                   5030:                     } else {
                   5031:                         if (defined($changed_items{$itemnum})) {
                   5032:                             $new_control{$changed_items{$itemnum}} = $now;
                   5033:                             push(@deletions,$file_name."\0".$control_item);
                   5034:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   5035:                         } else {
                   5036:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   5037:                         }
                   5038:                     }
1.745     raeburn  5039:                 }
                   5040:             }
                   5041:         }
1.749     raeburn  5042:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   5043:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   5044:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   5045:         #  remove lock
                   5046:         my @del_lock = ($file_name."\0".'locked_access_records');
                   5047:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
                   5048:     } else {
                   5049:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  5050:     }
1.749     raeburn  5051:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  5052: }
                   5053: 
                   5054: #------------------------------------------------------Get Marked as Read Only
                   5055: 
                   5056: sub get_marked_as_readonly {
                   5057:     my ($domain,$user,$what,$group) = @_;
                   5058:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 5059:     my @readonly_files;
1.629     banghart 5060:     my $cmp1=$what;
                   5061:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  5062:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   5063:         if (defined($group)) {
                   5064:             if ($file_name !~ m-^\Q$group\E/-) {
                   5065:                 next;
                   5066:             }
                   5067:         }
1.561     banghart 5068:         if (ref($value) eq "ARRAY"){
                   5069:             foreach my $stored_what (@{$value}) {
1.629     banghart 5070:                 my $cmp2=$stored_what;
1.759     albertel 5071:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  5072:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  5073:                 }
1.629     banghart 5074:                 if ($cmp1 eq $cmp2) {
1.561     banghart 5075:                     push(@readonly_files, $file_name);
1.745     raeburn  5076:                     last;
1.563     banghart 5077:                 } elsif (!defined($what)) {
                   5078:                     push(@readonly_files, $file_name);
1.745     raeburn  5079:                     last;
1.561     banghart 5080:                 }
                   5081:             }
1.745     raeburn  5082:         }
1.561     banghart 5083:     }
                   5084:     return @readonly_files;
                   5085: }
1.577     banghart 5086: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 5087: 
1.577     banghart 5088: sub get_marked_as_readonly_hash {
1.745     raeburn  5089:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 5090:     my %readonly_files;
1.745     raeburn  5091:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   5092:         if (defined($group)) {
                   5093:             if ($file_name !~ m-^\Q$group\E/-) {
                   5094:                 next;
                   5095:             }
                   5096:         }
1.577     banghart 5097:         if (ref($value) eq "ARRAY"){
                   5098:             foreach my $stored_what (@{$value}) {
1.745     raeburn  5099:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 5100:                     foreach my $lock_descriptor(@{$stored_what}) {
                   5101:                         if ($lock_descriptor eq 'graded') {
                   5102:                             $readonly_files{$file_name} = 'graded';
                   5103:                         } elsif ($lock_descriptor eq 'handback') {
                   5104:                             $readonly_files{$file_name} = 'handback';
                   5105:                         } else {
                   5106:                             if (!exists($readonly_files{$file_name})) {
                   5107:                                 $readonly_files{$file_name} = 'locked';
                   5108:                             }
                   5109:                         }
1.745     raeburn  5110:                     }
1.750     banghart 5111:                 } 
1.577     banghart 5112:             }
                   5113:         } 
                   5114:     }
                   5115:     return %readonly_files;
                   5116: }
1.559     banghart 5117: # ------------------------------------------------------------ Unmark as Read Only
                   5118: 
                   5119: sub unmark_as_readonly {
1.629     banghart 5120:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   5121:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  5122:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 5123:     $file_name = &declutter_portfile($file_name);
1.634     albertel 5124:     my $symb_crs = $what;
                   5125:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  5126:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 5127:     my ($tmp)=keys(%current_permissions);
                   5128:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  5129:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 5130:     foreach my $file (@readonly_files) {
1.759     albertel 5131: 	my $clean_file = &declutter_portfile($file);
                   5132: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 5133: 	my $current_locks = $current_permissions{$file};
1.563     banghart 5134:         my @new_locks;
                   5135:         my @del_keys;
                   5136:         if (ref($current_locks) eq "ARRAY"){
                   5137:             foreach my $locker (@{$current_locks}) {
1.632     albertel 5138:                 my $compare=$locker;
1.749     raeburn  5139:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  5140:                     $compare=join('',@{$locker});
1.746     raeburn  5141:                     if ($compare ne $symb_crs) {
                   5142:                         push(@new_locks, $locker);
                   5143:                     }
1.563     banghart 5144:                 }
                   5145:             }
1.650     albertel 5146:             if (scalar(@new_locks) > 0) {
1.563     banghart 5147:                 $current_permissions{$file} = \@new_locks;
                   5148:             } else {
                   5149:                 push(@del_keys, $file);
1.613     albertel 5150:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 5151:                 delete($current_permissions{$file});
1.563     banghart 5152:             }
                   5153:         }
1.561     banghart 5154:     }
1.613     albertel 5155:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 5156:     return;
                   5157: }
1.512     banghart 5158: 
1.17      www      5159: # ------------------------------------------------------------ Directory lister
                   5160: 
                   5161: sub dirlist {
1.253     stredwic 5162:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
                   5163: 
1.18      www      5164:     $uri=~s/^\///;
                   5165:     $uri=~s/\/$//;
1.253     stredwic 5166:     my ($udom, $uname);
                   5167:     (undef,$udom,$uname)=split(/\//,$uri);
                   5168:     if(defined($userdomain)) {
                   5169:         $udom = $userdomain;
                   5170:     }
                   5171:     if(defined($username)) {
                   5172:         $uname = $username;
                   5173:     }
                   5174: 
                   5175:     my $dirRoot = $perlvar{'lonDocRoot'};
                   5176:     if(defined($alternateDirectoryRoot)) {
                   5177:         $dirRoot = $alternateDirectoryRoot;
                   5178:         $dirRoot =~ s/\/$//;
1.751     banghart 5179:     }
1.253     stredwic 5180: 
                   5181:     if($udom) {
                   5182:         if($uname) {
1.605     matthew  5183:             my $listing=reply('ls2:'.$dirRoot.'/'.$uri,
1.253     stredwic 5184:                               homeserver($uname,$udom));
1.605     matthew  5185:             my @listing_results;
                   5186:             if ($listing eq 'unknown_cmd') {
                   5187:                 $listing=reply('ls:'.$dirRoot.'/'.$uri,
                   5188:                                homeserver($uname,$udom));
                   5189:                 @listing_results = split(/:/,$listing);
                   5190:             } else {
                   5191:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   5192:             }
                   5193:             return @listing_results;
1.253     stredwic 5194:         } elsif(!defined($alternateDirectoryRoot)) {
                   5195:             my $tryserver;
                   5196:             my %allusers=();
                   5197:             foreach $tryserver (keys %libserv) {
                   5198:                 if($hostdom{$tryserver} eq $udom) {
1.605     matthew  5199:                     my $listing=reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
1.253     stredwic 5200:                                       $udom, $tryserver);
1.605     matthew  5201:                     my @listing_results;
                   5202:                     if ($listing eq 'unknown_cmd') {
                   5203:                         $listing=reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   5204:                                        $udom, $tryserver);
                   5205:                         @listing_results = split(/:/,$listing);
                   5206:                     } else {
                   5207:                         @listing_results =
                   5208:                             map { &unescape($_); } split(/:/,$listing);
                   5209:                     }
                   5210:                     if ($listing_results[0] ne 'no_such_dir' && 
                   5211:                         $listing_results[0] ne 'empty'       &&
                   5212:                         $listing_results[0] ne 'con_lost') {
                   5213:                         foreach (@listing_results) {
1.253     stredwic 5214:                             my ($entry,@stat)=split(/&/,$_);
                   5215:                             $allusers{$entry}=1;
                   5216:                         }
                   5217:                     }
1.191     harris41 5218:                 }
1.253     stredwic 5219:             }
                   5220:             my $alluserstr='';
                   5221:             foreach (sort keys %allusers) {
                   5222:                 $alluserstr.=$_.'&user:';
                   5223:             }
                   5224:             $alluserstr=~s/:$//;
                   5225:             return split(/:/,$alluserstr);
                   5226:         } else {
                   5227:             my @emptyResults = ();
                   5228:             push(@emptyResults, 'missing user name');
                   5229:             return split(':',@emptyResults);
                   5230:         }
                   5231:     } elsif(!defined($alternateDirectoryRoot)) {
                   5232:         my $tryserver;
                   5233:         my %alldom=();
                   5234:         foreach $tryserver (keys %libserv) {
                   5235:             $alldom{$hostdom{$tryserver}}=1;
                   5236:         }
                   5237:         my $alldomstr='';
                   5238:         foreach (sort keys %alldom) {
1.397     albertel 5239:             $alldomstr.=$perlvar{'lonDocRoot'}.'/res/'.$_.'/&domain:';
1.253     stredwic 5240:         }
                   5241:         $alldomstr=~s/:$//;
                   5242:         return split(/:/,$alldomstr);       
                   5243:     } else {
                   5244:         my @emptyResults = ();
                   5245:         push(@emptyResults, 'missing domain');
                   5246:         return split(':',@emptyResults);
1.275     stredwic 5247:     }
                   5248: }
                   5249: 
                   5250: # --------------------------------------------- GetFileTimestamp
                   5251: # This function utilizes dirlist and returns the date stamp for
                   5252: # when it was last modified.  It will also return an error of -1
                   5253: # if an error occurs
                   5254: 
1.410     matthew  5255: ##
                   5256: ## FIXME: This subroutine assumes its caller knows something about the
                   5257: ## directory structure of the home server for the student ($root).
                   5258: ## Not a good assumption to make.  Since this is for looking up files
                   5259: ## in user directories, the full path should be constructed by lond, not
                   5260: ## whatever machine we request data from.
                   5261: ##
1.275     stredwic 5262: sub GetFileTimestamp {
                   5263:     my ($studentDomain,$studentName,$filename,$root)=@_;
                   5264:     $studentDomain=~s/\W//g;
                   5265:     $studentName=~s/\W//g;
                   5266:     my $subdir=$studentName.'__';
                   5267:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   5268:     my $proname="$studentDomain/$subdir/$studentName";
                   5269:     $proname .= '/'.$filename;
1.375     matthew  5270:     my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain, 
                   5271:                                               $studentName, $root);
1.275     stredwic 5272:     my @stats = split('&', $fileStat);
                   5273:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  5274:         # @stats contains first the filename, then the stat output
                   5275:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 5276:     } else {
                   5277:         return -1;
1.253     stredwic 5278:     }
1.26      www      5279: }
                   5280: 
1.712     albertel 5281: sub stat_file {
                   5282:     my ($uri) = @_;
1.722     albertel 5283:     $uri = &clutter($uri);
                   5284: 
                   5285:     # we want just the url part without the unneeded accessor url bits
1.723     banghart 5286:     if ($uri =~ m-^/adm/-) {
                   5287: 	$uri=~s-^/adm/wrapper/-/-;
                   5288: 	$uri=~s-^/adm/coursedocs/showdoc/-/-;
1.722     albertel 5289:     }
1.712     albertel 5290:     my ($udom,$uname,$file,$dir);
                   5291:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   5292: 	($udom,$uname,$file) =
                   5293: 	    ($uri =~ m-/(?:uploaded|editupload)/?([^/]*)/?([^/]*)/?(.*)-);
                   5294: 	$file = 'userfiles/'.$file;
1.740     www      5295: 	$dir = &propath($udom,$uname);
1.712     albertel 5296:     }
                   5297:     if ($uri =~ m-^/res/-) {
                   5298: 	($udom,$uname) = 
                   5299: 	    ($uri =~ m-/(?:res)/?([^/]*)/?([^/]*)/-);
                   5300: 	$file = $uri;
                   5301:     }
                   5302: 
                   5303:     if (!$udom || !$uname || !$file) {
                   5304: 	# unable to handle the uri
                   5305: 	return ();
                   5306:     }
                   5307: 
                   5308:     my ($result) = &dirlist($file,$udom,$uname,$dir);
                   5309:     my @stats = split('&', $result);
1.721     banghart 5310:     
1.712     albertel 5311:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   5312: 	shift(@stats); #filename is first
                   5313: 	return @stats;
                   5314:     }
                   5315:     return ();
                   5316: }
                   5317: 
1.26      www      5318: # -------------------------------------------------------- Value of a Condition
                   5319: 
1.713     albertel 5320: # gets the value of a specific preevaluated condition
                   5321: #    stored in the string  $env{user.state.<cid>}
                   5322: # or looks up a condition reference in the bighash and if if hasn't
                   5323: # already been evaluated recurses into docondval to get the value of
                   5324: # the condition, then memoizing it to 
                   5325: #   $env{user.state.<cid>.<condition>}
1.40      www      5326: sub directcondval {
                   5327:     my $number=shift;
1.620     albertel 5328:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 5329: 	&Apache::lonuserstate::evalstate();
                   5330:     }
1.713     albertel 5331:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   5332: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   5333:     } elsif ($number =~ /^_/) {
                   5334: 	my $sub_condition;
                   5335: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   5336: 		&GDBM_READER(),0640)) {
                   5337: 	    $sub_condition=$bighash{'conditions'.$number};
                   5338: 	    untie(%bighash);
                   5339: 	}
                   5340: 	my $value = &docondval($sub_condition);
                   5341: 	&appenv('user.state.'.$env{'request.course.id'}.".$number" => $value);
                   5342: 	return $value;
                   5343:     }
1.620     albertel 5344:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   5345:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      5346:     } else {
                   5347:        return 2;
                   5348:     }
                   5349: }
                   5350: 
1.713     albertel 5351: # get the collection of conditions for this resource
1.26      www      5352: sub condval {
                   5353:     my $condidx=shift;
1.54      www      5354:     my $allpathcond='';
1.713     albertel 5355:     foreach my $cond (split(/\|/,$condidx)) {
                   5356: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   5357: 	    $allpathcond.=
                   5358: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   5359: 	}
1.191     harris41 5360:     }
1.54      www      5361:     $allpathcond=~s/\|$//;
1.713     albertel 5362:     return &docondval($allpathcond);
                   5363: }
                   5364: 
                   5365: #evaluates an expression of conditions
                   5366: sub docondval {
                   5367:     my ($allpathcond) = @_;
                   5368:     my $result=0;
                   5369:     if ($env{'request.course.id'}
                   5370: 	&& defined($allpathcond)) {
                   5371: 	my $operand='|';
                   5372: 	my @stack;
                   5373: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   5374: 	    if ($chunk eq '(') {
                   5375: 		push @stack,($operand,$result);
                   5376: 	    } elsif ($chunk eq ')') {
                   5377: 		my $before=pop @stack;
                   5378: 		if (pop @stack eq '&') {
                   5379: 		    $result=$result>$before?$before:$result;
                   5380: 		} else {
                   5381: 		    $result=$result>$before?$result:$before;
                   5382: 		}
                   5383: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   5384: 		$operand=$chunk;
                   5385: 	    } else {
                   5386: 		my $new=directcondval($chunk);
                   5387: 		if ($operand eq '&') {
                   5388: 		    $result=$result>$new?$new:$result;
                   5389: 		} else {
                   5390: 		    $result=$result>$new?$result:$new;
                   5391: 		}
                   5392: 	    }
                   5393: 	}
1.26      www      5394:     }
                   5395:     return $result;
1.421     albertel 5396: }
                   5397: 
                   5398: # ---------------------------------------------------- Devalidate courseresdata
                   5399: 
                   5400: sub devalidatecourseresdata {
                   5401:     my ($coursenum,$coursedomain)=@_;
                   5402:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 5403:     &devalidate_cache_new('courseres',$hashid);
1.28      www      5404: }
                   5405: 
1.763     www      5406: 
1.200     www      5407: # --------------------------------------------------- Course Resourcedata Query
                   5408: 
1.624     albertel 5409: sub get_courseresdata {
                   5410:     my ($coursenum,$coursedomain)=@_;
1.200     www      5411:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   5412:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 5413:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 5414:     my %dumpreply;
1.417     albertel 5415:     unless (defined($cached)) {
1.624     albertel 5416: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 5417: 	$result=\%dumpreply;
1.251     albertel 5418: 	my ($tmp) = keys(%dumpreply);
                   5419: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 5420: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 5421: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   5422: 	    return $tmp;
1.416     albertel 5423: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 5424: 	    $result=undef;
1.599     albertel 5425: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 5426: 	}
                   5427:     }
1.624     albertel 5428:     return $result;
                   5429: }
                   5430: 
1.633     albertel 5431: sub devalidateuserresdata {
                   5432:     my ($uname,$udom)=@_;
                   5433:     my $hashid="$udom:$uname";
                   5434:     &devalidate_cache_new('userres',$hashid);
                   5435: }
                   5436: 
1.624     albertel 5437: sub get_userresdata {
                   5438:     my ($uname,$udom)=@_;
                   5439:     #most student don\'t have any data set, check if there is some data
                   5440:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   5441: 
                   5442:     my $hashid="$udom:$uname";
                   5443:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   5444:     if (!defined($cached)) {
                   5445: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   5446: 	$result=\%resourcedata;
                   5447: 	&do_cache_new('userres',$hashid,$result,600);
                   5448:     }
                   5449:     my ($tmp)=keys(%$result);
                   5450:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   5451: 	return $result;
                   5452:     }
                   5453:     #error 2 occurs when the .db doesn't exist
                   5454:     if ($tmp!~/error: 2 /) {
1.672     albertel 5455: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 5456: 		 " Trying to get resource data for ".
                   5457: 		 $uname." at ".$udom.": ".
                   5458: 		 $tmp."</font>");
                   5459:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 5460: 	#&EXT_cache_set($udom,$uname);
                   5461: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 5462: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 5463:     }
                   5464:     return $tmp;
                   5465: }
                   5466: 
                   5467: sub resdata {
                   5468:     my ($name,$domain,$type,@which)=@_;
                   5469:     my $result;
                   5470:     if ($type eq 'course') {
                   5471: 	$result=&get_courseresdata($name,$domain);
                   5472:     } elsif ($type eq 'user') {
                   5473: 	$result=&get_userresdata($name,$domain);
                   5474:     }
                   5475:     if (!ref($result)) { return $result; }    
1.251     albertel 5476:     foreach my $item (@which) {
1.417     albertel 5477: 	if (defined($result->{$item})) {
                   5478: 	    return $result->{$item};
1.251     albertel 5479: 	}
1.250     albertel 5480:     }
1.291     albertel 5481:     return undef;
1.200     www      5482: }
                   5483: 
1.379     matthew  5484: #
                   5485: # EXT resource caching routines
                   5486: #
                   5487: 
                   5488: sub clear_EXT_cache_status {
1.383     albertel 5489:     &delenv('cache.EXT.');
1.379     matthew  5490: }
                   5491: 
                   5492: sub EXT_cache_status {
                   5493:     my ($target_domain,$target_user) = @_;
1.383     albertel 5494:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 5495:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  5496:         # We know already the user has no data
                   5497:         return 1;
                   5498:     } else {
                   5499:         return 0;
                   5500:     }
                   5501: }
                   5502: 
                   5503: sub EXT_cache_set {
                   5504:     my ($target_domain,$target_user) = @_;
1.383     albertel 5505:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.633     albertel 5506:     #&appenv($cachename => time);
1.379     matthew  5507: }
                   5508: 
1.28      www      5509: # --------------------------------------------------------- Value of a Variable
1.58      www      5510: sub EXT {
1.715     albertel 5511: 
1.395     albertel 5512:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      5513:     unless ($varname) { return ''; }
1.218     albertel 5514:     #get real user name/domain, courseid and symb
                   5515:     my $courseid;
1.359     albertel 5516:     my $publicuser;
1.427     www      5517:     if ($symbparm) {
                   5518: 	$symbparm=&get_symb_from_alias($symbparm);
                   5519:     }
1.218     albertel 5520:     if (!($uname && $udom)) {
1.360     albertel 5521:       (my $cursymb,$courseid,$udom,$uname,$publicuser)=
1.378     matthew  5522: 	  &Apache::lonxml::whichuser($symbparm);
1.218     albertel 5523:       if (!$symbparm) {	$symbparm=$cursymb; }
                   5524:     } else {
1.620     albertel 5525: 	$courseid=$env{'request.course.id'};
1.218     albertel 5526:     }
1.48      www      5527:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   5528:     my $rest;
1.320     albertel 5529:     if (defined($therest[0])) {
1.48      www      5530:        $rest=join('.',@therest);
                   5531:     } else {
                   5532:        $rest='';
                   5533:     }
1.320     albertel 5534: 
1.57      www      5535:     my $qualifierrest=$qualifier;
                   5536:     if ($rest) { $qualifierrest.='.'.$rest; }
                   5537:     my $spacequalifierrest=$space;
                   5538:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      5539:     if ($realm eq 'user') {
1.48      www      5540: # --------------------------------------------------------------- user.resource
                   5541: 	if ($space eq 'resource') {
1.651     albertel 5542: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   5543: 		  || defined($Apache::lonhomework::parsing_a_task))
                   5544: 		 &&
1.744     albertel 5545: 		 ($symbparm eq &symbread()) ) {	
                   5546: 		# if we are in the middle of processing the resource the
                   5547: 		# get the value we are planning on committing
                   5548:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   5549:                     return $Apache::lonhomework::results{$qualifierrest};
                   5550:                 } else {
                   5551:                     return $Apache::lonhomework::history{$qualifierrest};
                   5552:                 }
1.335     albertel 5553: 	    } else {
1.359     albertel 5554: 		my %restored;
1.620     albertel 5555: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 5556: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   5557: 		} else {
                   5558: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   5559: 		}
1.335     albertel 5560: 		return $restored{$qualifierrest};
                   5561: 	    }
1.48      www      5562: # ----------------------------------------------------------------- user.access
                   5563:         } elsif ($space eq 'access') {
1.218     albertel 5564: 	    # FIXME - not supporting calls for a specific user
1.48      www      5565:             return &allowed($qualifier,$rest);
                   5566: # ------------------------------------------ user.preferences, user.environment
                   5567:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 5568: 	    if (($uname eq $env{'user.name'}) &&
                   5569: 		($udom eq $env{'user.domain'})) {
                   5570: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 5571: 	    } else {
1.359     albertel 5572: 		my %returnhash;
                   5573: 		if (!$publicuser) {
                   5574: 		    %returnhash=&userenvironment($udom,$uname,
                   5575: 						 $qualifierrest);
                   5576: 		}
1.218     albertel 5577: 		return $returnhash{$qualifierrest};
                   5578: 	    }
1.48      www      5579: # ----------------------------------------------------------------- user.course
                   5580:         } elsif ($space eq 'course') {
1.218     albertel 5581: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 5582:             return $env{join('.',('request.course',$qualifier))};
1.48      www      5583: # ------------------------------------------------------------------- user.role
                   5584:         } elsif ($space eq 'role') {
1.218     albertel 5585: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 5586:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      5587:             if ($qualifier eq 'value') {
                   5588: 		return $role;
                   5589:             } elsif ($qualifier eq 'extent') {
                   5590:                 return $where;
                   5591:             }
                   5592: # ----------------------------------------------------------------- user.domain
                   5593:         } elsif ($space eq 'domain') {
1.218     albertel 5594:             return $udom;
1.48      www      5595: # ------------------------------------------------------------------- user.name
                   5596:         } elsif ($space eq 'name') {
1.218     albertel 5597:             return $uname;
1.48      www      5598: # ---------------------------------------------------- Any other user namespace
1.29      www      5599:         } else {
1.359     albertel 5600: 	    my %reply;
                   5601: 	    if (!$publicuser) {
                   5602: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   5603: 	    }
                   5604: 	    return $reply{$qualifierrest};
1.48      www      5605:         }
1.236     www      5606:     } elsif ($realm eq 'query') {
                   5607: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 5608:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   5609: 						[$spacequalifierrest]);
1.620     albertel 5610: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      5611:    } elsif ($realm eq 'request') {
1.48      www      5612: # ------------------------------------------------------------- request.browser
                   5613:         if ($space eq 'browser') {
1.430     www      5614: 	    if ($qualifier eq 'textremote') {
1.676     albertel 5615: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      5616: 		    return 1;
                   5617: 		} else {
                   5618: 		    return 0;
                   5619: 		}
                   5620: 	    } else {
1.620     albertel 5621: 		return $env{'browser.'.$qualifier};
1.430     www      5622: 	    }
1.57      www      5623: # ------------------------------------------------------------ request.filename
                   5624:         } else {
1.620     albertel 5625:             return $env{'request.'.$spacequalifierrest};
1.29      www      5626:         }
1.28      www      5627:     } elsif ($realm eq 'course') {
1.48      www      5628: # ---------------------------------------------------------- course.description
1.620     albertel 5629:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      5630:     } elsif ($realm eq 'resource') {
1.165     www      5631: 
1.620     albertel 5632: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 5633: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   5634: 	}
1.693     albertel 5635: 
                   5636: 	if ($space eq 'title') {
                   5637: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   5638: 	    return &gettitle($symbparm);
                   5639: 	}
                   5640: 	
                   5641: 	if ($space eq 'map') {
                   5642: 	    my ($map) = &decode_symb($symbparm);
                   5643: 	    return &symbread($map);
                   5644: 	}
                   5645: 
                   5646: 	my ($section, $group, @groups);
1.593     albertel 5647: 	my ($courselevelm,$courselevel);
1.539     albertel 5648: 	if ($symbparm && defined($courseid) && 
1.620     albertel 5649: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      5650: 
1.218     albertel 5651: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      5652: 
1.60      www      5653: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 5654: 	    my $symbp=$symbparm;
1.735     albertel 5655: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 5656: 
                   5657: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   5658: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   5659: 
1.620     albertel 5660: 	    if (($env{'user.name'} eq $uname) &&
                   5661: 		($env{'user.domain'} eq $udom)) {
                   5662: 		$section=$env{'request.course.sec'};
1.733     raeburn  5663:                 @groups = split(/:/,$env{'request.course.groups'});  
                   5664:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 5665: 	    } else {
1.539     albertel 5666: 		if (! defined($usection)) {
1.551     albertel 5667: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 5668: 		} else {
                   5669: 		    $section = $usection;
                   5670: 		}
1.733     raeburn  5671:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 5672: 	    }
                   5673: 
                   5674: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   5675: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   5676: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   5677: 
1.593     albertel 5678: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 5679: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 5680: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      5681: 
1.60      www      5682: # ----------------------------------------------------------- first, check user
1.624     albertel 5683: 
                   5684: 	    my $userreply=&resdata($uname,$udom,'user',
                   5685: 				       ($courselevelr,$courselevelm,
                   5686: 					$courselevel));
                   5687: 	    if (defined($userreply)) { return $userreply; }
1.95      www      5688: 
1.594     albertel 5689: # ------------------------------------------------ second, check some of course
1.684     raeburn  5690:             my $coursereply;
1.691     raeburn  5691:             if (@groups > 0) {
                   5692:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   5693:                                        $mapparm,$spacequalifierrest);
1.684     raeburn  5694:                 if (defined($coursereply)) { return $coursereply; }
                   5695:             }
1.96      www      5696: 
1.684     raeburn  5697: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.624     albertel 5698: 				     $env{'course.'.$courseid.'.domain'},
                   5699: 				     'course',
                   5700: 				     ($seclevelr,$seclevelm,$seclevel,
                   5701: 				      $courselevelr));
1.287     albertel 5702: 	    if (defined($coursereply)) { return $coursereply; }
1.200     www      5703: 
1.60      www      5704: # ------------------------------------------------------ third, check map parms
1.218     albertel 5705: 	    my %parmhash=();
                   5706: 	    my $thisparm='';
                   5707: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 5708: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 5709: 		    &GDBM_READER(),0640)) {
1.218     albertel 5710: 		$thisparm=$parmhash{$symbparm};
                   5711: 		untie(%parmhash);
                   5712: 	    }
                   5713: 	    if ($thisparm) { return $thisparm; }
                   5714: 	}
1.594     albertel 5715: # ------------------------------------------ fourth, look in resource metadata
1.71      www      5716: 
1.218     albertel 5717: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 5718: 	my $filename;
                   5719: 	if (!$symbparm) { $symbparm=&symbread(); }
                   5720: 	if ($symbparm) {
1.409     www      5721: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 5722: 	} else {
1.620     albertel 5723: 	    $filename=$env{'request.filename'};
1.282     albertel 5724: 	}
                   5725: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.288     albertel 5726: 	if (defined($metadata)) { return $metadata; }
1.282     albertel 5727: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.288     albertel 5728: 	if (defined($metadata)) { return $metadata; }
1.142     www      5729: 
1.594     albertel 5730: # ---------------------------------------------- fourth, look in rest pf course
1.593     albertel 5731: 	if ($symbparm && defined($courseid) && 
1.620     albertel 5732: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 5733: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   5734: 				     $env{'course.'.$courseid.'.domain'},
                   5735: 				     'course',
                   5736: 				     ($courselevelm,$courselevel));
1.593     albertel 5737: 	    if (defined($coursereply)) { return $coursereply; }
                   5738: 	}
1.145     www      5739: # ------------------------------------------------------------------ Cascade up
1.218     albertel 5740: 	unless ($space eq '0') {
1.336     albertel 5741: 	    my @parts=split(/_/,$space);
                   5742: 	    my $id=pop(@parts);
                   5743: 	    my $part=join('_',@parts);
                   5744: 	    if ($part eq '') { $part='0'; }
                   5745: 	    my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 5746: 				 $symbparm,$udom,$uname,$section,1);
1.337     albertel 5747: 	    if (defined($partgeneral)) { return $partgeneral; }
1.218     albertel 5748: 	}
1.395     albertel 5749: 	if ($recurse) { return undef; }
                   5750: 	my $pack_def=&packages_tab_default($filename,$varname);
                   5751: 	if (defined($pack_def)) { return $pack_def; }
1.71      www      5752: 
1.48      www      5753: # ---------------------------------------------------- Any other user namespace
                   5754:     } elsif ($realm eq 'environment') {
                   5755: # ----------------------------------------------------------------- environment
1.620     albertel 5756: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   5757: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 5758: 	} else {
1.770     albertel 5759: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   5760: 		return '';
                   5761: 	    }
1.219     albertel 5762: 	    my %returnhash=&userenvironment($udom,$uname,
                   5763: 					    $spacequalifierrest);
                   5764: 	    return $returnhash{$spacequalifierrest};
                   5765: 	}
1.28      www      5766:     } elsif ($realm eq 'system') {
1.48      www      5767: # ----------------------------------------------------------------- system.time
                   5768: 	if ($space eq 'time') {
                   5769: 	    return time;
                   5770:         }
1.696     albertel 5771:     } elsif ($realm eq 'server') {
                   5772: # ----------------------------------------------------------------- system.time
                   5773: 	if ($space eq 'name') {
                   5774: 	    return $ENV{'SERVER_NAME'};
                   5775:         }
1.28      www      5776:     }
1.48      www      5777:     return '';
1.61      www      5778: }
                   5779: 
1.691     raeburn  5780: sub check_group_parms {
                   5781:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   5782:     my @groupitems = ();
                   5783:     my $resultitem;
                   5784:     my @levels = ($symbparm,$mapparm,$what);
                   5785:     foreach my $group (@{$groups}) {
                   5786:         foreach my $level (@levels) {
                   5787:              my $item = $courseid.'.['.$group.'].'.$level;
                   5788:              push(@groupitems,$item);
                   5789:         }
                   5790:     }
                   5791:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   5792:                             $env{'course.'.$courseid.'.domain'},
                   5793:                                      'course',@groupitems);
                   5794:     return $coursereply;
                   5795: }
                   5796: 
                   5797: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  5798:     my ($courseid,@groups) = @_;
                   5799:     @groups = sort(@groups);
1.691     raeburn  5800:     return @groups;
                   5801: }
                   5802: 
1.395     albertel 5803: sub packages_tab_default {
                   5804:     my ($uri,$varname)=@_;
                   5805:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 5806: 
                   5807:     my (@extension,@specifics,$do_default);
                   5808:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 5809: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 5810: 	if ($pack_type eq 'default') {
                   5811: 	    $do_default=1;
                   5812: 	} elsif ($pack_type eq 'extension') {
                   5813: 	    push(@extension,[$package,$pack_type,$pack_part]);
                   5814: 	} else {
                   5815: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   5816: 	}
                   5817:     }
                   5818:     # first look for a package that matches the requested part id
                   5819:     foreach my $package (@specifics) {
                   5820: 	my (undef,$pack_type,$pack_part)=@{$package};
                   5821: 	next if ($pack_part ne $part);
                   5822: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   5823: 	    return $packagetab{"$pack_type&$name&default"};
                   5824: 	}
                   5825:     }
                   5826:     # look for any possible matching non extension_ package
                   5827:     foreach my $package (@specifics) {
                   5828: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 5829: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   5830: 	    return $packagetab{"$pack_type&$name&default"};
                   5831: 	}
1.585     albertel 5832: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 5833: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   5834: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 5835: 	}
                   5836:     }
1.738     albertel 5837:     # look for any posible extension_ match
                   5838:     foreach my $package (@extension) {
                   5839: 	my ($package,$pack_type)=@{$package};
                   5840: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   5841: 	    return $packagetab{"$pack_type&$name&default"};
                   5842: 	}
                   5843: 	if (defined($packagetab{$package."&$name&default"})) {
                   5844: 	    return $packagetab{$package."&$name&default"};
                   5845: 	}
                   5846:     }
                   5847:     # look for a global default setting
                   5848:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   5849: 	return $packagetab{"default&$name&default"};
                   5850:     }
1.395     albertel 5851:     return undef;
                   5852: }
                   5853: 
1.334     albertel 5854: sub add_prefix_and_part {
                   5855:     my ($prefix,$part)=@_;
                   5856:     my $keyroot;
                   5857:     if (defined($prefix) && $prefix !~ /^__/) {
                   5858: 	# prefix that has a part already
                   5859: 	$keyroot=$prefix;
                   5860:     } elsif (defined($prefix)) {
                   5861: 	# prefix that is missing a part
                   5862: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   5863:     } else {
                   5864: 	# no prefix at all
                   5865: 	if (defined($part)) { $keyroot='_'.$part; }
                   5866:     }
                   5867:     return $keyroot;
                   5868: }
                   5869: 
1.71      www      5870: # ---------------------------------------------------------------- Get metadata
                   5871: 
1.599     albertel 5872: my %metaentry;
1.71      www      5873: sub metadata {
1.176     www      5874:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      5875:     $uri=&declutter($uri);
1.288     albertel 5876:     # if it is a non metadata possible uri return quickly
1.529     albertel 5877:     if (($uri eq '') || 
                   5878: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 5879: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.423     albertel 5880:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) ||
1.489     albertel 5881: 	($uri =~ m|home/[^/]+/public_html/|)) {
1.468     albertel 5882: 	return undef;
1.288     albertel 5883:     }
1.73      www      5884:     my $filename=$uri;
                   5885:     $uri=~s/\.meta$//;
1.172     www      5886: #
                   5887: # Is the metadata already cached?
1.177     www      5888: # Look at timestamp of caching
1.172     www      5889: # Everything is cached by the main uri, libraries are never directly cached
                   5890: #
1.428     albertel 5891:     if (!defined($liburi)) {
1.599     albertel 5892: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 5893: 	if (defined($cached)) { return $result->{':'.$what}; }
                   5894:     }
                   5895:     {
1.172     www      5896: #
                   5897: # Is this a recursive call for a library?
                   5898: #
1.599     albertel 5899: #	if (! exists($metacache{$uri})) {
                   5900: #	    $metacache{$uri}={};
                   5901: #	}
1.171     www      5902:         if ($liburi) {
                   5903: 	    $liburi=&declutter($liburi);
                   5904:             $filename=$liburi;
1.401     bowersj2 5905:         } else {
1.599     albertel 5906: 	    &devalidate_cache_new('meta',$uri);
                   5907: 	    undef(%metaentry);
1.401     bowersj2 5908: 	}
1.140     www      5909:         my %metathesekeys=();
1.73      www      5910:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 5911: 	my $metastring;
1.768     albertel 5912: 	if ($uri !~ m -^(editupload)/-) {
1.543     albertel 5913: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 5914: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 5915: 	    $metastring=&getfile($file);
1.489     albertel 5916: 	}
1.208     albertel 5917:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      5918:         my $token;
1.140     www      5919:         undef %metathesekeys;
1.71      www      5920:         while ($token=$parser->get_token) {
1.339     albertel 5921: 	    if ($token->[0] eq 'S') {
                   5922: 		if (defined($token->[2]->{'package'})) {
1.172     www      5923: #
                   5924: # This is a package - get package info
                   5925: #
1.339     albertel 5926: 		    my $package=$token->[2]->{'package'};
                   5927: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   5928: 		    if (defined($token->[2]->{'id'})) { 
                   5929: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   5930: 		    }
1.599     albertel 5931: 		    if ($metaentry{':packages'}) {
                   5932: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 5933: 		    } else {
1.599     albertel 5934: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 5935: 		    }
1.736     albertel 5936: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 5937: 			my $part=$keyroot;
                   5938: 			$part=~s/^\_//;
1.736     albertel 5939: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   5940: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   5941: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 5942: 			    # ignore package.tab specified default values
                   5943:                             # here &package_tab_default() will fetch those
                   5944: 			    if ($subp eq 'default') { next; }
1.736     albertel 5945: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 5946: 			    my $unikey;
                   5947: 			    if ($pack =~ /_0$/) {
                   5948: 				$unikey='parameter_0_'.$name;
                   5949: 				$part=0;
                   5950: 			    } else {
                   5951: 				$unikey='parameter'.$keyroot.'_'.$name;
                   5952: 			    }
1.339     albertel 5953: 			    if ($subp eq 'display') {
                   5954: 				$value.=' [Part: '.$part.']';
                   5955: 			    }
1.599     albertel 5956: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 5957: 			    $metathesekeys{$unikey}=1;
1.599     albertel 5958: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   5959: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 5960: 			    }
1.599     albertel 5961: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   5962: 				$metaentry{':'.$unikey}=
                   5963: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 5964: 			    }
1.339     albertel 5965: 			}
                   5966: 		    }
                   5967: 		} else {
1.172     www      5968: #
                   5969: # This is not a package - some other kind of start tag
1.339     albertel 5970: #
                   5971: 		    my $entry=$token->[1];
                   5972: 		    my $unikey;
                   5973: 		    if ($entry eq 'import') {
                   5974: 			$unikey='';
                   5975: 		    } else {
                   5976: 			$unikey=$entry;
                   5977: 		    }
                   5978: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   5979: 
                   5980: 		    if (defined($token->[2]->{'id'})) { 
                   5981: 			$unikey.='_'.$token->[2]->{'id'}; 
                   5982: 		    }
1.175     www      5983: 
1.339     albertel 5984: 		    if ($entry eq 'import') {
1.175     www      5985: #
                   5986: # Importing a library here
1.339     albertel 5987: #
                   5988: 			if ($depthcount<20) {
                   5989: 			    my $location=$parser->get_text('/import');
                   5990: 			    my $dir=$filename;
                   5991: 			    $dir=~s|[^/]*$||;
                   5992: 			    $location=&filelocation($dir,$location);
1.736     albertel 5993: 			    my $metadata = 
                   5994: 				&metadata($uri,'keys', $location,$unikey,
                   5995: 					  $depthcount+1);
                   5996: 			    foreach my $meta (split(',',$metadata)) {
                   5997: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   5998: 				$metathesekeys{$meta}=1;
1.339     albertel 5999: 			    }
                   6000: 			}
                   6001: 		    } else { 
                   6002: 			
                   6003: 			if (defined($token->[2]->{'name'})) { 
                   6004: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   6005: 			}
                   6006: 			$metathesekeys{$unikey}=1;
1.736     albertel 6007: 			foreach my $param (@{$token->[3]}) {
                   6008: 			    $metaentry{':'.$unikey.'.'.$param} =
                   6009: 				$token->[2]->{$param};
1.339     albertel 6010: 			}
                   6011: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 6012: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 6013: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   6014: 		 # only ws inside the tag, and not in default, so use default
                   6015: 		 # as value
1.599     albertel 6016: 			    $metaentry{':'.$unikey}=$default;
1.339     albertel 6017: 			} else {
1.321     albertel 6018: 		  # either something interesting inside the tag or default
                   6019:                   # uninteresting
1.599     albertel 6020: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 6021: 			}
1.172     www      6022: # end of not-a-package not-a-library import
1.339     albertel 6023: 		    }
1.172     www      6024: # end of not-a-package start tag
1.339     albertel 6025: 		}
1.172     www      6026: # the next is the end of "start tag"
1.339     albertel 6027: 	    }
                   6028: 	}
1.483     albertel 6029: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.737     albertel 6030: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 6031: 	    #no specific packages #how's our extension
                   6032: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 6033: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 6034: 					 \%metathesekeys);
                   6035: 	}
1.599     albertel 6036: 	if (!exists($metaentry{':packages'})) {
1.737     albertel 6037: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 6038: 		#no specific packages well let's get default then
                   6039: 		if ($key!~/^default&/) { next; }
1.488     albertel 6040: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 6041: 					     \%metathesekeys);
                   6042: 	    }
                   6043: 	}
1.338     www      6044: # are there custom rights to evaluate
1.599     albertel 6045: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 6046: 
1.338     www      6047:     #
                   6048:     # Importing a rights file here
1.339     albertel 6049:     #
                   6050: 	    unless ($depthcount) {
1.599     albertel 6051: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 6052: 		my $dir=$filename;
                   6053: 		$dir=~s|[^/]*$||;
                   6054: 		$location=&filelocation($dir,$location);
1.736     albertel 6055: 		my $rights_metadata =
                   6056: 		    &metadata($uri,'keys',$location,'_rights',
                   6057: 			      $depthcount+1);
                   6058: 		foreach my $rights (split(',',$rights_metadata)) {
                   6059: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   6060: 		    $metathesekeys{$rights}=1;
1.339     albertel 6061: 		}
                   6062: 	    }
                   6063: 	}
1.737     albertel 6064: 	# uniqifiy package listing
                   6065: 	my %seen;
                   6066: 	my @uniq_packages =
                   6067: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   6068: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   6069: 
                   6070: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 6071: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   6072: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.699     albertel 6073: 	&do_cache_new('meta',$uri,\%metaentry,60*60);
1.177     www      6074: # this is the end of "was not already recently cached
1.71      www      6075:     }
1.599     albertel 6076:     return $metaentry{':'.$what};
1.261     albertel 6077: }
                   6078: 
1.488     albertel 6079: sub metadata_create_package_def {
1.483     albertel 6080:     my ($uri,$key,$package,$metathesekeys)=@_;
                   6081:     my ($pack,$name,$subp)=split(/\&/,$key);
                   6082:     if ($subp eq 'default') { next; }
                   6083:     
1.599     albertel 6084:     if (defined($metaentry{':packages'})) {
                   6085: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 6086:     } else {
1.599     albertel 6087: 	$metaentry{':packages'}=$package;
1.483     albertel 6088:     }
                   6089:     my $value=$packagetab{$key};
                   6090:     my $unikey;
                   6091:     $unikey='parameter_0_'.$name;
1.599     albertel 6092:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 6093:     $$metathesekeys{$unikey}=1;
1.599     albertel 6094:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   6095: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 6096:     }
1.599     albertel 6097:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   6098: 	$metaentry{':'.$unikey}=
                   6099: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 6100:     }
                   6101: }
                   6102: 
1.261     albertel 6103: sub metadata_generate_part0 {
                   6104:     my ($metadata,$metacache,$uri) = @_;
                   6105:     my %allnames;
1.737     albertel 6106:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 6107: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 6108: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   6109: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 6110: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 6111: 	    $allnames{$name}=$part;
                   6112: 	  }
                   6113: 	}
                   6114:     }
                   6115:     foreach my $name (keys(%allnames)) {
                   6116:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 6117:       my $key=":parameter_0_$name";
1.261     albertel 6118:       $$metacache{"$key.part"}='0';
                   6119:       $$metacache{"$key.name"}=$name;
1.428     albertel 6120:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 6121: 					   $allnames{$name}.'_'.$name.
                   6122: 					   '.type'};
1.428     albertel 6123:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 6124: 			     '.display'};
1.644     www      6125:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 6126:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 6127:       $$metacache{"$key.display"}=$olddis;
                   6128:     }
1.71      www      6129: }
                   6130: 
1.764     albertel 6131: # ------------------------------------------------------ Devalidate title cache
                   6132: 
                   6133: sub devalidate_title_cache {
                   6134:     my ($url)=@_;
                   6135:     if (!$env{'request.course.id'}) { return; }
                   6136:     my $symb=&symbread($url);
                   6137:     if (!$symb) { return; }
                   6138:     my $key=$env{'request.course.id'}."\0".$symb;
                   6139:     &devalidate_cache_new('title',$key);
                   6140: }
                   6141: 
1.301     www      6142: # ------------------------------------------------- Get the title of a resource
                   6143: 
                   6144: sub gettitle {
                   6145:     my $urlsymb=shift;
                   6146:     my $symb=&symbread($urlsymb);
1.534     albertel 6147:     if ($symb) {
1.620     albertel 6148: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 6149: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 6150: 	if (defined($cached)) { 
                   6151: 	    return $result;
                   6152: 	}
1.534     albertel 6153: 	my ($map,$resid,$url)=&decode_symb($symb);
                   6154: 	my $title='';
                   6155: 	my %bighash;
1.620     albertel 6156: 	if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.534     albertel 6157: 		&GDBM_READER(),0640)) {
                   6158: 	    my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   6159: 	    $title=$bighash{'title_'.$mapid.'.'.$resid};
                   6160: 	    untie %bighash;
                   6161: 	}
                   6162: 	$title=~s/\&colon\;/\:/gs;
                   6163: 	if ($title) {
1.599     albertel 6164: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 6165: 	}
                   6166: 	$urlsymb=$url;
                   6167:     }
                   6168:     my $title=&metadata($urlsymb,'title');
                   6169:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   6170:     return $title;
1.301     www      6171: }
1.613     albertel 6172: 
1.614     albertel 6173: sub get_slot {
                   6174:     my ($which,$cnum,$cdom)=@_;
                   6175:     if (!$cnum || !$cdom) {
                   6176: 	(undef,my $courseid)=&Apache::lonxml::whichuser();
1.620     albertel 6177: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   6178: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 6179:     }
1.703     albertel 6180:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   6181:     my %slotinfo;
                   6182:     if (exists($remembered{$key})) {
                   6183: 	$slotinfo{$which} = $remembered{$key};
                   6184:     } else {
                   6185: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   6186: 	&Apache::lonhomework::showhash(%slotinfo);
                   6187: 	my ($tmp)=keys(%slotinfo);
                   6188: 	if ($tmp=~/^error:/) { return (); }
                   6189: 	$remembered{$key} = $slotinfo{$which};
                   6190:     }
1.616     albertel 6191:     if (ref($slotinfo{$which}) eq 'HASH') {
                   6192: 	return %{$slotinfo{$which}};
                   6193:     }
                   6194:     return $slotinfo{$which};
1.614     albertel 6195: }
1.31      www      6196: # ------------------------------------------------- Update symbolic store links
                   6197: 
                   6198: sub symblist {
                   6199:     my ($mapname,%newhash)=@_;
1.438     www      6200:     $mapname=&deversion(&declutter($mapname));
1.31      www      6201:     my %hash;
1.620     albertel 6202:     if (($env{'request.course.fn'}) && (%newhash)) {
                   6203:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 6204:                       &GDBM_WRCREAT(),0640)) {
1.711     albertel 6205: 	    foreach my $url (keys %newhash) {
                   6206: 		next if ($url eq 'last_known'
                   6207: 			 && $env{'form.no_update_last_known'});
                   6208: 		$hash{declutter($url)}=&encode_symb($mapname,
                   6209: 						    $newhash{$url}->[1],
                   6210: 						    $newhash{$url}->[0]);
1.191     harris41 6211:             }
1.31      www      6212:             if (untie(%hash)) {
                   6213: 		return 'ok';
                   6214:             }
                   6215:         }
                   6216:     }
                   6217:     return 'error';
1.212     www      6218: }
                   6219: 
                   6220: # --------------------------------------------------------------- Verify a symb
                   6221: 
                   6222: sub symbverify {
1.510     www      6223:     my ($symb,$thisurl)=@_;
                   6224:     my $thisfn=$thisurl;
                   6225: # wrapper not part of symbs
                   6226:     $thisfn=~s/^\/adm\/wrapper//;
1.694     albertel 6227:     $thisfn=~s/^\/adm\/coursedocs\/showdoc\///;
1.439     www      6228:     $thisfn=&declutter($thisfn);
1.215     www      6229: # direct jump to resource in page or to a sequence - will construct own symbs
                   6230:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   6231: # check URL part
1.409     www      6232:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      6233: 
1.431     www      6234:     unless ($url eq $thisfn) { return 0; }
1.213     www      6235: 
1.216     www      6236:     $symb=&symbclean($symb);
1.510     www      6237:     $thisurl=&deversion($thisurl);
1.439     www      6238:     $thisfn=&deversion($thisfn);
1.213     www      6239: 
                   6240:     my %bighash;
                   6241:     my $okay=0;
1.431     www      6242: 
1.620     albertel 6243:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 6244:                             &GDBM_READER(),0640)) {
1.510     www      6245:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      6246:         unless ($ids) { 
1.510     www      6247:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      6248:         }
                   6249:         if ($ids) {
                   6250: # ------------------------------------------------------------------- Has ID(s)
                   6251: 	    foreach (split(/\,/,$ids)) {
1.644     www      6252: 	       my ($mapid,$resid)=split(/\./,$_);
1.216     www      6253:                if (
                   6254:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   6255:    eq $symb) { 
1.620     albertel 6256: 		   if (($env{'request.role.adv'}) ||
                   6257: 		       $bighash{'encrypted_'.$_} eq $env{'request.enc'}) {
1.582     albertel 6258: 		       $okay=1; 
                   6259: 		   }
                   6260: 	       }
1.216     www      6261: 	   }
                   6262:         }
1.213     www      6263: 	untie(%bighash);
                   6264:     }
                   6265:     return $okay;
1.31      www      6266: }
                   6267: 
1.210     www      6268: # --------------------------------------------------------------- Clean-up symb
                   6269: 
                   6270: sub symbclean {
                   6271:     my $symb=shift;
1.568     albertel 6272:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      6273: # remove version from map
                   6274:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      6275: 
1.210     www      6276: # remove version from URL
                   6277:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      6278: 
1.507     www      6279: # remove wrapper
                   6280: 
1.510     www      6281:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 6282:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      6283:     return $symb;
1.409     www      6284: }
                   6285: 
                   6286: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 6287: 
                   6288: sub encode_symb {
                   6289:     my ($map,$resid,$url)=@_;
                   6290:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   6291: }
1.409     www      6292: 
                   6293: sub decode_symb {
1.568     albertel 6294:     my $symb=shift;
                   6295:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   6296:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      6297:     return (&fixversion($map),$resid,&fixversion($url));
                   6298: }
                   6299: 
                   6300: sub fixversion {
                   6301:     my $fn=shift;
1.609     banghart 6302:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      6303:     my %bighash;
                   6304:     my $uri=&clutter($fn);
1.620     albertel 6305:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      6306: # is this cached?
1.599     albertel 6307:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      6308:     if (defined($cached)) { return $result; }
                   6309: # unfortunately not cached, or expired
1.620     albertel 6310:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      6311: 	    &GDBM_READER(),0640)) {
                   6312:  	if ($bighash{'version_'.$uri}) {
                   6313:  	    my $version=$bighash{'version_'.$uri};
1.444     www      6314:  	    unless (($version eq 'mostrecent') || 
                   6315: 		    ($version==&getversion($uri))) {
1.440     www      6316:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   6317:  	    }
                   6318:  	}
                   6319:  	untie %bighash;
1.413     www      6320:     }
1.599     albertel 6321:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      6322: }
                   6323: 
                   6324: sub deversion {
                   6325:     my $url=shift;
                   6326:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   6327:     return $url;
1.210     www      6328: }
                   6329: 
1.31      www      6330: # ------------------------------------------------------ Return symb list entry
                   6331: 
                   6332: sub symbread {
1.249     www      6333:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 6334:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 6335:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      6336: # no filename provided? try from environment
1.44      www      6337:     unless ($thisfn) {
1.620     albertel 6338:         if ($env{'request.symb'}) {
                   6339: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 6340: 	}
1.620     albertel 6341: 	$thisfn=$env{'request.filename'};
1.44      www      6342:     }
1.569     albertel 6343:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      6344: # is that filename actually a symb? Verify, clean, and return
                   6345:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 6346: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 6347: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 6348: 	}
1.242     www      6349:     }
1.44      www      6350:     $thisfn=declutter($thisfn);
1.31      www      6351:     my %hash;
1.37      www      6352:     my %bighash;
                   6353:     my $syval='';
1.620     albertel 6354:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  6355:         my $targetfn = $thisfn;
1.609     banghart 6356:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  6357:             $targetfn = 'adm/wrapper/'.$thisfn;
                   6358:         }
1.687     albertel 6359: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   6360: 	    $targetfn=$1;
                   6361: 	}
1.620     albertel 6362:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 6363:                       &GDBM_READER(),0640)) {
1.481     raeburn  6364: 	    $syval=$hash{$targetfn};
1.37      www      6365:             untie(%hash);
                   6366:         }
                   6367: # ---------------------------------------------------------- There was an entry
                   6368:         if ($syval) {
1.601     albertel 6369: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 6370: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.601     albertel 6371: 		    #&appenv('request.ambiguous' => $thisfn);
1.620     albertel 6372: 		    #return $env{$cache_str}='';
1.601     albertel 6373: 		#}    
                   6374: 		#$syval.=$1;
                   6375: 	    #}
1.37      www      6376:         } else {
                   6377: # ------------------------------------------------------- Was not in symb table
1.620     albertel 6378:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 6379:                             &GDBM_READER(),0640)) {
1.37      www      6380: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      6381:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      6382:               unless ($ids) { 
                   6383:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      6384:               }
                   6385:               unless ($ids) {
                   6386: # alias?
                   6387: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      6388:               }
1.37      www      6389:               if ($ids) {
                   6390: # ------------------------------------------------------------------- Has ID(s)
                   6391:                  my @possibilities=split(/\,/,$ids);
1.39      www      6392:                  if ($#possibilities==0) {
                   6393: # ----------------------------------------------- There is only one possibility
1.37      www      6394: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 6395: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   6396: 						    $resid,$thisfn);
1.249     www      6397:                  } elsif (!$donotrecurse) {
1.39      www      6398: # ------------------------------------------ There is more than one possibility
                   6399:                      my $realpossible=0;
1.191     harris41 6400:                      foreach (@possibilities) {
1.39      www      6401: 			 my $file=$bighash{'src_'.$_};
                   6402:                          if (&allowed('bre',$file)) {
                   6403:          		    my ($mapid,$resid)=split(/\./,$_);
                   6404:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   6405: 				$realpossible++;
1.626     albertel 6406:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   6407: 						    $resid,$thisfn);
1.39      www      6408:                             }
                   6409: 			 }
1.191     harris41 6410:                      }
1.39      www      6411: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      6412:                  } else {
                   6413:                      $syval='';
1.37      www      6414:                  }
                   6415: 	      }
                   6416:               untie(%bighash)
1.481     raeburn  6417:            }
1.31      www      6418:         }
1.62      www      6419:         if ($syval) {
1.620     albertel 6420: 	    return $env{$cache_str}=$syval;
1.62      www      6421:         }
1.31      www      6422:     }
1.44      www      6423:     &appenv('request.ambiguous' => $thisfn);
1.620     albertel 6424:     return $env{$cache_str}='';
1.31      www      6425: }
                   6426: 
                   6427: # ---------------------------------------------------------- Return random seed
                   6428: 
1.32      www      6429: sub numval {
                   6430:     my $txt=shift;
                   6431:     $txt=~tr/A-J/0-9/;
                   6432:     $txt=~tr/a-j/0-9/;
                   6433:     $txt=~tr/K-T/0-9/;
                   6434:     $txt=~tr/k-t/0-9/;
                   6435:     $txt=~tr/U-Z/0-5/;
                   6436:     $txt=~tr/u-z/0-5/;
                   6437:     $txt=~s/\D//g;
1.564     albertel 6438:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      6439:     return int($txt);
1.368     albertel 6440: }
                   6441: 
1.484     albertel 6442: sub numval2 {
                   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;
                   6451:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   6452:     my $total;
                   6453:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 6454:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 6455:     return int($total);
                   6456: }
                   6457: 
1.575     albertel 6458: sub numval3 {
                   6459:     use integer;
                   6460:     my $txt=shift;
                   6461:     $txt=~tr/A-J/0-9/;
                   6462:     $txt=~tr/a-j/0-9/;
                   6463:     $txt=~tr/K-T/0-9/;
                   6464:     $txt=~tr/k-t/0-9/;
                   6465:     $txt=~tr/U-Z/0-5/;
                   6466:     $txt=~tr/u-z/0-5/;
                   6467:     $txt=~s/\D//g;
                   6468:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   6469:     my $total;
                   6470:     foreach my $val (@txts) { $total+=$val; }
                   6471:     if ($_64bit) { $total=(($total<<32)>>32); }
                   6472:     return $total;
                   6473: }
                   6474: 
1.675     albertel 6475: sub digest {
                   6476:     my ($data)=@_;
                   6477:     my $digest=&Digest::MD5::md5($data);
                   6478:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   6479:     my ($e,$f);
                   6480:     {
                   6481:         use integer;
                   6482:         $e=($a+$b);
                   6483:         $f=($c+$d);
                   6484:         if ($_64bit) {
                   6485:             $e=(($e<<32)>>32);
                   6486:             $f=(($f<<32)>>32);
                   6487:         }
                   6488:     }
                   6489:     if (wantarray) {
                   6490: 	return ($e,$f);
                   6491:     } else {
                   6492: 	my $g;
                   6493: 	{
                   6494: 	    use integer;
                   6495: 	    $g=($e+$f);
                   6496: 	    if ($_64bit) {
                   6497: 		$g=(($g<<32)>>32);
                   6498: 	    }
                   6499: 	}
                   6500: 	return $g;
                   6501:     }
                   6502: }
                   6503: 
1.368     albertel 6504: sub latest_rnd_algorithm_id {
1.675     albertel 6505:     return '64bit5';
1.366     albertel 6506: }
1.32      www      6507: 
1.503     albertel 6508: sub get_rand_alg {
                   6509:     my ($courseid)=@_;
                   6510:     if (!$courseid) { $courseid=(&Apache::lonxml::whichuser())[1]; }
                   6511:     if ($courseid) {
1.620     albertel 6512: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 6513:     }
                   6514:     return &latest_rnd_algorithm_id();
                   6515: }
                   6516: 
1.562     albertel 6517: sub validCODE {
                   6518:     my ($CODE)=@_;
                   6519:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   6520:     return 0;
                   6521: }
                   6522: 
1.491     albertel 6523: sub getCODE {
1.620     albertel 6524:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 6525:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   6526: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   6527: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 6528: 	return $Apache::lonhomework::history{'resource.CODE'};
                   6529:     }
                   6530:     return undef;
                   6531: }
                   6532: 
1.31      www      6533: sub rndseed {
1.155     albertel 6534:     my ($symb,$courseid,$domain,$username)=@_;
1.366     albertel 6535: 
                   6536:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&Apache::lonxml::whichuser();
1.155     albertel 6537:     if (!$symb) {
1.366     albertel 6538: 	unless ($symb=$wsymb) { return time; }
                   6539:     }
                   6540:     if (!$courseid) { $courseid=$wcourseid; }
                   6541:     if (!$domain) { $domain=$wdomain; }
                   6542:     if (!$username) { $username=$wusername }
1.503     albertel 6543:     my $which=&get_rand_alg();
1.491     albertel 6544:     if (defined(&getCODE())) {
1.675     albertel 6545: 	if ($which eq '64bit5') {
                   6546: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   6547: 	} elsif ($which eq '64bit4') {
1.575     albertel 6548: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   6549: 	} else {
                   6550: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   6551: 	}
1.675     albertel 6552:     } elsif ($which eq '64bit5') {
                   6553: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 6554:     } elsif ($which eq '64bit4') {
                   6555: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 6556:     } elsif ($which eq '64bit3') {
                   6557: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 6558:     } elsif ($which eq '64bit2') {
                   6559: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 6560:     } elsif ($which eq '64bit') {
                   6561: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   6562:     }
                   6563:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   6564: }
                   6565: 
                   6566: sub rndseed_32bit {
                   6567:     my ($symb,$courseid,$domain,$username)=@_;
                   6568:     {
                   6569: 	use integer;
                   6570: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   6571: 	my $symbseed=numval($symb) << 22;
                   6572: 	my $namechck=unpack("%32C*",$username) << 17;
                   6573: 	my $nameseed=numval($username) << 12;
                   6574: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   6575: 	my $courseseed=unpack("%32C*",$courseid);
                   6576: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
                   6577: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6578: 	#&Apache::lonxml::debug("rndseed :$num:$symb");
1.564     albertel 6579: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 6580: 	return $num;
                   6581:     }
                   6582: }
                   6583: 
                   6584: sub rndseed_64bit {
                   6585:     my ($symb,$courseid,$domain,$username)=@_;
                   6586:     {
                   6587: 	use integer;
                   6588: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   6589: 	my $symbseed=numval($symb) << 10;
                   6590: 	my $namechck=unpack("%32S*",$username);
                   6591: 	
                   6592: 	my $nameseed=numval($username) << 21;
                   6593: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   6594: 	my $courseseed=unpack("%32S*",$courseid);
                   6595: 	
                   6596: 	my $num1=$symbchck+$symbseed+$namechck;
                   6597: 	my $num2=$nameseed+$domainseed+$courseseed;
                   6598: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6599: 	#&Apache::lonxml::debug("rndseed :$num:$symb");
1.564     albertel 6600: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   6601: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 6602: 	return "$num1,$num2";
1.155     albertel 6603:     }
1.366     albertel 6604: }
                   6605: 
1.443     albertel 6606: sub rndseed_64bit2 {
                   6607:     my ($symb,$courseid,$domain,$username)=@_;
                   6608:     {
                   6609: 	use integer;
                   6610: 	# strings need to be an even # of cahracters long, it it is odd the
                   6611:         # last characters gets thrown away
                   6612: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6613: 	my $symbseed=numval($symb) << 10;
                   6614: 	my $namechck=unpack("%32S*",$username.' ');
                   6615: 	
                   6616: 	my $nameseed=numval($username) << 21;
1.501     albertel 6617: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   6618: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6619: 	
                   6620: 	my $num1=$symbchck+$symbseed+$namechck;
                   6621: 	my $num2=$nameseed+$domainseed+$courseseed;
                   6622: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6623: 	#&Apache::lonxml::debug("rndseed :$num:$symb");
                   6624: 	return "$num1,$num2";
                   6625:     }
                   6626: }
                   6627: 
                   6628: sub rndseed_64bit3 {
                   6629:     my ($symb,$courseid,$domain,$username)=@_;
                   6630:     {
                   6631: 	use integer;
                   6632: 	# strings need to be an even # of cahracters long, it it is odd the
                   6633:         # last characters gets thrown away
                   6634: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6635: 	my $symbseed=numval2($symb) << 10;
                   6636: 	my $namechck=unpack("%32S*",$username.' ');
                   6637: 	
                   6638: 	my $nameseed=numval2($username) << 21;
1.443     albertel 6639: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   6640: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6641: 	
                   6642: 	my $num1=$symbchck+$symbseed+$namechck;
                   6643: 	my $num2=$nameseed+$domainseed+$courseseed;
                   6644: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
1.564     albertel 6645: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$_64bit");
                   6646: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   6647: 	
1.503     albertel 6648: 	return "$num1:$num2";
1.443     albertel 6649:     }
                   6650: }
                   6651: 
1.575     albertel 6652: sub rndseed_64bit4 {
                   6653:     my ($symb,$courseid,$domain,$username)=@_;
                   6654:     {
                   6655: 	use integer;
                   6656: 	# strings need to be an even # of cahracters long, it it is odd the
                   6657:         # last characters gets thrown away
                   6658: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6659: 	my $symbseed=numval3($symb) << 10;
                   6660: 	my $namechck=unpack("%32S*",$username.' ');
                   6661: 	
                   6662: 	my $nameseed=numval3($username) << 21;
                   6663: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   6664: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6665: 	
                   6666: 	my $num1=$symbchck+$symbseed+$namechck;
                   6667: 	my $num2=$nameseed+$domainseed+$courseseed;
                   6668: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6669: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$_64bit");
                   6670: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   6671: 	
                   6672: 	return "$num1:$num2";
                   6673:     }
                   6674: }
                   6675: 
1.675     albertel 6676: sub rndseed_64bit5 {
                   6677:     my ($symb,$courseid,$domain,$username)=@_;
                   6678:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   6679:     return "$num1:$num2";
                   6680: }
                   6681: 
1.366     albertel 6682: sub rndseed_CODE_64bit {
                   6683:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 6684:     {
1.366     albertel 6685: 	use integer;
1.443     albertel 6686: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 6687: 	my $symbseed=numval2($symb);
1.491     albertel 6688: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   6689: 	my $CODEseed=numval(&getCODE());
1.443     albertel 6690: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 6691: 	my $num1=$symbseed+$CODEchck;
                   6692: 	my $num2=$CODEseed+$courseseed+$symbchck;
                   6693: 	#&Apache::lonxml::debug("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
1.366     albertel 6694: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$symb");
1.564     albertel 6695: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   6696: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 6697: 	return "$num1:$num2";
1.366     albertel 6698:     }
                   6699: }
                   6700: 
1.575     albertel 6701: sub rndseed_CODE_64bit4 {
                   6702:     my ($symb,$courseid,$domain,$username)=@_;
                   6703:     {
                   6704: 	use integer;
                   6705: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   6706: 	my $symbseed=numval3($symb);
                   6707: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   6708: 	my $CODEseed=numval3(&getCODE());
                   6709: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6710: 	my $num1=$symbseed+$CODEchck;
                   6711: 	my $num2=$CODEseed+$courseseed+$symbchck;
                   6712: 	#&Apache::lonxml::debug("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   6713: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$symb");
                   6714: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   6715: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   6716: 	return "$num1:$num2";
                   6717:     }
                   6718: }
                   6719: 
1.675     albertel 6720: sub rndseed_CODE_64bit5 {
                   6721:     my ($symb,$courseid,$domain,$username)=@_;
                   6722:     my $code = &getCODE();
                   6723:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   6724:     return "$num1:$num2";
                   6725: }
                   6726: 
1.366     albertel 6727: sub setup_random_from_rndseed {
                   6728:     my ($rndseed)=@_;
1.503     albertel 6729:     if ($rndseed =~/([,:])/) {
                   6730: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 6731: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   6732:     } else {
                   6733: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 6734:     }
1.36      albertel 6735: }
                   6736: 
1.474     albertel 6737: sub latest_receipt_algorithm_id {
                   6738:     return 'receipt2';
                   6739: }
                   6740: 
1.480     www      6741: sub recunique {
                   6742:     my $fucourseid=shift;
                   6743:     my $unique;
1.620     albertel 6744:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   6745: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      6746:     } else {
                   6747: 	$unique=$perlvar{'lonReceipt'};
                   6748:     }
                   6749:     return unpack("%32C*",$unique);
                   6750: }
                   6751: 
                   6752: sub recprefix {
                   6753:     my $fucourseid=shift;
                   6754:     my $prefix;
1.620     albertel 6755:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   6756: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      6757:     } else {
                   6758: 	$prefix=$perlvar{'lonHostID'};
                   6759:     }
                   6760:     return unpack("%32C*",$prefix);
                   6761: }
                   6762: 
1.76      www      6763: sub ireceipt {
1.474     albertel 6764:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.76      www      6765:     my $cuname=unpack("%32C*",$funame);
                   6766:     my $cudom=unpack("%32C*",$fudom);
                   6767:     my $cucourseid=unpack("%32C*",$fucourseid);
                   6768:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      6769:     my $cunique=&recunique($fucourseid);
1.474     albertel 6770:     my $cpart=unpack("%32S*",$part);
1.480     www      6771:     my $return =&recprefix($fucourseid).'-';
1.620     albertel 6772:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   6773: 	$env{'request.state'} eq 'construct') {
1.474     albertel 6774: 	&Apache::lonxml::debug("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname).
                   6775: 			       " and ".($cpart%$cudom));
                   6776: 			       
                   6777: 	$return.= ($cunique%$cuname+
                   6778: 		   $cunique%$cudom+
                   6779: 		   $cusymb%$cuname+
                   6780: 		   $cusymb%$cudom+
                   6781: 		   $cucourseid%$cuname+
                   6782: 		   $cucourseid%$cudom+
                   6783: 		   $cpart%$cuname+
                   6784: 		   $cpart%$cudom);
                   6785:     } else {
                   6786: 	$return.= ($cunique%$cuname+
                   6787: 		   $cunique%$cudom+
                   6788: 		   $cusymb%$cuname+
                   6789: 		   $cusymb%$cudom+
                   6790: 		   $cucourseid%$cuname+
                   6791: 		   $cucourseid%$cudom);
                   6792:     }
                   6793:     return $return;
1.76      www      6794: }
                   6795: 
                   6796: sub receipt {
1.474     albertel 6797:     my ($part)=@_;
                   6798:     my ($symb,$courseid,$domain,$name) = &Apache::lonxml::whichuser();
                   6799:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      6800: }
1.260     ng       6801: 
1.36      albertel 6802: # ------------------------------------------------------------ Serves up a file
1.472     albertel 6803: # returns either the contents of the file or 
                   6804: # -1 if the file doesn't exist
1.481     raeburn  6805: #
                   6806: # if the target is a file that was uploaded via DOCS, 
                   6807: # a check will be made to see if a current copy exists on the local server,
                   6808: # if it does this will be served, otherwise a copy will be retrieved from
                   6809: # the home server for the course and stored in /home/httpd/html/userfiles on
                   6810: # the local server.   
1.472     albertel 6811: 
1.36      albertel 6812: sub getfile {
1.538     albertel 6813:     my ($file) = @_;
1.609     banghart 6814:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 6815:     &repcopy($file);
                   6816:     return &readfile($file);
                   6817: }
                   6818: 
                   6819: sub repcopy_userfile {
                   6820:     my ($file)=@_;
1.609     banghart 6821:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 6822:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 6823:     my ($cdom,$cnum,$filename) = 
                   6824: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+([^/]+)/+([^/]+)/+(.*)|);
                   6825:     my ($info,$rtncode);
                   6826:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   6827:     if (-e "$file") {
                   6828: 	my @fileinfo = stat($file);
                   6829: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 6830: 	if ($lwpresp ne 'ok') {
                   6831: 	    if ($rtncode eq '404') {
1.538     albertel 6832: 		unlink($file);
1.482     albertel 6833: 	    }
1.517     albertel 6834: 	    #my $ua=new LWP::UserAgent;
1.538     albertel 6835: 	    #my $request=new HTTP::Request('GET',&tokenwrapper($uri));
1.517     albertel 6836: 	    #my $response=$ua->request($request);
                   6837: 	    #if ($response->is_success()) {
                   6838: 	#	return $response->content;
                   6839: 	#    } else {
                   6840: 	#	return -1;
                   6841: 	#    }
1.482     albertel 6842: 	    return -1;
                   6843: 	}
                   6844: 	if ($info < $fileinfo[9]) {
1.607     raeburn  6845: 	    return 'ok';
1.482     albertel 6846: 	}
                   6847: 	$info = '';
1.538     albertel 6848: 	$lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 6849: 	if ($lwpresp ne 'ok') {
                   6850: 	    return -1;
                   6851: 	}
                   6852:     } else {
1.538     albertel 6853: 	my $lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 6854: 	if ($lwpresp ne 'ok') {
1.517     albertel 6855: 	    my $ua=new LWP::UserAgent;
1.538     albertel 6856: 	    my $request=new HTTP::Request('GET',&tokenwrapper($uri));
1.517     albertel 6857: 	    my $response=$ua->request($request);
                   6858: 	    if ($response->is_success()) {
1.538     albertel 6859: 		$info=$response->content;
1.517     albertel 6860: 	    } else {
                   6861: 		return -1;
                   6862: 	    }
1.482     albertel 6863: 	}
                   6864: 	my @parts = ($cdom,$cnum); 
                   6865: 	if ($filename =~ m|^(.+)/[^/]+$|) {
                   6866: 	    push @parts, split(/\//,$1);
1.518     albertel 6867: 	}
1.538     albertel 6868: 	my $path = $perlvar{'lonDocRoot'}.'/userfiles';
1.482     albertel 6869: 	foreach my $part (@parts) {
                   6870: 	    $path .= '/'.$part;
                   6871: 	    if (!-e $path) {
                   6872: 		mkdir($path,0770);
                   6873: 	    }
                   6874: 	}
                   6875:     }
1.538     albertel 6876:     open(FILE,">$file");
1.482     albertel 6877:     print FILE $info;
                   6878:     close(FILE);
1.607     raeburn  6879:     return 'ok';
1.481     raeburn  6880: }
                   6881: 
1.517     albertel 6882: sub tokenwrapper {
                   6883:     my $uri=shift;
1.552     albertel 6884:     $uri=~s|^http\://([^/]+)||;
                   6885:     $uri=~s|^/||;
1.620     albertel 6886:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 6887:     my $token=$1;
1.552     albertel 6888:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   6889:     if ($udom && $uname && $file) {
                   6890: 	$file=~s|(\?\.*)*$||;
1.620     albertel 6891:         &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
1.552     albertel 6892:         return 'http://'.$hostname{ &homeserver($uname,$udom)}.'/'.$uri.
1.517     albertel 6893:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   6894:                                '&tokenissued='.$perlvar{'lonHostID'};
                   6895:     } else {
                   6896:         return '/adm/notfound.html';
                   6897:     }
                   6898: }
                   6899: 
1.481     raeburn  6900: sub getuploaded {
                   6901:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   6902:     $uri=~s/^\///;
                   6903:     $uri = 'http://'.$hostname{ &homeserver($cnum,$cdom)}.'/raw/'.$uri;
                   6904:     my $ua=new LWP::UserAgent;
                   6905:     my $request=new HTTP::Request($reqtype,$uri);
                   6906:     my $response=$ua->request($request);
                   6907:     $$rtncode = $response->code;
1.482     albertel 6908:     if (! $response->is_success()) {
                   6909: 	return 'failed';
                   6910:     }      
                   6911:     if ($reqtype eq 'HEAD') {
1.486     www      6912: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 6913:     } elsif ($reqtype eq 'GET') {
                   6914: 	$$info = $response->content;
1.472     albertel 6915:     }
1.482     albertel 6916:     return 'ok';
1.36      albertel 6917: }
                   6918: 
1.481     raeburn  6919: sub readfile {
                   6920:     my $file = shift;
                   6921:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   6922:     my $fh;
                   6923:     open($fh,"<$file");
                   6924:     my $a='';
                   6925:     while (<$fh>) { $a .=$_; }
                   6926:     return $a;
                   6927: }
                   6928: 
1.36      albertel 6929: sub filelocation {
1.590     banghart 6930:     my ($dir,$file) = @_;
                   6931:     my $location;
                   6932:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 6933: 
                   6934:     if ($file =~ m-^/adm/-) {
                   6935: 	$file=~s-^/adm/wrapper/-/-;
                   6936: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   6937:     }
1.590     banghart 6938:     if ($file=~m:^/~:) { # is a contruction space reference
                   6939:         $location = $file;
                   6940:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.649     albertel 6941:     } elsif ($file=~m:^/home/[^/]*/public_html/:) {
                   6942: 	# is a correct contruction space reference
                   6943:         $location = $file;
1.609     banghart 6944:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 6945:         my ($udom,$uname,$filename)=
1.609     banghart 6946:   	    ($file=~m -^/+(?:uploaded|editupload)/+([^/]+)/+([^/]+)/+(.*)$-);
1.590     banghart 6947:         my $home=&homeserver($uname,$udom);
                   6948:         my $is_me=0;
                   6949:         my @ids=&current_machine_ids();
                   6950:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   6951:         if ($is_me) {
1.740     www      6952:   	    $location=&propath($udom,$uname).
1.590     banghart 6953:   	      '/userfiles/'.$filename;
                   6954:         } else {
                   6955:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   6956:   	      $udom.'/'.$uname.'/'.$filename;
                   6957:         }
                   6958:     } else {
                   6959:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   6960:         $file=~s:^/res/:/:;
                   6961:         if ( !( $file =~ m:^/:) ) {
                   6962:             $location = $dir. '/'.$file;
                   6963:         } else {
                   6964:             $location = '/home/httpd/html/res'.$file;
                   6965:         }
1.59      albertel 6966:     }
1.590     banghart 6967:     $location=~s://+:/:g; # remove duplicate /
                   6968:     while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
                   6969:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   6970:     return $location;
1.46      www      6971: }
1.36      albertel 6972: 
1.46      www      6973: sub hreflocation {
                   6974:     my ($dir,$file)=@_;
1.460     albertel 6975:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
1.666     albertel 6976: 	$file=filelocation($dir,$file);
1.700     albertel 6977:     } elsif ($file=~m-^/adm/-) {
                   6978: 	$file=~s-^/adm/wrapper/-/-;
                   6979: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 6980:     }
                   6981:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   6982: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   6983:     } elsif ($file=~m-/home/(\w+)/public_html/-) {
1.462     albertel 6984: 	$file=~s-^/home/(\w+)/public_html/-/~$1/-;
1.666     albertel 6985:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
                   6986: 	$file=~s-^/home/httpd/lonUsers/([^/]*)/./././([^/]*)/userfiles/
                   6987: 	    -/uploaded/$1/$2/-x;
1.46      www      6988:     }
1.462     albertel 6989:     return $file;
1.465     albertel 6990: }
                   6991: 
                   6992: sub current_machine_domains {
                   6993:     my $hostname=$hostname{$perlvar{'lonHostID'}};
                   6994:     my @domains;
                   6995:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  6996: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 6997: 	if ($hostname eq $name) {
                   6998: 	    push(@domains,$hostdom{$id});
                   6999: 	}
                   7000:     }
                   7001:     return @domains;
                   7002: }
                   7003: 
                   7004: sub current_machine_ids {
                   7005:     my $hostname=$hostname{$perlvar{'lonHostID'}};
                   7006:     my @ids;
                   7007:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  7008: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 7009: 	if ($hostname eq $name) {
                   7010: 	    push(@ids,$id);
                   7011: 	}
                   7012:     }
                   7013:     return @ids;
1.31      www      7014: }
                   7015: 
                   7016: # ------------------------------------------------------------- Declutters URLs
                   7017: 
                   7018: sub declutter {
                   7019:     my $thisfn=shift;
1.569     albertel 7020:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 7021:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      7022:     $thisfn=~s/^\///;
1.697     albertel 7023:     $thisfn=~s|^adm/wrapper/||;
                   7024:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      7025:     $thisfn=~s/^res\///;
1.235     www      7026:     $thisfn=~s/\?.+$//;
1.268     www      7027:     return $thisfn;
                   7028: }
                   7029: 
                   7030: # ------------------------------------------------------------- Clutter up URLs
                   7031: 
                   7032: sub clutter {
                   7033:     my $thisfn='/'.&declutter(shift);
1.609     banghart 7034:     unless ($thisfn=~/^\/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)\//) { 
1.270     www      7035:        $thisfn='/res'.$thisfn; 
                   7036:     }
1.694     albertel 7037:     if ($thisfn !~m|/adm|) {
1.695     albertel 7038: 	if ($thisfn =~ m|/ext/|) {
1.694     albertel 7039: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 7040: 	} else {
                   7041: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   7042: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 7043: 	    if ($embstyle eq 'ssi'
                   7044: 		|| ($embstyle eq 'hdn')
                   7045: 		|| ($embstyle eq 'rat')
                   7046: 		|| ($embstyle eq 'prv')
                   7047: 		|| ($embstyle eq 'ign')) {
                   7048: 		#do nothing with these
                   7049: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 7050: 		|| ($embstyle eq 'emb')
                   7051: 		|| ($embstyle eq 'wrp')) {
                   7052: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 7053: 	    } elsif ($embstyle eq 'unk'
                   7054: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 7055: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 7056: 	    } else {
1.718     www      7057: #		&logthis("Got a blank emb style");
1.695     albertel 7058: 	    }
1.694     albertel 7059: 	}
                   7060:     }
1.31      www      7061:     return $thisfn;
1.12      www      7062: }
                   7063: 
1.557     albertel 7064: sub freeze_escape {
                   7065:     my ($value)=@_;
                   7066:     if (ref($value)) {
                   7067: 	$value=&nfreeze($value);
                   7068: 	return '__FROZEN__'.&escape($value);
                   7069:     }
                   7070:     return &escape($value);
                   7071: }
                   7072: 
1.11      www      7073: 
1.557     albertel 7074: sub thaw_unescape {
                   7075:     my ($value)=@_;
                   7076:     if ($value =~ /^__FROZEN__/) {
                   7077: 	substr($value,0,10,undef);
                   7078: 	$value=&unescape($value);
                   7079: 	return &thaw($value);
                   7080:     }
                   7081:     return &unescape($value);
                   7082: }
                   7083: 
1.436     albertel 7084: sub correct_line_ends {
                   7085:     my ($result)=@_;
                   7086:     $$result =~s/\r\n/\n/mg;
                   7087:     $$result =~s/\r/\n/mg;
1.415     albertel 7088: }
1.1       albertel 7089: # ================================================================ Main Program
                   7090: 
1.184     www      7091: sub goodbye {
1.204     albertel 7092:    &logthis("Starting Shut down");
1.443     albertel 7093: #not converted to using infrastruture and probably shouldn't be
1.599     albertel 7094:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&freeze(\%badServerCache))));
1.443     albertel 7095: #converted
1.599     albertel 7096: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
                   7097:    &logthis(sprintf("%-20s is %s",'%homecache',length(&freeze(\%homecache))));
                   7098: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&freeze(\%titlecache))));
                   7099: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&freeze(\%courseresdatacache))));
1.425     albertel 7100: #1.1 only
1.599     albertel 7101: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&freeze(\%userresdatacache))));
                   7102: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&freeze(\%getsectioncache))));
                   7103: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&freeze(\%courseresversioncache))));
                   7104: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&freeze(\%resversioncache))));
                   7105:    &logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
                   7106:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   7107:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      7108:    &flushcourselogs();
                   7109:    &logthis("Shutting down");
                   7110: }
                   7111: 
1.179     www      7112: BEGIN {
1.228     harris41 7113: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
1.195     www      7114:     unless ($readit) {
1.217     harris41 7115: {
1.581     matthew  7116:     # FIXME: Use LONCAPA::Configuration::read_conf here and omit next block
1.448     albertel 7117:     open(my $config,"</etc/httpd/conf/loncapa.conf");
1.217     harris41 7118: 
                   7119:     while (my $configline=<$config>) {
1.484     albertel 7120:         if ($configline=~/\S/ && $configline =~ /^[^\#]*PerlSetVar/) {
1.1       albertel 7121: 	   my ($dummy,$varname,$varvalue)=split(/\s+/,$configline);
1.8       www      7122:            chomp($varvalue);
1.1       albertel 7123:            $perlvar{$varname}=$varvalue;
                   7124:         }
                   7125:     }
1.448     albertel 7126:     close($config);
1.1       albertel 7127: }
1.227     harris41 7128: {
1.448     albertel 7129:     open(my $config,"</etc/httpd/conf/loncapa_apache.conf");
1.227     harris41 7130: 
                   7131:     while (my $configline=<$config>) {
                   7132:         if ($configline =~ /^[^\#]*PerlSetVar/) {
                   7133: 	   my ($dummy,$varname,$varvalue)=split(/\s+/,$configline);
                   7134:            chomp($varvalue);
                   7135:            $perlvar{$varname}=$varvalue;
                   7136:         }
                   7137:     }
1.448     albertel 7138:     close($config);
1.227     harris41 7139: }
1.1       albertel 7140: 
1.327     albertel 7141: # ------------------------------------------------------------ Read domain file
                   7142: {
                   7143:     %domaindescription = ();
                   7144:     %domain_auth_def = ();
                   7145:     %domain_auth_arg_def = ();
1.448     albertel 7146:     my $fh;
                   7147:     if (open($fh,"<".$Apache::lonnet::perlvar{'lonTabDir'}.'/domain.tab')) {
1.327     albertel 7148:        while (<$fh>) {
1.390     matthew  7149:            next if (/^(\#|\s*$)/);
                   7150: #           next if /^\#/;
1.327     albertel 7151:            chomp;
1.403     www      7152:            my ($domain, $domain_description, $def_auth, $def_auth_arg,
1.685     raeburn  7153: 	       $def_lang, $city, $longi, $lati, $primary) = split(/:/,$_);
1.403     www      7154: 	   $domain_auth_def{$domain}=$def_auth;
1.327     albertel 7155:            $domain_auth_arg_def{$domain}=$def_auth_arg;
1.403     www      7156: 	   $domaindescription{$domain}=$domain_description;
                   7157: 	   $domain_lang_def{$domain}=$def_lang;
                   7158: 	   $domain_city{$domain}=$city;
                   7159: 	   $domain_longi{$domain}=$longi;
                   7160: 	   $domain_lati{$domain}=$lati;
1.685     raeburn  7161:            $domain_primary{$domain}=$primary;
1.403     www      7162: 
1.448     albertel 7163:  #         &logthis("Domain.tab: $domain, $domain_auth_def{$domain}, $domain_auth_arg_def{$domain},$domaindescription{$domain}");
1.327     albertel 7164: #          &logthis("Domain.tab: $domain ".$domaindescription{$domain} );
1.448     albertel 7165: 	}
1.327     albertel 7166:     }
1.448     albertel 7167:     close ($fh);
1.327     albertel 7168: }
                   7169: 
                   7170: 
1.1       albertel 7171: # ------------------------------------------------------------- Read hosts file
                   7172: {
1.448     albertel 7173:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
1.1       albertel 7174: 
                   7175:     while (my $configline=<$config>) {
1.303     matthew  7176:        next if ($configline =~ /^(\#|\s*$)/);
1.154     www      7177:        chomp($configline);
1.595     albertel 7178:        my ($id,$domain,$role,$name)=split(/:/,$configline);
1.597     albertel 7179:        $name=~s/\s//g;
1.595     albertel 7180:        if ($id && $domain && $role && $name) {
1.252     albertel 7181: 	 $hostname{$id}=$name;
                   7182: 	 $hostdom{$id}=$domain;
                   7183: 	 if ($role eq 'library') { $libserv{$id}=$name; }
1.245     www      7184:        }
1.1       albertel 7185:     }
1.448     albertel 7186:     close($config);
1.619     albertel 7187:     # FIXME: dev server don't want this, production servers _do_ want this
1.654     albertel 7188:     #&get_iphost();
1.1       albertel 7189: }
                   7190: 
1.598     albertel 7191: sub get_iphost {
                   7192:     if (%iphost) { return %iphost; }
1.653     albertel 7193:     my %name_to_ip;
1.598     albertel 7194:     foreach my $id (keys(%hostname)) {
                   7195: 	my $name=$hostname{$id};
1.653     albertel 7196: 	my $ip;
                   7197: 	if (!exists($name_to_ip{$name})) {
                   7198: 	    $ip = gethostbyname($name);
                   7199: 	    if (!$ip || length($ip) ne 4) {
                   7200: 		&logthis("Skipping host $id name $name no IP found\n");
                   7201: 		next;
                   7202: 	    }
                   7203: 	    $ip=inet_ntoa($ip);
                   7204: 	    $name_to_ip{$name} = $ip;
                   7205: 	} else {
                   7206: 	    $ip = $name_to_ip{$name};
1.598     albertel 7207: 	}
                   7208: 	push(@{$iphost{$ip}},$id);
                   7209:     }
                   7210:     return %iphost;
                   7211: }
                   7212: 
1.1       albertel 7213: # ------------------------------------------------------ Read spare server file
                   7214: {
1.448     albertel 7215:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 7216: 
                   7217:     while (my $configline=<$config>) {
                   7218:        chomp($configline);
1.284     matthew  7219:        if ($configline) {
1.1       albertel 7220:           $spareid{$configline}=1;
                   7221:        }
                   7222:     }
1.448     albertel 7223:     close($config);
1.1       albertel 7224: }
1.11      www      7225: # ------------------------------------------------------------ Read permissions
                   7226: {
1.448     albertel 7227:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      7228: 
                   7229:     while (my $configline=<$config>) {
1.448     albertel 7230: 	chomp($configline);
                   7231: 	if ($configline) {
                   7232: 	    my ($role,$perm)=split(/ /,$configline);
                   7233: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   7234: 	}
1.11      www      7235:     }
1.448     albertel 7236:     close($config);
1.11      www      7237: }
                   7238: 
                   7239: # -------------------------------------------- Read plain texts for permissions
                   7240: {
1.448     albertel 7241:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      7242: 
                   7243:     while (my $configline=<$config>) {
1.448     albertel 7244: 	chomp($configline);
                   7245: 	if ($configline) {
1.742     raeburn  7246: 	    my ($short,@plain)=split(/:/,$configline);
                   7247:             %{$prp{$short}} = ();
                   7248: 	    if (@plain > 0) {
                   7249:                 $prp{$short}{'std'} = $plain[0];
                   7250:                 for (my $i=1; $i<@plain; $i++) {
                   7251:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   7252:                 }
                   7253:             }
1.448     albertel 7254: 	}
1.135     www      7255:     }
1.448     albertel 7256:     close($config);
1.135     www      7257: }
                   7258: 
                   7259: # ---------------------------------------------------------- Read package table
                   7260: {
1.448     albertel 7261:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      7262: 
                   7263:     while (my $configline=<$config>) {
1.483     albertel 7264: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 7265: 	chomp($configline);
                   7266: 	my ($short,$plain)=split(/:/,$configline);
                   7267: 	my ($pack,$name)=split(/\&/,$short);
                   7268: 	if ($plain ne '') {
                   7269: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   7270: 	    $packagetab{$short}=$plain; 
                   7271: 	}
1.11      www      7272:     }
1.448     albertel 7273:     close($config);
1.329     matthew  7274: }
                   7275: 
                   7276: # ------------- set up temporary directory
                   7277: {
                   7278:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   7279: 
1.11      www      7280: }
                   7281: 
1.599     albertel 7282: $memcache=new Cache::Memcached({'servers'=>['127.0.0.1:11211']});
1.185     www      7283: 
1.281     www      7284: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      7285: $dumpcount=0;
1.22      www      7286: 
1.163     harris41 7287: &logtouch();
1.672     albertel 7288: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      7289: $readit=1;
1.564     albertel 7290:     {
                   7291: 	use integer;
                   7292: 	my $test=(2**32)+1;
1.568     albertel 7293: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 7294: 	&logthis(" Detected 64bit platform ($_64bit)");
                   7295:     }
1.195     www      7296: }
1.1       albertel 7297: }
1.179     www      7298: 
1.1       albertel 7299: 1;
1.191     harris41 7300: __END__
                   7301: 
1.243     albertel 7302: =pod
                   7303: 
1.191     harris41 7304: =head1 NAME
                   7305: 
1.243     albertel 7306: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 7307: 
                   7308: =head1 SYNOPSIS
                   7309: 
1.243     albertel 7310: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 7311: 
                   7312:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   7313: 
1.243     albertel 7314: Common parameters:
                   7315: 
                   7316: =over 4
                   7317: 
                   7318: =item *
                   7319: 
                   7320: $uname : an internal username (if $cname expecting a course Id specifically)
                   7321: 
                   7322: =item *
                   7323: 
                   7324: $udom : a domain (if $cdom expecting a course's domain specifically)
                   7325: 
                   7326: =item *
                   7327: 
                   7328: $symb : a resource instance identifier
                   7329: 
                   7330: =item *
                   7331: 
                   7332: $namespace : the name of a .db file that contains the data needed or
                   7333: being set.
                   7334: 
                   7335: =back
                   7336: 
1.394     bowersj2 7337: =head1 OVERVIEW
1.191     harris41 7338: 
1.394     bowersj2 7339: lonnet provides subroutines which interact with the
                   7340: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   7341: about classes, users, and resources.
1.243     albertel 7342: 
                   7343: For many of these objects you can also use this to store data about
                   7344: them or modify them in various ways.
1.191     harris41 7345: 
1.394     bowersj2 7346: =head2 Symbs
1.191     harris41 7347: 
1.394     bowersj2 7348: To identify a specific instance of a resource, LON-CAPA uses symbols
                   7349: or "symbs"X<symb>. These identifiers are built from the URL of the
                   7350: map, the resource number of the resource in the map, and the URL of
                   7351: the resource itself. The latter is somewhat redundant, but might help
                   7352: if maps change.
                   7353: 
                   7354: An example is
                   7355: 
                   7356:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   7357: 
                   7358: The respective map entry is
                   7359: 
                   7360:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   7361:   title="Problem 2">
                   7362:  </resource>
                   7363: 
                   7364: Symbs are used by the random number generator, as well as to store and
                   7365: restore data specific to a certain instance of for example a problem.
                   7366: 
                   7367: =head2 Storing And Retrieving Data
                   7368: 
                   7369: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   7370: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   7371: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   7372: is is the non-critical message twin of cstore. These functions are for
                   7373: handlers to store a perl hash to a user's permanent data space in an
                   7374: easy manner, and to retrieve it again on another call. It is expected
                   7375: that a handler would use this once at the beginning to retrieve data,
                   7376: and then again once at the end to send only the new data back.
                   7377: 
                   7378: The data is stored in the user's data directory on the user's
                   7379: homeserver under the ID of the course.
                   7380: 
                   7381: The hash that is returned by restore will have all of the previous
                   7382: value for all of the elements of the hash.
                   7383: 
                   7384: Example:
                   7385: 
                   7386:  #creating a hash
                   7387:  my %hash;
                   7388:  $hash{'foo'}='bar';
                   7389: 
                   7390:  #storing it
                   7391:  &Apache::lonnet::cstore(\%hash);
                   7392: 
                   7393:  #changing a value
                   7394:  $hash{'foo'}='notbar';
                   7395: 
                   7396:  #adding a new value
                   7397:  $hash{'bar'}='foo';
                   7398:  &Apache::lonnet::cstore(\%hash);
                   7399: 
                   7400:  #retrieving the hash
                   7401:  my %history=&Apache::lonnet::restore();
                   7402: 
                   7403:  #print the hash
                   7404:  foreach my $key (sort(keys(%history))) {
                   7405:    print("\%history{$key} = $history{$key}");
                   7406:  }
                   7407: 
                   7408: Will print out:
1.191     harris41 7409: 
1.394     bowersj2 7410:  %history{1:foo} = bar
                   7411:  %history{1:keys} = foo:timestamp
                   7412:  %history{1:timestamp} = 990455579
                   7413:  %history{2:bar} = foo
                   7414:  %history{2:foo} = notbar
                   7415:  %history{2:keys} = foo:bar:timestamp
                   7416:  %history{2:timestamp} = 990455580
                   7417:  %history{bar} = foo
                   7418:  %history{foo} = notbar
                   7419:  %history{timestamp} = 990455580
                   7420:  %history{version} = 2
                   7421: 
                   7422: Note that the special hash entries C<keys>, C<version> and
                   7423: C<timestamp> were added to the hash. C<version> will be equal to the
                   7424: total number of versions of the data that have been stored. The
                   7425: C<timestamp> attribute will be the UNIX time the hash was
                   7426: stored. C<keys> is available in every historical section to list which
                   7427: keys were added or changed at a specific historical revision of a
                   7428: hash.
                   7429: 
                   7430: B<Warning>: do not store the hash that restore returns directly. This
                   7431: will cause a mess since it will restore the historical keys as if the
                   7432: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 7433: 
1.394     bowersj2 7434: Calling convention:
1.191     harris41 7435: 
1.394     bowersj2 7436:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   7437:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 7438: 
1.394     bowersj2 7439: For more detailed information, see lonnet specific documentation.
1.191     harris41 7440: 
1.394     bowersj2 7441: =head1 RETURN MESSAGES
1.191     harris41 7442: 
1.394     bowersj2 7443: =over 4
1.191     harris41 7444: 
1.394     bowersj2 7445: =item * B<con_lost>: unable to contact remote host
1.191     harris41 7446: 
1.394     bowersj2 7447: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   7448: when the connection is brought back up
1.191     harris41 7449: 
1.394     bowersj2 7450: =item * B<con_failed>: unable to contact remote host and unable to save message
                   7451: for later delivery
1.191     harris41 7452: 
1.394     bowersj2 7453: =item * B<error:>: an error a occured, a description of the error follows the :
1.191     harris41 7454: 
1.394     bowersj2 7455: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 7456: that was requested
1.191     harris41 7457: 
1.243     albertel 7458: =back
1.191     harris41 7459: 
1.243     albertel 7460: =head1 PUBLIC SUBROUTINES
1.191     harris41 7461: 
1.243     albertel 7462: =head2 Session Environment Functions
1.191     harris41 7463: 
1.243     albertel 7464: =over 4
1.191     harris41 7465: 
1.394     bowersj2 7466: =item * 
                   7467: X<appenv()>
                   7468: B<appenv(%hash)>: the value of %hash is written to
                   7469: the user envirnoment file, and will be restored for each access this
1.620     albertel 7470: user makes during this session, also modifies the %env for the current
1.394     bowersj2 7471: process
1.191     harris41 7472: 
                   7473: =item *
1.394     bowersj2 7474: X<delenv()>
                   7475: B<delenv($regexp)>: removes all items from the session
                   7476: environment file that matches the regular expression in $regexp. The
1.620     albertel 7477: values are also delted from the current processes %env.
1.191     harris41 7478: 
1.243     albertel 7479: =back
                   7480: 
                   7481: =head2 User Information
1.191     harris41 7482: 
1.243     albertel 7483: =over 4
1.191     harris41 7484: 
                   7485: =item *
1.394     bowersj2 7486: X<queryauthenticate()>
                   7487: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 7488: authentication scheme
                   7489: 
                   7490: =item *
1.394     bowersj2 7491: X<authenticate()>
                   7492: B<authenticate($uname,$upass,$udom)>: try to
                   7493: authenticate user from domain's lib servers (first use the current
                   7494: one). C<$upass> should be the users password.
1.191     harris41 7495: 
                   7496: =item *
1.394     bowersj2 7497: X<homeserver()>
                   7498: B<homeserver($uname,$udom)>: find the server which has
                   7499: the user's directory and files (there must be only one), this caches
                   7500: the answer, and also caches if there is a borken connection.
1.191     harris41 7501: 
                   7502: =item *
1.394     bowersj2 7503: X<idget()>
                   7504: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   7505: (IDs are a unique resource in a domain, there must be only 1 ID per
                   7506: username, and only 1 username per ID in a specific domain) (returns
                   7507: hash: id=>name,id=>name)
1.191     harris41 7508: 
                   7509: =item *
1.394     bowersj2 7510: X<idrget()>
                   7511: B<idrget($udom,@unames)>: find the IDs behind a list of
                   7512: usernames (returns hash: name=>id,name=>id)
1.191     harris41 7513: 
                   7514: =item *
1.394     bowersj2 7515: X<idput()>
                   7516: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 7517: 
                   7518: =item *
1.394     bowersj2 7519: X<rolesinit()>
                   7520: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 7521: 
                   7522: =item *
1.551     albertel 7523: X<getsection()>
                   7524: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 7525: course $cname, return section name/number or '' for "not in course"
                   7526: and '-1' for "no section"
                   7527: 
                   7528: =item *
1.394     bowersj2 7529: X<userenvironment()>
                   7530: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 7531: passed in @what from the requested user's environment, returns a hash
                   7532: 
                   7533: =back
                   7534: 
                   7535: =head2 User Roles
                   7536: 
                   7537: =over 4
                   7538: 
                   7539: =item *
                   7540: 
                   7541: allowed($priv,$uri) : check for a user privilege; returns codes for allowed
                   7542: actions
                   7543:  F: full access
                   7544:  U,I,K: authentication modes (cxx only)
                   7545:  '': forbidden
                   7546:  1: user needs to choose course
                   7547:  2: browse allowed
1.766     albertel 7548:  A: passphrase authentication needed
1.243     albertel 7549: 
                   7550: =item *
                   7551: 
                   7552: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   7553: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   7554: and course level
                   7555: 
                   7556: =item *
                   7557: 
                   7558: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
                   7559: explanation of a user role term
                   7560: 
                   7561: =back
                   7562: 
                   7563: =head2 User Modification
                   7564: 
                   7565: =over 4
                   7566: 
                   7567: =item *
                   7568: 
                   7569: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
                   7570: user for the level given by URL.  Optional start and end dates (leave empty
                   7571: string or zero for "no date")
1.191     harris41 7572: 
                   7573: =item *
                   7574: 
1.243     albertel 7575: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   7576: change a users, password, possible return values are: ok,
                   7577: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   7578: refused
1.191     harris41 7579: 
                   7580: =item *
                   7581: 
1.243     albertel 7582: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 7583: 
                   7584: =item *
                   7585: 
1.243     albertel 7586: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
                   7587: modify user
1.191     harris41 7588: 
                   7589: =item *
                   7590: 
1.286     matthew  7591: modifystudent
                   7592: 
                   7593: modify a students enrollment and identification information.
                   7594: The course id is resolved based on the current users environment.  
                   7595: This means the envoking user must be a course coordinator or otherwise
                   7596: associated with a course.
                   7597: 
1.297     matthew  7598: This call is essentially a wrapper for lonnet::modifyuser and
                   7599: lonnet::modify_student_enrollment
1.286     matthew  7600: 
                   7601: Inputs: 
                   7602: 
                   7603: =over 4
                   7604: 
                   7605: =item B<$udom> Students loncapa domain
                   7606: 
                   7607: =item B<$uname> Students loncapa login name
                   7608: 
                   7609: =item B<$uid> Students id/student number
                   7610: 
                   7611: =item B<$umode> Students authentication mode
                   7612: 
                   7613: =item B<$upass> Students password
                   7614: 
                   7615: =item B<$first> Students first name
                   7616: 
                   7617: =item B<$middle> Students middle name
                   7618: 
                   7619: =item B<$last> Students last name
                   7620: 
                   7621: =item B<$gene> Students generation
                   7622: 
                   7623: =item B<$usec> Students section in course
                   7624: 
                   7625: =item B<$end> Unix time of the roles expiration
                   7626: 
                   7627: =item B<$start> Unix time of the roles start date
                   7628: 
                   7629: =item B<$forceid> If defined, allow $uid to be changed
                   7630: 
                   7631: =item B<$desiredhome> server to use as home server for student
                   7632: 
                   7633: =back
1.297     matthew  7634: 
                   7635: =item *
                   7636: 
                   7637: modify_student_enrollment
                   7638: 
                   7639: Change a students enrollment status in a class.  The environment variable
                   7640: 'role.request.course' must be defined for this function to proceed.
                   7641: 
                   7642: Inputs:
                   7643: 
                   7644: =over 4
                   7645: 
                   7646: =item $udom, students domain
                   7647: 
                   7648: =item $uname, students name
                   7649: 
                   7650: =item $uid, students user id
                   7651: 
                   7652: =item $first, students first name
                   7653: 
                   7654: =item $middle
                   7655: 
                   7656: =item $last
                   7657: 
                   7658: =item $gene
                   7659: 
                   7660: =item $usec
                   7661: 
                   7662: =item $end
                   7663: 
                   7664: =item $start
                   7665: 
                   7666: =back
                   7667: 
1.191     harris41 7668: 
                   7669: =item *
                   7670: 
1.243     albertel 7671: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   7672: custom role; give a custom role to a user for the level given by URL.  Specify
                   7673: name and domain of role author, and role name
1.191     harris41 7674: 
                   7675: =item *
                   7676: 
1.243     albertel 7677: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 7678: 
                   7679: =item *
                   7680: 
1.243     albertel 7681: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   7682: 
                   7683: =back
                   7684: 
                   7685: =head2 Course Infomation
                   7686: 
                   7687: =over 4
1.191     harris41 7688: 
                   7689: =item *
                   7690: 
1.631     albertel 7691: coursedescription($courseid) : returns a hash of information about the
                   7692: specified course id, including all environment settings for the
                   7693: course, the description of the course will be in the hash under the
                   7694: key 'description'
1.191     harris41 7695: 
                   7696: =item *
                   7697: 
1.624     albertel 7698: resdata($name,$domain,$type,@which) : request for current parameter
                   7699: setting for a specific $type, where $type is either 'course' or 'user',
                   7700: @what should be a list of parameters to ask about. This routine caches
                   7701: answers for 5 minutes.
1.243     albertel 7702: 
                   7703: =back
                   7704: 
                   7705: =head2 Course Modification
                   7706: 
                   7707: =over 4
1.191     harris41 7708: 
                   7709: =item *
                   7710: 
1.243     albertel 7711: writecoursepref($courseid,%prefs) : write preferences (environment
                   7712: database) for a course
1.191     harris41 7713: 
                   7714: =item *
                   7715: 
1.243     albertel 7716: createcourse($udom,$description,$url) : make/modify course
                   7717: 
                   7718: =back
                   7719: 
                   7720: =head2 Resource Subroutines
                   7721: 
                   7722: =over 4
1.191     harris41 7723: 
                   7724: =item *
                   7725: 
1.243     albertel 7726: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 7727: 
                   7728: =item *
                   7729: 
1.243     albertel 7730: repcopy($filename) : subscribes to the requested file, and attempts to
                   7731: replicate from the owning library server, Might return
1.607     raeburn  7732: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   7733: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 7734: resource. Expects the local filesystem pathname
                   7735: (/home/httpd/html/res/....)
                   7736: 
                   7737: =back
                   7738: 
                   7739: =head2 Resource Information
                   7740: 
                   7741: =over 4
1.191     harris41 7742: 
                   7743: =item *
                   7744: 
1.243     albertel 7745: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   7746: a vairety of different possible values, $varname should be a request
                   7747: string, and the other parameters can be used to specify who and what
                   7748: one is asking about.
                   7749: 
                   7750: Possible values for $varname are environment.lastname (or other item
                   7751: from the envirnment hash), user.name (or someother aspect about the
                   7752: user), resource.0.maxtries (or some other part and parameter of a
                   7753: resource)
1.204     albertel 7754: 
                   7755: =item *
                   7756: 
1.243     albertel 7757: directcondval($number) : get current value of a condition; reads from a state
                   7758: string
1.204     albertel 7759: 
                   7760: =item *
                   7761: 
1.243     albertel 7762: condval($condidx) : value of condition index based on state
1.204     albertel 7763: 
                   7764: =item *
                   7765: 
1.243     albertel 7766: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   7767: resource's metadata, $what should be either a specific key, or either
                   7768: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   7769: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   7770: 
                   7771: this function automatically caches all requests
1.191     harris41 7772: 
                   7773: =item *
                   7774: 
1.243     albertel 7775: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   7776: network of library servers; returns file handle of where SQL and regex results
                   7777: will be stored for query
1.191     harris41 7778: 
                   7779: =item *
                   7780: 
1.243     albertel 7781: symbread($filename) : return symbolic list entry (filename argument optional);
                   7782: returns the data handle
1.191     harris41 7783: 
                   7784: =item *
                   7785: 
1.243     albertel 7786: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 7787: a possible symb for the URL in $thisfn, and if is an encryypted
                   7788: resource that the user accessed using /enc/ returns a 1 on success, 0
                   7789: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 7790: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 7791: 
1.191     harris41 7792: 
                   7793: =item *
                   7794: 
1.243     albertel 7795: symbclean($symb) : removes versions numbers from a symb, returns the
                   7796: cleaned symb
1.191     harris41 7797: 
                   7798: =item *
                   7799: 
1.243     albertel 7800: is_on_map($uri) : checks if the $uri is somewhere on the current
                   7801: course map, user must be in a course for it to work.
1.191     harris41 7802: 
                   7803: =item *
                   7804: 
1.243     albertel 7805: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 7806: 
                   7807: =item *
                   7808: 
1.243     albertel 7809: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   7810: a random seed, all arguments are optional, if they aren't sent it uses the
                   7811: environment to derive them. Note: if symb isn't sent and it can't get one
                   7812: from &symbread it will use the current time as its return value
1.191     harris41 7813: 
                   7814: =item *
                   7815: 
1.243     albertel 7816: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   7817: unfakeable, receipt
1.191     harris41 7818: 
                   7819: =item *
                   7820: 
1.620     albertel 7821: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 7822: 
                   7823: =item *
                   7824: 
1.243     albertel 7825: countacc($url) : count the number of accesses to a given URL
1.191     harris41 7826: 
                   7827: =item *
                   7828: 
1.243     albertel 7829: 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 7830: 
                   7831: =item *
                   7832: 
1.243     albertel 7833: 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 7834: 
                   7835: =item *
                   7836: 
1.243     albertel 7837: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 7838: 
                   7839: =item *
                   7840: 
1.243     albertel 7841: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   7842: forcing spreadsheet to reevaluate the resource scores next time.
                   7843: 
                   7844: =back
                   7845: 
                   7846: =head2 Storing/Retreiving Data
                   7847: 
                   7848: =over 4
1.191     harris41 7849: 
                   7850: =item *
                   7851: 
1.243     albertel 7852: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   7853: for this url; hashref needs to be given and should be a \%hashname; the
                   7854: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 7855: be derived from the env
1.191     harris41 7856: 
                   7857: =item *
                   7858: 
1.243     albertel 7859: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   7860: uses critical subroutine
1.191     harris41 7861: 
                   7862: =item *
                   7863: 
1.243     albertel 7864: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   7865: all args are optional
1.191     harris41 7866: 
                   7867: =item *
                   7868: 
1.717     albertel 7869: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   7870: dumps the complete (or key matching regexp) namespace into a hash
                   7871: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   7872: normally &store()ed into
                   7873: 
                   7874: $range should be either an integer '100' (give me the first 100
                   7875:                                            matching records)
                   7876:               or be  two integers sperated by a - with no spaces
                   7877:                  '30-50' (give me the 30th through the 50th matching
                   7878:                           records)
                   7879: 
                   7880: 
                   7881: =item *
                   7882: 
                   7883: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   7884: replaces a &store() version of data with a replacement set of data
                   7885: for a particular resource in a namespace passed in the $storehash hash 
                   7886: reference
                   7887: 
                   7888: =item *
                   7889: 
1.243     albertel 7890: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   7891: works very similar to store/cstore, but all data is stored in a
                   7892: temporary location and can be reset using tmpreset, $storehash should
                   7893: be a hash reference, returns nothing on success
1.191     harris41 7894: 
                   7895: =item *
                   7896: 
1.243     albertel 7897: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   7898: similar to restore, but all data is stored in a temporary location and
                   7899: can be reset using tmpreset. Returns a hash of values on success,
                   7900: error string otherwise.
1.191     harris41 7901: 
                   7902: =item *
                   7903: 
1.243     albertel 7904: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   7905: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 7906: 
                   7907: =item *
                   7908: 
1.243     albertel 7909: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   7910: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 7911: 
                   7912: =item *
                   7913: 
1.243     albertel 7914: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   7915: namesp ($udom and $uname are optional)
1.191     harris41 7916: 
                   7917: =item *
                   7918: 
1.702     albertel 7919: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 7920: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 7921: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  7922: 
1.702     albertel 7923: $range should be either an integer '100' (give me the first 100
                   7924:                                            matching records)
                   7925:               or be  two integers sperated by a - with no spaces
                   7926:                  '30-50' (give me the 30th through the 50th matching
                   7927:                           records)
1.449     matthew  7928: =item *
                   7929: 
                   7930: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   7931: $store can be a scalar, an array reference, or if the amount to be 
                   7932: incremented is > 1, a hash reference.
                   7933: 
                   7934: ($udom and $uname are optional)
1.191     harris41 7935: 
                   7936: =item *
                   7937: 
1.243     albertel 7938: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   7939: ($udom and $uname are optional)
1.191     harris41 7940: 
                   7941: =item *
                   7942: 
1.243     albertel 7943: cput($namespace,$storehash,$udom,$uname) : critical put
                   7944: ($udom and $uname are optional)
1.191     harris41 7945: 
                   7946: =item *
                   7947: 
1.748     albertel 7948: newput($namespace,$storehash,$udom,$uname) :
                   7949: 
                   7950: Attempts to store the items in the $storehash, but only if they don't
                   7951: currently exist, if this succeeds you can be certain that you have 
                   7952: successfully created a new key value pair in the $namespace db.
                   7953: 
                   7954: 
                   7955: Args:
                   7956:  $namespace: name of database to store values to
                   7957:  $storehash: hashref to store to the db
                   7958:  $udom: (optional) domain of user containing the db
                   7959:  $uname: (optional) name of user caontaining the db
                   7960: 
                   7961: Returns:
                   7962:  'ok' -> succeeded in storing all keys of $storehash
                   7963:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   7964:                         least <key> already existed in the db (other
                   7965:                         requested keys may also already exist)
                   7966:  'error: <msg>' -> unable to tie the DB or other erorr occured
                   7967:  'con_lost' -> unable to contact request server
                   7968:  'refused' -> action was not allowed by remote machine
                   7969: 
                   7970: 
                   7971: =item *
                   7972: 
1.243     albertel 7973: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   7974: reference filled in from namesp (encrypts the return communication)
                   7975: ($udom and $uname are optional)
1.191     harris41 7976: 
                   7977: =item *
                   7978: 
1.243     albertel 7979: log($udom,$name,$home,$message) : write to permanent log for user; use
                   7980: critical subroutine
                   7981: 
                   7982: =back
                   7983: 
                   7984: =head2 Network Status Functions
                   7985: 
                   7986: =over 4
1.191     harris41 7987: 
                   7988: =item *
                   7989: 
                   7990: dirlist($uri) : return directory list based on URI
                   7991: 
                   7992: =item *
                   7993: 
1.243     albertel 7994: spareserver() : find server with least workload from spare.tab
                   7995: 
                   7996: =back
                   7997: 
                   7998: =head2 Apache Request
                   7999: 
                   8000: =over 4
1.191     harris41 8001: 
                   8002: =item *
                   8003: 
1.243     albertel 8004: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   8005: localhost, posts hash
                   8006: 
                   8007: =back
                   8008: 
                   8009: =head2 Data to String to Data
                   8010: 
                   8011: =over 4
1.191     harris41 8012: 
                   8013: =item *
                   8014: 
1.243     albertel 8015: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   8016: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 8017: 
                   8018: =item *
                   8019: 
1.243     albertel 8020: hashref2str($hashref) : convert a hashref into a string complete with
                   8021: escaping and '=' and '&' separators, supports elements that are
                   8022: arrayrefs and hashrefs
1.191     harris41 8023: 
                   8024: =item *
                   8025: 
1.243     albertel 8026: arrayref2str($arrayref) : convert an arrayref into a string complete
                   8027: with escaping and '&' separators, supports elements that are arrayrefs
                   8028: and hashrefs
1.191     harris41 8029: 
                   8030: =item *
                   8031: 
1.243     albertel 8032: str2hash($string) : convert string to hash using unescaping and
                   8033: splitting on '=' and '&', supports elements that are arrayrefs and
                   8034: hashrefs
1.191     harris41 8035: 
                   8036: =item *
                   8037: 
1.243     albertel 8038: str2array($string) : convert string to hash using unescaping and
                   8039: splitting on '&', supports elements that are arrayrefs and hashrefs
                   8040: 
                   8041: =back
                   8042: 
                   8043: =head2 Logging Routines
                   8044: 
                   8045: =over 4
                   8046: 
                   8047: These routines allow one to make log messages in the lonnet.log and
                   8048: lonnet.perm logfiles.
1.191     harris41 8049: 
                   8050: =item *
                   8051: 
1.243     albertel 8052: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 8053: 
                   8054: =item *
                   8055: 
1.243     albertel 8056: logthis() : append message to the normal lonnet.log file, it gets
                   8057: preiodically rolled over and deleted.
1.191     harris41 8058: 
                   8059: =item *
                   8060: 
1.243     albertel 8061: logperm() : append a permanent message to lonnet.perm.log, this log
                   8062: file never gets deleted by any automated portion of the system, only
                   8063: messages of critical importance should go in here.
                   8064: 
                   8065: =back
                   8066: 
                   8067: =head2 General File Helper Routines
                   8068: 
                   8069: =over 4
1.191     harris41 8070: 
                   8071: =item *
                   8072: 
1.481     raeburn  8073: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   8074: (a) files in /uploaded
                   8075:   (i) If a local copy of the file exists - 
                   8076:       compares modification date of local copy with last-modified date for 
                   8077:       definitive version stored on home server for course. If local copy is 
                   8078:       stale, requests a new version from the home server and stores it. 
                   8079:       If the original has been removed from the home server, then local copy 
                   8080:       is unlinked.
                   8081:   (ii) If local copy does not exist -
                   8082:       requests the file from the home server and stores it. 
                   8083:   
                   8084:   If $caller is 'uploadrep':  
                   8085:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   8086:     for request for files originally uploaded via DOCS. 
                   8087:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   8088:   
                   8089:   Otherwise:
                   8090:      This indicates a call from the content generation phase of the request.
                   8091:      -  returns the entire contents of the file or -1.
                   8092:      
                   8093: (b) files in /res
                   8094:    - returns the entire contents of a file or -1; 
                   8095:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 8096: 
1.712     albertel 8097: 
                   8098: =item *
                   8099: 
                   8100: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   8101:                   reference
                   8102: 
                   8103: returns either a stat() list of data about the file or an empty list
                   8104: if the file doesn't exist or couldn't find out about it (connection
                   8105: problems or user unknown)
                   8106: 
1.191     harris41 8107: =item *
                   8108: 
1.243     albertel 8109: filelocation($dir,$file) : returns file system location of a file
                   8110: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   8111: directory that relative $file lookups are to looked in ($dir of /a/dir
                   8112: and a file of ../bob will become /a/bob)
1.191     harris41 8113: 
                   8114: =item *
                   8115: 
                   8116: hreflocation($dir,$file) : returns file system location or a URL; same as
                   8117: filelocation except for hrefs
                   8118: 
                   8119: =item *
                   8120: 
                   8121: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   8122: 
1.243     albertel 8123: =back
                   8124: 
1.608     albertel 8125: =head2 Usererfile file routines (/uploaded*)
                   8126: 
                   8127: =over 4
                   8128: 
                   8129: =item *
                   8130: 
                   8131: userfileupload(): main rotine for putting a file in a user or course's
                   8132:                   filespace, arguments are,
                   8133: 
1.620     albertel 8134:  formname - required - this is the name of the element in $env where the
1.608     albertel 8135:            filename, and the contents of the file to create/modifed exist
1.620     albertel 8136:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   8137:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 8138:  coursedoc - if true, store the file in the course of the active role
                   8139:              of the current user
                   8140:  subdir - required - subdirectory to put the file in under ../userfiles/
                   8141:          if undefined, it will be placed in "unknown"
                   8142: 
                   8143:  (This routine calls clean_filename() to remove any dangerous
                   8144:  characters from the filename, and then calls finuserfileupload() to
                   8145:  complete the transaction)
                   8146: 
                   8147:  returns either the url of the uploaded file (/uploaded/....) if successful
                   8148:  and /adm/notfound.html if unsuccessful
                   8149: 
                   8150: =item *
                   8151: 
                   8152: clean_filename(): routine for cleaing a filename up for storage in
                   8153:                  userfile space, argument is:
                   8154: 
                   8155:  filename - proposed filename
                   8156: 
                   8157: returns: the new clean filename
                   8158: 
                   8159: =item *
                   8160: 
                   8161: finishuserfileupload(): routine that creaes and sends the file to
                   8162: userspace, probably shouldn't be called directly
                   8163: 
                   8164:   docuname: username or courseid of destination for the file
                   8165:   docudom: domain of user/course of destination for the file
                   8166:   formname: same as for userfileupload()
                   8167:   fname: filename (inculding subdirectories) for the file
                   8168: 
                   8169:  returns either the url of the uploaded file (/uploaded/....) if successful
                   8170:  and /adm/notfound.html if unsuccessful
                   8171: 
                   8172: =item *
                   8173: 
                   8174: renameuserfile(): renames an existing userfile to a new name
                   8175: 
                   8176:   Args:
                   8177:    docuname: username or courseid of destination for the file
                   8178:    docudom: domain of user/course of destination for the file
                   8179:    old: current file name (including any subdirs under userfiles)
                   8180:    new: desired file name (including any subdirs under userfiles)
                   8181: 
                   8182: =item *
                   8183: 
                   8184: mkdiruserfile(): creates a directory is a userfiles dir
                   8185: 
                   8186:   Args:
                   8187:    docuname: username or courseid of destination for the file
                   8188:    docudom: domain of user/course of destination for the file
                   8189:    dir: dir to create (including any subdirs under userfiles)
                   8190: 
                   8191: =item *
                   8192: 
                   8193: removeuserfile(): removes a file that exists in userfiles
                   8194: 
                   8195:   Args:
                   8196:    docuname: username or courseid of destination for the file
                   8197:    docudom: domain of user/course of destination for the file
                   8198:    fname: filname to delete (including any subdirs under userfiles)
                   8199: 
                   8200: =item *
                   8201: 
                   8202: removeuploadedurl(): convience function for removeuserfile()
                   8203: 
                   8204:   Args:
                   8205:    url:  a full /uploaded/... url to delete
                   8206: 
1.747     albertel 8207: =item * 
                   8208: 
                   8209: get_portfile_permissions():
                   8210:   Args:
                   8211:     domain: domain of user or course contain the portfolio files
                   8212:     user: name of user or num of course contain the portfolio files
                   8213:   Returns:
                   8214:     hashref of a dump of the proper file_permissions.db
                   8215:    
                   8216: 
                   8217: =item * 
                   8218: 
                   8219: get_access_controls():
                   8220: 
                   8221: Args:
                   8222:   current_permissions: the hash ref returned from get_portfile_permissions()
                   8223:   group: (optional) the group you want the files associated with
                   8224:   file: (optional) the file you want access info on
                   8225: 
                   8226: Returns:
1.749     raeburn  8227:     a hash (keys are file names) of hashes containing
                   8228:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   8229:         values are XML containing access control settings (see below) 
1.747     albertel 8230: 
                   8231: Internal notes:
                   8232: 
1.749     raeburn  8233:  access controls are stored in file_permissions.db as key=value pairs.
                   8234:     key -> path to file/file_name\0uniqueID:scope_end_start
                   8235:         where scope -> public,guest,course,group,domains or users.
                   8236:               end -> UNIX time for end of access (0 -> no end date)
                   8237:               start -> UNIX time for start of access
                   8238: 
                   8239:     value -> XML description of access control
                   8240:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   8241:             <start></start>
                   8242:             <end></end>
                   8243: 
                   8244:             <password></password>  for scope type = guest
                   8245: 
                   8246:             <domain></domain>     for scope type = course or group
                   8247:             <number></number>
                   8248:             <roles id="">
                   8249:              <role></role>
                   8250:              <access></access>
                   8251:              <section></section>
                   8252:              <group></group>
                   8253:             </roles>
                   8254: 
                   8255:             <dom></dom>         for scope type = domains
                   8256: 
                   8257:             <users>             for scope type = users
                   8258:              <user>
                   8259:               <uname></uname>
                   8260:               <udom></udom>
                   8261:              </user>
                   8262:             </users>
                   8263:            </scope> 
                   8264:               
                   8265:  Access data is also aggregated for each file in an additional key=value pair:
                   8266:  key -> path to file/file_name\0accesscontrol 
                   8267:  value -> reference to hash
                   8268:           hash contains key = value pairs
                   8269:           where key = uniqueID:scope_end_start
                   8270:                 value = UNIX time record was last updated
                   8271: 
                   8272:           Used to improve speed of look-ups of access controls for each file.  
                   8273:  
                   8274:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   8275: 
                   8276: modify_access_controls():
                   8277: 
                   8278: Modifies access controls for a portfolio file
                   8279: Args
                   8280: 1. file name
                   8281: 2. reference to hash of required changes,
                   8282: 3. domain
                   8283: 4. username
                   8284:   where domain,username are the domain of the portfolio owner 
                   8285:   (either a user or a course) 
                   8286: 
                   8287: Returns:
                   8288: 1. result of additions or updates ('ok' or 'error', with error message). 
                   8289: 2. result of deletions ('ok' or 'error', with error message).
                   8290: 3. reference to hash of any new or updated access controls.
                   8291: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   8292:    key = integer (inbound ID)
                   8293:    value = uniqueID  
1.747     albertel 8294: 
1.608     albertel 8295: =back
                   8296: 
1.243     albertel 8297: =head2 HTTP Helper Routines
                   8298: 
                   8299: =over 4
                   8300: 
1.191     harris41 8301: =item *
                   8302: 
                   8303: escape() : unpack non-word characters into CGI-compatible hex codes
                   8304: 
                   8305: =item *
                   8306: 
                   8307: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   8308: 
1.243     albertel 8309: =back
                   8310: 
                   8311: =head1 PRIVATE SUBROUTINES
                   8312: 
                   8313: =head2 Underlying communication routines (Shouldn't call)
                   8314: 
                   8315: =over 4
                   8316: 
                   8317: =item *
                   8318: 
                   8319: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   8320: 
                   8321: =item *
                   8322: 
                   8323: reply() : uses subreply to send a message to remote machine, logs all failures
                   8324: 
                   8325: =item *
                   8326: 
                   8327: critical() : passes a critical message to another server; if cannot
                   8328: get through then place message in connection buffer directory and
                   8329: returns con_delayed, if incapable of saving message, returns
                   8330: con_failed
                   8331: 
                   8332: =item *
                   8333: 
                   8334: reconlonc() : tries to reconnect lonc client processes.
                   8335: 
                   8336: =back
                   8337: 
                   8338: =head2 Resource Access Logging
                   8339: 
                   8340: =over 4
                   8341: 
                   8342: =item *
                   8343: 
                   8344: flushcourselogs() : flush (save) buffer logs and access logs
                   8345: 
                   8346: =item *
                   8347: 
                   8348: courselog($what) : save message for course in hash
                   8349: 
                   8350: =item *
                   8351: 
                   8352: courseacclog($what) : save message for course using &courselog().  Perform
                   8353: special processing for specific resource types (problems, exams, quizzes, etc).
                   8354: 
1.191     harris41 8355: =item *
                   8356: 
                   8357: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   8358: as a PerlChildExitHandler
1.243     albertel 8359: 
                   8360: =back
                   8361: 
                   8362: =head2 Other
                   8363: 
                   8364: =over 4
                   8365: 
                   8366: =item *
                   8367: 
                   8368: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 8369: 
                   8370: =back
                   8371: 
                   8372: =cut

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