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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.782.2.4! albertel    4: # $Id: lonnet.pm,v 1.782.2.3 2006/10/04 19:52:08 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
1.780     albertel  296: my $env_loaded;
                    297: sub transfer_profile_to_env {
1.782.2.3  albertel  298:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    299:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       300: 
1.720     albertel  301:     if (!defined($lonidsdir)) {
                    302: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    303:     }
                    304:     if (!defined($handle)) {
                    305:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    306:     }
                    307: 
1.374     www       308:     my @profile;
                    309:     {
1.448     albertel  310: 	open(my $idf,"$lonidsdir/$handle.id");
1.374     www       311: 	flock($idf,LOCK_SH);
                    312: 	@profile=<$idf>;
1.448     albertel  313: 	close($idf);
1.374     www       314:     }
                    315:     my $envi;
1.433     matthew   316:     my %Remove;
1.374     www       317:     for ($envi=0;$envi<=$#profile;$envi++) {
                    318: 	chomp($profile[$envi]);
1.690     albertel  319: 	my ($envname,$envvalue)=split(/=/,$profile[$envi],2);
1.726     albertel  320: 	$envname=&unescape($envname);
                    321: 	$envvalue=&unescape($envvalue);
1.619     albertel  322: 	$env{$envname} = $envvalue;
1.433     matthew   323:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    324:             if ($time < time-300) {
                    325:                 $Remove{$key}++;
                    326:             }
                    327:         }
                    328:     }
1.619     albertel  329:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  330:     $env_loaded=1;
1.433     matthew   331:     foreach my $expired_key (keys(%Remove)) {
                    332:         &delenv($expired_key);
1.374     www       333:     }
1.1       albertel  334: }
                    335: 
1.5       www       336: # ---------------------------------------------------------- Append Environment
                    337: 
                    338: sub appenv {
1.6       www       339:     my %newenv=@_;
1.692     albertel  340:     foreach my $key (keys(%newenv)) {
                    341: 	if (($newenv{$key}=~/^user\.role/) || ($newenv{$key}=~/^user\.priv/)) {
1.672     albertel  342:             &logthis("<font color=\"blue\">WARNING: ".
1.692     albertel  343:                 "Attempt to modify environment ".$key." to ".$newenv{$key}
1.151     www       344:                 .'</font>');
1.692     albertel  345: 	    delete($newenv{$key});
1.35      www       346:         } else {
1.692     albertel  347:             $env{$key}=$newenv{$key};
1.35      www       348:         }
1.191     harris41  349:     }
1.779     albertel  350:     foreach my $key (keys(%newenv)) {
                    351: 	my $value = &escape($newenv{$key});
                    352: 	delete($newenv{$key});
                    353: 	$newenv{&escape($key)}=$value;
                    354:     }
1.95      www       355: 
                    356:     my $lockfh;
1.620     albertel  357:     unless (open($lockfh,"$env{'user.environment'}")) {
1.448     albertel  358: 	return 'error: '.$!;
1.95      www       359:     }
                    360:     unless (flock($lockfh,LOCK_EX)) {
1.672     albertel  361:          &logthis("<font color=\"blue\">WARNING: ".
1.95      www       362:                   'Could not obtain exclusive lock in appenv: '.$!);
1.448     albertel  363:          close($lockfh);
1.95      www       364:          return 'error: '.$!;
                    365:     }
                    366: 
1.6       www       367:     my @oldenv;
                    368:     {
1.448     albertel  369: 	my $fh;
1.620     albertel  370: 	unless (open($fh,"$env{'user.environment'}")) {
1.448     albertel  371: 	    return 'error: '.$!;
                    372: 	}
                    373: 	@oldenv=<$fh>;
                    374: 	close($fh);
1.6       www       375:     }
                    376:     for (my $i=0; $i<=$#oldenv; $i++) {
                    377:         chomp($oldenv[$i]);
1.9       www       378:         if ($oldenv[$i] ne '') {
1.690     albertel  379: 	    my ($name,$value)=split(/=/,$oldenv[$i],2);
1.448     albertel  380: 	    unless (defined($newenv{$name})) {
                    381: 		$newenv{$name}=$value;
                    382: 	    }
1.9       www       383:         }
1.6       www       384:     }
                    385:     {
1.448     albertel  386: 	my $fh;
1.620     albertel  387: 	unless (open($fh,">$env{'user.environment'}")) {
1.448     albertel  388: 	    return 'error';
                    389: 	}
                    390: 	my $newname;
                    391: 	foreach $newname (keys %newenv) {
1.779     albertel  392: 	    print $fh $newname.'='.$newenv{$newname}."\n";
1.448     albertel  393: 	}
                    394: 	close($fh);
1.56      www       395:     }
1.448     albertel  396: 	
                    397:     close($lockfh);
1.56      www       398:     return 'ok';
                    399: }
                    400: # ----------------------------------------------------- Delete from Environment
                    401: 
                    402: sub delenv {
                    403:     my $delthis=shift;
                    404:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
1.672     albertel  405:         &logthis("<font color=\"blue\">WARNING: ".
1.56      www       406:                 "Attempt to delete from environment ".$delthis);
                    407:         return 'error';
                    408:     }
                    409:     my @oldenv;
                    410:     {
1.448     albertel  411: 	my $fh;
1.620     albertel  412: 	unless (open($fh,"$env{'user.environment'}")) {
1.448     albertel  413: 	    return 'error';
                    414: 	}
                    415: 	unless (flock($fh,LOCK_SH)) {
1.672     albertel  416: 	    &logthis("<font color=\"blue\">WARNING: ".
1.448     albertel  417: 		     'Could not obtain shared lock in delenv: '.$!);
                    418: 	    close($fh);
                    419: 	    return 'error: '.$!;
                    420: 	}
                    421: 	@oldenv=<$fh>;
                    422: 	close($fh);
1.56      www       423:     }
                    424:     {
1.448     albertel  425: 	my $fh;
1.620     albertel  426: 	unless (open($fh,">$env{'user.environment'}")) {
1.448     albertel  427: 	    return 'error';
                    428: 	}
                    429: 	unless (flock($fh,LOCK_EX)) {
1.672     albertel  430: 	    &logthis("<font color=\"blue\">WARNING: ".
1.448     albertel  431: 		     'Could not obtain exclusive lock in delenv: '.$!);
                    432: 	    close($fh);
                    433: 	    return 'error: '.$!;
                    434: 	}
1.692     albertel  435: 	foreach my $cur_key (@oldenv) {
1.726     albertel  436: 	    my $unescaped_cur_key = &unescape($cur_key);
                    437: 	    if ($unescaped_cur_key=~/^$delthis/) { 
                    438:                 my ($key) = split('=',$cur_key,2);
                    439: 		$key = &unescape($key);
1.619     albertel  440:                 delete($env{$key});
1.473     matthew   441:             } else {
1.692     albertel  442:                 print $fh $cur_key; 
1.473     matthew   443:             }
1.448     albertel  444: 	}
                    445: 	close($fh);
1.5       www       446:     }
                    447:     return 'ok';
1.369     albertel  448: }
                    449: 
                    450: # ------------------------------------------ Find out current server userload
                    451: # there is a copy in lond
                    452: sub userload {
                    453:     my $numusers=0;
                    454:     {
                    455: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    456: 	my $filename;
                    457: 	my $curtime=time;
                    458: 	while ($filename=readdir(LONIDS)) {
                    459: 	    if ($filename eq '.' || $filename eq '..') {next;}
1.404     albertel  460: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  461: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  462: 	}
                    463: 	closedir(LONIDS);
                    464:     }
                    465:     my $userloadpercent=0;
                    466:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    467:     if ($maxuserload) {
1.371     albertel  468: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  469:     }
1.372     albertel  470:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  471:     return $userloadpercent;
1.283     www       472: }
                    473: 
                    474: # ------------------------------------------ Fight off request when overloaded
                    475: 
                    476: sub overloaderror {
                    477:     my ($r,$checkserver)=@_;
                    478:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
                    479:     my $loadavg;
                    480:     if ($checkserver eq $perlvar{'lonHostID'}) {
1.448     albertel  481:        open(my $loadfile,'/proc/loadavg');
1.283     www       482:        $loadavg=<$loadfile>;
                    483:        $loadavg =~ s/\s.*//g;
1.285     matthew   484:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
1.448     albertel  485:        close($loadfile);
1.283     www       486:     } else {
                    487:        $loadavg=&reply('load',$checkserver);
                    488:     }
1.285     matthew   489:     my $overload=$loadavg-100;
1.283     www       490:     if ($overload>0) {
1.285     matthew   491: 	$r->err_headers_out->{'Retry-After'}=$overload;
1.283     www       492:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
1.554     www       493:         return 413;
1.283     www       494:     }    
                    495:     return '';
1.5       www       496: }
1.1       albertel  497: 
                    498: # ------------------------------ Find server with least workload from spare.tab
1.11      www       499: 
1.1       albertel  500: sub spareserver {
1.670     albertel  501:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
1.782.2.1  albertel  502:     my $spare_server;
1.370     albertel  503:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.782.2.1  albertel  504:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    505:                                                      :  $userloadpercent;
                    506:     
                    507:     foreach my $try_server (@{ $spareid{'primary'} }) {
                    508: 	($spare_server, $lowest_load) =
                    509: 	    &compare_server_load($try_server, $spare_server, $lowest_load);
                    510:     }
                    511: 
                    512:     my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    513: 
                    514:     if (!$found_server) {
                    515: 	foreach my $try_server (@{ $spareid{'default'} }) {
                    516: 	    ($spare_server, $lowest_load) =
                    517: 		&compare_server_load($try_server, $spare_server, $lowest_load);
1.411     albertel  518: 	}
1.370     albertel  519:     }
1.782.2.1  albertel  520: 
                    521:     if (!$want_server_name) {
                    522: 	$spare_server="http://$hostname{$spare_server}";
                    523:     }
                    524:     return $spare_server;
1.202     matthew   525: }
                    526: 
1.782.2.1  albertel  527: sub compare_server_load {
                    528:     my ($try_server, $spare_server, $lowest_load) = @_;
                    529: 
                    530:     my $loadans     = &reply('load',    $try_server);
                    531:     my $userloadans = &reply('userload',$try_server);
                    532: 
                    533:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
                    534: 	next; #didn't get a number from the server
                    535:     }
                    536: 
                    537:     my $load;
                    538:     if ($loadans =~ /\d/) {
                    539: 	if ($userloadans =~ /\d/) {
                    540: 	    #both are numbers, pick the bigger one
                    541: 	    $load = ($loadans > $userloadans) ? $loadans 
                    542: 		                              : $userloadans;
                    543: 	} else {
                    544: 	    $load = $loadans;
                    545: 	}
                    546:     } else {
                    547: 	$load = $userloadans;
                    548:     }
                    549: 
                    550:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    551: 	$spare_server = $try_server;
                    552: 	$lowest_load  = $load;
                    553:     }
                    554:     return ($spare_server,$lowest_load);
                    555: }
1.202     matthew   556: # --------------------------------------------- Try to change a user's password
                    557: 
                    558: sub changepass {
                    559:     my ($uname,$udom,$currentpass,$newpass,$server)=@_;
                    560:     $currentpass = &escape($currentpass);
                    561:     $newpass     = &escape($newpass);
                    562:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass",
                    563: 		       $server);
                    564:     if (! $answer) {
                    565: 	&logthis("No reply on password change request to $server ".
                    566: 		 "by $uname in domain $udom.");
                    567:     } elsif ($answer =~ "^ok") {
                    568:         &logthis("$uname in $udom successfully changed their password ".
                    569: 		 "on $server.");
                    570:     } elsif ($answer =~ "^pwchange_failure") {
                    571: 	&logthis("$uname in $udom was unable to change their password ".
                    572: 		 "on $server.  The action was blocked by either lcpasswd ".
                    573: 		 "or pwchange");
                    574:     } elsif ($answer =~ "^non_authorized") {
                    575:         &logthis("$uname in $udom did not get their password correct when ".
                    576: 		 "attempting to change it on $server.");
                    577:     } elsif ($answer =~ "^auth_mode_error") {
                    578:         &logthis("$uname in $udom attempted to change their password despite ".
                    579: 		 "not being locally or internally authenticated on $server.");
                    580:     } elsif ($answer =~ "^unknown_user") {
                    581:         &logthis("$uname in $udom attempted to change their password ".
                    582: 		 "on $server but were unable to because $server is not ".
                    583: 		 "their home server.");
                    584:     } elsif ($answer =~ "^refused") {
                    585: 	&logthis("$server refused to change $uname in $udom password because ".
                    586: 		 "it was sent an unencrypted request to change the password.");
                    587:     }
                    588:     return $answer;
1.1       albertel  589: }
                    590: 
1.169     harris41  591: # ----------------------- Try to determine user's current authentication scheme
                    592: 
                    593: sub queryauthenticate {
                    594:     my ($uname,$udom)=@_;
1.456     albertel  595:     my $uhome=&homeserver($uname,$udom);
                    596:     if (!$uhome) {
                    597: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                    598: 	return 'no_host';
                    599:     }
                    600:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                    601:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                    602: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41  603:     }
1.456     albertel  604:     return $answer;
1.169     harris41  605: }
                    606: 
1.1       albertel  607: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www       608: 
1.1       albertel  609: sub authenticate {
                    610:     my ($uname,$upass,$udom)=@_;
1.12      www       611:     $upass=escape($upass);
1.199     www       612:     $uname=~s/\W//g;
1.471     albertel  613:     my $uhome=&homeserver($uname,$udom);
                    614:     if (!$uhome) {
                    615: 	&logthis("User $uname at $udom is unknown in authenticate");
                    616: 	return 'no_host';
1.1       albertel  617:     }
1.471     albertel  618:     my $answer=reply("encrypt:auth:$udom:$uname:$upass",$uhome);
                    619:     if ($answer eq 'authorized') {
                    620: 	&logthis("User $uname at $udom authorized by $uhome"); 
                    621: 	return $uhome; 
                    622:     }
                    623:     if ($answer eq 'non_authorized') {
                    624: 	&logthis("User $uname at $udom rejected by $uhome");
                    625: 	return 'no_host'; 
1.9       www       626:     }
1.471     albertel  627:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel  628:     return 'no_host';
                    629: }
                    630: 
                    631: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www       632: 
1.599     albertel  633: my %homecache;
1.1       albertel  634: sub homeserver {
1.230     stredwic  635:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel  636:     my $index="$uname:$udom";
1.426     albertel  637: 
1.599     albertel  638:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.1       albertel  639:     my $tryserver;
                    640:     foreach $tryserver (keys %libserv) {
1.230     stredwic  641:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic  642: 		 exists($badServerCache{$tryserver}));
1.1       albertel  643: 	if ($hostdom{$tryserver} eq $udom) {
                    644:            my $answer=reply("home:$udom:$uname",$tryserver);
                    645:            if ($answer eq 'found') { 
1.599     albertel  646: 	       return $homecache{$index}=$tryserver;
1.231     stredwic  647:            } elsif ($answer eq 'no_host') {
                    648: 	       $badServerCache{$tryserver}=1;
1.221     matthew   649:            }
1.1       albertel  650:        }
                    651:     }    
                    652:     return 'no_host';
1.70      www       653: }
                    654: 
                    655: # ------------------------------------- Find the usernames behind a list of IDs
                    656: 
                    657: sub idget {
                    658:     my ($udom,@ids)=@_;
                    659:     my %returnhash=();
                    660:     
                    661:     my $tryserver;
                    662:     foreach $tryserver (keys %libserv) {
                    663:        if ($hostdom{$tryserver} eq $udom) {
                    664: 	  my $idlist=join('&',@ids);
                    665:           $idlist=~tr/A-Z/a-z/; 
                    666: 	  my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                    667:           my @answer=();
1.76      www       668:           if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1.70      www       669: 	      @answer=split(/\&/,$reply);
                    670:           }                    ;
                    671:           my $i;
                    672:           for ($i=0;$i<=$#ids;$i++) {
                    673:               if ($answer[$i]) {
                    674: 		  $returnhash{$ids[$i]}=$answer[$i];
                    675:               } 
                    676:           }
                    677:        }
                    678:     }    
                    679:     return %returnhash;
                    680: }
                    681: 
                    682: # ------------------------------------- Find the IDs behind a list of usernames
                    683: 
                    684: sub idrget {
                    685:     my ($udom,@unames)=@_;
                    686:     my %returnhash=();
1.191     harris41  687:     foreach (@unames) {
1.70      www       688:         $returnhash{$_}=(&userenvironment($udom,$_,'id'))[1];
1.191     harris41  689:     }
1.70      www       690:     return %returnhash;
                    691: }
                    692: 
                    693: # ------------------------------- Store away a list of names and associated IDs
                    694: 
                    695: sub idput {
                    696:     my ($udom,%ids)=@_;
                    697:     my %servers=();
1.191     harris41  698:     foreach (keys %ids) {
1.487     albertel  699: 	&cput('environment',{'id'=>$ids{$_}},$udom,$_);
1.70      www       700:         my $uhom=&homeserver($_,$udom);
                    701:         if ($uhom ne 'no_host') {
                    702:             my $id=&escape($ids{$_});
                    703:             $id=~tr/A-Z/a-z/;
                    704:             my $unam=&escape($_);
                    705: 	    if ($servers{$uhom}) {
                    706: 		$servers{$uhom}.='&'.$id.'='.$unam;
                    707:             } else {
                    708:                 $servers{$uhom}=$id.'='.$unam;
                    709:             }
                    710:         }
1.191     harris41  711:     }
                    712:     foreach (keys %servers) {
1.70      www       713:         &critical('idput:'.$udom.':'.$servers{$_},$_);
1.191     harris41  714:     }
1.344     www       715: }
                    716: 
                    717: # --------------------------------------------------- Assign a key to a student
                    718: 
                    719: sub assign_access_key {
1.364     www       720: #
                    721: # a valid key looks like uname:udom#comments
                    722: # comments are being appended
                    723: #
1.498     www       724:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                    725:     $kdom=
1.620     albertel  726:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www       727:     $knum=
1.620     albertel  728:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www       729:     $cdom=
1.620     albertel  730:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       731:     $cnum=
1.620     albertel  732:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                    733:     $udom=$env{'user.name'} unless (defined($udom));
                    734:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www       735:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www       736:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel  737:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www       738:                                                   # assigned to this person
                    739:                                                   # - this should not happen,
1.345     www       740:                                                   # unless something went wrong
                    741:                                                   # the first time around
                    742: # ready to assign
1.364     www       743:         $logentry=$1.'; '.$logentry;
1.496     www       744:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www       745:                                                  $kdom,$knum) eq 'ok') {
1.345     www       746: # key now belongs to user
1.346     www       747: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www       748:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
                    749:                 &appenv('environment.'.$envkey => $ckey);
                    750:                 return 'ok';
                    751:             } else {
                    752:                 return 
                    753:   'error: Count not permanently assign key, will need to be re-entered later.';
                    754: 	    }
                    755:         } else {
                    756:             return 'error: Could not assign key, try again later.';
                    757:         }
1.364     www       758:     } elsif (!$existing{$ckey}) {
1.345     www       759: # the key does not exist
                    760: 	return 'error: The key does not exist';
                    761:     } else {
                    762: # the key is somebody else's
                    763: 	return 'error: The key is already in use';
                    764:     }
1.344     www       765: }
                    766: 
1.364     www       767: # ------------------------------------------ put an additional comment on a key
                    768: 
                    769: sub comment_access_key {
                    770: #
                    771: # a valid key looks like uname:udom#comments
                    772: # comments are being appended
                    773: #
                    774:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                    775:     $cdom=
1.620     albertel  776:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www       777:     $cnum=
1.620     albertel  778:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www       779:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                    780:     if ($existing{$ckey}) {
                    781:         $existing{$ckey}.='; '.$logentry;
                    782: # ready to assign
1.367     www       783:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www       784:                                                  $cdom,$cnum) eq 'ok') {
                    785: 	    return 'ok';
                    786:         } else {
                    787: 	    return 'error: Count not store comment.';
                    788:         }
                    789:     } else {
                    790: # the key does not exist
                    791: 	return 'error: The key does not exist';
                    792:     }
                    793: }
                    794: 
1.344     www       795: # ------------------------------------------------------ Generate a set of keys
                    796: 
                    797: sub generate_access_keys {
1.364     www       798:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www       799:     $cdom=
1.620     albertel  800:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       801:     $cnum=
1.620     albertel  802:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www       803:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www       804:     unless (($cdom) && ($cnum)) { return 0; }
                    805:     if ($number>10000) { return 0; }
                    806:     sleep(2); # make sure don't get same seed twice
                    807:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                    808:     my $total=0;
                    809:     for (my $i=1;$i<=$number;$i++) {
                    810:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                    811:                   sprintf("%lx",int(100000*rand)).'-'.
                    812:                   sprintf("%lx",int(100000*rand));
                    813:        $newkey=~s/1/g/g; # folks mix up 1 and l
                    814:        $newkey=~s/0/h/g; # and also 0 and O
                    815:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                    816:        if ($existing{$newkey}) {
                    817:            $i--;
                    818:        } else {
1.364     www       819: 	  if (&put('accesskeys',
                    820:               { $newkey => '# generated '.localtime().
1.620     albertel  821:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www       822:                            '; '.$logentry },
                    823: 		   $cdom,$cnum) eq 'ok') {
1.344     www       824:               $total++;
                    825: 	  }
                    826:        }
                    827:     }
1.620     albertel  828:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www       829:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                    830:     return $total;
                    831: }
                    832: 
                    833: # ------------------------------------------------------- Validate an accesskey
                    834: 
                    835: sub validate_access_key {
                    836:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                    837:     $cdom=
1.620     albertel  838:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       839:     $cnum=
1.620     albertel  840:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                    841:     $udom=$env{'user.domain'} unless (defined($udom));
                    842:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www       843:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel  844:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www       845: }
                    846: 
                    847: # ------------------------------------- Find the section of student in a course
1.652     albertel  848: sub devalidate_getsection_cache {
                    849:     my ($udom,$unam,$courseid)=@_;
                    850:     $courseid=~s/\_/\//g;
                    851:     $courseid=~s/^(\w)/\/$1/;
                    852:     my $hashid="$udom:$unam:$courseid";
                    853:     &devalidate_cache_new('getsection',$hashid);
                    854: }
1.298     matthew   855: 
                    856: sub getsection {
                    857:     my ($udom,$unam,$courseid)=@_;
1.599     albertel  858:     my $cachetime=1800;
1.298     matthew   859:     $courseid=~s/\_/\//g;
                    860:     $courseid=~s/^(\w)/\/$1/;
1.551     albertel  861: 
                    862:     my $hashid="$udom:$unam:$courseid";
1.599     albertel  863:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel  864:     if (defined($cached)) { return $result; }
                    865: 
1.298     matthew   866:     my %Pending; 
                    867:     my %Expired;
                    868:     #
                    869:     # Each role can either have not started yet (pending), be active, 
                    870:     #    or have expired.
                    871:     #
                    872:     # If there is an active role, we are done.
                    873:     #
                    874:     # If there is more than one role which has not started yet, 
                    875:     #     choose the one which will start sooner
                    876:     # If there is one role which has not started yet, return it.
                    877:     #
                    878:     # If there is more than one expired role, choose the one which ended last.
                    879:     # If there is a role which has expired, return it.
                    880:     #
                    881:     foreach (split(/\&/,&reply('dump:'.$udom.':'.$unam.':roles',
                    882:                         &homeserver($unam,$udom)))) {
                    883:         my ($key,$value)=split(/\=/,$_);
                    884:         $key=&unescape($key);
1.479     albertel  885:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew   886:         my $section=$1;
                    887:         if ($key eq $courseid.'_st') { $section=''; }
                    888:         my ($dummy,$end,$start)=split(/\_/,&unescape($value));
                    889:         my $now=time;
1.548     albertel  890:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew   891:             $Expired{$end}=$section;
                    892:             next;
                    893:         }
1.548     albertel  894:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew   895:             $Pending{$start}=$section;
                    896:             next;
                    897:         }
1.599     albertel  898:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew   899:     }
                    900:     #
                    901:     # Presumedly there will be few matching roles from the above
                    902:     # loop and the sorting time will be negligible.
                    903:     if (scalar(keys(%Pending))) {
                    904:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel  905:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew   906:     } 
                    907:     if (scalar(keys(%Expired))) {
                    908:         my @sorted = sort {$a <=> $b} keys(%Expired);
                    909:         my $time = pop(@sorted);
1.599     albertel  910:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew   911:     }
1.599     albertel  912:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew   913: }
1.70      www       914: 
1.599     albertel  915: sub save_cache {
                    916:     &purge_remembered();
1.722     albertel  917:     #&Apache::loncommon::validate_page();
1.620     albertel  918:     undef(%env);
1.780     albertel  919:     undef($env_loaded);
1.599     albertel  920: }
1.452     albertel  921: 
1.599     albertel  922: my $to_remember=-1;
                    923: my %remembered;
                    924: my %accessed;
                    925: my $kicks=0;
                    926: my $hits=0;
                    927: sub devalidate_cache_new {
                    928:     my ($name,$id,$debug) = @_;
                    929:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
                    930:     $id=&escape($name.':'.$id);
                    931:     $memcache->delete($id);
                    932:     delete($remembered{$id});
                    933:     delete($accessed{$id});
                    934: }
                    935: 
                    936: sub is_cached_new {
                    937:     my ($name,$id,$debug) = @_;
                    938:     $id=&escape($name.':'.$id);
                    939:     if (exists($remembered{$id})) {
                    940: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                    941: 	$accessed{$id}=[&gettimeofday()];
                    942: 	$hits++;
                    943: 	return ($remembered{$id},1);
                    944:     }
                    945:     my $value = $memcache->get($id);
                    946:     if (!(defined($value))) {
                    947: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel  948: 	return (undef,undef);
1.416     albertel  949:     }
1.599     albertel  950:     if ($value eq '__undef__') {
                    951: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                    952: 	$value=undef;
                    953:     }
                    954:     &make_room($id,$value,$debug);
                    955:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                    956:     return ($value,1);
                    957: }
                    958: 
                    959: sub do_cache_new {
                    960:     my ($name,$id,$value,$time,$debug) = @_;
                    961:     $id=&escape($name.':'.$id);
                    962:     my $setvalue=$value;
                    963:     if (!defined($setvalue)) {
                    964: 	$setvalue='__undef__';
                    965:     }
1.623     albertel  966:     if (!defined($time) ) {
                    967: 	$time=600;
                    968:     }
1.599     albertel  969:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.600     albertel  970:     $memcache->set($id,$setvalue,$time);
                    971:     # need to make a copy of $value
                    972:     #&make_room($id,$value,$debug);
1.599     albertel  973:     return $value;
                    974: }
                    975: 
                    976: sub make_room {
                    977:     my ($id,$value,$debug)=@_;
                    978:     $remembered{$id}=$value;
                    979:     if ($to_remember<0) { return; }
                    980:     $accessed{$id}=[&gettimeofday()];
                    981:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                    982:     my $to_kick;
                    983:     my $max_time=0;
                    984:     foreach my $other (keys(%accessed)) {
                    985: 	if (&tv_interval($accessed{$other}) > $max_time) {
                    986: 	    $to_kick=$other;
                    987: 	    $max_time=&tv_interval($accessed{$other});
                    988: 	}
                    989:     }
                    990:     delete($remembered{$to_kick});
                    991:     delete($accessed{$to_kick});
                    992:     $kicks++;
                    993:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel  994:     return;
                    995: }
                    996: 
1.599     albertel  997: sub purge_remembered {
1.604     albertel  998:     #&logthis("Tossing ".scalar(keys(%remembered)));
                    999:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 1000:     undef(%remembered);
                   1001:     undef(%accessed);
1.428     albertel 1002: }
1.70      www      1003: # ------------------------------------- Read an entry from a user's environment
                   1004: 
                   1005: sub userenvironment {
                   1006:     my ($udom,$unam,@what)=@_;
                   1007:     my %returnhash=();
                   1008:     my @answer=split(/\&/,
                   1009:                 &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
                   1010:                       &homeserver($unam,$udom)));
                   1011:     my $i;
                   1012:     for ($i=0;$i<=$#what;$i++) {
                   1013: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
                   1014:     }
                   1015:     return %returnhash;
1.1       albertel 1016: }
                   1017: 
1.617     albertel 1018: # ---------------------------------------------------------- Get a studentphoto
                   1019: sub studentphoto {
                   1020:     my ($udom,$unam,$ext) = @_;
                   1021:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  1022:     if (defined($env{'request.course.id'})) {
1.708     raeburn  1023:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  1024:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   1025:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   1026:             } else {
                   1027:                 my ($result,$perm_reqd)=
1.707     albertel 1028: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1029:                 if ($result eq 'ok') {
                   1030:                     if (!($perm_reqd eq 'yes')) {
                   1031:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   1032:                     }
                   1033:                 }
                   1034:             }
                   1035:         }
                   1036:     } else {
                   1037:         my ($result,$perm_reqd) = 
1.707     albertel 1038: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1039:         if ($result eq 'ok') {
                   1040:             if (!($perm_reqd eq 'yes')) {
                   1041:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   1042:             }
                   1043:         }
                   1044:     }
                   1045:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   1046: }
                   1047: 
                   1048: sub retrievestudentphoto {
                   1049:     my ($udom,$unam,$ext,$type) = @_;
                   1050:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   1051:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   1052:     if ($ret eq 'ok') {
                   1053:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   1054:         if ($type eq 'thumbnail') {
                   1055:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   1056:         }
                   1057:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   1058:         return $tokenurl;
                   1059:     } else {
                   1060:         if ($type eq 'thumbnail') {
                   1061:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   1062:         } else { 
                   1063:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   1064:         }
1.617     albertel 1065:     }
                   1066: }
                   1067: 
1.263     www      1068: # -------------------------------------------------------------------- New chat
                   1069: 
                   1070: sub chatsend {
1.724     raeburn  1071:     my ($newentry,$anon,$group)=@_;
1.620     albertel 1072:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1073:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1074:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      1075:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 1076: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  1077: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      1078: }
                   1079: 
                   1080: # ------------------------------------------ Find current version of a resource
                   1081: 
                   1082: sub getversion {
                   1083:     my $fname=&clutter(shift);
                   1084:     unless ($fname=~/^\/res\//) { return -1; }
                   1085:     return &currentversion(&filelocation('',$fname));
                   1086: }
                   1087: 
                   1088: sub currentversion {
                   1089:     my $fname=shift;
1.599     albertel 1090:     my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440     www      1091:     if (defined($cached)) { return $result; }
1.292     www      1092:     my $author=$fname;
                   1093:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1094:     my ($udom,$uname)=split(/\//,$author);
                   1095:     my $home=homeserver($uname,$udom);
                   1096:     if ($home eq 'no_host') { 
                   1097:         return -1; 
                   1098:     }
                   1099:     my $answer=reply("currentversion:$fname",$home);
                   1100:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1101: 	return -1;
                   1102:     }
1.599     albertel 1103:     return &do_cache_new('resversion',$fname,$answer,600);
1.263     www      1104: }
                   1105: 
1.1       albertel 1106: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      1107: 
1.1       albertel 1108: sub subscribe {
                   1109:     my $fname=shift;
1.761     raeburn  1110:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 1111:     $fname=~s/[\n\r]//g;
1.1       albertel 1112:     my $author=$fname;
                   1113:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1114:     my ($udom,$uname)=split(/\//,$author);
                   1115:     my $home=homeserver($uname,$udom);
1.335     albertel 1116:     if ($home eq 'no_host') {
                   1117:         return 'not_found';
1.1       albertel 1118:     }
                   1119:     my $answer=reply("sub:$fname",$home);
1.64      www      1120:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1121: 	$answer.=' by '.$home;
                   1122:     }
1.1       albertel 1123:     return $answer;
                   1124: }
                   1125:     
1.8       www      1126: # -------------------------------------------------------------- Replicate file
                   1127: 
                   1128: sub repcopy {
                   1129:     my $filename=shift;
1.23      www      1130:     $filename=~s/\/+/\//g;
1.607     raeburn  1131:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   1132:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 1133:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 1134: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 1135: 	return &repcopy_userfile($filename);
                   1136:     }
1.532     albertel 1137:     $filename=~s/[\n\r]//g;
1.8       www      1138:     my $transname="$filename.in.transfer";
1.607     raeburn  1139:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      1140:     my $remoteurl=subscribe($filename);
1.64      www      1141:     if ($remoteurl =~ /^con_lost by/) {
                   1142: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1143:            return 'unavailable';
1.8       www      1144:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 1145: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  1146: 	   return 'not_found';
1.64      www      1147:     } elsif ($remoteurl =~ /^rejected by/) {
                   1148: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1149:            return 'forbidden';
1.20      www      1150:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  1151:            return 'ok';
1.8       www      1152:     } else {
1.290     www      1153:         my $author=$filename;
                   1154:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1155:         my ($udom,$uname)=split(/\//,$author);
                   1156:         my $home=homeserver($uname,$udom);
                   1157:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      1158:            my @parts=split(/\//,$filename);
                   1159:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   1160:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   1161:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  1162: 	       return 'bad_request';
1.8       www      1163:            }
                   1164:            my $count;
                   1165:            for ($count=5;$count<$#parts;$count++) {
                   1166:                $path.="/$parts[$count]";
                   1167:                if ((-e $path)!=1) {
                   1168: 		   mkdir($path,0777);
                   1169:                }
                   1170:            }
                   1171:            my $ua=new LWP::UserAgent;
                   1172:            my $request=new HTTP::Request('GET',"$remoteurl");
                   1173:            my $response=$ua->request($request,$transname);
                   1174:            if ($response->is_error()) {
                   1175: 	       unlink($transname);
                   1176:                my $message=$response->status_line;
1.672     albertel 1177:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      1178:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  1179:                return 'unavailable';
1.8       www      1180:            } else {
1.16      www      1181: 	       if ($remoteurl!~/\.meta$/) {
                   1182:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   1183:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   1184:                   if ($mresponse->is_error()) {
                   1185: 		      unlink($filename.'.meta');
                   1186:                       &logthis(
1.672     albertel 1187:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      1188:                   }
                   1189: 	       }
1.8       www      1190:                rename($transname,$filename);
1.607     raeburn  1191:                return 'ok';
1.8       www      1192:            }
1.290     www      1193:        }
1.8       www      1194:     }
1.330     www      1195: }
                   1196: 
                   1197: # ------------------------------------------------ Get server side include body
                   1198: sub ssi_body {
1.381     albertel 1199:     my ($filelink,%form)=@_;
1.606     matthew  1200:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   1201:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   1202:     }
1.330     www      1203:     my $output=($filelink=~/^http\:/?&externalssi($filelink):
1.381     albertel 1204:                                      &ssi($filelink,%form));
1.778     albertel 1205:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 1206:     $output=~s/^.*?\<body[^\>]*\>//si;
                   1207:     $output=~s/(.*)\<\/body\s*\>.*?$/$1/si;
1.330     www      1208:     return $output;
1.8       www      1209: }
                   1210: 
1.15      www      1211: # --------------------------------------------------------- Server Side Include
                   1212: 
1.782     albertel 1213: sub absolute_url {
                   1214:     my ($host_name) = @_;
                   1215:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   1216:     if ($host_name eq '') {
                   1217: 	$host_name = $ENV{'SERVER_NAME'};
                   1218:     }
                   1219:     return $protocol.$host_name;
                   1220: }
                   1221: 
1.15      www      1222: sub ssi {
                   1223: 
1.23      www      1224:     my ($fn,%form)=@_;
1.15      www      1225: 
                   1226:     my $ua=new LWP::UserAgent;
1.23      www      1227:     
                   1228:     my $request;
1.711     albertel 1229: 
                   1230:     $form{'no_update_last_known'}=1;
                   1231: 
1.23      www      1232:     if (%form) {
1.782     albertel 1233:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.201     albertel 1234:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1.23      www      1235:     } else {
1.782     albertel 1236:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      1237:     }
                   1238: 
1.15      www      1239:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   1240:     my $response=$ua->request($request);
                   1241: 
1.324     www      1242:     return $response->content;
                   1243: }
                   1244: 
                   1245: sub externalssi {
                   1246:     my ($url)=@_;
                   1247:     my $ua=new LWP::UserAgent;
                   1248:     my $request=new HTTP::Request('GET',$url);
                   1249:     my $response=$ua->request($request);
1.15      www      1250:     return $response->content;
                   1251: }
1.254     www      1252: 
1.492     albertel 1253: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   1254: 
                   1255: sub allowuploaded {
                   1256:     my ($srcurl,$url)=@_;
                   1257:     $url=&clutter(&declutter($url));
                   1258:     my $dir=$url;
                   1259:     $dir=~s/\/[^\/]+$//;
                   1260:     my %httpref=();
                   1261:     my $httpurl=&hreflocation('',$url);
                   1262:     $httpref{'httpref.'.$httpurl}=$srcurl;
                   1263:     &Apache::lonnet::appenv(%httpref);
1.254     www      1264: }
1.477     raeburn  1265: 
1.478     albertel 1266: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 1267: # input: action, courseID, current domain, intended
1.637     raeburn  1268: #        path to file, source of file, instruction to parse file for objects,
                   1269: #        ref to hash for embedded objects,
                   1270: #        ref to hash for codebase of java objects.
                   1271: #
1.485     raeburn  1272: # output: url to file (if action was uploaddoc), 
                   1273: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  1274: #
1.478     albertel 1275: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   1276: # course.
1.477     raeburn  1277: #
1.478     albertel 1278: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1279: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   1280: #          course's home server.
1.477     raeburn  1281: #
1.478     albertel 1282: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   1283: #          be copied from $source (current location) to 
                   1284: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1285: #         and will then be copied to
                   1286: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   1287: #         course's home server.
1.485     raeburn  1288: #
1.481     raeburn  1289: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 1290: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  1291: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1292: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   1293: #         in course's home server.
1.637     raeburn  1294: #
1.477     raeburn  1295: 
                   1296: sub process_coursefile {
1.638     albertel 1297:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477     raeburn  1298:     my $fetchresult;
1.638     albertel 1299:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  1300:     if ($action eq 'propagate') {
1.638     albertel 1301:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   1302: 			     $home);
1.481     raeburn  1303:     } else {
1.477     raeburn  1304:         my $fpath = '';
                   1305:         my $fname = $file;
1.478     albertel 1306:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  1307:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  1308:         my $filepath = &build_filepath($fpath);
1.481     raeburn  1309:         if ($action eq 'copy') {
                   1310:             if ($source eq '') {
                   1311:                 $fetchresult = 'no source file';
                   1312:                 return $fetchresult;
                   1313:             } else {
                   1314:                 my $destination = $filepath.'/'.$fname;
                   1315:                 rename($source,$destination);
                   1316:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1317:                                  $home);
1.481     raeburn  1318:             }
                   1319:         } elsif ($action eq 'uploaddoc') {
                   1320:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 1321:             print $fh $env{'form.'.$source};
1.481     raeburn  1322:             close($fh);
1.637     raeburn  1323:             if ($parser eq 'parse') {
                   1324:                 my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
                   1325:                 unless ($parse_result eq 'ok') {
                   1326:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   1327:                 }
                   1328:             }
1.477     raeburn  1329:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1330:                                  $home);
1.481     raeburn  1331:             if ($fetchresult eq 'ok') {
                   1332:                 return '/uploaded/'.$fpath.'/'.$fname;
                   1333:             } else {
                   1334:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1335:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  1336:                 return '/adm/notfound.html';
                   1337:             }
1.477     raeburn  1338:         }
                   1339:     }
1.485     raeburn  1340:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  1341:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1342:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  1343:     }
                   1344:     return $fetchresult;
                   1345: }
                   1346: 
1.637     raeburn  1347: sub build_filepath {
                   1348:     my ($fpath) = @_;
                   1349:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   1350:     unless ($fpath eq '') {
                   1351:         my @parts=split('/',$fpath);
                   1352:         foreach my $part (@parts) {
                   1353:             $filepath.= '/'.$part;
                   1354:             if ((-e $filepath)!=1) {
                   1355:                 mkdir($filepath,0777);
                   1356:             }
                   1357:         }
                   1358:     }
                   1359:     return $filepath;
                   1360: }
                   1361: 
                   1362: sub store_edited_file {
1.638     albertel 1363:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  1364:     my $file = $primary_url;
                   1365:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   1366:     my $fpath = '';
                   1367:     my $fname = $file;
                   1368:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   1369:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   1370:     my $filepath = &build_filepath($fpath);
                   1371:     open(my $fh,'>'.$filepath.'/'.$fname);
                   1372:     print $fh $content;
                   1373:     close($fh);
1.638     albertel 1374:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  1375:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1376: 			  $home);
1.637     raeburn  1377:     if ($$fetchresult eq 'ok') {
                   1378:         return '/uploaded/'.$fpath.'/'.$fname;
                   1379:     } else {
1.638     albertel 1380:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   1381: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  1382:         return '/adm/notfound.html';
                   1383:     }
                   1384: }
                   1385: 
1.531     albertel 1386: sub clean_filename {
                   1387:     my ($fname)=@_;
1.315     www      1388: # Replace Windows backslashes by forward slashes
1.257     www      1389:     $fname=~s/\\/\//g;
1.315     www      1390: # Get rid of everything but the actual filename
1.257     www      1391:     $fname=~s/^.*\/([^\/]+)$/$1/;
1.315     www      1392: # Replace spaces by underscores
                   1393:     $fname=~s/\s+/\_/g;
                   1394: # Replace all other weird characters by nothing
1.317     www      1395:     $fname=~s/[^\w\.\-]//g;
1.540     albertel 1396: # Replace all .\d. sequences with _\d. so they no longer look like version
                   1397: # numbers
                   1398:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 1399:     return $fname;
                   1400: }
                   1401: 
1.608     albertel 1402: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 1403: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719     banghart 1404: #                    the desired filenam is in $env{"form.$formname.filename"}
1.686     albertel 1405: #        $coursedoc - if true up to the current course
                   1406: #                     if false
                   1407: #        $subdir - directory in userfile to store the file into
                   1408: #        $parser, $allfiles, $codebase - unknown
                   1409: #
                   1410: # output: url of file in userspace, or error: <message> 
                   1411: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 1412: 
                   1413: 
1.531     albertel 1414: sub userfileupload {
1.719     banghart 1415:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,$destudom)=@_;
1.531     albertel 1416:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 1417:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 1418:     $fname=&clean_filename($fname);
1.315     www      1419: # See if there is anything left
1.257     www      1420:     unless ($fname) { return 'error: no uploaded file'; }
1.620     albertel 1421:     chop($env{'form.'.$formname});
1.523     raeburn  1422:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
                   1423:         my $now = time;
                   1424:         my $filepath = 'tmp/helprequests/'.$now;
                   1425:         my @parts=split(/\//,$filepath);
                   1426:         my $fullpath = $perlvar{'lonDaemons'};
                   1427:         for (my $i=0;$i<@parts;$i++) {
                   1428:             $fullpath .= '/'.$parts[$i];
                   1429:             if ((-e $fullpath)!=1) {
                   1430:                 mkdir($fullpath,0777);
                   1431:             }
                   1432:         }
                   1433:         open(my $fh,'>'.$fullpath.'/'.$fname);
1.620     albertel 1434:         print $fh $env{'form.'.$formname};
1.523     raeburn  1435:         close($fh);
1.741     raeburn  1436:         return $fullpath.'/'.$fname;
                   1437:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
                   1438:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   1439:                        '_'.$env{'user.domain'}.'/pending';
                   1440:         my @parts=split(/\//,$filepath);
                   1441:         my $fullpath = $perlvar{'lonDaemons'};
                   1442:         for (my $i=0;$i<@parts;$i++) {
                   1443:             $fullpath .= '/'.$parts[$i];
                   1444:             if ((-e $fullpath)!=1) {
                   1445:                 mkdir($fullpath,0777);
                   1446:             }
                   1447:         }
                   1448:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   1449:         print $fh $env{'form.'.$formname};
                   1450:         close($fh);
                   1451:         return $fullpath.'/'.$fname;
1.523     raeburn  1452:     }
1.719     banghart 1453:     
1.258     www      1454: # Create the directory if not present
1.493     albertel 1455:     $fname="$subdir/$fname";
1.259     www      1456:     if ($coursedoc) {
1.638     albertel 1457: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1458: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  1459:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 1460:             return &finishuserfileupload($docuname,$docudom,
                   1461: 					 $formname,$fname,$parser,$allfiles,
                   1462: 					 $codebase);
1.481     raeburn  1463:         } else {
1.620     albertel 1464:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 1465:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   1466: 				       $fname,$formname,$parser,
                   1467: 				       $allfiles,$codebase);
1.481     raeburn  1468:         }
1.719     banghart 1469:     } elsif (defined($destuname)) {
                   1470:         my $docuname=$destuname;
                   1471:         my $docudom=$destudom;
                   1472: 	return &finishuserfileupload($docuname,$docudom,$formname,
                   1473: 				     $fname,$parser,$allfiles,$codebase);
                   1474:         
1.259     www      1475:     } else {
1.638     albertel 1476:         my $docuname=$env{'user.name'};
                   1477:         my $docudom=$env{'user.domain'};
1.714     raeburn  1478:         if (exists($env{'form.group'})) {
                   1479:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1480:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1481:         }
1.638     albertel 1482: 	return &finishuserfileupload($docuname,$docudom,$formname,
                   1483: 				     $fname,$parser,$allfiles,$codebase);
1.259     www      1484:     }
1.271     www      1485: }
                   1486: 
                   1487: sub finishuserfileupload {
1.638     albertel 1488:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase) = @_;
1.477     raeburn  1489:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      1490:     my $filepath=$perlvar{'lonDocRoot'};
1.494     albertel 1491:     my ($fnamepath,$file);
                   1492:     $file=$fname;
                   1493:     if ($fname=~m|/|) {
                   1494:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   1495: 	$path.=$fnamepath.'/';
                   1496:     }
1.259     www      1497:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      1498:     my $count;
                   1499:     for ($count=4;$count<=$#parts;$count++) {
                   1500:         $filepath.="/$parts[$count]";
                   1501:         if ((-e $filepath)!=1) {
                   1502: 	    mkdir($filepath,0777);
                   1503:         }
                   1504:     }
                   1505: # Save the file
                   1506:     {
1.701     albertel 1507: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   1508: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   1509: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   1510: 	    return '/adm/notfound.html';
                   1511: 	}
                   1512: 	if (!print FH ($env{'form.'.$formname})) {
                   1513: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   1514: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   1515: 	    return '/adm/notfound.html';
                   1516: 	}
1.570     albertel 1517: 	close(FH);
1.258     www      1518:     }
1.637     raeburn  1519:     if ($parser eq 'parse') {
1.638     albertel 1520:         my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
                   1521: 						   $codebase);
1.637     raeburn  1522:         unless ($parse_result eq 'ok') {
1.638     albertel 1523:             &logthis('Failed to parse '.$filepath.$file.
                   1524: 		     ' for embedded media: '.$parse_result); 
1.637     raeburn  1525:         }
                   1526:     }
1.259     www      1527: # Notify homeserver to grep it
                   1528: #
1.638     albertel 1529:     my $docuhome=&homeserver($docuname,$docudom);
1.494     albertel 1530:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      1531:     if ($fetchresult eq 'ok') {
1.259     www      1532: #
1.258     www      1533: # Return the URL to it
1.494     albertel 1534:         return '/uploaded/'.$path.$file;
1.263     www      1535:     } else {
1.494     albertel 1536:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   1537: 		 ': '.$fetchresult);
1.263     www      1538:         return '/adm/notfound.html';
                   1539:     }    
1.493     albertel 1540: }
                   1541: 
1.637     raeburn  1542: sub extract_embedded_items {
1.648     raeburn  1543:     my ($filepath,$file,$allfiles,$codebase,$content) = @_;
1.637     raeburn  1544:     my @state = ();
                   1545:     my %javafiles = (
                   1546:                       codebase => '',
                   1547:                       code => '',
                   1548:                       archive => ''
                   1549:                     );
                   1550:     my %mediafiles = (
                   1551:                       src => '',
                   1552:                       movie => '',
                   1553:                      );
1.648     raeburn  1554:     my $p;
                   1555:     if ($content) {
                   1556:         $p = HTML::LCParser->new($content);
                   1557:     } else {
                   1558:         $p = HTML::LCParser->new($filepath.'/'.$file);
                   1559:     }
1.641     albertel 1560:     while (my $t=$p->get_token()) {
1.640     albertel 1561: 	if ($t->[0] eq 'S') {
                   1562: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
                   1563: 	    push (@state, $tagname);
1.648     raeburn  1564:             if (lc($tagname) eq 'allow') {
                   1565:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   1566:             }
1.640     albertel 1567: 	    if (lc($tagname) eq 'img') {
                   1568: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   1569: 	    }
1.645     raeburn  1570:             if (lc($tagname) eq 'script') {
                   1571:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   1572:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   1573:                 } else {
                   1574:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   1575:                 }
                   1576:             }
                   1577:             if (lc($tagname) eq 'link') {
                   1578:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   1579:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   1580:                 }
                   1581:             }
1.640     albertel 1582: 	    if (lc($tagname) eq 'object' ||
                   1583: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   1584: 		foreach my $item (keys(%javafiles)) {
                   1585: 		    $javafiles{$item} = '';
                   1586: 		}
                   1587: 	    }
                   1588: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   1589: 		my $name = lc($attr->{'name'});
                   1590: 		foreach my $item (keys(%javafiles)) {
                   1591: 		    if ($name eq $item) {
                   1592: 			$javafiles{$item} = $attr->{'value'};
                   1593: 			last;
                   1594: 		    }
                   1595: 		}
                   1596: 		foreach my $item (keys(%mediafiles)) {
                   1597: 		    if ($name eq $item) {
                   1598: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   1599: 			last;
                   1600: 		    }
                   1601: 		}
                   1602: 	    }
                   1603: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   1604: 		foreach my $item (keys(%javafiles)) {
                   1605: 		    if ($attr->{$item}) {
                   1606: 			$javafiles{$item} = $attr->{$item};
                   1607: 			last;
                   1608: 		    }
                   1609: 		}
                   1610: 		foreach my $item (keys(%mediafiles)) {
                   1611: 		    if ($attr->{$item}) {
                   1612: 			&add_filetype($allfiles,$attr->{$item},$item);
                   1613: 			last;
                   1614: 		    }
                   1615: 		}
                   1616: 	    }
                   1617: 	} elsif ($t->[0] eq 'E') {
                   1618: 	    my ($tagname) = ($t->[1]);
                   1619: 	    if ($javafiles{'codebase'} ne '') {
                   1620: 		$javafiles{'codebase'} .= '/';
                   1621: 	    }  
                   1622: 	    if (lc($tagname) eq 'applet' ||
                   1623: 		lc($tagname) eq 'object' ||
                   1624: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   1625: 		) {
                   1626: 		foreach my $item (keys(%javafiles)) {
                   1627: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   1628: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   1629: 			&add_filetype($allfiles,$file,$item);
                   1630: 		    }
                   1631: 		}
                   1632: 	    } 
                   1633: 	    pop @state;
                   1634: 	}
                   1635:     }
1.637     raeburn  1636:     return 'ok';
                   1637: }
                   1638: 
1.639     albertel 1639: sub add_filetype {
                   1640:     my ($allfiles,$file,$type)=@_;
                   1641:     if (exists($allfiles->{$file})) {
                   1642: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   1643: 	    push(@{$allfiles->{$file}}, &escape($type));
                   1644: 	}
                   1645:     } else {
                   1646: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  1647:     }
                   1648: }
                   1649: 
1.493     albertel 1650: sub removeuploadedurl {
                   1651:     my ($url)=@_;
                   1652:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613     albertel 1653:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 1654: }
                   1655: 
                   1656: sub removeuserfile {
                   1657:     my ($docuname,$docudom,$fname)=@_;
                   1658:     my $home=&homeserver($docuname,$docudom);
                   1659:     return &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.257     www      1660: }
1.15      www      1661: 
1.530     albertel 1662: sub mkdiruserfile {
                   1663:     my ($docuname,$docudom,$dir)=@_;
                   1664:     my $home=&homeserver($docuname,$docudom);
                   1665:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   1666: }
                   1667: 
1.531     albertel 1668: sub renameuserfile {
                   1669:     my ($docuname,$docudom,$old,$new)=@_;
                   1670:     my $home=&homeserver($docuname,$docudom);
                   1671:     return &reply("renameuserfile:$docudom:$docuname:".&escape("$old").':'.
                   1672: 		  &escape("$new"),$home);
                   1673: }
                   1674: 
1.14      www      1675: # ------------------------------------------------------------------------- Log
                   1676: 
                   1677: sub log {
                   1678:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      1679:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      1680: }
                   1681: 
                   1682: # ------------------------------------------------------------------ Course Log
1.352     www      1683: #
                   1684: # This routine flushes several buffers of non-mission-critical nature
                   1685: #
1.157     www      1686: 
                   1687: sub flushcourselogs {
1.352     www      1688:     &logthis('Flushing log buffers');
                   1689: #
                   1690: # course logs
                   1691: # This is a log of all transactions in a course, which can be used
                   1692: # for data mining purposes
                   1693: #
                   1694: # It also collects the courseid database, which lists last transaction
                   1695: # times and course titles for all courseids
                   1696: #
                   1697:     my %courseidbuffer=();
1.191     harris41 1698:     foreach (keys %courselogs) {
1.157     www      1699:         my $crsid=$_;
1.352     www      1700:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      1701: 		          &escape($courselogs{$crsid}),
                   1702: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      1703: 	    delete $courselogs{$crsid};
                   1704:         } else {
                   1705:             &logthis('Failed to flush log buffer for '.$crsid);
                   1706:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 1707:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      1708:                         " exceeded maximum size, deleting.</font>");
                   1709:                delete $courselogs{$crsid};
                   1710:             }
1.352     www      1711:         }
                   1712:         if ($courseidbuffer{$coursehombuf{$crsid}}) {
                   1713:            $courseidbuffer{$coursehombuf{$crsid}}.='&'.
1.516     raeburn  1714: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.741     raeburn  1715:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1.352     www      1716:         } else {
                   1717:            $courseidbuffer{$coursehombuf{$crsid}}=
1.516     raeburn  1718: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.741     raeburn  1719:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1.571     raeburn  1720:         }
1.191     harris41 1721:     }
1.352     www      1722: #
                   1723: # Write course id database (reverse lookup) to homeserver of courses 
                   1724: # Is used in pickcourse
                   1725: #
                   1726:     foreach (keys %courseidbuffer) {
1.353     www      1727:         &courseidput($hostdom{$_},$courseidbuffer{$_},$_);
1.352     www      1728:     }
                   1729: #
                   1730: # File accesses
                   1731: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   1732: #
1.449     matthew  1733:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  1734:         if ($entry =~ /___count$/) {
                   1735:             my ($dom,$name);
                   1736:             ($dom,$name,undef)=($entry=~m:___(\w+)/(\w+)/(.*)___count$:);
                   1737:             if (! defined($dom) || $dom eq '' || 
                   1738:                 ! defined($name) || $name eq '') {
1.620     albertel 1739:                 my $cid = $env{'request.course.id'};
                   1740:                 $dom  = $env{'request.'.$cid.'.domain'};
                   1741:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  1742:             }
1.450     matthew  1743:             my $value = $accesshash{$entry};
                   1744:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   1745:             my %temphash=($url => $value);
1.449     matthew  1746:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   1747:             if ($result eq 'ok') {
                   1748:                 delete $accesshash{$entry};
                   1749:             } elsif ($result eq 'unknown_cmd') {
                   1750:                 # Target server has old code running on it.
1.450     matthew  1751:                 my %temphash=($entry => $value);
1.449     matthew  1752:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   1753:                     delete $accesshash{$entry};
                   1754:                 }
                   1755:             }
                   1756:         } else {
1.458     matthew  1757:             my ($dom,$name) = ($entry=~m:___(\w+)/(\w+)/(.*)___(\w+)$:);
1.450     matthew  1758:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  1759:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   1760:                 delete $accesshash{$entry};
                   1761:             }
1.185     www      1762:         }
1.191     harris41 1763:     }
1.352     www      1764: #
                   1765: # Roles
                   1766: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   1767: #
1.349     www      1768:     foreach (keys %userrolehash) {
                   1769:         my $entry=$_;
1.351     www      1770:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      1771: 	    split(/\:/,$entry);
                   1772:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      1773:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      1774:                 $rudom,$runame) eq 'ok') {
                   1775: 	    delete $userrolehash{$entry};
                   1776:         }
                   1777:     }
1.662     raeburn  1778: #
                   1779: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   1780: #
                   1781:     my %domrolebuffer = ();
                   1782:     foreach my $entry (keys %domainrolehash) {
                   1783:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split/:/,$entry;
                   1784:         if ($domrolebuffer{$rudom}) {
                   1785:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   1786:                       '='.&escape($domainrolehash{$entry});
                   1787:         } else {
                   1788:             $domrolebuffer{$rudom}.=&escape($entry).
                   1789:                       '='.&escape($domainrolehash{$entry});
                   1790:         }
                   1791:         delete $domainrolehash{$entry};
                   1792:     }
                   1793:     foreach my $dom (keys(%domrolebuffer)) {
                   1794:         foreach my $tryserver (keys %libserv) {
                   1795:             if ($hostdom{$tryserver} eq $dom) {
                   1796:                 unless (&reply('domroleput:'.$dom.':'.
                   1797:                   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   1798:                     &logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   1799:                 }
                   1800:             }
                   1801:         }
                   1802:     }
1.186     www      1803:     $dumpcount++;
1.157     www      1804: }
                   1805: 
                   1806: sub courselog {
                   1807:     my $what=shift;
1.158     www      1808:     $what=time.':'.$what;
1.620     albertel 1809:     unless ($env{'request.course.id'}) { return ''; }
                   1810:     $coursedombuf{$env{'request.course.id'}}=
                   1811:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   1812:     $coursenumbuf{$env{'request.course.id'}}=
                   1813:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   1814:     $coursehombuf{$env{'request.course.id'}}=
                   1815:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   1816:     $coursedescrbuf{$env{'request.course.id'}}=
                   1817:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   1818:     $courseinstcodebuf{$env{'request.course.id'}}=
                   1819:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   1820:     $courseownerbuf{$env{'request.course.id'}}=
                   1821:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  1822:     $coursetypebuf{$env{'request.course.id'}}=
                   1823:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 1824:     if (defined $courselogs{$env{'request.course.id'}}) {
                   1825: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      1826:     } else {
1.620     albertel 1827: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      1828:     }
1.620     albertel 1829:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      1830: 	&flushcourselogs();
                   1831:     }
1.158     www      1832: }
                   1833: 
                   1834: sub courseacclog {
                   1835:     my $fnsymb=shift;
1.620     albertel 1836:     unless ($env{'request.course.id'}) { return ''; }
                   1837:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 1838:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      1839:         $what.=':POST';
1.583     matthew  1840:         # FIXME: Probably ought to escape things....
1.620     albertel 1841: 	foreach (keys %env) {
1.158     www      1842:             if ($_=~/^form\.(.*)/) {
1.620     albertel 1843: 		$what.=':'.$1.'='.$env{$_};
1.158     www      1844:             }
1.191     harris41 1845:         }
1.583     matthew  1846:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   1847:         # FIXME: We should not be depending on a form parameter that someone
                   1848:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 1849:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  1850:             $what.= ':POST';
                   1851:             # FIXME: Probably ought to escape things....
                   1852:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   1853:                                  'crsdiscuss') {
1.620     albertel 1854:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  1855:             }
                   1856:         }
1.158     www      1857:     }
                   1858:     &courselog($what);
1.149     www      1859: }
                   1860: 
1.185     www      1861: sub countacc {
                   1862:     my $url=&declutter(shift);
1.458     matthew  1863:     return if (! defined($url) || $url eq '');
1.620     albertel 1864:     unless ($env{'request.course.id'}) { return ''; }
                   1865:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      1866:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  1867:     $accesshash{$key}++;
1.185     www      1868: }
1.349     www      1869: 
1.361     www      1870: sub linklog {
                   1871:     my ($from,$to)=@_;
                   1872:     $from=&declutter($from);
                   1873:     $to=&declutter($to);
                   1874:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   1875:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   1876: }
                   1877:   
1.349     www      1878: sub userrolelog {
                   1879:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  1880:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  1881:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  1882:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
                   1883:         ($trole=~/^ta/)) {
1.350     www      1884:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   1885:        $userrolehash
                   1886:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      1887:                     =$tend.':'.$tstart;
1.662     raeburn  1888:     }
                   1889:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   1890:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   1891:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   1892:         ($trole=~/^sc/)) {
                   1893:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   1894:        $domainrolehash
                   1895:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   1896:                     = $tend.':'.$tstart;
                   1897:     }
1.351     www      1898: }
                   1899: 
                   1900: sub get_course_adv_roles {
                   1901:     my $cid=shift;
1.620     albertel 1902:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      1903:     my %coursehash=&coursedescription($cid);
1.470     www      1904:     my %nothide=();
                   1905:     foreach (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   1906: 	$nothide{join(':',split(/[\@\:]/,$_))}=1;
                   1907:     }
1.351     www      1908:     my %returnhash=();
                   1909:     my %dumphash=
                   1910:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   1911:     my $now=time;
                   1912:     foreach (keys %dumphash) {
                   1913: 	my ($tend,$tstart)=split(/\:/,$dumphash{$_});
                   1914:         if (($tstart) && ($tstart<0)) { next; }
                   1915:         if (($tend) && ($tend<$now)) { next; }
                   1916:         if (($tstart) && ($now<$tstart)) { next; }
                   1917:         my ($role,$username,$domain,$section)=split(/\:/,$_);
1.576     albertel 1918: 	if ($username eq '' || $domain eq '') { next; }
1.470     www      1919: 	if ((&privileged($username,$domain)) && 
                   1920: 	    (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 1921: 	if ($role eq 'cr') { next; }
1.351     www      1922:         my $key=&plaintext($role);
                   1923:         if ($section) { $key.=' (Sec/Grp '.$section.')'; }
                   1924:         if ($returnhash{$key}) {
                   1925: 	    $returnhash{$key}.=','.$username.':'.$domain;
                   1926:         } else {
                   1927:             $returnhash{$key}=$username.':'.$domain;
                   1928:         }
1.400     www      1929:      }
                   1930:     return %returnhash;
                   1931: }
                   1932: 
                   1933: sub get_my_roles {
                   1934:     my ($uname,$udom)=@_;
1.620     albertel 1935:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   1936:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.400     www      1937:     my %dumphash=
                   1938:             &dump('nohist_userroles',$udom,$uname);
                   1939:     my %returnhash=();
                   1940:     my $now=time;
                   1941:     foreach (keys %dumphash) {
                   1942: 	my ($tend,$tstart)=split(/\:/,$dumphash{$_});
                   1943:         if (($tstart) && ($tstart<0)) { next; }
                   1944:         if (($tend) && ($tend<$now)) { next; }
                   1945:         if (($tstart) && ($now<$tstart)) { next; }
                   1946:         my ($role,$username,$domain,$section)=split(/\:/,$_);
                   1947: 	$returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
1.373     www      1948:      }
                   1949:     return %returnhash;
1.399     www      1950: }
                   1951: 
                   1952: # ----------------------------------------------------- Frontpage Announcements
                   1953: #
                   1954: #
                   1955: 
                   1956: sub postannounce {
                   1957:     my ($server,$text)=@_;
                   1958:     unless (&allowed('psa',$hostdom{$server})) { return 'refused'; }
                   1959:     unless ($text=~/\w/) { $text=''; }
                   1960:     return &reply('setannounce:'.&escape($text),$server);
                   1961: }
                   1962: 
                   1963: sub getannounce {
1.448     albertel 1964: 
                   1965:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      1966: 	my $announcement='';
                   1967: 	while (<$fh>) { $announcement .=$_; }
1.448     albertel 1968: 	close($fh);
1.399     www      1969: 	if ($announcement=~/\w/) { 
                   1970: 	    return 
                   1971:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 1972:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      1973: 	} else {
                   1974: 	    return '';
                   1975: 	}
                   1976:     } else {
                   1977: 	return '';
                   1978:     }
1.351     www      1979: }
1.353     www      1980: 
                   1981: # ---------------------------------------------------------- Course ID routines
                   1982: # Deal with domain's nohist_courseid.db files
                   1983: #
                   1984: 
                   1985: sub courseidput {
                   1986:     my ($domain,$what,$coursehome)=@_;
                   1987:     return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   1988: }
                   1989: 
                   1990: sub courseiddump {
1.741     raeburn  1991:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,$coursefilter,$hostidflag,$hostidref,$typefilter)=@_;
1.353     www      1992:     my %returnhash=();
1.355     www      1993:     unless ($domfilter) { $domfilter=''; }
1.353     www      1994:     foreach my $tryserver (keys %libserv) {
1.511     raeburn  1995:         if ( ($hostidflag == 1 && grep/^$tryserver$/,@{$hostidref}) || (!defined($hostidflag)) ) {
1.506     raeburn  1996: 	    if ((!$domfilter) || ($hostdom{$tryserver} eq $domfilter)) {
                   1997: 	        foreach (
                   1998:                  split(/\&/,&reply('courseiddump:'.$hostdom{$tryserver}.':'.
1.571     raeburn  1999: 			       $sincefilter.':'.&escape($descfilter).':'.
1.741     raeburn  2000:                                &escape($instcodefilter).':'.&escape($ownerfilter).':'.&escape($coursefilter).':'.&escape($typefilter),
1.354     www      2001:                                $tryserver))) {
1.506     raeburn  2002: 		    my ($key,$value)=split(/\=/,$_);
                   2003:                     if (($key) && ($value)) {
1.516     raeburn  2004: 		        $returnhash{&unescape($key)}=$value;
1.506     raeburn  2005:                     }
1.353     www      2006:                 }
                   2007:             }
                   2008:         }
                   2009:     }
                   2010:     return %returnhash;
                   2011: }
                   2012: 
1.658     raeburn  2013: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  2014: 
                   2015: sub dcmailput {
1.685     raeburn  2016:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  2017:     my $status = &Apache::lonnet::critical(
1.740     www      2018:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   2019:        &escape($message),$server);
1.662     raeburn  2020:     return $status;
                   2021: }
                   2022: 
1.658     raeburn  2023: sub dcmaildump {
                   2024:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  2025:     my %returnhash=();
                   2026:     if (exists($domain_primary{$dom})) {
                   2027:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   2028:                                                          &escape($enddate).':';
                   2029: 	my @esc_senders=map { &escape($_)} @$senders;
                   2030: 	$cmd.=&escape(join('&',@esc_senders));
                   2031: 	foreach (split(/\&/,&reply($cmd,$domain_primary{$dom}))) {
                   2032:             my ($key,$value) = split(/\=/,$_);
                   2033:             if (($key) && ($value)) {
                   2034:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  2035:             }
                   2036:         }
                   2037:     }
                   2038:     return %returnhash;
                   2039: }
1.662     raeburn  2040: # ---------------------------------------------------------- Domain roles
                   2041: 
                   2042: sub get_domain_roles {
                   2043:     my ($dom,$roles,$startdate,$enddate)=@_;
                   2044:     if (undef($startdate) || $startdate eq '') {
                   2045:         $startdate = '.';
                   2046:     }
                   2047:     if (undef($enddate) || $enddate eq '') {
                   2048:         $enddate = '.';
                   2049:     }
                   2050:     my $rolelist = join(':',@{$roles});
                   2051:     my %personnel = ();
                   2052:     foreach my $tryserver (keys(%libserv)) {
                   2053:         if ($hostdom{$tryserver} eq $dom) {
                   2054:             %{$personnel{$tryserver}}=();
                   2055:             foreach (
                   2056:                 split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   2057:                    &escape($startdate).':'.&escape($enddate).':'.
                   2058:                    &escape($rolelist), $tryserver))) {
                   2059:                 my($key,$value) = split(/\=/,$_);
                   2060:                 if (($key) && ($value)) {
                   2061:                     $personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   2062:                 }
                   2063:             }
                   2064:         }
                   2065:     }
                   2066:     return %personnel;
                   2067: }
1.658     raeburn  2068: 
1.149     www      2069: # ----------------------------------------------------------- Check out an item
                   2070: 
1.504     albertel 2071: sub get_first_access {
                   2072:     my ($type,$argsymb)=@_;
                   2073:     my ($symb,$courseid,$udom,$uname)=&Apache::lonxml::whichuser();
                   2074:     if ($argsymb) { $symb=$argsymb; }
                   2075:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 2076:     if ($type eq 'map') {
                   2077: 	$res=&symbread($map);
                   2078:     } else {
                   2079: 	$res=$symb;
                   2080:     }
                   2081:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   2082:     return $times{"$courseid\0$res"};
1.504     albertel 2083: }
                   2084: 
                   2085: sub set_first_access {
                   2086:     my ($type)=@_;
                   2087:     my ($symb,$courseid,$udom,$uname)=&Apache::lonxml::whichuser();
                   2088:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 2089:     if ($type eq 'map') {
                   2090: 	$res=&symbread($map);
                   2091:     } else {
                   2092: 	$res=$symb;
                   2093:     }
                   2094:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 2095:     if (!$firstaccess) {
1.588     albertel 2096: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 2097:     }
                   2098:     return 'already_set';
1.504     albertel 2099: }
                   2100: 
1.149     www      2101: sub checkout {
                   2102:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   2103:     my $now=time;
                   2104:     my $lonhost=$perlvar{'lonHostID'};
                   2105:     my $infostr=&escape(
1.234     www      2106:                  'CHECKOUTTOKEN&'.
1.149     www      2107:                  $tuname.'&'.
                   2108:                  $tudom.'&'.
                   2109:                  $tcrsid.'&'.
                   2110:                  $symb.'&'.
                   2111: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                   2112:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www      2113:     if ($token=~/^error\:/) { 
1.672     albertel 2114:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2115:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2116:                  "</font>");
                   2117:         return ''; 
                   2118:     }
                   2119: 
1.149     www      2120:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   2121:     $token=~tr/a-z/A-Z/;
                   2122: 
1.153     www      2123:     my %infohash=('resource.0.outtoken' => $token,
                   2124:                   'resource.0.checkouttime' => $now,
                   2125:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www      2126: 
                   2127:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2128:        return '';
1.151     www      2129:     } else {
1.672     albertel 2130:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2131:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2132:                  "</font>");
1.149     www      2133:     }    
                   2134: 
                   2135:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2136:                          &escape('Checkout '.$infostr.' - '.
                   2137:                                                  $token)) ne 'ok') {
                   2138: 	return '';
1.151     www      2139:     } else {
1.672     albertel 2140:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2141:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2142:                  "</font>");
1.149     www      2143:     }
1.151     www      2144:     return $token;
1.149     www      2145: }
                   2146: 
                   2147: # ------------------------------------------------------------ Check in an item
                   2148: 
                   2149: sub checkin {
                   2150:     my $token=shift;
1.150     www      2151:     my $now=time;
                   2152:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   2153:     $lonhost=~tr/A-Z/a-z/;
1.595     albertel 2154:     my $dtoken=$ta.'_'.$hostname{$lonhost}.'_'.$tb;
1.150     www      2155:     $dtoken=~s/\W/\_/g;
1.234     www      2156:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www      2157:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   2158: 
1.154     www      2159:     unless (($tuname) && ($tudom)) {
                   2160:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   2161:         return '';
                   2162:     }
                   2163:     
                   2164:     unless (&allowed('mgr',$tcrsid)) {
                   2165:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620     albertel 2166:                  $env{'user.name'}.' - '.$env{'user.domain'});
1.154     www      2167:         return '';
                   2168:     }
                   2169: 
1.153     www      2170:     my %infohash=('resource.0.intoken' => $token,
                   2171:                   'resource.0.checkintime' => $now,
                   2172:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      2173: 
                   2174:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2175:        return '';
                   2176:     }    
                   2177: 
                   2178:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2179:                          &escape('Checkin - '.$token)) ne 'ok') {
                   2180: 	return '';
                   2181:     }
                   2182: 
                   2183:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      2184: }
                   2185: 
                   2186: # --------------------------------------------- Set Expire Date for Spreadsheet
                   2187: 
                   2188: sub expirespread {
                   2189:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 2190:     my $cid=$env{'request.course.id'}; 
1.110     www      2191:     if ($cid) {
                   2192:        my $now=time;
                   2193:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 2194:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   2195:                             $env{'course.'.$cid.'.num'}.
1.110     www      2196: 	        	    ':nohist_expirationdates:'.
                   2197:                             &escape($key).'='.$now,
1.620     albertel 2198:                             $env{'course.'.$cid.'.home'})
1.110     www      2199:     }
                   2200:     return 'ok';
1.14      www      2201: }
                   2202: 
1.109     www      2203: # ----------------------------------------------------- Devalidate Spreadsheets
                   2204: 
                   2205: sub devalidate {
1.325     www      2206:     my ($symb,$uname,$udom)=@_;
1.620     albertel 2207:     my $cid=$env{'request.course.id'}; 
1.109     www      2208:     if ($cid) {
1.391     matthew  2209:         # delete the stored spreadsheets for
                   2210:         # - the student level sheet of this user in course's homespace
                   2211:         # - the assessment level sheet for this resource 
                   2212:         #   for this user in user's homespace
1.553     albertel 2213: 	# - current conditional state info
1.325     www      2214: 	my $key=$uname.':'.$udom.':';
1.109     www      2215:         my $status=
1.299     matthew  2216: 	    &del('nohist_calculatedsheets',
1.391     matthew  2217: 		 [$key.'studentcalc:'],
1.620     albertel 2218: 		 $env{'course.'.$cid.'.domain'},
                   2219: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 2220: 		.' '.
                   2221: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  2222: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      2223:         unless ($status eq 'ok ok') {
                   2224:            &logthis('Could not devalidate spreadsheet '.
1.325     www      2225:                     $uname.' at '.$udom.' for '.
1.109     www      2226: 		    $symb.': '.$status);
1.133     albertel 2227:         }
1.553     albertel 2228: 	&delenv('user.state.'.$cid);
1.109     www      2229:     }
                   2230: }
                   2231: 
1.265     albertel 2232: sub get_scalar {
                   2233:     my ($string,$end) = @_;
                   2234:     my $value;
                   2235:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   2236: 	$value = $1;
                   2237:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   2238: 	$value = $1;
                   2239:     }
                   2240:     return &unescape($value);
                   2241: }
                   2242: 
                   2243: sub array2str {
                   2244:   my (@array) = @_;
                   2245:   my $result=&arrayref2str(\@array);
                   2246:   $result=~s/^__ARRAY_REF__//;
                   2247:   $result=~s/__END_ARRAY_REF__$//;
                   2248:   return $result;
                   2249: }
                   2250: 
1.204     albertel 2251: sub arrayref2str {
                   2252:   my ($arrayref) = @_;
1.265     albertel 2253:   my $result='__ARRAY_REF__';
1.204     albertel 2254:   foreach my $elem (@$arrayref) {
1.265     albertel 2255:     if(ref($elem) eq 'ARRAY') {
                   2256:       $result.=&arrayref2str($elem).'&';
                   2257:     } elsif(ref($elem) eq 'HASH') {
                   2258:       $result.=&hashref2str($elem).'&';
                   2259:     } elsif(ref($elem)) {
                   2260:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 2261:     } else {
                   2262:       $result.=&escape($elem).'&';
                   2263:     }
                   2264:   }
                   2265:   $result=~s/\&$//;
1.265     albertel 2266:   $result .= '__END_ARRAY_REF__';
1.204     albertel 2267:   return $result;
                   2268: }
                   2269: 
1.168     albertel 2270: sub hash2str {
1.204     albertel 2271:   my (%hash) = @_;
                   2272:   my $result=&hashref2str(\%hash);
1.265     albertel 2273:   $result=~s/^__HASH_REF__//;
                   2274:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 2275:   return $result;
                   2276: }
                   2277: 
                   2278: sub hashref2str {
                   2279:   my ($hashref)=@_;
1.265     albertel 2280:   my $result='__HASH_REF__';
1.495     albertel 2281:   foreach (sort(keys(%$hashref))) {
1.204     albertel 2282:     if (ref($_) eq 'ARRAY') {
1.265     albertel 2283:       $result.=&arrayref2str($_).'=';
1.204     albertel 2284:     } elsif (ref($_) eq 'HASH') {
1.265     albertel 2285:       $result.=&hashref2str($_).'=';
1.204     albertel 2286:     } elsif (ref($_)) {
1.265     albertel 2287:       $result.='=';
                   2288:       #print("Got a ref of ".(ref($_))." skipping.");
1.204     albertel 2289:     } else {
1.265     albertel 2290: 	if ($_) {$result.=&escape($_).'=';} else { last; }
1.204     albertel 2291:     }
                   2292: 
1.265     albertel 2293:     if(ref($hashref->{$_}) eq 'ARRAY') {
                   2294:       $result.=&arrayref2str($hashref->{$_}).'&';
                   2295:     } elsif(ref($hashref->{$_}) eq 'HASH') {
                   2296:       $result.=&hashref2str($hashref->{$_}).'&';
                   2297:     } elsif(ref($hashref->{$_})) {
                   2298:        $result.='&';
                   2299:       #print("Got a ref of ".(ref($hashref->{$_}))." skipping.");
1.204     albertel 2300:     } else {
1.265     albertel 2301:       $result.=&escape($hashref->{$_}).'&';
1.204     albertel 2302:     }
                   2303:   }
1.168     albertel 2304:   $result=~s/\&$//;
1.265     albertel 2305:   $result .= '__END_HASH_REF__';
1.168     albertel 2306:   return $result;
                   2307: }
                   2308: 
                   2309: sub str2hash {
1.265     albertel 2310:     my ($string)=@_;
                   2311:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   2312:     return %$hash;
                   2313: }
                   2314: 
                   2315: sub str2hashref {
1.168     albertel 2316:   my ($string) = @_;
1.265     albertel 2317: 
                   2318:   my %hash;
                   2319: 
                   2320:   if($string !~ /^__HASH_REF__/) {
                   2321:       if (! ($string eq '' || !defined($string))) {
                   2322: 	  $hash{'error'}='Not hash reference';
                   2323:       }
                   2324:       return (\%hash, $string);
                   2325:   }
                   2326: 
                   2327:   $string =~ s/^__HASH_REF__//;
                   2328: 
                   2329:   while($string !~ /^__END_HASH_REF__/) {
                   2330:       #key
                   2331:       my $key='';
                   2332:       if($string =~ /^__HASH_REF__/) {
                   2333:           ($key, $string)=&str2hashref($string);
                   2334:           if(defined($key->{'error'})) {
                   2335:               $hash{'error'}='Bad data';
                   2336:               return (\%hash, $string);
                   2337:           }
                   2338:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2339:           ($key, $string)=&str2arrayref($string);
                   2340:           if($key->[0] eq 'Array reference error') {
                   2341:               $hash{'error'}='Bad data';
                   2342:               return (\%hash, $string);
                   2343:           }
                   2344:       } else {
                   2345:           $string =~ s/^(.*?)=//;
1.267     albertel 2346: 	  $key=&unescape($1);
1.265     albertel 2347:       }
                   2348:       $string =~ s/^=//;
                   2349: 
                   2350:       #value
                   2351:       my $value='';
                   2352:       if($string =~ /^__HASH_REF__/) {
                   2353:           ($value, $string)=&str2hashref($string);
                   2354:           if(defined($value->{'error'})) {
                   2355:               $hash{'error'}='Bad data';
                   2356:               return (\%hash, $string);
                   2357:           }
                   2358:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2359:           ($value, $string)=&str2arrayref($string);
                   2360:           if($value->[0] eq 'Array reference error') {
                   2361:               $hash{'error'}='Bad data';
                   2362:               return (\%hash, $string);
                   2363:           }
                   2364:       } else {
                   2365: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   2366:       }
                   2367:       $string =~ s/^&//;
                   2368: 
                   2369:       $hash{$key}=$value;
1.204     albertel 2370:   }
1.265     albertel 2371: 
                   2372:   $string =~ s/^__END_HASH_REF__//;
                   2373: 
                   2374:   return (\%hash, $string);
1.204     albertel 2375: }
                   2376: 
                   2377: sub str2array {
1.265     albertel 2378:     my ($string)=@_;
                   2379:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   2380:     return @$array;
                   2381: }
                   2382: 
                   2383: sub str2arrayref {
1.204     albertel 2384:   my ($string) = @_;
1.265     albertel 2385:   my @array;
                   2386: 
                   2387:   if($string !~ /^__ARRAY_REF__/) {
                   2388:       if (! ($string eq '' || !defined($string))) {
                   2389: 	  $array[0]='Array reference error';
                   2390:       }
                   2391:       return (\@array, $string);
                   2392:   }
                   2393: 
                   2394:   $string =~ s/^__ARRAY_REF__//;
                   2395: 
                   2396:   while($string !~ /^__END_ARRAY_REF__/) {
                   2397:       my $value='';
                   2398:       if($string =~ /^__HASH_REF__/) {
                   2399:           ($value, $string)=&str2hashref($string);
                   2400:           if(defined($value->{'error'})) {
                   2401:               $array[0] ='Array reference error';
                   2402:               return (\@array, $string);
                   2403:           }
                   2404:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2405:           ($value, $string)=&str2arrayref($string);
                   2406:           if($value->[0] eq 'Array reference error') {
                   2407:               $array[0] ='Array reference error';
                   2408:               return (\@array, $string);
                   2409:           }
                   2410:       } else {
                   2411: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   2412:       }
                   2413:       $string =~ s/^&//;
                   2414: 
                   2415:       push(@array, $value);
1.191     harris41 2416:   }
1.265     albertel 2417: 
                   2418:   $string =~ s/^__END_ARRAY_REF__//;
                   2419: 
                   2420:   return (\@array, $string);
1.168     albertel 2421: }
                   2422: 
1.167     albertel 2423: # -------------------------------------------------------------------Temp Store
                   2424: 
1.168     albertel 2425: sub tmpreset {
                   2426:   my ($symb,$namespace,$domain,$stuname) = @_;
                   2427:   if (!$symb) {
                   2428:     $symb=&symbread();
1.620     albertel 2429:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2430:   }
                   2431:   $symb=escape($symb);
                   2432: 
1.620     albertel 2433:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 2434:   $namespace=~s/\//\_/g;
                   2435:   $namespace=~s/\W//g;
                   2436: 
1.620     albertel 2437:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2438:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2439:   if ($domain eq 'public' && $stuname eq 'public') {
                   2440:       $stuname=$ENV{'REMOTE_ADDR'};
                   2441:   }
1.168     albertel 2442:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2443:   my %hash;
                   2444:   if (tie(%hash,'GDBM_File',
                   2445: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2446: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2447:     foreach my $key (keys %hash) {
1.180     albertel 2448:       if ($key=~ /:$symb/) {
1.168     albertel 2449: 	delete($hash{$key});
                   2450:       }
                   2451:     }
                   2452:   }
                   2453: }
                   2454: 
1.167     albertel 2455: sub tmpstore {
1.168     albertel 2456:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2457: 
                   2458:   if (!$symb) {
                   2459:     $symb=&symbread();
1.620     albertel 2460:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2461:   }
                   2462:   $symb=escape($symb);
                   2463: 
                   2464:   if (!$namespace) {
                   2465:     # I don't think we would ever want to store this for a course.
                   2466:     # it seems this will only be used if we don't have a course.
1.620     albertel 2467:     #$namespace=$env{'request.course.id'};
1.168     albertel 2468:     #if (!$namespace) {
1.620     albertel 2469:       $namespace=$env{'request.state'};
1.168     albertel 2470:     #}
                   2471:   }
                   2472:   $namespace=~s/\//\_/g;
                   2473:   $namespace=~s/\W//g;
1.620     albertel 2474:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2475:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2476:   if ($domain eq 'public' && $stuname eq 'public') {
                   2477:       $stuname=$ENV{'REMOTE_ADDR'};
                   2478:   }
1.168     albertel 2479:   my $now=time;
                   2480:   my %hash;
                   2481:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2482:   if (tie(%hash,'GDBM_File',
                   2483: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2484: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2485:     $hash{"version:$symb"}++;
                   2486:     my $version=$hash{"version:$symb"};
                   2487:     my $allkeys=''; 
                   2488:     foreach my $key (keys(%$storehash)) {
                   2489:       $allkeys.=$key.':';
1.591     albertel 2490:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 2491:     }
                   2492:     $hash{"$version:$symb:timestamp"}=$now;
                   2493:     $allkeys.='timestamp';
                   2494:     $hash{"$version:keys:$symb"}=$allkeys;
                   2495:     if (untie(%hash)) {
                   2496:       return 'ok';
                   2497:     } else {
                   2498:       return "error:$!";
                   2499:     }
                   2500:   } else {
                   2501:     return "error:$!";
                   2502:   }
                   2503: }
1.167     albertel 2504: 
1.168     albertel 2505: # -----------------------------------------------------------------Temp Restore
1.167     albertel 2506: 
1.168     albertel 2507: sub tmprestore {
                   2508:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 2509: 
1.168     albertel 2510:   if (!$symb) {
                   2511:     $symb=&symbread();
1.620     albertel 2512:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2513:   }
                   2514:   $symb=escape($symb);
                   2515: 
1.620     albertel 2516:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 2517: 
1.620     albertel 2518:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2519:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2520:   if ($domain eq 'public' && $stuname eq 'public') {
                   2521:       $stuname=$ENV{'REMOTE_ADDR'};
                   2522:   }
1.168     albertel 2523:   my %returnhash;
                   2524:   $namespace=~s/\//\_/g;
                   2525:   $namespace=~s/\W//g;
                   2526:   my %hash;
                   2527:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2528:   if (tie(%hash,'GDBM_File',
                   2529: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2530: 	  &GDBM_READER(),0640)) {
1.168     albertel 2531:     my $version=$hash{"version:$symb"};
                   2532:     $returnhash{'version'}=$version;
                   2533:     my $scope;
                   2534:     for ($scope=1;$scope<=$version;$scope++) {
                   2535:       my $vkeys=$hash{"$scope:keys:$symb"};
                   2536:       my @keys=split(/:/,$vkeys);
                   2537:       my $key;
                   2538:       $returnhash{"$scope:keys"}=$vkeys;
                   2539:       foreach $key (@keys) {
1.591     albertel 2540: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   2541: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 2542:       }
                   2543:     }
1.168     albertel 2544:     if (!(untie(%hash))) {
                   2545:       return "error:$!";
                   2546:     }
                   2547:   } else {
                   2548:     return "error:$!";
                   2549:   }
                   2550:   return %returnhash;
1.167     albertel 2551: }
                   2552: 
1.9       www      2553: # ----------------------------------------------------------------------- Store
                   2554: 
                   2555: sub store {
1.124     www      2556:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2557:     my $home='';
                   2558: 
1.168     albertel 2559:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2560: 
1.213     www      2561:     $symb=&symbclean($symb);
1.122     albertel 2562:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      2563: 
1.620     albertel 2564:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2565:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      2566: 
                   2567:     &devalidate($symb,$stuname,$domain);
1.109     www      2568: 
                   2569:     $symb=escape($symb);
1.187     www      2570:     if (!$namespace) { 
1.620     albertel 2571:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      2572:           return ''; 
                   2573:        } 
                   2574:     }
1.620     albertel 2575:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      2576: 
                   2577:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   2578:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   2579: 
1.12      www      2580:     my $namevalue='';
1.191     harris41 2581:     foreach (keys %$storehash) {
1.591     albertel 2582:         $namevalue.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
1.191     harris41 2583:     }
1.12      www      2584:     $namevalue=~s/\&$//;
1.187     www      2585:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      2586:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      2587: }
                   2588: 
1.47      www      2589: # -------------------------------------------------------------- Critical Store
                   2590: 
                   2591: sub cstore {
1.124     www      2592:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2593:     my $home='';
                   2594: 
1.168     albertel 2595:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2596: 
1.213     www      2597:     $symb=&symbclean($symb);
1.122     albertel 2598:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      2599: 
1.620     albertel 2600:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2601:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      2602: 
                   2603:     &devalidate($symb,$stuname,$domain);
1.109     www      2604: 
                   2605:     $symb=escape($symb);
1.187     www      2606:     if (!$namespace) { 
1.620     albertel 2607:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      2608:           return ''; 
                   2609:        } 
                   2610:     }
1.620     albertel 2611:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      2612: 
                   2613:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   2614:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 2615: 
1.47      www      2616:     my $namevalue='';
1.191     harris41 2617:     foreach (keys %$storehash) {
1.591     albertel 2618:         $namevalue.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
1.191     harris41 2619:     }
1.47      www      2620:     $namevalue=~s/\&$//;
1.187     www      2621:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      2622:     return critical
                   2623:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      2624: }
                   2625: 
1.9       www      2626: # --------------------------------------------------------------------- Restore
                   2627: 
                   2628: sub restore {
1.124     www      2629:     my ($symb,$namespace,$domain,$stuname) = @_;
                   2630:     my $home='';
                   2631: 
1.168     albertel 2632:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2633: 
1.122     albertel 2634:     if (!$symb) {
                   2635:       unless ($symb=escape(&symbread())) { return ''; }
                   2636:     } else {
1.213     www      2637:       $symb=&escape(&symbclean($symb));
1.122     albertel 2638:     }
1.188     www      2639:     if (!$namespace) { 
1.620     albertel 2640:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      2641:           return ''; 
                   2642:        } 
                   2643:     }
1.620     albertel 2644:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2645:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   2646:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 2647:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   2648: 
1.12      www      2649:     my %returnhash=();
1.191     harris41 2650:     foreach (split(/\&/,$answer)) {
1.12      www      2651: 	my ($name,$value)=split(/\=/,$_);
1.591     albertel 2652:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 2653:     }
1.75      www      2654:     my $version;
                   2655:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.191     harris41 2656:        foreach (split(/\:/,$returnhash{$version.':keys'})) {
1.75      www      2657:           $returnhash{$_}=$returnhash{$version.':'.$_};
1.191     harris41 2658:        }
1.75      www      2659:     }
1.13      www      2660:     return %returnhash;
1.34      www      2661: }
                   2662: 
                   2663: # ---------------------------------------------------------- Course Description
                   2664: 
                   2665: sub coursedescription {
1.731     albertel 2666:     my ($courseid,$args)=@_;
1.34      www      2667:     $courseid=~s/^\///;
1.49      www      2668:     $courseid=~s/\_/\//g;
1.34      www      2669:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 2670:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 2671:     my $normalid=$cdomain.'_'.$cnum;
                   2672:     # need to always cache even if we get errors otherwise we keep 
                   2673:     # trying and trying and trying to get the course description.
                   2674:     my %envhash=();
                   2675:     my %returnhash=();
1.731     albertel 2676:     
                   2677:     my $expiretime=600;
                   2678:     if ($env{'request.course.id'} eq $normalid) {
                   2679: 	$expiretime=120;
                   2680:     }
                   2681: 
                   2682:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   2683:     if (!$args->{'freshen_cache'}
                   2684: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   2685: 	foreach my $key (keys(%env)) {
                   2686: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   2687: 	    my ($setting) = $1;
                   2688: 	    $returnhash{$setting} = $env{$key};
                   2689: 	}
                   2690: 	return %returnhash;
                   2691:     }
                   2692: 
                   2693:     # get the data agin
                   2694:     if (!$args->{'one_time'}) {
                   2695: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   2696:     }
1.34      www      2697:     if ($chome ne 'no_host') {
1.302     albertel 2698:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 2699:        if (!exists($returnhash{'con_lost'})) {
                   2700:            $returnhash{'home'}= $chome;
                   2701: 	   $returnhash{'domain'} = $cdomain;
                   2702: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  2703:            if (!defined($returnhash{'type'})) {
                   2704:                $returnhash{'type'} = 'Course';
                   2705:            }
1.130     albertel 2706:            while (my ($name,$value) = each %returnhash) {
1.53      www      2707:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 2708:            }
1.270     www      2709:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      2710:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 2711: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      2712:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   2713:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   2714:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      2715:        }
                   2716:     }
1.731     albertel 2717:     if (!$args->{'one_time'}) {
                   2718: 	&appenv(%envhash);
                   2719:     }
1.302     albertel 2720:     return %returnhash;
1.461     www      2721: }
                   2722: 
                   2723: # -------------------------------------------------See if a user is privileged
                   2724: 
                   2725: sub privileged {
                   2726:     my ($username,$domain)=@_;
                   2727:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   2728: 			&homeserver($username,$domain));
                   2729:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
                   2730:     my $now=time;
                   2731:     if ($rolesdump ne '') {
                   2732:         foreach (split(/&/,$rolesdump)) {
1.586     albertel 2733: 	    if ($_!~/^rolesdef_/) {
1.461     www      2734: 		my ($area,$role)=split(/=/,$_);
                   2735: 		$area=~s/\_\w\w$//;
                   2736: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   2737: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   2738: 		    my $active=1;
                   2739: 		    if ($tend) {
                   2740: 			if ($tend<$now) { $active=0; }
                   2741: 		    }
                   2742: 		    if ($tstart) {
                   2743: 			if ($tstart>$now) { $active=0; }
                   2744: 		    }
                   2745: 		    if ($active) { return 1; }
                   2746: 		}
                   2747: 	    }
                   2748: 	}
                   2749:     }
                   2750:     return 0;
1.9       www      2751: }
1.1       albertel 2752: 
1.103     harris41 2753: # -------------------------------------------------------- Get user privileges
1.11      www      2754: 
                   2755: sub rolesinit {
                   2756:     my ($domain,$username,$authhost)=@_;
                   2757:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.12      www      2758:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
1.11      www      2759:     my %allroles=();
1.678     raeburn  2760:     my %allgroups=();   
1.11      www      2761:     my $now=time;
1.743     albertel 2762:     my %userroles = ('user.login.time' => $now);
1.678     raeburn  2763:     my $group_privs;
1.11      www      2764: 
                   2765:     if ($rolesdump ne '') {
1.191     harris41 2766:         foreach (split(/&/,$rolesdump)) {
1.586     albertel 2767: 	  if ($_!~/^rolesdef_/) {
1.11      www      2768:             my ($area,$role)=split(/=/,$_);
1.587     albertel 2769: 	    $area=~s/\_\w\w$//;
1.678     raeburn  2770:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 2771: 	    if ($role=~/^cr/) { 
1.655     albertel 2772: 		if ($role=~m|^(cr/\w+/\w+/[a-zA-Z0-9]+)_(.*)$|) {
                   2773: 		    ($trole,my $trest)=($role=~m|^(cr/\w+/\w+/[a-zA-Z0-9]+)_(.*)$|);
                   2774: 		    ($tend,$tstart)=split('_',$trest);
                   2775: 		} else {
                   2776: 		    $trole=$role;
                   2777: 		}
1.678     raeburn  2778:             } elsif ($role =~ m|^gr/|) {
                   2779:                 ($trole,$tend,$tstart) = split(/_/,$role);
                   2780:                 ($trole,$group_privs) = split(/\//,$trole);
                   2781:                 $group_privs = &unescape($group_privs);
1.587     albertel 2782: 	    } else {
                   2783: 		($trole,$tend,$tstart)=split(/_/,$role);
                   2784: 	    }
1.743     albertel 2785: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   2786: 					 $username);
                   2787: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  2788:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   2789:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      2790:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 2791: 		my $spec=$trole.'.'.$area;
                   2792: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   2793: 		if ($trole =~ /^cr\//) {
1.567     raeburn  2794:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  2795:                 } elsif ($trole eq 'gr') {
                   2796:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 2797: 		} else {
1.567     raeburn  2798:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 2799: 		}
1.12      www      2800:             }
1.662     raeburn  2801:           }
1.191     harris41 2802:         }
1.743     albertel 2803:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   2804:         $userroles{'user.adv'}    = $adv;
                   2805: 	$userroles{'user.author'} = $author;
1.620     albertel 2806:         $env{'user.adv'}=$adv;
1.11      www      2807:     }
1.743     albertel 2808:     return \%userroles;  
1.11      www      2809: }
                   2810: 
1.567     raeburn  2811: sub set_arearole {
                   2812:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   2813: # log the associated role with the area
                   2814:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 2815:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  2816: }
                   2817: 
                   2818: sub custom_roleprivs {
                   2819:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   2820:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   2821:     my $homsvr=homeserver($rauthor,$rdomain);
                   2822:     if ($hostname{$homsvr} ne '') {
                   2823:         my ($rdummy,$roledef)=
                   2824:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   2825:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   2826:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   2827:             if (defined($syspriv)) {
                   2828:                 $$allroles{'cm./'}.=':'.$syspriv;
                   2829:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   2830:             }
                   2831:             if ($tdomain ne '') {
                   2832:                 if (defined($dompriv)) {
                   2833:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   2834:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   2835:                 }
                   2836:                 if (($trest ne '') && (defined($coursepriv))) {
                   2837:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   2838:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   2839:                 }
                   2840:             }
                   2841:         }
                   2842:     }
                   2843: }
                   2844: 
1.678     raeburn  2845: sub group_roleprivs {
                   2846:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   2847:     my $access = 1;
                   2848:     my $now = time;
                   2849:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   2850:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   2851:     if ($access) {
                   2852:         my ($course,$group) = ($area =~ m|(/\w+/\w+)/([^/]+)$|);
                   2853:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   2854:     }
                   2855: }
1.567     raeburn  2856: 
                   2857: sub standard_roleprivs {
                   2858:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   2859:     if (defined($pr{$trole.':s'})) {
                   2860:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   2861:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   2862:     }
                   2863:     if ($tdomain ne '') {
                   2864:         if (defined($pr{$trole.':d'})) {
                   2865:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   2866:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   2867:         }
                   2868:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   2869:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   2870:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   2871:         }
                   2872:     }
                   2873: }
                   2874: 
                   2875: sub set_userprivs {
1.678     raeburn  2876:     my ($userroles,$allroles,$allgroups) = @_; 
1.567     raeburn  2877:     my $author=0;
                   2878:     my $adv=0;
1.678     raeburn  2879:     my %grouproles = ();
                   2880:     if (keys(%{$allgroups}) > 0) {
                   2881:         foreach my $role (keys %{$allroles}) {
1.681     raeburn  2882:             my ($trole,$area,$sec,$extendedarea);
1.771     raeburn  2883:             if ($role =~ m-^(\w+|cr/\w+/\w+/\w+)\.(/\w+/\w+)(/?\w*)-) {
1.678     raeburn  2884:                 $trole = $1;
                   2885:                 $area = $2;
1.681     raeburn  2886:                 $sec = $3;
                   2887:                 $extendedarea = $area.$sec;
                   2888:                 if (exists($$allgroups{$area})) {
                   2889:                     foreach my $group (keys(%{$$allgroups{$area}})) {
                   2890:                         my $spec = $trole.'.'.$extendedarea;
                   2891:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
                   2892:                                                 $$allgroups{$area}{$group};
1.678     raeburn  2893:                     }
                   2894:                 }
                   2895:             }
                   2896:         }
                   2897:     }
                   2898:     foreach (keys(%grouproles)) {
                   2899:         $$allroles{$_} = $grouproles{$_};
                   2900:     }
1.567     raeburn  2901:     foreach (keys %{$allroles}) {
                   2902:         my %thesepriv=();
                   2903:         if (($_=~/^au/) || ($_=~/^ca/)) { $author=1; }
                   2904:         foreach (split(/:/,$$allroles{$_})) {
                   2905:             if ($_ ne '') {
                   2906:                 my ($privilege,$restrictions)=split(/&/,$_);
                   2907:                 if ($restrictions eq '') {
                   2908:                     $thesepriv{$privilege}='F';
                   2909:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   2910:                     $thesepriv{$privilege}.=$restrictions;
                   2911:                 }
                   2912:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   2913:             }
                   2914:         }
                   2915:         my $thesestr='';
                   2916:         foreach (keys %thesepriv) { $thesestr.=':'.$_.'&'.$thesepriv{$_}; }
1.743     albertel 2917:         $userroles->{'user.priv.'.$_} = $thesestr;
1.567     raeburn  2918:     }
                   2919:     return ($author,$adv);
                   2920: }
                   2921: 
1.12      www      2922: # --------------------------------------------------------------- get interface
                   2923: 
                   2924: sub get {
1.131     albertel 2925:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      2926:    my $items='';
1.191     harris41 2927:    foreach (@$storearr) {
1.12      www      2928:        $items.=escape($_).'&';
1.191     harris41 2929:    }
1.12      www      2930:    $items=~s/\&$//;
1.620     albertel 2931:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2932:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 2933:    my $uhome=&homeserver($uname,$udomain);
                   2934: 
1.133     albertel 2935:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      2936:    my @pairs=split(/\&/,$rep);
1.273     albertel 2937:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   2938:      return @pairs;
                   2939:    }
1.15      www      2940:    my %returnhash=();
1.42      www      2941:    my $i=0;
1.191     harris41 2942:    foreach (@$storearr) {
1.557     albertel 2943:       $returnhash{$_}=&thaw_unescape($pairs[$i]);
1.42      www      2944:       $i++;
1.191     harris41 2945:    }
1.15      www      2946:    return %returnhash;
1.27      www      2947: }
                   2948: 
                   2949: # --------------------------------------------------------------- del interface
                   2950: 
                   2951: sub del {
1.133     albertel 2952:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      2953:    my $items='';
1.191     harris41 2954:    foreach (@$storearr) {
1.27      www      2955:        $items.=escape($_).'&';
1.191     harris41 2956:    }
1.27      www      2957:    $items=~s/\&$//;
1.620     albertel 2958:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2959:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 2960:    my $uhome=&homeserver($uname,$udomain);
                   2961: 
                   2962:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      2963: }
                   2964: 
                   2965: # -------------------------------------------------------------- dump interface
                   2966: 
                   2967: sub dump {
1.755     albertel 2968:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   2969:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2970:     if (!$uname) { $uname=$env{'user.name'}; }
                   2971:     my $uhome=&homeserver($uname,$udomain);
                   2972:     if ($regexp) {
                   2973: 	$regexp=&escape($regexp);
                   2974:     } else {
                   2975: 	$regexp='.';
                   2976:     }
                   2977:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   2978:     my @pairs=split(/\&/,$rep);
                   2979:     my %returnhash=();
                   2980:     foreach my $item (@pairs) {
                   2981: 	my ($key,$value)=split(/=/,$item,2);
                   2982: 	$key = &unescape($key);
                   2983: 	next if ($key =~ /^error: 2 /);
                   2984: 	$returnhash{$key}=&thaw_unescape($value);
                   2985:     }
                   2986:     return %returnhash;
1.407     www      2987: }
                   2988: 
1.717     albertel 2989: # --------------------------------------------------------- dumpstore interface
                   2990: 
                   2991: sub dumpstore {
                   2992:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   2993:    return &dump($namespace,$udomain,$uname,$regexp,$range);
                   2994: }
                   2995: 
1.407     www      2996: # -------------------------------------------------------------- keys interface
                   2997: 
                   2998: sub getkeys {
                   2999:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 3000:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3001:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      3002:    my $uhome=&homeserver($uname,$udomain);
                   3003:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   3004:    my @keyarray=();
                   3005:    foreach (split(/\&/,$rep)) {
                   3006:       push (@keyarray,&unescape($_));
                   3007:    }
                   3008:    return @keyarray;
1.318     matthew  3009: }
                   3010: 
1.319     matthew  3011: # --------------------------------------------------------------- currentdump
                   3012: sub currentdump {
1.328     matthew  3013:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 3014:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   3015:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   3016:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  3017:    my $uhome = &homeserver($sname,$sdom);
                   3018:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  3019:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  3020:    #
1.318     matthew  3021:    my %returnhash=();
1.319     matthew  3022:    #
                   3023:    if ($rep eq "unknown_cmd") { 
                   3024:        # an old lond will not know currentdump
                   3025:        # Do a dump and make it look like a currentdump
1.326     matthew  3026:        my @tmp = &dump($courseid,$sdom,$sname,'.');
1.319     matthew  3027:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   3028:        my %hash = @tmp;
                   3029:        @tmp=();
1.424     matthew  3030:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  3031:    } else {
                   3032:        my @pairs=split(/\&/,$rep);
                   3033:        foreach (@pairs) {
                   3034:            my ($key,$value)=split(/=/,$_);
                   3035:            my ($symb,$param) = split(/:/,$key);
                   3036:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 3037:                                                         &thaw_unescape($value);
1.319     matthew  3038:        }
1.191     harris41 3039:    }
1.12      www      3040:    return %returnhash;
1.424     matthew  3041: }
                   3042: 
                   3043: sub convert_dump_to_currentdump{
                   3044:     my %hash = %{shift()};
                   3045:     my %returnhash;
                   3046:     # Code ripped from lond, essentially.  The only difference
                   3047:     # here is the unescaping done by lonnet::dump().  Conceivably
                   3048:     # we might run in to problems with parameter names =~ /^v\./
                   3049:     while (my ($key,$value) = each(%hash)) {
                   3050:         my ($v,$symb,$param) = split(/:/,$key);
                   3051:         next if ($v eq 'version' || $symb eq 'keys');
                   3052:         next if (exists($returnhash{$symb}) &&
                   3053:                  exists($returnhash{$symb}->{$param}) &&
                   3054:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   3055:         $returnhash{$symb}->{$param}=$value;
                   3056:         $returnhash{$symb}->{'v.'.$param}=$v;
                   3057:     }
                   3058:     #
                   3059:     # Remove all of the keys in the hashes which keep track of
                   3060:     # the version of the parameter.
                   3061:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   3062:         # use a foreach because we are going to delete from the hash.
                   3063:         foreach my $key (keys(%$param_hash)) {
                   3064:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   3065:         }
                   3066:     }
                   3067:     return \%returnhash;
1.12      www      3068: }
                   3069: 
1.627     albertel 3070: # ------------------------------------------------------ critical inc interface
                   3071: 
                   3072: sub cinc {
                   3073:     return &inc(@_,'critical');
                   3074: }
                   3075: 
1.449     matthew  3076: # --------------------------------------------------------------- inc interface
                   3077: 
                   3078: sub inc {
1.627     albertel 3079:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 3080:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3081:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  3082:     my $uhome=&homeserver($uname,$udomain);
                   3083:     my $items='';
                   3084:     if (! ref($store)) {
                   3085:         # got a single value, so use that instead
                   3086:         $items = &escape($store).'=&';
                   3087:     } elsif (ref($store) eq 'SCALAR') {
                   3088:         $items = &escape($$store).'=&';        
                   3089:     } elsif (ref($store) eq 'ARRAY') {
                   3090:         $items = join('=&',map {&escape($_);} @{$store});
                   3091:     } elsif (ref($store) eq 'HASH') {
                   3092:         while (my($key,$value) = each(%{$store})) {
                   3093:             $items.= &escape($key).'='.&escape($value).'&';
                   3094:         }
                   3095:     }
                   3096:     $items=~s/\&$//;
1.627     albertel 3097:     if ($critical) {
                   3098: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3099:     } else {
                   3100: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3101:     }
1.449     matthew  3102: }
                   3103: 
1.12      www      3104: # --------------------------------------------------------------- put interface
                   3105: 
                   3106: sub put {
1.134     albertel 3107:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3108:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3109:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3110:    my $uhome=&homeserver($uname,$udomain);
1.12      www      3111:    my $items='';
1.191     harris41 3112:    foreach (keys %$storehash) {
1.557     albertel 3113:        $items.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
1.191     harris41 3114:    }
1.12      www      3115:    $items=~s/\&$//;
1.134     albertel 3116:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      3117: }
                   3118: 
1.631     albertel 3119: # ------------------------------------------------------------ newput interface
                   3120: 
                   3121: sub newput {
                   3122:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   3123:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3124:    if (!$uname) { $uname=$env{'user.name'}; }
                   3125:    my $uhome=&homeserver($uname,$udomain);
                   3126:    my $items='';
                   3127:    foreach my $key (keys(%$storehash)) {
                   3128:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   3129:    }
                   3130:    $items=~s/\&$//;
                   3131:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   3132: }
                   3133: 
                   3134: # ---------------------------------------------------------  putstore interface
                   3135: 
1.524     raeburn  3136: sub putstore {
1.715     albertel 3137:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 3138:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3139:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  3140:    my $uhome=&homeserver($uname,$udomain);
                   3141:    my $items='';
1.715     albertel 3142:    foreach my $key (keys(%$storehash)) {
                   3143:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  3144:    }
1.715     albertel 3145:    $items=~s/\&$//;
1.716     albertel 3146:    my $esc_symb=&escape($symb);
                   3147:    my $esc_v=&escape($version);
1.715     albertel 3148:    my $reply =
1.716     albertel 3149:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 3150: 	      $uhome);
                   3151:    if ($reply eq 'unknown_cmd') {
1.716     albertel 3152:        # gfall back to way things use to be done
1.715     albertel 3153:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   3154: 			    $uname);
1.524     raeburn  3155:    }
1.715     albertel 3156:    return $reply;
                   3157: }
                   3158: 
                   3159: sub old_putstore {
1.716     albertel 3160:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   3161:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3162:     if (!$uname) { $uname=$env{'user.name'}; }
                   3163:     my $uhome=&homeserver($uname,$udomain);
                   3164:     my %newstorehash;
                   3165:     foreach (keys %$storehash) {
                   3166: 	my $key = $version.':'.&escape($symb).':'.$_;
                   3167: 	$newstorehash{$key} = $storehash->{$_};
                   3168:     }
                   3169:     my $items='';
                   3170:     my %allitems = ();
                   3171:     foreach (keys %newstorehash) {
                   3172: 	if ($_ =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
                   3173: 	    my $key = $1.':keys:'.$2;
                   3174: 	    $allitems{$key} .= $3.':';
                   3175: 	}
                   3176: 	$items.=$_.'='.&freeze_escape($newstorehash{$_}).'&';
                   3177:     }
                   3178:     foreach (keys %allitems) {
                   3179: 	$allitems{$_} =~ s/\:$//;
                   3180: 	$items.= $_.'='.$allitems{$_}.'&';
                   3181:     }
                   3182:     $items=~s/\&$//;
                   3183:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  3184: }
                   3185: 
1.47      www      3186: # ------------------------------------------------------ critical put interface
                   3187: 
                   3188: sub cput {
1.134     albertel 3189:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3190:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3191:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3192:    my $uhome=&homeserver($uname,$udomain);
1.47      www      3193:    my $items='';
1.191     harris41 3194:    foreach (keys %$storehash) {
1.715     albertel 3195:        $items.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
1.191     harris41 3196:    }
1.47      www      3197:    $items=~s/\&$//;
1.134     albertel 3198:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3199: }
                   3200: 
                   3201: # -------------------------------------------------------------- eget interface
                   3202: 
                   3203: sub eget {
1.133     albertel 3204:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3205:    my $items='';
1.191     harris41 3206:    foreach (@$storearr) {
1.12      www      3207:        $items.=escape($_).'&';
1.191     harris41 3208:    }
1.12      www      3209:    $items=~s/\&$//;
1.620     albertel 3210:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3211:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3212:    my $uhome=&homeserver($uname,$udomain);
                   3213:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3214:    my @pairs=split(/\&/,$rep);
                   3215:    my %returnhash=();
1.42      www      3216:    my $i=0;
1.191     harris41 3217:    foreach (@$storearr) {
1.557     albertel 3218:       $returnhash{$_}=&thaw_unescape($pairs[$i]);
1.42      www      3219:       $i++;
1.191     harris41 3220:    }
1.12      www      3221:    return %returnhash;
                   3222: }
                   3223: 
1.667     albertel 3224: # ------------------------------------------------------------ tmpput interface
                   3225: sub tmpput {
                   3226:     my ($storehash,$server)=@_;
                   3227:     my $items='';
                   3228:     foreach (keys(%$storehash)) {
                   3229: 	$items.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
                   3230:     }
                   3231:     $items=~s/\&$//;
                   3232:     return &reply("tmpput:$items",$server);
                   3233: }
                   3234: 
                   3235: # ------------------------------------------------------------ tmpget interface
                   3236: sub tmpget {
1.688     albertel 3237:     my ($token,$server)=@_;
                   3238:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3239:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 3240:     my %returnhash;
                   3241:     foreach my $item (split(/\&/,$rep)) {
                   3242: 	my ($key,$value)=split(/=/,$item);
                   3243: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   3244:     }
                   3245:     return %returnhash;
                   3246: }
                   3247: 
1.688     albertel 3248: # ------------------------------------------------------------ tmpget interface
                   3249: sub tmpdel {
                   3250:     my ($token,$server)=@_;
                   3251:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3252:     return &reply("tmpdel:$token",$server);
                   3253: }
                   3254: 
1.765     albertel 3255: # -------------------------------------------------- portfolio access checking
                   3256: 
                   3257: sub portfolio_access {
1.766     albertel 3258:     my ($requrl) = @_;
1.765     albertel 3259:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   3260:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
                   3261:     if ($result eq 'ok') {
1.766     albertel 3262:        return 'F';
1.765     albertel 3263:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 3264:        return 'A';
1.765     albertel 3265:     }
1.766     albertel 3266:     return '';
1.765     albertel 3267: }
                   3268: 
                   3269: sub get_portfolio_access {
1.767     albertel 3270:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   3271: 
                   3272:     if (!ref($access_hash)) {
                   3273: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   3274: 	my %access_controls = &get_access_controls($current_perms,$group,
                   3275: 						   $file_name);
                   3276: 	$access_hash = $access_controls{$file_name};
                   3277:     }
                   3278: 
1.765     albertel 3279:     my ($public,$guest,@domains,@users,@courses,@groups);
                   3280:     my $now = time;
                   3281:     if (ref($access_hash) eq 'HASH') {
                   3282:         foreach my $key (keys(%{$access_hash})) {
                   3283:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   3284:             if ($start > $now) {
                   3285:                 next;
                   3286:             }
                   3287:             if ($end && $end<$now) {
                   3288:                 next;
                   3289:             }
                   3290:             if ($scope eq 'public') {
                   3291:                 $public = $key;
                   3292:                 last;
                   3293:             } elsif ($scope eq 'guest') {
                   3294:                 $guest = $key;
                   3295:             } elsif ($scope eq 'domains') {
                   3296:                 push(@domains,$key);
                   3297:             } elsif ($scope eq 'users') {
                   3298:                 push(@users,$key);
                   3299:             } elsif ($scope eq 'course') {
                   3300:                 push(@courses,$key);
                   3301:             } elsif ($scope eq 'group') {
                   3302:                 push(@groups,$key);
                   3303:             }
                   3304:         }
                   3305:         if ($public) {
                   3306:             return 'ok';
                   3307:         }
                   3308:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   3309:             if ($guest) {
                   3310:                 return $guest;
                   3311:             }
                   3312:         } else {
                   3313:             if (@domains > 0) {
                   3314:                 foreach my $domkey (@domains) {
                   3315:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   3316:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   3317:                             return 'ok';
                   3318:                         }
                   3319:                     }
                   3320:                 }
                   3321:             }
                   3322:             if (@users > 0) {
                   3323:                 foreach my $userkey (@users) {
                   3324:                     if (exists($access_hash->{$userkey}{'users'}{$env{'user.name'}.':'.$env{'user.domain'}})) {
                   3325:                         return 'ok';
                   3326:                     }
                   3327:                 }
                   3328:             }
                   3329:             my %roleshash;
                   3330:             my @courses_and_groups = @courses;
                   3331:             push(@courses_and_groups,@groups); 
                   3332:             if (@courses_and_groups > 0) {
                   3333:                 my (%allgroups,%allroles); 
                   3334:                 my ($start,$end,$role,$sec,$group);
                   3335:                 foreach my $envkey (%env) {
                   3336:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./([^/]+)/([^/]+)/?([^/]*)$-) {
                   3337:                         my $cid = $2.'_'.$3; 
                   3338:                         if ($1 eq 'gr') {
                   3339:                             $group = $4;
                   3340:                             $allgroups{$cid}{$group} = $env{$envkey};
                   3341:                         } else {
                   3342:                             if ($4 eq '') {
                   3343:                                 $sec = 'none';
                   3344:                             } else {
                   3345:                                 $sec = $4;
                   3346:                             }
                   3347:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   3348:                         }
                   3349:                     } elsif ($envkey =~ m-^user\.role\./cr/(\w+/\w+/\w*)./([^/]+)/([^/]+)/?([^/]*)$-) {
                   3350:                         my $cid = $2.'_'.$3;
                   3351:                         if ($4 eq '') {
                   3352:                             $sec = 'none';
                   3353:                         } else {
                   3354:                             $sec = $4;
                   3355:                         }
                   3356:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   3357:                     }
                   3358:                 }
                   3359:                 if (keys(%allroles) == 0) {
                   3360:                     return;
                   3361:                 }
                   3362:                 foreach my $key (@courses_and_groups) {
                   3363:                     my %content = %{$$access_hash{$key}};
                   3364:                     my $cnum = $content{'number'};
                   3365:                     my $cdom = $content{'domain'};
                   3366:                     my $cid = $cdom.'_'.$cnum;
                   3367:                     if (!exists($allroles{$cid})) {
                   3368:                         next;
                   3369:                     }    
                   3370:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   3371:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   3372:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   3373:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   3374:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   3375:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   3376:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   3377:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   3378:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   3379:                                         if (grep/^all$/,@sections) {
                   3380:                                             return 'ok';
                   3381:                                         } else {
                   3382:                                             if (grep/^$sec$/,@sections) {
                   3383:                                                 return 'ok';
                   3384:                                             }
                   3385:                                         }
                   3386:                                     }
                   3387:                                 }
                   3388:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   3389:                                     if (grep/^none$/,@groups) {
                   3390:                                         return 'ok';
                   3391:                                     }
                   3392:                                 } else {
                   3393:                                     if (grep/^all$/,@groups) {
                   3394:                                         return 'ok';
                   3395:                                     } 
                   3396:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   3397:                                         if (grep/^$group$/,@groups) {
                   3398:                                             return 'ok';
                   3399:                                         }
                   3400:                                     }
                   3401:                                 } 
                   3402:                             }
                   3403:                         }
                   3404:                     }
                   3405:                 }
                   3406:             }
                   3407:             if ($guest) {
                   3408:                 return $guest;
                   3409:             }
                   3410:         }
                   3411:     }
                   3412:     return;
                   3413: }
                   3414: 
                   3415: sub course_group_datechecker {
                   3416:     my ($dates,$now,$status) = @_;
                   3417:     my ($start,$end) = split(/\./,$dates);
                   3418:     if (!$start && !$end) {
                   3419:         return 'ok';
                   3420:     }
                   3421:     if (grep/^active$/,@{$status}) {
                   3422:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   3423:             return 'ok';
                   3424:         }
                   3425:     }
                   3426:     if (grep/^previous$/,@{$status}) {
                   3427:         if ($end > $now ) {
                   3428:             return 'ok';
                   3429:         }
                   3430:     }
                   3431:     if (grep/^future$/,@{$status}) {
                   3432:         if ($start > $now) {
                   3433:             return 'ok';
                   3434:         }
                   3435:     }
                   3436:     return; 
                   3437: }
                   3438: 
                   3439: sub parse_portfolio_url {
                   3440:     my ($url) = @_;
                   3441: 
                   3442:     my ($type,$udom,$unum,$group,$file_name);
                   3443:     
                   3444:     if ($url =~  m-^/*uploaded/([^/]+)/([^/]+)/portfolio(/.+)$-) {
                   3445: 	$type = 1;
                   3446:         $udom = $1;
                   3447:         $unum = $2;
                   3448:         $file_name = $3;
                   3449:     } elsif ($url =~ m-^/*uploaded/([^/]+)/([^/]+)/groups/([^/]+)/portfolio/(.+)$-) {
                   3450: 	$type = 2;
                   3451:         $udom = $1;
                   3452:         $unum = $2;
                   3453:         $group = $3;
                   3454:         $file_name = $3.'/'.$4;
                   3455:     }
                   3456:     if (wantarray) {
                   3457: 	return ($type,$udom,$unum,$file_name,$group);
                   3458:     }
                   3459:     return $type;
                   3460: }
                   3461: 
                   3462: sub is_portfolio_url {
                   3463:     my ($url) = @_;
                   3464:     return scalar(&parse_portfolio_url($url));
                   3465: }
                   3466: 
1.341     www      3467: # ---------------------------------------------- Custom access rule evaluation
                   3468: 
                   3469: sub customaccess {
                   3470:     my ($priv,$uri)=@_;
1.620     albertel 3471:     my ($urole,$urealm)=split(/\./,$env{'request.role'});
1.343     www      3472:     $urealm=~s/^\W//;
                   3473:     my ($udom,$ucrs,$usec)=split(/\//,$urealm);
1.341     www      3474:     my $access=0;
                   3475:     foreach (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.342     www      3476: 	my ($effect,$realm,$role)=split(/\:/,$_);
1.343     www      3477:         if ($role) {
                   3478: 	   if ($role ne $urole) { next; }
                   3479:         }
                   3480:         foreach (split(/\s*\,\s*/,$realm)) {
                   3481:             my ($tdom,$tcrs,$tsec)=split(/\_/,$_);
                   3482:             if ($tdom) {
                   3483: 		if ($tdom ne $udom) { next; }
                   3484:             }
                   3485:             if ($tcrs) {
                   3486: 		if ($tcrs ne $ucrs) { next; }
                   3487:             }
                   3488:             if ($tsec) {
                   3489: 		if ($tsec ne $usec) { next; }
                   3490:             }
                   3491:             $access=($effect eq 'allow');
                   3492:             last;
1.342     www      3493:         }
1.402     bowersj2 3494: 	if ($realm eq '' && $role eq '') {
                   3495:             $access=($effect eq 'allow');
                   3496: 	}
1.341     www      3497:     }
                   3498:     return $access;
                   3499: }
                   3500: 
1.103     harris41 3501: # ------------------------------------------------- Check for a user privilege
1.12      www      3502: 
                   3503: sub allowed {
1.579     albertel 3504:     my ($priv,$uri,$symb)=@_;
1.705     albertel 3505:     my $ver_orguri=$uri;
1.439     www      3506:     $uri=&deversion($uri);
1.152     www      3507:     my $orguri=$uri;
1.52      www      3508:     $uri=&declutter($uri);
1.545     banghart 3509:     
1.620     albertel 3510:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      3511: # Free bre access to adm and meta resources
1.775     albertel 3512:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 3513: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   3514: 	&& ($priv eq 'bre')) {
1.14      www      3515: 	return 'F';
1.159     www      3516:     }
                   3517: 
1.545     banghart 3518: # Free bre access to user's own portfolio contents
1.714     raeburn  3519:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  3520:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  3521: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.545     banghart 3522:         return 'F';
                   3523:     }
                   3524: 
1.762     raeburn  3525: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  3526:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   3527:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   3528:         if (exists($env{'request.course.id'})) {
                   3529:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3530:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3531:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   3532:                 my $courseprivid=$env{'request.course.id'};
                   3533:                 $courseprivid=~s/\_/\//;
                   3534:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   3535:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   3536:                     return $1; 
1.762     raeburn  3537:                 } else {
                   3538:                     if ($env{'request.course.sec'}) {
                   3539:                         $courseprivid.='/'.$env{'request.course.sec'};
                   3540:                     }
                   3541:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   3542:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   3543:                         return $2;
                   3544:                     }
1.714     raeburn  3545:                 }
                   3546:             }
                   3547:         }
                   3548:     }
                   3549: 
1.159     www      3550: # Free bre to public access
                   3551: 
                   3552:     if ($priv eq 'bre') {
1.238     www      3553:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 3554: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      3555:            return 'F'; 
                   3556:         }
1.238     www      3557:         if ($copyright eq 'priv') {
                   3558:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 3559: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      3560: 		return '';
                   3561:             }
                   3562:         }
                   3563:         if ($copyright eq 'domain') {
                   3564:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 3565: 	    unless (($env{'user.domain'} eq $1) ||
                   3566:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      3567: 		return '';
                   3568:             }
1.262     matthew  3569:         }
1.620     albertel 3570:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  3571:             # Library role, so allow browsing of resources in this domain.
                   3572:             return 'F';
1.238     www      3573:         }
1.341     www      3574:         if ($copyright eq 'custom') {
                   3575: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   3576:         }
1.14      www      3577:     }
1.264     matthew  3578:     # Domain coordinator is trying to create a course
1.620     albertel 3579:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  3580:         # uri is the requested domain in this case.
                   3581:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  3582:         # a role of dc for the domain in question.
1.620     albertel 3583:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  3584:     }
1.29      www      3585: 
1.52      www      3586:     my $thisallowed='';
                   3587:     my $statecond=0;
                   3588:     my $courseprivid='';
                   3589: 
                   3590: # Course
                   3591: 
1.620     albertel 3592:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3593:        $thisallowed.=$1;
                   3594:     }
1.29      www      3595: 
1.52      www      3596: # Domain
                   3597: 
1.620     albertel 3598:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 3599:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      3600:        $thisallowed.=$1;
                   3601:     }
1.52      www      3602: 
                   3603: # Course: uri itself is a course
1.66      www      3604:     my $courseuri=$uri;
                   3605:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      3606:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      3607: 
1.620     albertel 3608:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 3609:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      3610:        $thisallowed.=$1;
                   3611:     }
1.29      www      3612: 
1.665     albertel 3613: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 3614: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 3615:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 3616: 	$thisallowed='';
1.671     raeburn  3617:         my ($match)=&is_on_map($uri);
                   3618:         if ($match) {
                   3619:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   3620:                   =~/\Q$priv\E\&([^\:]*)/) {
                   3621:                 $thisallowed.=$1;
                   3622:             }
                   3623:         } else {
1.705     albertel 3624:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  3625:             if ($refuri) {
                   3626:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  3627:                     $thisallowed='F';
1.671     raeburn  3628:                 } else {
                   3629:                     $refuri=&declutter($refuri);
                   3630:                     my ($match) = &is_on_map($refuri);
                   3631:                     if ($match) {
                   3632:                         $thisallowed='F';
                   3633:                     }
1.669     raeburn  3634:                 }
1.671     raeburn  3635:             }
                   3636:         }
1.314     www      3637:     }
1.492     albertel 3638: 
1.766     albertel 3639:     if ($priv eq 'bre'
                   3640: 	&& $thisallowed ne 'F' 
                   3641: 	&& $thisallowed ne '2'
                   3642: 	&& &is_portfolio_url($uri)) {
                   3643: 	$thisallowed = &portfolio_access($uri);
                   3644:     }
                   3645:     
1.52      www      3646: # Full access at system, domain or course-wide level? Exit.
1.29      www      3647: 
                   3648:     if ($thisallowed=~/F/) {
                   3649: 	return 'F';
                   3650:     }
                   3651: 
1.52      www      3652: # If this is generating or modifying users, exit with special codes
1.29      www      3653: 
1.643     www      3654:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   3655: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 3656: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      3657: # no author name given, so this just checks on the general right to make a co-author in this domain
                   3658: 	    unless ($auname) { return $thisallowed; }
                   3659: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 3660: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   3661: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   3662: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   3663: 	}
1.52      www      3664: 	return $thisallowed;
                   3665:     }
                   3666: #
1.103     harris41 3667: # Gathered so far: system, domain and course wide privileges
1.52      www      3668: #
                   3669: # Course: See if uri or referer is an individual resource that is part of 
                   3670: # the course
                   3671: 
1.620     albertel 3672:     if ($env{'request.course.id'}) {
1.232     www      3673: 
1.620     albertel 3674:        $courseprivid=$env{'request.course.id'};
                   3675:        if ($env{'request.course.sec'}) {
                   3676:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      3677:        }
                   3678:        $courseprivid=~s/\_/\//;
                   3679:        my $checkreferer=1;
1.232     www      3680:        my ($match,$cond)=&is_on_map($uri);
                   3681:        if ($match) {
                   3682:            $statecond=$cond;
1.620     albertel 3683:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 3684:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3685:                $thisallowed.=$1;
                   3686:                $checkreferer=0;
                   3687:            }
1.29      www      3688:        }
1.83      www      3689:        
1.148     www      3690:        if ($checkreferer) {
1.620     albertel 3691: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      3692:             unless ($refuri) {
1.620     albertel 3693:                 foreach (keys %env) {
1.148     www      3694: 		    if ($_=~/^httpref\..*\*/) {
                   3695: 			my $pattern=$_;
1.156     www      3696:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      3697:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   3698:                         $pattern=~s/\//\\\//g;
1.152     www      3699:                         if ($orguri=~/$pattern/) {
1.620     albertel 3700: 			    $refuri=$env{$_};
1.148     www      3701:                         }
                   3702:                     }
1.191     harris41 3703:                 }
1.148     www      3704:             }
1.232     www      3705: 
1.148     www      3706:          if ($refuri) { 
1.152     www      3707: 	  $refuri=&declutter($refuri);
1.232     www      3708:           my ($match,$cond)=&is_on_map($refuri);
                   3709:             if ($match) {
                   3710:               my $refstatecond=$cond;
1.620     albertel 3711:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 3712:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3713:                   $thisallowed.=$1;
1.53      www      3714:                   $uri=$refuri;
                   3715:                   $statecond=$refstatecond;
1.52      www      3716:               }
                   3717:           }
1.148     www      3718:         }
1.29      www      3719:        }
1.52      www      3720:    }
1.29      www      3721: 
1.52      www      3722: #
1.103     harris41 3723: # Gathered now: all privileges that could apply, and condition number
1.52      www      3724: # 
                   3725: #
                   3726: # Full or no access?
                   3727: #
1.29      www      3728: 
1.52      www      3729:     if ($thisallowed=~/F/) {
                   3730: 	return 'F';
                   3731:     }
1.29      www      3732: 
1.52      www      3733:     unless ($thisallowed) {
                   3734:         return '';
                   3735:     }
1.29      www      3736: 
1.52      www      3737: # Restrictions exist, deal with them
                   3738: #
                   3739: #   C:according to course preferences
                   3740: #   R:according to resource settings
                   3741: #   L:unless locked
                   3742: #   X:according to user session state
                   3743: #
                   3744: 
                   3745: # Possibly locked functionality, check all courses
1.54      www      3746: # Locks might take effect only after 10 minutes cache expiration for other
                   3747: # courses, and 2 minutes for current course
1.52      www      3748: 
                   3749:     my $envkey;
                   3750:     if ($thisallowed=~/L/) {
1.620     albertel 3751:         foreach $envkey (keys %env) {
1.54      www      3752:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   3753:                my $courseid=$2;
                   3754:                my $roleid=$1.'.'.$2;
1.92      www      3755:                $courseid=~s/^\///;
1.54      www      3756:                my $expiretime=600;
1.620     albertel 3757:                if ($env{'request.role'} eq $roleid) {
1.54      www      3758: 		  $expiretime=120;
                   3759:                }
                   3760: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   3761:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 3762:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 3763: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      3764:                }
1.620     albertel 3765:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   3766:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   3767: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   3768:                        &log($env{'user.domain'},$env{'user.name'},
                   3769:                             $env{'user.home'},
1.57      www      3770:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      3771:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 3772:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      3773: 		       return '';
                   3774:                    }
                   3775:                }
1.620     albertel 3776:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   3777:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   3778: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   3779:                        &log($env{'user.domain'},$env{'user.name'},
                   3780:                             $env{'user.home'},
1.57      www      3781:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      3782:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 3783:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      3784: 		       return '';
                   3785:                    }
                   3786:                }
                   3787: 	   }
1.29      www      3788:        }
1.52      www      3789:     }
                   3790:    
                   3791: #
                   3792: # Rest of the restrictions depend on selected course
                   3793: #
                   3794: 
1.620     albertel 3795:     unless ($env{'request.course.id'}) {
1.766     albertel 3796: 	if ($thisallowed eq 'A') {
                   3797: 	    return 'A';
                   3798: 	} else {
                   3799: 	    return '1';
                   3800: 	}
1.52      www      3801:     }
1.29      www      3802: 
1.52      www      3803: #
                   3804: # Now user is definitely in a course
                   3805: #
1.53      www      3806: 
                   3807: 
                   3808: # Course preferences
                   3809: 
                   3810:    if ($thisallowed=~/C/) {
1.620     albertel 3811:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   3812:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   3813:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 3814: 	   =~/\Q$rolecode\E/) {
1.689     albertel 3815: 	   if ($priv ne 'pch') { 
                   3816: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   3817: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   3818: 			$env{'request.course.id'});
                   3819: 	   }
1.237     www      3820:            return '';
                   3821:        }
                   3822: 
1.620     albertel 3823:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 3824: 	   =~/\Q$unamedom\E/) {
1.689     albertel 3825: 	   if ($priv ne 'pch') { 
                   3826: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   3827: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   3828: 			$env{'request.course.id'});
                   3829: 	   }
1.54      www      3830:            return '';
                   3831:        }
1.53      www      3832:    }
                   3833: 
                   3834: # Resource preferences
                   3835: 
                   3836:    if ($thisallowed=~/R/) {
1.620     albertel 3837:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 3838:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689     albertel 3839: 	   if ($priv ne 'pch') { 
                   3840: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   3841: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   3842: 	   }
                   3843: 	   return '';
1.54      www      3844:        }
1.53      www      3845:    }
1.30      www      3846: 
1.246     www      3847: # Restricted by state or randomout?
1.30      www      3848: 
1.52      www      3849:    if ($thisallowed=~/X/) {
1.620     albertel 3850:       if ($env{'acc.randomout'}) {
1.579     albertel 3851: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 3852:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      3853:             return ''; 
                   3854:          }
1.247     www      3855:       }
                   3856:       if (&condval($statecond)) {
1.52      www      3857: 	 return '2';
                   3858:       } else {
                   3859:          return '';
                   3860:       }
                   3861:    }
1.30      www      3862: 
1.766     albertel 3863:     if ($thisallowed eq 'A') {
                   3864: 	return 'A';
                   3865:     }
1.52      www      3866:    return 'F';
1.232     www      3867: }
                   3868: 
1.710     albertel 3869: sub split_uri_for_cond {
                   3870:     my $uri=&deversion(&declutter(shift));
                   3871:     my @uriparts=split(/\//,$uri);
                   3872:     my $filename=pop(@uriparts);
                   3873:     my $pathname=join('/',@uriparts);
                   3874:     return ($pathname,$filename);
                   3875: }
1.232     www      3876: # --------------------------------------------------- Is a resource on the map?
                   3877: 
                   3878: sub is_on_map {
1.710     albertel 3879:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 3880:     #Trying to find the conditional for the file
1.620     albertel 3881:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 3882: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      3883:     if ($match) {
1.289     bowersj2 3884: 	return (1,$1);
                   3885:     } else {
1.434     www      3886: 	return (0,0);
1.289     bowersj2 3887:     }
1.12      www      3888: }
                   3889: 
1.427     www      3890: # --------------------------------------------------------- Get symb from alias
                   3891: 
                   3892: sub get_symb_from_alias {
                   3893:     my $symb=shift;
                   3894:     my ($map,$resid,$url)=&decode_symb($symb);
                   3895: # Already is a symb
                   3896:     if ($url) { return $symb; }
                   3897: # Must be an alias
                   3898:     my $aliassymb='';
                   3899:     my %bighash;
1.620     albertel 3900:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      3901:                             &GDBM_READER(),0640)) {
                   3902:         my $rid=$bighash{'mapalias_'.$symb};
                   3903: 	if ($rid) {
                   3904: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 3905: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   3906: 				    $resid,$bighash{'src_'.$rid});
1.427     www      3907: 	}
                   3908:         untie %bighash;
                   3909:     }
                   3910:     return $aliassymb;
                   3911: }
                   3912: 
1.12      www      3913: # ----------------------------------------------------------------- Define Role
                   3914: 
                   3915: sub definerole {
                   3916:   if (allowed('mcr','/')) {
                   3917:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.392     www      3918:     foreach (split(':',$sysrole)) {
1.21      www      3919: 	my ($crole,$cqual)=split(/\&/,$_);
1.479     albertel 3920:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   3921:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   3922: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      3923:                return "refused:s:$crole&$cqual"; 
                   3924:             }
                   3925:         }
1.191     harris41 3926:     }
1.392     www      3927:     foreach (split(':',$domrole)) {
1.21      www      3928: 	my ($crole,$cqual)=split(/\&/,$_);
1.479     albertel 3929:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   3930:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   3931: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      3932:                return "refused:d:$crole&$cqual"; 
                   3933:             }
                   3934:         }
1.191     harris41 3935:     }
1.392     www      3936:     foreach (split(':',$courole)) {
1.21      www      3937: 	my ($crole,$cqual)=split(/\&/,$_);
1.479     albertel 3938:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   3939:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   3940: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      3941:                return "refused:c:$crole&$cqual"; 
                   3942:             }
                   3943:         }
1.191     harris41 3944:     }
1.620     albertel 3945:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   3946:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      3947: 	        "rolesdef_$rolename=".
                   3948:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 3949:     return reply($command,$env{'user.home'});
1.12      www      3950:   } else {
                   3951:     return 'refused';
                   3952:   }
1.105     harris41 3953: }
                   3954: 
                   3955: # ---------------- Make a metadata query against the network of library servers
                   3956: 
                   3957: sub metadata_query {
1.244     matthew  3958:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 3959:     my %rhash;
1.244     matthew  3960:     my @server_list = (defined($server_array) ? @$server_array
                   3961:                                               : keys(%libserv) );
                   3962:     for my $server (@server_list) {
1.118     harris41 3963: 	unless ($custom or $customshow) {
                   3964: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   3965: 	    $rhash{$server}=$reply;
                   3966: 	}
                   3967: 	else {
                   3968: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   3969: 			     &escape($custom).':'.&escape($customshow),
                   3970: 			     $server);
                   3971: 	    $rhash{$server}=$reply;
                   3972: 	}
1.112     harris41 3973:     }
1.118     harris41 3974:     return \%rhash;
1.240     www      3975: }
                   3976: 
                   3977: # ----------------------------------------- Send log queries and wait for reply
                   3978: 
                   3979: sub log_query {
                   3980:     my ($uname,$udom,$query,%filters)=@_;
                   3981:     my $uhome=&homeserver($uname,$udom);
                   3982:     if ($uhome eq 'no_host') { return 'error: no_host'; }
                   3983:     my $uhost=$hostname{$uhome};
1.241     www      3984:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys %filters));
1.240     www      3985:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   3986:                        $uhome);
1.479     albertel 3987:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      3988:     return get_query_reply($queryid);
                   3989: }
                   3990: 
1.508     raeburn  3991: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  3992: 
                   3993: sub fetch_enrollment_query {
1.511     raeburn  3994:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  3995:     my $homeserver;
1.547     raeburn  3996:     my $maxtries = 1;
1.508     raeburn  3997:     if ($context eq 'automated') {
                   3998:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  3999:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  4000:     } else {
                   4001:         $homeserver = &homeserver($cnum,$dom);
                   4002:     }
1.506     raeburn  4003:     my $host=$hostname{$homeserver};
                   4004:     my $cmd = '';
                   4005:     foreach (keys %{$affiliatesref}) {
1.508     raeburn  4006:         $cmd .= $_.'='.join(",",@{$$affiliatesref{$_}}).'%%';
1.506     raeburn  4007:     }
                   4008:     $cmd =~ s/%%$//;
                   4009:     $cmd = &escape($cmd);
                   4010:     my $query = 'fetchenrollment';
1.620     albertel 4011:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  4012:     unless ($queryid=~/^\Q$host\E\_/) { 
                   4013:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   4014:         return 'error: '.$queryid;
                   4015:     }
1.506     raeburn  4016:     my $reply = &get_query_reply($queryid);
1.547     raeburn  4017:     my $tries = 1;
                   4018:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   4019:         $reply = &get_query_reply($queryid);
                   4020:         $tries ++;
                   4021:     }
1.526     raeburn  4022:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 4023:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  4024:     } else {
1.515     raeburn  4025:         my @responses = split/:/,$reply;
                   4026:         if ($homeserver eq $perlvar{'lonHostID'}) {
                   4027:             foreach (@responses) {
                   4028:                 my ($key,$value) = split/=/,$_;
                   4029:                 $$replyref{$key} = $value;
                   4030:             }
                   4031:         } else {
1.506     raeburn  4032:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
                   4033:             foreach (@responses) {
                   4034:                 my ($key,$value) = split/=/,$_;
                   4035:                 $$replyref{$key} = $value;
                   4036:                 if ($value > 0) {
                   4037:                     foreach (@{$$affiliatesref{$key}}) {
                   4038:                         my $filename = $dom.'_'.$key.'_'.$_.'_classlist.xml';
                   4039:                         my $destname = $pathname.'/'.$filename;
                   4040:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  4041:                         if ($xml_classlist =~ /^error/) {
                   4042:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   4043:                         } else {
1.506     raeburn  4044:                             if ( open(FILE,">$destname") ) {
                   4045:                                 print FILE &unescape($xml_classlist);
                   4046:                                 close(FILE);
1.526     raeburn  4047:                             } else {
                   4048:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  4049:                             }
                   4050:                         }
                   4051:                     }
                   4052:                 }
                   4053:             }
                   4054:         }
                   4055:         return 'ok';
                   4056:     }
                   4057:     return 'error';
                   4058: }
                   4059: 
1.242     www      4060: sub get_query_reply {
                   4061:     my $queryid=shift;
1.240     www      4062:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   4063:     my $reply='';
                   4064:     for (1..100) {
                   4065: 	sleep 2;
                   4066:         if (-e $replyfile.'.end') {
1.448     albertel 4067: 	    if (open(my $fh,$replyfile)) {
1.240     www      4068:                $reply.=<$fh>;
1.448     albertel 4069:                close($fh);
1.240     www      4070: 	   } else { return 'error: reply_file_error'; }
1.242     www      4071:            return &unescape($reply);
                   4072: 	}
1.240     www      4073:     }
1.242     www      4074:     return 'timeout:'.$queryid;
1.240     www      4075: }
                   4076: 
                   4077: sub courselog_query {
1.241     www      4078: #
                   4079: # possible filters:
                   4080: # url: url or symb
                   4081: # username
                   4082: # domain
                   4083: # action: view, submit, grade
                   4084: # start: timestamp
                   4085: # end: timestamp
                   4086: #
1.240     www      4087:     my (%filters)=@_;
1.620     albertel 4088:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      4089:     if ($filters{'url'}) {
                   4090: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   4091:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   4092:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   4093:     }
1.620     albertel 4094:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4095:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      4096:     return &log_query($cname,$cdom,'courselog',%filters);
                   4097: }
                   4098: 
                   4099: sub userlog_query {
                   4100:     my ($uname,$udom,%filters)=@_;
                   4101:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      4102: }
                   4103: 
1.506     raeburn  4104: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   4105: 
                   4106: sub auto_run {
1.508     raeburn  4107:     my ($cnum,$cdom) = @_;
                   4108:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  4109:     my $response = &reply('autorun:'.$cdom,$homeserver);
1.506     raeburn  4110:     return $response;
                   4111: }
1.776     albertel 4112: 
1.506     raeburn  4113: sub auto_get_sections {
1.508     raeburn  4114:     my ($cnum,$cdom,$inst_coursecode) = @_;
                   4115:     my $homeserver = &homeserver($cnum,$cdom);
1.506     raeburn  4116:     my @secs = ();
1.511     raeburn  4117:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506     raeburn  4118:     unless ($response eq 'refused') {
                   4119:         @secs = split/:/,$response;
                   4120:     }
                   4121:     return @secs;
                   4122: }
1.776     albertel 4123: 
1.506     raeburn  4124: sub auto_new_course {
1.508     raeburn  4125:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
                   4126:     my $homeserver = &homeserver($cnum,$cdom);
1.515     raeburn  4127:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506     raeburn  4128:     return $response;
                   4129: }
1.776     albertel 4130: 
1.506     raeburn  4131: sub auto_validate_courseID {
1.508     raeburn  4132:     my ($cnum,$cdom,$inst_course_id) = @_;
                   4133:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  4134:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  4135:     return $response;
                   4136: }
1.776     albertel 4137: 
1.506     raeburn  4138: sub auto_create_password {
1.508     raeburn  4139:     my ($cnum,$cdom,$authparam) = @_;
                   4140:     my $homeserver = &homeserver($cnum,$cdom); 
1.506     raeburn  4141:     my $create_passwd = 0;
                   4142:     my $authchk = '';
1.511     raeburn  4143:     my $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
1.506     raeburn  4144:     if ($response eq 'refused') {
                   4145:         $authchk = 'refused';
                   4146:     } else {
                   4147:         ($authparam,$create_passwd,$authchk) = split/:/,$response;
                   4148:     }
                   4149:     return ($authparam,$create_passwd,$authchk);
                   4150: }
                   4151: 
1.706     raeburn  4152: sub auto_photo_permission {
                   4153:     my ($cnum,$cdom,$students) = @_;
                   4154:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 4155:     my ($outcome,$perm_reqd,$conditions) = 
                   4156: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 4157:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4158: 	return (undef,undef);
                   4159:     }
1.706     raeburn  4160:     return ($outcome,$perm_reqd,$conditions);
                   4161: }
                   4162: 
                   4163: sub auto_checkphotos {
                   4164:     my ($uname,$udom,$pid) = @_;
                   4165:     my $homeserver = &homeserver($uname,$udom);
                   4166:     my ($result,$resulttype);
                   4167:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 4168: 				   &escape($uname).':'.&escape($pid),
                   4169: 				   $homeserver));
1.709     albertel 4170:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4171: 	return (undef,undef);
                   4172:     }
1.706     raeburn  4173:     if ($outcome) {
                   4174:         ($result,$resulttype) = split(/:/,$outcome);
                   4175:     } 
                   4176:     return ($result,$resulttype);
                   4177: }
                   4178: 
                   4179: sub auto_photochoice {
                   4180:     my ($cnum,$cdom) = @_;
                   4181:     my $homeserver = &homeserver($cnum,$cdom);
                   4182:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 4183: 						       &escape($cdom),
                   4184: 						       $homeserver)));
1.709     albertel 4185:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4186: 	return (undef,undef);
                   4187:     }
1.706     raeburn  4188:     return ($update,$comment);
                   4189: }
                   4190: 
                   4191: sub auto_photoupdate {
                   4192:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   4193:     my $homeserver = &homeserver($cnum,$dom);
                   4194:     my $host=$hostname{$homeserver};
                   4195:     my $cmd = '';
                   4196:     my $maxtries = 1;
                   4197:     foreach (keys %{$affiliatesref}) {
                   4198:         $cmd .= $_.'='.join(",",@{$$affiliatesref{$_}}).'%%';
                   4199:     }
                   4200:     $cmd =~ s/%%$//;
                   4201:     $cmd = &escape($cmd);
                   4202:     my $query = 'institutionalphotos';
                   4203:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   4204:     unless ($queryid=~/^\Q$host\E\_/) {
                   4205:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   4206:         return 'error: '.$queryid;
                   4207:     }
                   4208:     my $reply = &get_query_reply($queryid);
                   4209:     my $tries = 1;
                   4210:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   4211:         $reply = &get_query_reply($queryid);
                   4212:         $tries ++;
                   4213:     }
                   4214:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   4215:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   4216:     } else {
                   4217:         my @responses = split(/:/,$reply);
                   4218:         my $outcome = shift(@responses); 
                   4219:         foreach my $item (@responses) {
                   4220:             my ($key,$value) = split(/=/,$item);
                   4221:             $$photo{$key} = $value;
                   4222:         }
                   4223:         return $outcome;
                   4224:     }
                   4225:     return 'error';
                   4226: }
                   4227: 
1.521     raeburn  4228: sub auto_instcode_format {
                   4229:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,$cat_order) = @_;
                   4230:     my $courses = '';
1.772     raeburn  4231:     my @homeservers;
1.521     raeburn  4232:     if ($caller eq 'global') {
1.584     raeburn  4233:         foreach my $tryserver (keys %libserv) {
                   4234:             if ($hostdom{$tryserver} eq $codedom) {
1.772     raeburn  4235:                 if (!grep/^\Q$tryserver\E$/,@homeservers) {
                   4236:                     push(@homeservers,$tryserver);
                   4237:                 }
1.584     raeburn  4238:             }
                   4239:         }
1.521     raeburn  4240:     } else {
1.772     raeburn  4241:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  4242:     }
                   4243:     foreach (keys %{$instcodes}) {
                   4244:         $courses .= &escape($_).'='.&escape($$instcodes{$_}).'&';
                   4245:     }
                   4246:     chop($courses);
1.772     raeburn  4247:     my $ok_response = 0;
                   4248:     my $response;
                   4249:     while (@homeservers > 0 && $ok_response == 0) {
                   4250:         my $server = shift(@homeservers); 
                   4251:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   4252:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   4253:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
                   4254:                                                             split/:/,$response;
                   4255:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   4256:             push(@{$codetitles},&str2array($codetitles_str));
                   4257:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   4258:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   4259:             $ok_response = 1;
                   4260:         }
                   4261:     }
                   4262:     if ($ok_response) {
1.521     raeburn  4263:         return 'ok';
1.772     raeburn  4264:     } else {
                   4265:         return $response;
1.521     raeburn  4266:     }
                   4267: }
                   4268: 
1.777     albertel 4269: sub auto_validate_class_sec {
1.773     raeburn  4270:     my ($cdom,$cnum,$owner,$inst_class) = @_;
                   4271:     my $homeserver = &homeserver($cnum,$cdom);
                   4272:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.774     banghart 4273:                         &escape($owner).':'.$cdom,$homeserver);
1.773     raeburn  4274:     return $response;
                   4275: }
                   4276: 
1.679     raeburn  4277: # ------------------------------------------------------- Course Group routines
                   4278: 
                   4279: sub get_coursegroups {
1.683     raeburn  4280:     my ($cdom,$cnum,$group) = @_;
                   4281:     return(&dump('coursegroups',$cdom,$cnum,$group));
1.679     raeburn  4282: }
                   4283: 
                   4284: sub modify_coursegroup {
                   4285:     my ($cdom,$cnum,$groupsettings) = @_;
                   4286:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   4287: }
                   4288: 
                   4289: sub modify_group_roles {
                   4290:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
                   4291:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   4292:     my $role = 'gr/'.&escape($userprivs);
                   4293:     my ($uname,$udom) = split(/:/,$user);
                   4294:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
1.684     raeburn  4295:     if ($result eq 'ok') {
                   4296:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   4297:     }
1.679     raeburn  4298:     return $result;
                   4299: }
                   4300: 
                   4301: sub modify_coursegroup_membership {
                   4302:     my ($cdom,$cnum,$membership) = @_;
                   4303:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   4304:     return $result;
                   4305: }
                   4306: 
1.682     raeburn  4307: sub get_active_groups {
                   4308:     my ($udom,$uname,$cdom,$cnum) = @_;
                   4309:     my $now = time;
                   4310:     my %groups = ();
                   4311:     foreach my $key (keys(%env)) {
                   4312:         if ($key =~ m-user\.role\.gr\./([^/]+)/([^/]+)/(\w+)$-) {
                   4313:             my ($start,$end) = split(/\./,$env{$key});
                   4314:             if (($end!=0) && ($end<$now)) { next; }
                   4315:             if (($start!=0) && ($start>$now)) { next; }
                   4316:             if ($1 eq $cdom && $2 eq $cnum) {
                   4317:                 $groups{$3} = $env{$key} ;
                   4318:             }
                   4319:         }
                   4320:     }
                   4321:     return %groups;
                   4322: }
                   4323: 
1.683     raeburn  4324: sub get_group_membership {
                   4325:     my ($cdom,$cnum,$group) = @_;
                   4326:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   4327: }
                   4328: 
                   4329: sub get_users_groups {
                   4330:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  4331:     my @usersgroups;
1.683     raeburn  4332:     my $cachetime=1800;
                   4333:     $courseid=~s/\_/\//g;
                   4334:     $courseid=~s/^(\w)/\/$1/;
                   4335: 
                   4336:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  4337:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   4338:     if (defined($cached)) {
1.734     albertel 4339:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  4340:     } else {  
                   4341:         $grouplist = '';
                   4342:         my %roleshash = &dump('roles',$udom,$uname,$courseid);
                   4343:         my ($tmp) = keys(%roleshash);
                   4344:         if ($tmp=~/^error:/) {
                   4345:             &logthis('Error retrieving roles: '.$tmp.' for '.$uname.':'.$udom);
                   4346:         } else {
                   4347:             my $access_end = $env{'course.'.$courseid.
                   4348:                                   '.default_enrollment_end_date'};
                   4349:             my $now = time;
1.734     albertel 4350:             foreach my $key (keys(%roleshash)) {
1.733     raeburn  4351:                 if ($key =~ /^\Q$courseid\E\/(\w+)\_gr$/) {
                   4352:                     my $group = $1;
                   4353:                     if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   4354:                         my $start = $2;
                   4355:                         my $end = $1;
                   4356:                         if ($start == -1) { next; } # deleted from group
                   4357:                         if (($start!=0) && ($start>$now)) { next; }
                   4358:                         if (($end!=0) && ($end<$now)) {
                   4359:                             if ($access_end && $access_end < $now) {
                   4360:                                 if ($access_end - $end < 86400) {
                   4361:                                     push(@usersgroups,$group);
                   4362:                                 }
                   4363:                             }
                   4364:                             next;
                   4365:                         }
                   4366:                         push(@usersgroups,$group);
                   4367:                     }
1.683     raeburn  4368:                 }
                   4369:             }
1.733     raeburn  4370:             @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   4371:             $grouplist = join(':',@usersgroups);
                   4372:             &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  4373:         }
                   4374:     }
1.733     raeburn  4375:     return @usersgroups;
1.683     raeburn  4376: }
                   4377: 
                   4378: sub devalidate_getgroups_cache {
                   4379:     my ($udom,$uname,$cdom,$cnum)=@_;
                   4380:     my $courseid = $cdom.'_'.$cnum;
                   4381:     $courseid=~s/\_/\//g;
                   4382:     $courseid=~s/^(\w)/\/$1/;
                   4383:     my $hashid="$udom:$uname:$courseid";
                   4384:     &devalidate_cache_new('getgroups',$hashid);
                   4385: }
                   4386: 
1.12      www      4387: # ------------------------------------------------------------------ Plain Text
                   4388: 
                   4389: sub plaintext {
1.742     raeburn  4390:     my ($short,$type,$cid) = @_;
1.758     albertel 4391:     if ($short =~ /^cr/) {
                   4392: 	return (split('/',$short))[-1];
                   4393:     }
1.742     raeburn  4394:     if (!defined($cid)) {
                   4395:         $cid = $env{'request.course.id'};
                   4396:     }
                   4397:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
                   4398:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
                   4399:                                           '.plaintext'});
                   4400:     }
                   4401:     my %rolenames = (
                   4402:                       Course => 'std',
                   4403:                       Group => 'alt1',
                   4404:                     );
                   4405:     if (defined($type) && 
                   4406:          defined($rolenames{$type}) && 
                   4407:          defined($prp{$short}{$rolenames{$type}})) {
                   4408:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
                   4409:     } else {
                   4410:         return &Apache::lonlocal::mt($prp{$short}{'std'});
                   4411:     }
1.12      www      4412: }
                   4413: 
                   4414: # ----------------------------------------------------------------- Assign Role
                   4415: 
                   4416: sub assignrole {
1.357     www      4417:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
1.21      www      4418:     my $mrole;
                   4419:     if ($role =~ /^cr\//) {
1.393     www      4420:         my $cwosec=$url;
                   4421:         $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
                   4422: 	unless (&allowed('ccr',$cwosec)) {
1.104     www      4423:            &logthis('Refused custom assignrole: '.
                   4424:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 4425: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      4426:            return 'refused'; 
                   4427:         }
1.21      www      4428:         $mrole='cr';
1.678     raeburn  4429:     } elsif ($role =~ /^gr\//) {
                   4430:         my $cwogrp=$url;
                   4431:         $cwogrp=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
                   4432:         unless (&allowed('mdg',$cwogrp)) {
                   4433:             &logthis('Refused group assignrole: '.
                   4434:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   4435:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   4436:             return 'refused';
                   4437:         }
                   4438:         $mrole='gr';
1.21      www      4439:     } else {
1.82      www      4440:         my $cwosec=$url;
1.83      www      4441:         $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
1.373     www      4442:         unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) { 
1.104     www      4443:            &logthis('Refused assignrole: '.
                   4444:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 4445: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      4446:            return 'refused'; 
                   4447:         }
1.21      www      4448:         $mrole=$role;
                   4449:     }
1.620     albertel 4450:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      4451:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      4452:     if ($end) { $command.='_'.$end; }
1.21      www      4453:     if ($start) {
                   4454: 	if ($end) { 
1.81      www      4455:            $command.='_'.$start; 
1.21      www      4456:         } else {
1.81      www      4457:            $command.='_0_'.$start;
1.21      www      4458:         }
                   4459:     }
1.739     raeburn  4460:     my $origstart = $start;
                   4461:     my $origend = $end;
1.357     www      4462: # actually delete
                   4463:     if ($deleteflag) {
1.373     www      4464: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      4465: # modify command to delete the role
1.620     albertel 4466:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      4467:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 4468: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      4469: # set start and finish to negative values for userrolelog
                   4470:            $start=-1;
                   4471:            $end=-1;
                   4472:         }
                   4473:     }
                   4474: # send command
1.349     www      4475:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      4476: # log new user role if status is ok
1.349     www      4477:     if ($answer eq 'ok') {
1.663     raeburn  4478: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  4479: # for course roles, perform group memberships changes triggered by role change.
                   4480:         unless ($role =~ /^gr/) {
                   4481:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   4482:                                              $origstart);
                   4483:         }
1.349     www      4484:     }
                   4485:     return $answer;
1.169     harris41 4486: }
                   4487: 
                   4488: # -------------------------------------------------- Modify user authentication
1.197     www      4489: # Overrides without validation
                   4490: 
1.169     harris41 4491: sub modifyuserauth {
                   4492:     my ($udom,$uname,$umode,$upass)=@_;
                   4493:     my $uhome=&homeserver($uname,$udom);
1.197     www      4494:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   4495:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 4496:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   4497:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 4498:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   4499: 		     &escape($upass),$uhome);
1.620     albertel 4500:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      4501:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   4502:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   4503:     &log($udom,,$uname,$uhome,
1.620     albertel 4504:         'Authentication changed by '.$env{'user.domain'}.', '.
                   4505:                                      $env{'user.name'}.', '.$umode.
1.197     www      4506:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 4507:     unless ($reply eq 'ok') {
1.197     www      4508:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 4509: 	return 'error: '.$reply;
                   4510:     }   
1.170     harris41 4511:     return 'ok';
1.80      www      4512: }
                   4513: 
1.81      www      4514: # --------------------------------------------------------------- Modify a user
1.80      www      4515: 
1.81      www      4516: sub modifyuser {
1.206     matthew  4517:     my ($udom,    $uname, $uid,
                   4518:         $umode,   $upass, $first,
                   4519:         $middle,  $last,  $gene,
1.387     www      4520:         $forceid, $desiredhome, $email)=@_;
1.198     www      4521:     $udom=~s/\W//g;
                   4522:     $uname=~s/\W//g;
1.81      www      4523:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      4524:              $umode.', '.$first.', '.$middle.', '.
1.206     matthew  4525: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
                   4526:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   4527:                                      ' desiredhome not specified'). 
1.620     albertel 4528:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   4529:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 4530:     my $uhome=&homeserver($uname,$udom,'true');
1.80      www      4531: # ----------------------------------------------------------------- Create User
1.406     albertel 4532:     if (($uhome eq 'no_host') && 
                   4533: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      4534:         my $unhome='';
1.209     matthew  4535:         if (defined($desiredhome) && $hostdom{$desiredhome} eq $udom) { 
                   4536:             $unhome = $desiredhome;
1.620     albertel 4537: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   4538: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  4539:         } else { # load balancing routine for determining $unhome
1.80      www      4540:             my $tryserver;
1.81      www      4541:             my $loadm=10000000;
1.80      www      4542:             foreach $tryserver (keys %libserv) {
                   4543: 	       if ($hostdom{$tryserver} eq $udom) {
                   4544:                   my $answer=reply('load',$tryserver);
                   4545:                   if (($answer=~/\d+/) && ($answer<$loadm)) {
                   4546: 		      $loadm=$answer;
                   4547:                       $unhome=$tryserver;
                   4548:                   }
                   4549: 	       }
                   4550: 	    }
                   4551:         }
                   4552:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  4553: 	    return 'error: unable to find a home server for '.$uname.
                   4554:                    ' in domain '.$udom;
1.80      www      4555:         }
                   4556:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   4557:                          &escape($upass),$unhome);
                   4558: 	unless ($reply eq 'ok') {
                   4559:             return 'error: '.$reply;
                   4560:         }   
1.230     stredwic 4561:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      4562:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  4563: 	    return 'error: unable verify users home machine.';
1.80      www      4564:         }
1.209     matthew  4565:     }   # End of creation of new user
1.80      www      4566: # ---------------------------------------------------------------------- Add ID
                   4567:     if ($uid) {
                   4568:        $uid=~tr/A-Z/a-z/;
                   4569:        my %uidhash=&idrget($udom,$uname);
1.196     www      4570:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   4571:          && (!$forceid)) {
1.80      www      4572: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  4573: 	      return 'error: user id "'.$uid.'" does not match '.
                   4574:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      4575:           }
                   4576:        } else {
                   4577: 	  &idput($udom,($uname => $uid));
                   4578:        }
                   4579:     }
                   4580: # -------------------------------------------------------------- Add names, etc
1.313     matthew  4581:     my @tmp=&get('environment',
1.134     albertel 4582: 		   ['firstname','middlename','lastname','generation'],
                   4583: 		   $udom,$uname);
1.313     matthew  4584:     my %names;
                   4585:     if ($tmp[0] =~ m/^error:.*/) { 
                   4586:         %names=(); 
                   4587:     } else {
                   4588:         %names = @tmp;
                   4589:     }
1.388     www      4590: #
                   4591: # Make sure to not trash student environment if instructor does not bother
                   4592: # to supply name and email information
                   4593: #
                   4594:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  4595:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      4596:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  4597:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      4598:     if ($email) {
                   4599:        $email=~s/[^\w\@\.\-\,]//gs;
                   4600:        if ($email=~/\@/) { $names{'notification'} = $email;
                   4601: 			   $names{'critnotification'} = $email;
                   4602: 			   $names{'permanentemail'} = $email; }
                   4603:     }
1.134     albertel 4604:     my $reply = &put('environment', \%names, $udom,$uname);
                   4605:     if ($reply ne 'ok') { return 'error: '.$reply; }
1.680     www      4606:     &devalidate_cache_new('namescache',$uname.':'.$udom);
1.81      www      4607:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      4608:              $umode.', '.$first.', '.$middle.', '.
                   4609: 	     $last.', '.$gene.' by '.
1.620     albertel 4610:              $env{'user.name'}.' at '.$env{'user.domain'});
1.134     albertel 4611:     return 'ok';
1.80      www      4612: }
                   4613: 
1.81      www      4614: # -------------------------------------------------------------- Modify student
1.80      www      4615: 
1.81      www      4616: sub modifystudent {
                   4617:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.515     raeburn  4618:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
1.455     albertel 4619:     if (!$cid) {
1.620     albertel 4620: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 4621: 	    return 'not_in_class';
                   4622: 	}
1.80      www      4623:     }
                   4624: # --------------------------------------------------------------- Make the user
1.81      www      4625:     my $reply=&modifyuser
1.209     matthew  4626: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387     www      4627:          $desiredhome,$email);
1.80      www      4628:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  4629:     # This will cause &modify_student_enrollment to get the uid from the
                   4630:     # students environment
                   4631:     $uid = undef if (!$forceid);
1.455     albertel 4632:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.515     raeburn  4633: 					$gene,$usec,$end,$start,$type,$locktype,$cid);
1.297     matthew  4634:     return $reply;
                   4635: }
                   4636: 
                   4637: sub modify_student_enrollment {
1.515     raeburn  4638:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
1.455     albertel 4639:     my ($cdom,$cnum,$chome);
                   4640:     if (!$cid) {
1.620     albertel 4641: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 4642: 	    return 'not_in_class';
                   4643: 	}
1.620     albertel 4644: 	$cdom=$env{'course.'.$cid.'.domain'};
                   4645: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 4646:     } else {
                   4647: 	($cdom,$cnum)=split(/_/,$cid);
                   4648:     }
1.620     albertel 4649:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 4650:     if (!$chome) {
1.457     raeburn  4651: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  4652:     }
1.455     albertel 4653:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  4654:     # Make sure the user exists
1.81      www      4655:     my $uhome=&homeserver($uname,$udom);
                   4656:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   4657: 	return 'error: no such user';
                   4658:     }
1.297     matthew  4659:     # Get student data if we were not given enough information
                   4660:     if (!defined($first)  || $first  eq '' || 
                   4661:         !defined($last)   || $last   eq '' || 
                   4662:         !defined($uid)    || $uid    eq '' || 
                   4663:         !defined($middle) || $middle eq '' || 
                   4664:         !defined($gene)   || $gene   eq '') {
1.294     matthew  4665:         # They did not supply us with enough data to enroll the student, so
                   4666:         # we need to pick up more information.
1.297     matthew  4667:         my %tmp = &get('environment',
1.294     matthew  4668:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  4669:                        ,$udom,$uname);
                   4670: 
1.455     albertel 4671:         #foreach (keys(%tmp)) {
                   4672:         #    &logthis("key $_ = ".$tmp{$_});
                   4673:         #}
1.294     matthew  4674:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   4675:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   4676:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  4677:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  4678:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   4679:     }
1.556     albertel 4680:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 4681:     my $reply=cput('classlist',
                   4682: 		   {"$uname:$udom" => 
1.515     raeburn  4683: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 4684: 		   $cdom,$cnum);
1.81      www      4685:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   4686: 	return 'error: '.$reply;
1.652     albertel 4687:     } else {
                   4688: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      4689:     }
1.297     matthew  4690:     # Add student role to user
1.83      www      4691:     my $uurl='/'.$cid;
1.81      www      4692:     $uurl=~s/\_/\//g;
                   4693:     if ($usec) {
                   4694: 	$uurl.='/'.$usec;
                   4695:     }
                   4696:     return &assignrole($udom,$uname,$uurl,'st',$end,$start);
1.21      www      4697: }
                   4698: 
1.556     albertel 4699: sub format_name {
                   4700:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   4701:     my $name;
                   4702:     if ($first ne 'lastname') {
                   4703: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   4704:     } else {
                   4705: 	if ($lastname=~/\S/) {
                   4706: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   4707: 	    $name=~s/\s+,/,/;
                   4708: 	} else {
                   4709: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   4710: 	}
                   4711:     }
                   4712:     $name=~s/^\s+//;
                   4713:     $name=~s/\s+$//;
                   4714:     $name=~s/\s+/ /g;
                   4715:     return $name;
                   4716: }
                   4717: 
1.84      www      4718: # ------------------------------------------------- Write to course preferences
                   4719: 
                   4720: sub writecoursepref {
                   4721:     my ($courseid,%prefs)=@_;
                   4722:     $courseid=~s/^\///;
                   4723:     $courseid=~s/\_/\//g;
                   4724:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   4725:     my $chome=homeserver($cnum,$cdomain);
                   4726:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   4727: 	return 'error: no such course';
                   4728:     }
                   4729:     my $cstring='';
1.191     harris41 4730:     foreach (keys %prefs) {
1.84      www      4731: 	$cstring.=escape($_).'='.escape($prefs{$_}).'&';
1.191     harris41 4732:     }
1.84      www      4733:     $cstring=~s/\&$//;
                   4734:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   4735: }
                   4736: 
                   4737: # ---------------------------------------------------------- Make/modify course
                   4738: 
                   4739: sub createcourse {
1.741     raeburn  4740:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
                   4741:         $course_owner,$crstype)=@_;
1.84      www      4742:     $url=&declutter($url);
                   4743:     my $cid='';
1.264     matthew  4744:     unless (&allowed('ccc',$udom)) {
1.84      www      4745:         return 'refused';
                   4746:     }
                   4747: # ------------------------------------------------------------------- Create ID
1.674     www      4748:    my $uname=int(1+rand(9)).
                   4749:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   4750:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
1.84      www      4751:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   4752: # ----------------------------------------------- Make sure that does not exist
1.230     stredwic 4753:    my $uhome=&homeserver($uname,$udom,'true');
1.84      www      4754:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   4755:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   4756:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230     stredwic 4757:        $uhome=&homeserver($uname,$udom,'true');       
1.84      www      4758:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   4759:            return 'error: unable to generate unique course-ID';
                   4760:        } 
                   4761:    }
1.264     matthew  4762: # ------------------------------------------------ Check supplied server name
1.620     albertel 4763:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.264     matthew  4764:     if (! exists($libserv{$course_server})) {
                   4765:         return 'error:bad server name '.$course_server;
                   4766:     }
1.84      www      4767: # ------------------------------------------------------------- Make the course
                   4768:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  4769:                       $course_server);
1.84      www      4770:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230     stredwic 4771:     $uhome=&homeserver($uname,$udom,'true');
1.84      www      4772:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   4773: 	return 'error: no such course';
                   4774:     }
1.271     www      4775: # ----------------------------------------------------------------- Course made
1.516     raeburn  4776: # log existence
                   4777:     &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description).
1.741     raeburn  4778:                  ':'.&escape($inst_code).':'.&escape($course_owner).':'.
                   4779:                   &escape($crstype),$uhome);
1.358     www      4780:     &flushcourselogs();
                   4781: # set toplevel url
1.271     www      4782:     my $topurl=$url;
                   4783:     unless ($nonstandard) {
                   4784: # ------------------------------------------ For standard courses, make top url
                   4785:         my $mapurl=&clutter($url);
1.278     www      4786:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 4787:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      4788: <map>
                   4789: <resource id="1" type="start"></resource>
                   4790: <resource id="2" src="$mapurl"></resource>
                   4791: <resource id="3" type="finish"></resource>
                   4792: <link index="1" from="1" to="2"></link>
                   4793: <link index="2" from="2" to="3"></link>
                   4794: </map>
                   4795: ENDINITMAP
                   4796:         $topurl=&declutter(
1.638     albertel 4797:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      4798:                           );
                   4799:     }
                   4800: # ----------------------------------------------------------- Write preferences
1.84      www      4801:     &writecoursepref($udom.'_'.$uname,
                   4802:                      ('description' => $description,
1.271     www      4803:                       'url'         => $topurl));
1.84      www      4804:     return '/'.$udom.'/'.$uname;
                   4805: }
                   4806: 
1.21      www      4807: # ---------------------------------------------------------- Assign Custom Role
                   4808: 
                   4809: sub assigncustomrole {
1.357     www      4810:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
1.21      www      4811:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.357     www      4812:                        $end,$start,$deleteflag);
1.21      www      4813: }
                   4814: 
                   4815: # ----------------------------------------------------------------- Revoke Role
                   4816: 
                   4817: sub revokerole {
1.357     www      4818:     my ($udom,$uname,$url,$role,$deleteflag)=@_;
1.21      www      4819:     my $now=time;
1.357     www      4820:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
1.21      www      4821: }
                   4822: 
                   4823: # ---------------------------------------------------------- Revoke Custom Role
                   4824: 
                   4825: sub revokecustomrole {
1.357     www      4826:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
1.21      www      4827:     my $now=time;
1.357     www      4828:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
                   4829:            $deleteflag);
1.17      www      4830: }
                   4831: 
1.533     banghart 4832: # ------------------------------------------------------------ Disk usage
1.535     albertel 4833: sub diskusage {
1.533     banghart 4834:     my ($udom,$uname,$directoryRoot)=@_;
                   4835:     $directoryRoot =~ s/\/$//;
1.535     albertel 4836:     my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
1.514     albertel 4837:     return $listing;
1.512     banghart 4838: }
                   4839: 
1.566     banghart 4840: sub is_locked {
                   4841:     my ($file_name, $domain, $user) = @_;
                   4842:     my @check;
                   4843:     my $is_locked;
                   4844:     push @check, $file_name;
1.613     albertel 4845:     my %locked = &get('file_permissions',\@check,
1.620     albertel 4846: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 4847:     my ($tmp)=keys(%locked);
                   4848:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  4849:     
1.566     banghart 4850:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  4851:         $is_locked = 'false';
                   4852:         foreach my $entry (@{$locked{$file_name}}) {
                   4853:            if (ref($entry) eq 'ARRAY') { 
1.746     raeburn  4854:                $is_locked = 'true';
                   4855:                last;
1.745     raeburn  4856:            }
                   4857:        }
1.566     banghart 4858:     } else {
                   4859:         $is_locked = 'false';
                   4860:     }
                   4861: }
                   4862: 
1.759     albertel 4863: sub declutter_portfile {
                   4864:     my ($file) = @_;
                   4865:     &logthis("got $file");
                   4866:     $file =~ s-^(/portfolio/|portfolio/)-/-;
                   4867:     &logthis("ret $file");
                   4868:     return $file;
                   4869: }
                   4870: 
1.559     banghart 4871: # ------------------------------------------------------------- Mark as Read Only
                   4872: 
                   4873: sub mark_as_readonly {
                   4874:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 4875:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 4876:     my ($tmp)=keys(%current_permissions);
                   4877:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 4878:     foreach my $file (@{$files}) {
1.759     albertel 4879: 	$file = &declutter_portfile($file);
1.561     banghart 4880:         push(@{$current_permissions{$file}},$what);
1.559     banghart 4881:     }
1.613     albertel 4882:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 4883:     return;
                   4884: }
                   4885: 
1.572     banghart 4886: # ------------------------------------------------------------Save Selected Files
                   4887: 
                   4888: sub save_selected_files {
                   4889:     my ($user, $path, @files) = @_;
                   4890:     my $filename = $user."savedfiles";
1.573     banghart 4891:     my @other_files = &files_not_in_path($user, $path);
1.574     banghart 4892:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 4893:     foreach my $file (@files) {
1.620     albertel 4894:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 4895:     }
                   4896:     foreach my $file (@other_files) {
1.574     banghart 4897:         print (OUT $file."\n");
1.572     banghart 4898:     }
1.574     banghart 4899:     close (OUT);
1.572     banghart 4900:     return 'ok';
                   4901: }
                   4902: 
1.574     banghart 4903: sub clear_selected_files {
                   4904:     my ($user) = @_;
                   4905:     my $filename = $user."savedfiles";
                   4906:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   4907:     print (OUT undef);
                   4908:     close (OUT);
                   4909:     return ("ok");    
                   4910: }
                   4911: 
1.572     banghart 4912: sub files_in_path {
                   4913:     my ($user, $path) = @_;
                   4914:     my $filename = $user."savedfiles";
                   4915:     my %return_files;
1.574     banghart 4916:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 4917:     while (my $line_in = <IN>) {
1.574     banghart 4918:         chomp ($line_in);
                   4919:         my @paths_and_file = split (m!/!, $line_in);
                   4920:         my $file_part = pop (@paths_and_file);
                   4921:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 4922:         $path_part.='/';
                   4923:         my $path_and_file = $path_part.$file_part;
                   4924:         if ($path_part eq $path) {
                   4925:             $return_files{$file_part}= 'selected';
                   4926:         }
                   4927:     }
1.574     banghart 4928:     close (IN);
                   4929:     return (\%return_files);
1.572     banghart 4930: }
                   4931: 
                   4932: # called in portfolio select mode, to show files selected NOT in current directory
                   4933: sub files_not_in_path {
                   4934:     my ($user, $path) = @_;
                   4935:     my $filename = $user."savedfiles";
                   4936:     my @return_files;
                   4937:     my $path_part;
1.574     banghart 4938:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.572     banghart 4939:     while (<IN>) {
                   4940:         #ok, I know it's clunky, but I want it to work
                   4941:         my @paths_and_file = split m!/!, $_;
1.574     banghart 4942:         my $file_part = pop (@paths_and_file);
                   4943:         chomp ($file_part);
                   4944:         my $path_part = join ('/', @paths_and_file);
1.572     banghart 4945:         $path_part .= '/';
                   4946:         my $path_and_file = $path_part.$file_part;
                   4947:         if ($path_part ne $path) {
1.574     banghart 4948:             push (@return_files, ($path_and_file));
1.572     banghart 4949:         }
                   4950:     }
1.574     banghart 4951:     close (OUT);
                   4952:     return (@return_files);
1.572     banghart 4953: }
                   4954: 
1.745     raeburn  4955: #----------------------------------------------Get portfolio file permissions
1.629     banghart 4956: 
1.745     raeburn  4957: sub get_portfile_permissions {
                   4958:     my ($domain,$user) = @_;
1.613     albertel 4959:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 4960:     my ($tmp)=keys(%current_permissions);
                   4961:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  4962:     return \%current_permissions;
                   4963: }
                   4964: 
                   4965: #---------------------------------------------Get portfolio file access controls
                   4966: 
1.749     raeburn  4967: sub get_access_controls {
1.745     raeburn  4968:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 4969:     my %access;
                   4970:     my $real_file = $file;
                   4971:     $file =~ s/\.meta$//;
1.745     raeburn  4972:     if (defined($file)) {
1.749     raeburn  4973:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   4974:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 4975:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  4976:             }
                   4977:         }
1.745     raeburn  4978:     } else {
1.749     raeburn  4979:         foreach my $key (keys(%{$current_permissions})) {
                   4980:             if ($key =~ /\0accesscontrol$/) {
                   4981:                 if (defined($group)) {
                   4982:                     if ($key !~ m-^\Q$group\E/-) {
                   4983:                         next;
                   4984:                     }
                   4985:                 }
                   4986:                 my ($fullpath) = split(/\0/,$key);
                   4987:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   4988:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   4989:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   4990:                     }
                   4991:                 }
                   4992:             }
                   4993:         }
                   4994:     }
                   4995:     return %access;
                   4996: }
                   4997: 
                   4998: sub modify_access_controls {
                   4999:     my ($file_name,$changes,$domain,$user)=@_;
                   5000:     my ($outcome,$deloutcome);
                   5001:     my %store_permissions;
                   5002:     my %new_values;
                   5003:     my %new_control;
                   5004:     my %translation;
                   5005:     my @deletions = ();
                   5006:     my $now = time;
                   5007:     if (exists($$changes{'activate'})) {
                   5008:         if (ref($$changes{'activate'}) eq 'HASH') {
                   5009:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   5010:             my $numnew = scalar(@newitems);
                   5011:             for (my $i=0; $i<$numnew; $i++) {
                   5012:                 my $newkey = $newitems[$i];
                   5013:                 my $newid = &Apache::loncommon::get_cgi_id();
                   5014:                 $newkey =~ s/^(\d+)/$newid/;
                   5015:                 $translation{$1} = $newid;
                   5016:                 $new_values{$file_name."\0".$newkey} = 
                   5017:                                           $$changes{'activate'}{$newitems[$i]};
                   5018:                 $new_control{$newkey} = $now;
                   5019:             }
                   5020:         }
                   5021:     }
                   5022:     my %todelete;
                   5023:     my %changed_items;
                   5024:     foreach my $action ('delete','update') {
                   5025:         if (exists($$changes{$action})) {
                   5026:             if (ref($$changes{$action}) eq 'HASH') {
                   5027:                 foreach my $key (keys(%{$$changes{$action}})) {
                   5028:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   5029:                     if ($action eq 'delete') { 
                   5030:                         $todelete{$itemnum} = 1;
                   5031:                     } else {
                   5032:                         $changed_items{$itemnum} = $key;
                   5033:                     }
                   5034:                 }
1.745     raeburn  5035:             }
                   5036:         }
1.749     raeburn  5037:     }
                   5038:     # get lock on access controls for file.
                   5039:     my $lockhash = {
                   5040:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   5041:                                                        ':'.$env{'user.domain'},
                   5042:                    }; 
                   5043:     my $tries = 0;
                   5044:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   5045:    
                   5046:     while (($gotlock ne 'ok') && $tries <3) {
                   5047:         $tries ++;
                   5048:         sleep 1;
                   5049:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   5050:     }
                   5051:     if ($gotlock eq 'ok') {
                   5052:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   5053:         my ($tmp)=keys(%curr_permissions);
                   5054:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   5055:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   5056:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   5057:             if (ref($curr_controls) eq 'HASH') {
                   5058:                 foreach my $control_item (keys(%{$curr_controls})) {
                   5059:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   5060:                     if (defined($todelete{$itemnum})) {
                   5061:                         push(@deletions,$file_name."\0".$control_item);
                   5062:                     } else {
                   5063:                         if (defined($changed_items{$itemnum})) {
                   5064:                             $new_control{$changed_items{$itemnum}} = $now;
                   5065:                             push(@deletions,$file_name."\0".$control_item);
                   5066:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   5067:                         } else {
                   5068:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   5069:                         }
                   5070:                     }
1.745     raeburn  5071:                 }
                   5072:             }
                   5073:         }
1.749     raeburn  5074:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   5075:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   5076:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   5077:         #  remove lock
                   5078:         my @del_lock = ($file_name."\0".'locked_access_records');
                   5079:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
                   5080:     } else {
                   5081:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  5082:     }
1.749     raeburn  5083:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  5084: }
                   5085: 
                   5086: #------------------------------------------------------Get Marked as Read Only
                   5087: 
                   5088: sub get_marked_as_readonly {
                   5089:     my ($domain,$user,$what,$group) = @_;
                   5090:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 5091:     my @readonly_files;
1.629     banghart 5092:     my $cmp1=$what;
                   5093:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  5094:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   5095:         if (defined($group)) {
                   5096:             if ($file_name !~ m-^\Q$group\E/-) {
                   5097:                 next;
                   5098:             }
                   5099:         }
1.561     banghart 5100:         if (ref($value) eq "ARRAY"){
                   5101:             foreach my $stored_what (@{$value}) {
1.629     banghart 5102:                 my $cmp2=$stored_what;
1.759     albertel 5103:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  5104:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  5105:                 }
1.629     banghart 5106:                 if ($cmp1 eq $cmp2) {
1.561     banghart 5107:                     push(@readonly_files, $file_name);
1.745     raeburn  5108:                     last;
1.563     banghart 5109:                 } elsif (!defined($what)) {
                   5110:                     push(@readonly_files, $file_name);
1.745     raeburn  5111:                     last;
1.561     banghart 5112:                 }
                   5113:             }
1.745     raeburn  5114:         }
1.561     banghart 5115:     }
                   5116:     return @readonly_files;
                   5117: }
1.577     banghart 5118: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 5119: 
1.577     banghart 5120: sub get_marked_as_readonly_hash {
1.745     raeburn  5121:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 5122:     my %readonly_files;
1.745     raeburn  5123:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   5124:         if (defined($group)) {
                   5125:             if ($file_name !~ m-^\Q$group\E/-) {
                   5126:                 next;
                   5127:             }
                   5128:         }
1.577     banghart 5129:         if (ref($value) eq "ARRAY"){
                   5130:             foreach my $stored_what (@{$value}) {
1.745     raeburn  5131:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 5132:                     foreach my $lock_descriptor(@{$stored_what}) {
                   5133:                         if ($lock_descriptor eq 'graded') {
                   5134:                             $readonly_files{$file_name} = 'graded';
                   5135:                         } elsif ($lock_descriptor eq 'handback') {
                   5136:                             $readonly_files{$file_name} = 'handback';
                   5137:                         } else {
                   5138:                             if (!exists($readonly_files{$file_name})) {
                   5139:                                 $readonly_files{$file_name} = 'locked';
                   5140:                             }
                   5141:                         }
1.745     raeburn  5142:                     }
1.750     banghart 5143:                 } 
1.577     banghart 5144:             }
                   5145:         } 
                   5146:     }
                   5147:     return %readonly_files;
                   5148: }
1.559     banghart 5149: # ------------------------------------------------------------ Unmark as Read Only
                   5150: 
                   5151: sub unmark_as_readonly {
1.629     banghart 5152:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   5153:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  5154:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 5155:     $file_name = &declutter_portfile($file_name);
1.634     albertel 5156:     my $symb_crs = $what;
                   5157:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  5158:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 5159:     my ($tmp)=keys(%current_permissions);
                   5160:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  5161:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 5162:     foreach my $file (@readonly_files) {
1.759     albertel 5163: 	my $clean_file = &declutter_portfile($file);
                   5164: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 5165: 	my $current_locks = $current_permissions{$file};
1.563     banghart 5166:         my @new_locks;
                   5167:         my @del_keys;
                   5168:         if (ref($current_locks) eq "ARRAY"){
                   5169:             foreach my $locker (@{$current_locks}) {
1.632     albertel 5170:                 my $compare=$locker;
1.749     raeburn  5171:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  5172:                     $compare=join('',@{$locker});
1.746     raeburn  5173:                     if ($compare ne $symb_crs) {
                   5174:                         push(@new_locks, $locker);
                   5175:                     }
1.563     banghart 5176:                 }
                   5177:             }
1.650     albertel 5178:             if (scalar(@new_locks) > 0) {
1.563     banghart 5179:                 $current_permissions{$file} = \@new_locks;
                   5180:             } else {
                   5181:                 push(@del_keys, $file);
1.613     albertel 5182:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 5183:                 delete($current_permissions{$file});
1.563     banghart 5184:             }
                   5185:         }
1.561     banghart 5186:     }
1.613     albertel 5187:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 5188:     return;
                   5189: }
1.512     banghart 5190: 
1.17      www      5191: # ------------------------------------------------------------ Directory lister
                   5192: 
                   5193: sub dirlist {
1.253     stredwic 5194:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
                   5195: 
1.18      www      5196:     $uri=~s/^\///;
                   5197:     $uri=~s/\/$//;
1.253     stredwic 5198:     my ($udom, $uname);
                   5199:     (undef,$udom,$uname)=split(/\//,$uri);
                   5200:     if(defined($userdomain)) {
                   5201:         $udom = $userdomain;
                   5202:     }
                   5203:     if(defined($username)) {
                   5204:         $uname = $username;
                   5205:     }
                   5206: 
                   5207:     my $dirRoot = $perlvar{'lonDocRoot'};
                   5208:     if(defined($alternateDirectoryRoot)) {
                   5209:         $dirRoot = $alternateDirectoryRoot;
                   5210:         $dirRoot =~ s/\/$//;
1.751     banghart 5211:     }
1.253     stredwic 5212: 
                   5213:     if($udom) {
                   5214:         if($uname) {
1.605     matthew  5215:             my $listing=reply('ls2:'.$dirRoot.'/'.$uri,
1.253     stredwic 5216:                               homeserver($uname,$udom));
1.605     matthew  5217:             my @listing_results;
                   5218:             if ($listing eq 'unknown_cmd') {
                   5219:                 $listing=reply('ls:'.$dirRoot.'/'.$uri,
                   5220:                                homeserver($uname,$udom));
                   5221:                 @listing_results = split(/:/,$listing);
                   5222:             } else {
                   5223:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   5224:             }
                   5225:             return @listing_results;
1.253     stredwic 5226:         } elsif(!defined($alternateDirectoryRoot)) {
                   5227:             my $tryserver;
                   5228:             my %allusers=();
                   5229:             foreach $tryserver (keys %libserv) {
                   5230:                 if($hostdom{$tryserver} eq $udom) {
1.605     matthew  5231:                     my $listing=reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
1.253     stredwic 5232:                                       $udom, $tryserver);
1.605     matthew  5233:                     my @listing_results;
                   5234:                     if ($listing eq 'unknown_cmd') {
                   5235:                         $listing=reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   5236:                                        $udom, $tryserver);
                   5237:                         @listing_results = split(/:/,$listing);
                   5238:                     } else {
                   5239:                         @listing_results =
                   5240:                             map { &unescape($_); } split(/:/,$listing);
                   5241:                     }
                   5242:                     if ($listing_results[0] ne 'no_such_dir' && 
                   5243:                         $listing_results[0] ne 'empty'       &&
                   5244:                         $listing_results[0] ne 'con_lost') {
                   5245:                         foreach (@listing_results) {
1.253     stredwic 5246:                             my ($entry,@stat)=split(/&/,$_);
                   5247:                             $allusers{$entry}=1;
                   5248:                         }
                   5249:                     }
1.191     harris41 5250:                 }
1.253     stredwic 5251:             }
                   5252:             my $alluserstr='';
                   5253:             foreach (sort keys %allusers) {
                   5254:                 $alluserstr.=$_.'&user:';
                   5255:             }
                   5256:             $alluserstr=~s/:$//;
                   5257:             return split(/:/,$alluserstr);
                   5258:         } else {
                   5259:             my @emptyResults = ();
                   5260:             push(@emptyResults, 'missing user name');
                   5261:             return split(':',@emptyResults);
                   5262:         }
                   5263:     } elsif(!defined($alternateDirectoryRoot)) {
                   5264:         my $tryserver;
                   5265:         my %alldom=();
                   5266:         foreach $tryserver (keys %libserv) {
                   5267:             $alldom{$hostdom{$tryserver}}=1;
                   5268:         }
                   5269:         my $alldomstr='';
                   5270:         foreach (sort keys %alldom) {
1.397     albertel 5271:             $alldomstr.=$perlvar{'lonDocRoot'}.'/res/'.$_.'/&domain:';
1.253     stredwic 5272:         }
                   5273:         $alldomstr=~s/:$//;
                   5274:         return split(/:/,$alldomstr);       
                   5275:     } else {
                   5276:         my @emptyResults = ();
                   5277:         push(@emptyResults, 'missing domain');
                   5278:         return split(':',@emptyResults);
1.275     stredwic 5279:     }
                   5280: }
                   5281: 
                   5282: # --------------------------------------------- GetFileTimestamp
                   5283: # This function utilizes dirlist and returns the date stamp for
                   5284: # when it was last modified.  It will also return an error of -1
                   5285: # if an error occurs
                   5286: 
1.410     matthew  5287: ##
                   5288: ## FIXME: This subroutine assumes its caller knows something about the
                   5289: ## directory structure of the home server for the student ($root).
                   5290: ## Not a good assumption to make.  Since this is for looking up files
                   5291: ## in user directories, the full path should be constructed by lond, not
                   5292: ## whatever machine we request data from.
                   5293: ##
1.275     stredwic 5294: sub GetFileTimestamp {
                   5295:     my ($studentDomain,$studentName,$filename,$root)=@_;
                   5296:     $studentDomain=~s/\W//g;
                   5297:     $studentName=~s/\W//g;
                   5298:     my $subdir=$studentName.'__';
                   5299:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   5300:     my $proname="$studentDomain/$subdir/$studentName";
                   5301:     $proname .= '/'.$filename;
1.375     matthew  5302:     my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain, 
                   5303:                                               $studentName, $root);
1.275     stredwic 5304:     my @stats = split('&', $fileStat);
                   5305:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  5306:         # @stats contains first the filename, then the stat output
                   5307:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 5308:     } else {
                   5309:         return -1;
1.253     stredwic 5310:     }
1.26      www      5311: }
                   5312: 
1.712     albertel 5313: sub stat_file {
                   5314:     my ($uri) = @_;
1.722     albertel 5315:     $uri = &clutter($uri);
                   5316: 
                   5317:     # we want just the url part without the unneeded accessor url bits
1.723     banghart 5318:     if ($uri =~ m-^/adm/-) {
                   5319: 	$uri=~s-^/adm/wrapper/-/-;
                   5320: 	$uri=~s-^/adm/coursedocs/showdoc/-/-;
1.722     albertel 5321:     }
1.712     albertel 5322:     my ($udom,$uname,$file,$dir);
                   5323:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   5324: 	($udom,$uname,$file) =
                   5325: 	    ($uri =~ m-/(?:uploaded|editupload)/?([^/]*)/?([^/]*)/?(.*)-);
                   5326: 	$file = 'userfiles/'.$file;
1.740     www      5327: 	$dir = &propath($udom,$uname);
1.712     albertel 5328:     }
                   5329:     if ($uri =~ m-^/res/-) {
                   5330: 	($udom,$uname) = 
                   5331: 	    ($uri =~ m-/(?:res)/?([^/]*)/?([^/]*)/-);
                   5332: 	$file = $uri;
                   5333:     }
                   5334: 
                   5335:     if (!$udom || !$uname || !$file) {
                   5336: 	# unable to handle the uri
                   5337: 	return ();
                   5338:     }
                   5339: 
                   5340:     my ($result) = &dirlist($file,$udom,$uname,$dir);
                   5341:     my @stats = split('&', $result);
1.721     banghart 5342:     
1.712     albertel 5343:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   5344: 	shift(@stats); #filename is first
                   5345: 	return @stats;
                   5346:     }
                   5347:     return ();
                   5348: }
                   5349: 
1.26      www      5350: # -------------------------------------------------------- Value of a Condition
                   5351: 
1.713     albertel 5352: # gets the value of a specific preevaluated condition
                   5353: #    stored in the string  $env{user.state.<cid>}
                   5354: # or looks up a condition reference in the bighash and if if hasn't
                   5355: # already been evaluated recurses into docondval to get the value of
                   5356: # the condition, then memoizing it to 
                   5357: #   $env{user.state.<cid>.<condition>}
1.40      www      5358: sub directcondval {
                   5359:     my $number=shift;
1.620     albertel 5360:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 5361: 	&Apache::lonuserstate::evalstate();
                   5362:     }
1.713     albertel 5363:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   5364: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   5365:     } elsif ($number =~ /^_/) {
                   5366: 	my $sub_condition;
                   5367: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   5368: 		&GDBM_READER(),0640)) {
                   5369: 	    $sub_condition=$bighash{'conditions'.$number};
                   5370: 	    untie(%bighash);
                   5371: 	}
                   5372: 	my $value = &docondval($sub_condition);
                   5373: 	&appenv('user.state.'.$env{'request.course.id'}.".$number" => $value);
                   5374: 	return $value;
                   5375:     }
1.620     albertel 5376:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   5377:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      5378:     } else {
                   5379:        return 2;
                   5380:     }
                   5381: }
                   5382: 
1.713     albertel 5383: # get the collection of conditions for this resource
1.26      www      5384: sub condval {
                   5385:     my $condidx=shift;
1.54      www      5386:     my $allpathcond='';
1.713     albertel 5387:     foreach my $cond (split(/\|/,$condidx)) {
                   5388: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   5389: 	    $allpathcond.=
                   5390: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   5391: 	}
1.191     harris41 5392:     }
1.54      www      5393:     $allpathcond=~s/\|$//;
1.713     albertel 5394:     return &docondval($allpathcond);
                   5395: }
                   5396: 
                   5397: #evaluates an expression of conditions
                   5398: sub docondval {
                   5399:     my ($allpathcond) = @_;
                   5400:     my $result=0;
                   5401:     if ($env{'request.course.id'}
                   5402: 	&& defined($allpathcond)) {
                   5403: 	my $operand='|';
                   5404: 	my @stack;
                   5405: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   5406: 	    if ($chunk eq '(') {
                   5407: 		push @stack,($operand,$result);
                   5408: 	    } elsif ($chunk eq ')') {
                   5409: 		my $before=pop @stack;
                   5410: 		if (pop @stack eq '&') {
                   5411: 		    $result=$result>$before?$before:$result;
                   5412: 		} else {
                   5413: 		    $result=$result>$before?$result:$before;
                   5414: 		}
                   5415: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   5416: 		$operand=$chunk;
                   5417: 	    } else {
                   5418: 		my $new=directcondval($chunk);
                   5419: 		if ($operand eq '&') {
                   5420: 		    $result=$result>$new?$new:$result;
                   5421: 		} else {
                   5422: 		    $result=$result>$new?$result:$new;
                   5423: 		}
                   5424: 	    }
                   5425: 	}
1.26      www      5426:     }
                   5427:     return $result;
1.421     albertel 5428: }
                   5429: 
                   5430: # ---------------------------------------------------- Devalidate courseresdata
                   5431: 
                   5432: sub devalidatecourseresdata {
                   5433:     my ($coursenum,$coursedomain)=@_;
                   5434:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 5435:     &devalidate_cache_new('courseres',$hashid);
1.28      www      5436: }
                   5437: 
1.763     www      5438: 
1.200     www      5439: # --------------------------------------------------- Course Resourcedata Query
                   5440: 
1.624     albertel 5441: sub get_courseresdata {
                   5442:     my ($coursenum,$coursedomain)=@_;
1.200     www      5443:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   5444:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 5445:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 5446:     my %dumpreply;
1.417     albertel 5447:     unless (defined($cached)) {
1.624     albertel 5448: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 5449: 	$result=\%dumpreply;
1.251     albertel 5450: 	my ($tmp) = keys(%dumpreply);
                   5451: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 5452: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 5453: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   5454: 	    return $tmp;
1.416     albertel 5455: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 5456: 	    $result=undef;
1.599     albertel 5457: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 5458: 	}
                   5459:     }
1.624     albertel 5460:     return $result;
                   5461: }
                   5462: 
1.633     albertel 5463: sub devalidateuserresdata {
                   5464:     my ($uname,$udom)=@_;
                   5465:     my $hashid="$udom:$uname";
                   5466:     &devalidate_cache_new('userres',$hashid);
                   5467: }
                   5468: 
1.624     albertel 5469: sub get_userresdata {
                   5470:     my ($uname,$udom)=@_;
                   5471:     #most student don\'t have any data set, check if there is some data
                   5472:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   5473: 
                   5474:     my $hashid="$udom:$uname";
                   5475:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   5476:     if (!defined($cached)) {
                   5477: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   5478: 	$result=\%resourcedata;
                   5479: 	&do_cache_new('userres',$hashid,$result,600);
                   5480:     }
                   5481:     my ($tmp)=keys(%$result);
                   5482:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   5483: 	return $result;
                   5484:     }
                   5485:     #error 2 occurs when the .db doesn't exist
                   5486:     if ($tmp!~/error: 2 /) {
1.672     albertel 5487: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 5488: 		 " Trying to get resource data for ".
                   5489: 		 $uname." at ".$udom.": ".
                   5490: 		 $tmp."</font>");
                   5491:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 5492: 	#&EXT_cache_set($udom,$uname);
                   5493: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 5494: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 5495:     }
                   5496:     return $tmp;
                   5497: }
                   5498: 
                   5499: sub resdata {
                   5500:     my ($name,$domain,$type,@which)=@_;
                   5501:     my $result;
                   5502:     if ($type eq 'course') {
                   5503: 	$result=&get_courseresdata($name,$domain);
                   5504:     } elsif ($type eq 'user') {
                   5505: 	$result=&get_userresdata($name,$domain);
                   5506:     }
                   5507:     if (!ref($result)) { return $result; }    
1.251     albertel 5508:     foreach my $item (@which) {
1.417     albertel 5509: 	if (defined($result->{$item})) {
                   5510: 	    return $result->{$item};
1.251     albertel 5511: 	}
1.250     albertel 5512:     }
1.291     albertel 5513:     return undef;
1.200     www      5514: }
                   5515: 
1.379     matthew  5516: #
                   5517: # EXT resource caching routines
                   5518: #
                   5519: 
                   5520: sub clear_EXT_cache_status {
1.383     albertel 5521:     &delenv('cache.EXT.');
1.379     matthew  5522: }
                   5523: 
                   5524: sub EXT_cache_status {
                   5525:     my ($target_domain,$target_user) = @_;
1.383     albertel 5526:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 5527:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  5528:         # We know already the user has no data
                   5529:         return 1;
                   5530:     } else {
                   5531:         return 0;
                   5532:     }
                   5533: }
                   5534: 
                   5535: sub EXT_cache_set {
                   5536:     my ($target_domain,$target_user) = @_;
1.383     albertel 5537:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.633     albertel 5538:     #&appenv($cachename => time);
1.379     matthew  5539: }
                   5540: 
1.28      www      5541: # --------------------------------------------------------- Value of a Variable
1.58      www      5542: sub EXT {
1.715     albertel 5543: 
1.395     albertel 5544:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      5545:     unless ($varname) { return ''; }
1.218     albertel 5546:     #get real user name/domain, courseid and symb
                   5547:     my $courseid;
1.359     albertel 5548:     my $publicuser;
1.427     www      5549:     if ($symbparm) {
                   5550: 	$symbparm=&get_symb_from_alias($symbparm);
                   5551:     }
1.218     albertel 5552:     if (!($uname && $udom)) {
1.360     albertel 5553:       (my $cursymb,$courseid,$udom,$uname,$publicuser)=
1.378     matthew  5554: 	  &Apache::lonxml::whichuser($symbparm);
1.218     albertel 5555:       if (!$symbparm) {	$symbparm=$cursymb; }
                   5556:     } else {
1.620     albertel 5557: 	$courseid=$env{'request.course.id'};
1.218     albertel 5558:     }
1.48      www      5559:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   5560:     my $rest;
1.320     albertel 5561:     if (defined($therest[0])) {
1.48      www      5562:        $rest=join('.',@therest);
                   5563:     } else {
                   5564:        $rest='';
                   5565:     }
1.320     albertel 5566: 
1.57      www      5567:     my $qualifierrest=$qualifier;
                   5568:     if ($rest) { $qualifierrest.='.'.$rest; }
                   5569:     my $spacequalifierrest=$space;
                   5570:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      5571:     if ($realm eq 'user') {
1.48      www      5572: # --------------------------------------------------------------- user.resource
                   5573: 	if ($space eq 'resource') {
1.651     albertel 5574: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   5575: 		  || defined($Apache::lonhomework::parsing_a_task))
                   5576: 		 &&
1.744     albertel 5577: 		 ($symbparm eq &symbread()) ) {	
                   5578: 		# if we are in the middle of processing the resource the
                   5579: 		# get the value we are planning on committing
                   5580:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   5581:                     return $Apache::lonhomework::results{$qualifierrest};
                   5582:                 } else {
                   5583:                     return $Apache::lonhomework::history{$qualifierrest};
                   5584:                 }
1.335     albertel 5585: 	    } else {
1.359     albertel 5586: 		my %restored;
1.620     albertel 5587: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 5588: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   5589: 		} else {
                   5590: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   5591: 		}
1.335     albertel 5592: 		return $restored{$qualifierrest};
                   5593: 	    }
1.48      www      5594: # ----------------------------------------------------------------- user.access
                   5595:         } elsif ($space eq 'access') {
1.218     albertel 5596: 	    # FIXME - not supporting calls for a specific user
1.48      www      5597:             return &allowed($qualifier,$rest);
                   5598: # ------------------------------------------ user.preferences, user.environment
                   5599:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 5600: 	    if (($uname eq $env{'user.name'}) &&
                   5601: 		($udom eq $env{'user.domain'})) {
                   5602: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 5603: 	    } else {
1.359     albertel 5604: 		my %returnhash;
                   5605: 		if (!$publicuser) {
                   5606: 		    %returnhash=&userenvironment($udom,$uname,
                   5607: 						 $qualifierrest);
                   5608: 		}
1.218     albertel 5609: 		return $returnhash{$qualifierrest};
                   5610: 	    }
1.48      www      5611: # ----------------------------------------------------------------- user.course
                   5612:         } elsif ($space eq 'course') {
1.218     albertel 5613: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 5614:             return $env{join('.',('request.course',$qualifier))};
1.48      www      5615: # ------------------------------------------------------------------- user.role
                   5616:         } elsif ($space eq 'role') {
1.218     albertel 5617: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 5618:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      5619:             if ($qualifier eq 'value') {
                   5620: 		return $role;
                   5621:             } elsif ($qualifier eq 'extent') {
                   5622:                 return $where;
                   5623:             }
                   5624: # ----------------------------------------------------------------- user.domain
                   5625:         } elsif ($space eq 'domain') {
1.218     albertel 5626:             return $udom;
1.48      www      5627: # ------------------------------------------------------------------- user.name
                   5628:         } elsif ($space eq 'name') {
1.218     albertel 5629:             return $uname;
1.48      www      5630: # ---------------------------------------------------- Any other user namespace
1.29      www      5631:         } else {
1.359     albertel 5632: 	    my %reply;
                   5633: 	    if (!$publicuser) {
                   5634: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   5635: 	    }
                   5636: 	    return $reply{$qualifierrest};
1.48      www      5637:         }
1.236     www      5638:     } elsif ($realm eq 'query') {
                   5639: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 5640:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   5641: 						[$spacequalifierrest]);
1.620     albertel 5642: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      5643:    } elsif ($realm eq 'request') {
1.48      www      5644: # ------------------------------------------------------------- request.browser
                   5645:         if ($space eq 'browser') {
1.430     www      5646: 	    if ($qualifier eq 'textremote') {
1.676     albertel 5647: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      5648: 		    return 1;
                   5649: 		} else {
                   5650: 		    return 0;
                   5651: 		}
                   5652: 	    } else {
1.620     albertel 5653: 		return $env{'browser.'.$qualifier};
1.430     www      5654: 	    }
1.57      www      5655: # ------------------------------------------------------------ request.filename
                   5656:         } else {
1.620     albertel 5657:             return $env{'request.'.$spacequalifierrest};
1.29      www      5658:         }
1.28      www      5659:     } elsif ($realm eq 'course') {
1.48      www      5660: # ---------------------------------------------------------- course.description
1.620     albertel 5661:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      5662:     } elsif ($realm eq 'resource') {
1.165     www      5663: 
1.620     albertel 5664: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 5665: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   5666: 	}
1.693     albertel 5667: 
                   5668: 	if ($space eq 'title') {
                   5669: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   5670: 	    return &gettitle($symbparm);
                   5671: 	}
                   5672: 	
                   5673: 	if ($space eq 'map') {
                   5674: 	    my ($map) = &decode_symb($symbparm);
                   5675: 	    return &symbread($map);
                   5676: 	}
                   5677: 
                   5678: 	my ($section, $group, @groups);
1.593     albertel 5679: 	my ($courselevelm,$courselevel);
1.539     albertel 5680: 	if ($symbparm && defined($courseid) && 
1.620     albertel 5681: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      5682: 
1.218     albertel 5683: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      5684: 
1.60      www      5685: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 5686: 	    my $symbp=$symbparm;
1.735     albertel 5687: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 5688: 
                   5689: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   5690: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   5691: 
1.620     albertel 5692: 	    if (($env{'user.name'} eq $uname) &&
                   5693: 		($env{'user.domain'} eq $udom)) {
                   5694: 		$section=$env{'request.course.sec'};
1.733     raeburn  5695:                 @groups = split(/:/,$env{'request.course.groups'});  
                   5696:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 5697: 	    } else {
1.539     albertel 5698: 		if (! defined($usection)) {
1.551     albertel 5699: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 5700: 		} else {
                   5701: 		    $section = $usection;
                   5702: 		}
1.733     raeburn  5703:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 5704: 	    }
                   5705: 
                   5706: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   5707: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   5708: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   5709: 
1.593     albertel 5710: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 5711: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 5712: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      5713: 
1.60      www      5714: # ----------------------------------------------------------- first, check user
1.624     albertel 5715: 
                   5716: 	    my $userreply=&resdata($uname,$udom,'user',
                   5717: 				       ($courselevelr,$courselevelm,
                   5718: 					$courselevel));
                   5719: 	    if (defined($userreply)) { return $userreply; }
1.95      www      5720: 
1.594     albertel 5721: # ------------------------------------------------ second, check some of course
1.684     raeburn  5722:             my $coursereply;
1.691     raeburn  5723:             if (@groups > 0) {
                   5724:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   5725:                                        $mapparm,$spacequalifierrest);
1.684     raeburn  5726:                 if (defined($coursereply)) { return $coursereply; }
                   5727:             }
1.96      www      5728: 
1.684     raeburn  5729: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.624     albertel 5730: 				     $env{'course.'.$courseid.'.domain'},
                   5731: 				     'course',
                   5732: 				     ($seclevelr,$seclevelm,$seclevel,
                   5733: 				      $courselevelr));
1.287     albertel 5734: 	    if (defined($coursereply)) { return $coursereply; }
1.200     www      5735: 
1.60      www      5736: # ------------------------------------------------------ third, check map parms
1.218     albertel 5737: 	    my %parmhash=();
                   5738: 	    my $thisparm='';
                   5739: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 5740: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 5741: 		    &GDBM_READER(),0640)) {
1.218     albertel 5742: 		$thisparm=$parmhash{$symbparm};
                   5743: 		untie(%parmhash);
                   5744: 	    }
                   5745: 	    if ($thisparm) { return $thisparm; }
                   5746: 	}
1.594     albertel 5747: # ------------------------------------------ fourth, look in resource metadata
1.71      www      5748: 
1.218     albertel 5749: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 5750: 	my $filename;
                   5751: 	if (!$symbparm) { $symbparm=&symbread(); }
                   5752: 	if ($symbparm) {
1.409     www      5753: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 5754: 	} else {
1.620     albertel 5755: 	    $filename=$env{'request.filename'};
1.282     albertel 5756: 	}
                   5757: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.288     albertel 5758: 	if (defined($metadata)) { return $metadata; }
1.282     albertel 5759: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.288     albertel 5760: 	if (defined($metadata)) { return $metadata; }
1.142     www      5761: 
1.594     albertel 5762: # ---------------------------------------------- fourth, look in rest pf course
1.593     albertel 5763: 	if ($symbparm && defined($courseid) && 
1.620     albertel 5764: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 5765: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   5766: 				     $env{'course.'.$courseid.'.domain'},
                   5767: 				     'course',
                   5768: 				     ($courselevelm,$courselevel));
1.593     albertel 5769: 	    if (defined($coursereply)) { return $coursereply; }
                   5770: 	}
1.145     www      5771: # ------------------------------------------------------------------ Cascade up
1.218     albertel 5772: 	unless ($space eq '0') {
1.336     albertel 5773: 	    my @parts=split(/_/,$space);
                   5774: 	    my $id=pop(@parts);
                   5775: 	    my $part=join('_',@parts);
                   5776: 	    if ($part eq '') { $part='0'; }
                   5777: 	    my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 5778: 				 $symbparm,$udom,$uname,$section,1);
1.337     albertel 5779: 	    if (defined($partgeneral)) { return $partgeneral; }
1.218     albertel 5780: 	}
1.395     albertel 5781: 	if ($recurse) { return undef; }
                   5782: 	my $pack_def=&packages_tab_default($filename,$varname);
                   5783: 	if (defined($pack_def)) { return $pack_def; }
1.71      www      5784: 
1.48      www      5785: # ---------------------------------------------------- Any other user namespace
                   5786:     } elsif ($realm eq 'environment') {
                   5787: # ----------------------------------------------------------------- environment
1.620     albertel 5788: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   5789: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 5790: 	} else {
1.770     albertel 5791: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   5792: 		return '';
                   5793: 	    }
1.219     albertel 5794: 	    my %returnhash=&userenvironment($udom,$uname,
                   5795: 					    $spacequalifierrest);
                   5796: 	    return $returnhash{$spacequalifierrest};
                   5797: 	}
1.28      www      5798:     } elsif ($realm eq 'system') {
1.48      www      5799: # ----------------------------------------------------------------- system.time
                   5800: 	if ($space eq 'time') {
                   5801: 	    return time;
                   5802:         }
1.696     albertel 5803:     } elsif ($realm eq 'server') {
                   5804: # ----------------------------------------------------------------- system.time
                   5805: 	if ($space eq 'name') {
                   5806: 	    return $ENV{'SERVER_NAME'};
                   5807:         }
1.28      www      5808:     }
1.48      www      5809:     return '';
1.61      www      5810: }
                   5811: 
1.691     raeburn  5812: sub check_group_parms {
                   5813:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   5814:     my @groupitems = ();
                   5815:     my $resultitem;
                   5816:     my @levels = ($symbparm,$mapparm,$what);
                   5817:     foreach my $group (@{$groups}) {
                   5818:         foreach my $level (@levels) {
                   5819:              my $item = $courseid.'.['.$group.'].'.$level;
                   5820:              push(@groupitems,$item);
                   5821:         }
                   5822:     }
                   5823:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   5824:                             $env{'course.'.$courseid.'.domain'},
                   5825:                                      'course',@groupitems);
                   5826:     return $coursereply;
                   5827: }
                   5828: 
                   5829: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  5830:     my ($courseid,@groups) = @_;
                   5831:     @groups = sort(@groups);
1.691     raeburn  5832:     return @groups;
                   5833: }
                   5834: 
1.395     albertel 5835: sub packages_tab_default {
                   5836:     my ($uri,$varname)=@_;
                   5837:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 5838: 
                   5839:     my (@extension,@specifics,$do_default);
                   5840:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 5841: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 5842: 	if ($pack_type eq 'default') {
                   5843: 	    $do_default=1;
                   5844: 	} elsif ($pack_type eq 'extension') {
                   5845: 	    push(@extension,[$package,$pack_type,$pack_part]);
                   5846: 	} else {
                   5847: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   5848: 	}
                   5849:     }
                   5850:     # first look for a package that matches the requested part id
                   5851:     foreach my $package (@specifics) {
                   5852: 	my (undef,$pack_type,$pack_part)=@{$package};
                   5853: 	next if ($pack_part ne $part);
                   5854: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   5855: 	    return $packagetab{"$pack_type&$name&default"};
                   5856: 	}
                   5857:     }
                   5858:     # look for any possible matching non extension_ package
                   5859:     foreach my $package (@specifics) {
                   5860: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 5861: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   5862: 	    return $packagetab{"$pack_type&$name&default"};
                   5863: 	}
1.585     albertel 5864: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 5865: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   5866: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 5867: 	}
                   5868:     }
1.738     albertel 5869:     # look for any posible extension_ match
                   5870:     foreach my $package (@extension) {
                   5871: 	my ($package,$pack_type)=@{$package};
                   5872: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   5873: 	    return $packagetab{"$pack_type&$name&default"};
                   5874: 	}
                   5875: 	if (defined($packagetab{$package."&$name&default"})) {
                   5876: 	    return $packagetab{$package."&$name&default"};
                   5877: 	}
                   5878:     }
                   5879:     # look for a global default setting
                   5880:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   5881: 	return $packagetab{"default&$name&default"};
                   5882:     }
1.395     albertel 5883:     return undef;
                   5884: }
                   5885: 
1.334     albertel 5886: sub add_prefix_and_part {
                   5887:     my ($prefix,$part)=@_;
                   5888:     my $keyroot;
                   5889:     if (defined($prefix) && $prefix !~ /^__/) {
                   5890: 	# prefix that has a part already
                   5891: 	$keyroot=$prefix;
                   5892:     } elsif (defined($prefix)) {
                   5893: 	# prefix that is missing a part
                   5894: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   5895:     } else {
                   5896: 	# no prefix at all
                   5897: 	if (defined($part)) { $keyroot='_'.$part; }
                   5898:     }
                   5899:     return $keyroot;
                   5900: }
                   5901: 
1.71      www      5902: # ---------------------------------------------------------------- Get metadata
                   5903: 
1.599     albertel 5904: my %metaentry;
1.71      www      5905: sub metadata {
1.176     www      5906:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      5907:     $uri=&declutter($uri);
1.288     albertel 5908:     # if it is a non metadata possible uri return quickly
1.529     albertel 5909:     if (($uri eq '') || 
                   5910: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 5911: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.423     albertel 5912:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) ||
1.489     albertel 5913: 	($uri =~ m|home/[^/]+/public_html/|)) {
1.468     albertel 5914: 	return undef;
1.288     albertel 5915:     }
1.73      www      5916:     my $filename=$uri;
                   5917:     $uri=~s/\.meta$//;
1.172     www      5918: #
                   5919: # Is the metadata already cached?
1.177     www      5920: # Look at timestamp of caching
1.172     www      5921: # Everything is cached by the main uri, libraries are never directly cached
                   5922: #
1.428     albertel 5923:     if (!defined($liburi)) {
1.599     albertel 5924: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 5925: 	if (defined($cached)) { return $result->{':'.$what}; }
                   5926:     }
                   5927:     {
1.172     www      5928: #
                   5929: # Is this a recursive call for a library?
                   5930: #
1.599     albertel 5931: #	if (! exists($metacache{$uri})) {
                   5932: #	    $metacache{$uri}={};
                   5933: #	}
1.171     www      5934:         if ($liburi) {
                   5935: 	    $liburi=&declutter($liburi);
                   5936:             $filename=$liburi;
1.401     bowersj2 5937:         } else {
1.599     albertel 5938: 	    &devalidate_cache_new('meta',$uri);
                   5939: 	    undef(%metaentry);
1.401     bowersj2 5940: 	}
1.140     www      5941:         my %metathesekeys=();
1.73      www      5942:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 5943: 	my $metastring;
1.768     albertel 5944: 	if ($uri !~ m -^(editupload)/-) {
1.543     albertel 5945: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 5946: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 5947: 	    $metastring=&getfile($file);
1.489     albertel 5948: 	}
1.208     albertel 5949:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      5950:         my $token;
1.140     www      5951:         undef %metathesekeys;
1.71      www      5952:         while ($token=$parser->get_token) {
1.339     albertel 5953: 	    if ($token->[0] eq 'S') {
                   5954: 		if (defined($token->[2]->{'package'})) {
1.172     www      5955: #
                   5956: # This is a package - get package info
                   5957: #
1.339     albertel 5958: 		    my $package=$token->[2]->{'package'};
                   5959: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   5960: 		    if (defined($token->[2]->{'id'})) { 
                   5961: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   5962: 		    }
1.599     albertel 5963: 		    if ($metaentry{':packages'}) {
                   5964: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 5965: 		    } else {
1.599     albertel 5966: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 5967: 		    }
1.736     albertel 5968: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 5969: 			my $part=$keyroot;
                   5970: 			$part=~s/^\_//;
1.736     albertel 5971: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   5972: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   5973: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 5974: 			    # ignore package.tab specified default values
                   5975:                             # here &package_tab_default() will fetch those
                   5976: 			    if ($subp eq 'default') { next; }
1.736     albertel 5977: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 5978: 			    my $unikey;
                   5979: 			    if ($pack =~ /_0$/) {
                   5980: 				$unikey='parameter_0_'.$name;
                   5981: 				$part=0;
                   5982: 			    } else {
                   5983: 				$unikey='parameter'.$keyroot.'_'.$name;
                   5984: 			    }
1.339     albertel 5985: 			    if ($subp eq 'display') {
                   5986: 				$value.=' [Part: '.$part.']';
                   5987: 			    }
1.599     albertel 5988: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 5989: 			    $metathesekeys{$unikey}=1;
1.599     albertel 5990: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   5991: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 5992: 			    }
1.599     albertel 5993: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   5994: 				$metaentry{':'.$unikey}=
                   5995: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 5996: 			    }
1.339     albertel 5997: 			}
                   5998: 		    }
                   5999: 		} else {
1.172     www      6000: #
                   6001: # This is not a package - some other kind of start tag
1.339     albertel 6002: #
                   6003: 		    my $entry=$token->[1];
                   6004: 		    my $unikey;
                   6005: 		    if ($entry eq 'import') {
                   6006: 			$unikey='';
                   6007: 		    } else {
                   6008: 			$unikey=$entry;
                   6009: 		    }
                   6010: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   6011: 
                   6012: 		    if (defined($token->[2]->{'id'})) { 
                   6013: 			$unikey.='_'.$token->[2]->{'id'}; 
                   6014: 		    }
1.175     www      6015: 
1.339     albertel 6016: 		    if ($entry eq 'import') {
1.175     www      6017: #
                   6018: # Importing a library here
1.339     albertel 6019: #
                   6020: 			if ($depthcount<20) {
                   6021: 			    my $location=$parser->get_text('/import');
                   6022: 			    my $dir=$filename;
                   6023: 			    $dir=~s|[^/]*$||;
                   6024: 			    $location=&filelocation($dir,$location);
1.736     albertel 6025: 			    my $metadata = 
                   6026: 				&metadata($uri,'keys', $location,$unikey,
                   6027: 					  $depthcount+1);
                   6028: 			    foreach my $meta (split(',',$metadata)) {
                   6029: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   6030: 				$metathesekeys{$meta}=1;
1.339     albertel 6031: 			    }
                   6032: 			}
                   6033: 		    } else { 
                   6034: 			
                   6035: 			if (defined($token->[2]->{'name'})) { 
                   6036: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   6037: 			}
                   6038: 			$metathesekeys{$unikey}=1;
1.736     albertel 6039: 			foreach my $param (@{$token->[3]}) {
                   6040: 			    $metaentry{':'.$unikey.'.'.$param} =
                   6041: 				$token->[2]->{$param};
1.339     albertel 6042: 			}
                   6043: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 6044: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 6045: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   6046: 		 # only ws inside the tag, and not in default, so use default
                   6047: 		 # as value
1.599     albertel 6048: 			    $metaentry{':'.$unikey}=$default;
1.339     albertel 6049: 			} else {
1.321     albertel 6050: 		  # either something interesting inside the tag or default
                   6051:                   # uninteresting
1.599     albertel 6052: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 6053: 			}
1.172     www      6054: # end of not-a-package not-a-library import
1.339     albertel 6055: 		    }
1.172     www      6056: # end of not-a-package start tag
1.339     albertel 6057: 		}
1.172     www      6058: # the next is the end of "start tag"
1.339     albertel 6059: 	    }
                   6060: 	}
1.483     albertel 6061: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.737     albertel 6062: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 6063: 	    #no specific packages #how's our extension
                   6064: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 6065: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 6066: 					 \%metathesekeys);
                   6067: 	}
1.599     albertel 6068: 	if (!exists($metaentry{':packages'})) {
1.737     albertel 6069: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 6070: 		#no specific packages well let's get default then
                   6071: 		if ($key!~/^default&/) { next; }
1.488     albertel 6072: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 6073: 					     \%metathesekeys);
                   6074: 	    }
                   6075: 	}
1.338     www      6076: # are there custom rights to evaluate
1.599     albertel 6077: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 6078: 
1.338     www      6079:     #
                   6080:     # Importing a rights file here
1.339     albertel 6081:     #
                   6082: 	    unless ($depthcount) {
1.599     albertel 6083: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 6084: 		my $dir=$filename;
                   6085: 		$dir=~s|[^/]*$||;
                   6086: 		$location=&filelocation($dir,$location);
1.736     albertel 6087: 		my $rights_metadata =
                   6088: 		    &metadata($uri,'keys',$location,'_rights',
                   6089: 			      $depthcount+1);
                   6090: 		foreach my $rights (split(',',$rights_metadata)) {
                   6091: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   6092: 		    $metathesekeys{$rights}=1;
1.339     albertel 6093: 		}
                   6094: 	    }
                   6095: 	}
1.737     albertel 6096: 	# uniqifiy package listing
                   6097: 	my %seen;
                   6098: 	my @uniq_packages =
                   6099: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   6100: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   6101: 
                   6102: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 6103: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   6104: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.699     albertel 6105: 	&do_cache_new('meta',$uri,\%metaentry,60*60);
1.177     www      6106: # this is the end of "was not already recently cached
1.71      www      6107:     }
1.599     albertel 6108:     return $metaentry{':'.$what};
1.261     albertel 6109: }
                   6110: 
1.488     albertel 6111: sub metadata_create_package_def {
1.483     albertel 6112:     my ($uri,$key,$package,$metathesekeys)=@_;
                   6113:     my ($pack,$name,$subp)=split(/\&/,$key);
                   6114:     if ($subp eq 'default') { next; }
                   6115:     
1.599     albertel 6116:     if (defined($metaentry{':packages'})) {
                   6117: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 6118:     } else {
1.599     albertel 6119: 	$metaentry{':packages'}=$package;
1.483     albertel 6120:     }
                   6121:     my $value=$packagetab{$key};
                   6122:     my $unikey;
                   6123:     $unikey='parameter_0_'.$name;
1.599     albertel 6124:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 6125:     $$metathesekeys{$unikey}=1;
1.599     albertel 6126:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   6127: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 6128:     }
1.599     albertel 6129:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   6130: 	$metaentry{':'.$unikey}=
                   6131: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 6132:     }
                   6133: }
                   6134: 
1.261     albertel 6135: sub metadata_generate_part0 {
                   6136:     my ($metadata,$metacache,$uri) = @_;
                   6137:     my %allnames;
1.737     albertel 6138:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 6139: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 6140: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   6141: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 6142: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 6143: 	    $allnames{$name}=$part;
                   6144: 	  }
                   6145: 	}
                   6146:     }
                   6147:     foreach my $name (keys(%allnames)) {
                   6148:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 6149:       my $key=":parameter_0_$name";
1.261     albertel 6150:       $$metacache{"$key.part"}='0';
                   6151:       $$metacache{"$key.name"}=$name;
1.428     albertel 6152:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 6153: 					   $allnames{$name}.'_'.$name.
                   6154: 					   '.type'};
1.428     albertel 6155:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 6156: 			     '.display'};
1.644     www      6157:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 6158:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 6159:       $$metacache{"$key.display"}=$olddis;
                   6160:     }
1.71      www      6161: }
                   6162: 
1.764     albertel 6163: # ------------------------------------------------------ Devalidate title cache
                   6164: 
                   6165: sub devalidate_title_cache {
                   6166:     my ($url)=@_;
                   6167:     if (!$env{'request.course.id'}) { return; }
                   6168:     my $symb=&symbread($url);
                   6169:     if (!$symb) { return; }
                   6170:     my $key=$env{'request.course.id'}."\0".$symb;
                   6171:     &devalidate_cache_new('title',$key);
                   6172: }
                   6173: 
1.301     www      6174: # ------------------------------------------------- Get the title of a resource
                   6175: 
                   6176: sub gettitle {
                   6177:     my $urlsymb=shift;
                   6178:     my $symb=&symbread($urlsymb);
1.534     albertel 6179:     if ($symb) {
1.620     albertel 6180: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 6181: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 6182: 	if (defined($cached)) { 
                   6183: 	    return $result;
                   6184: 	}
1.534     albertel 6185: 	my ($map,$resid,$url)=&decode_symb($symb);
                   6186: 	my $title='';
                   6187: 	my %bighash;
1.620     albertel 6188: 	if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.534     albertel 6189: 		&GDBM_READER(),0640)) {
                   6190: 	    my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   6191: 	    $title=$bighash{'title_'.$mapid.'.'.$resid};
                   6192: 	    untie %bighash;
                   6193: 	}
                   6194: 	$title=~s/\&colon\;/\:/gs;
                   6195: 	if ($title) {
1.599     albertel 6196: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 6197: 	}
                   6198: 	$urlsymb=$url;
                   6199:     }
                   6200:     my $title=&metadata($urlsymb,'title');
                   6201:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   6202:     return $title;
1.301     www      6203: }
1.613     albertel 6204: 
1.614     albertel 6205: sub get_slot {
                   6206:     my ($which,$cnum,$cdom)=@_;
                   6207:     if (!$cnum || !$cdom) {
                   6208: 	(undef,my $courseid)=&Apache::lonxml::whichuser();
1.620     albertel 6209: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   6210: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 6211:     }
1.703     albertel 6212:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   6213:     my %slotinfo;
                   6214:     if (exists($remembered{$key})) {
                   6215: 	$slotinfo{$which} = $remembered{$key};
                   6216:     } else {
                   6217: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   6218: 	&Apache::lonhomework::showhash(%slotinfo);
                   6219: 	my ($tmp)=keys(%slotinfo);
                   6220: 	if ($tmp=~/^error:/) { return (); }
                   6221: 	$remembered{$key} = $slotinfo{$which};
                   6222:     }
1.616     albertel 6223:     if (ref($slotinfo{$which}) eq 'HASH') {
                   6224: 	return %{$slotinfo{$which}};
                   6225:     }
                   6226:     return $slotinfo{$which};
1.614     albertel 6227: }
1.31      www      6228: # ------------------------------------------------- Update symbolic store links
                   6229: 
                   6230: sub symblist {
                   6231:     my ($mapname,%newhash)=@_;
1.438     www      6232:     $mapname=&deversion(&declutter($mapname));
1.31      www      6233:     my %hash;
1.620     albertel 6234:     if (($env{'request.course.fn'}) && (%newhash)) {
                   6235:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 6236:                       &GDBM_WRCREAT(),0640)) {
1.711     albertel 6237: 	    foreach my $url (keys %newhash) {
                   6238: 		next if ($url eq 'last_known'
                   6239: 			 && $env{'form.no_update_last_known'});
                   6240: 		$hash{declutter($url)}=&encode_symb($mapname,
                   6241: 						    $newhash{$url}->[1],
                   6242: 						    $newhash{$url}->[0]);
1.191     harris41 6243:             }
1.31      www      6244:             if (untie(%hash)) {
                   6245: 		return 'ok';
                   6246:             }
                   6247:         }
                   6248:     }
                   6249:     return 'error';
1.212     www      6250: }
                   6251: 
                   6252: # --------------------------------------------------------------- Verify a symb
                   6253: 
                   6254: sub symbverify {
1.510     www      6255:     my ($symb,$thisurl)=@_;
                   6256:     my $thisfn=$thisurl;
                   6257: # wrapper not part of symbs
                   6258:     $thisfn=~s/^\/adm\/wrapper//;
1.694     albertel 6259:     $thisfn=~s/^\/adm\/coursedocs\/showdoc\///;
1.439     www      6260:     $thisfn=&declutter($thisfn);
1.215     www      6261: # direct jump to resource in page or to a sequence - will construct own symbs
                   6262:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   6263: # check URL part
1.409     www      6264:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      6265: 
1.431     www      6266:     unless ($url eq $thisfn) { return 0; }
1.213     www      6267: 
1.216     www      6268:     $symb=&symbclean($symb);
1.510     www      6269:     $thisurl=&deversion($thisurl);
1.439     www      6270:     $thisfn=&deversion($thisfn);
1.213     www      6271: 
                   6272:     my %bighash;
                   6273:     my $okay=0;
1.431     www      6274: 
1.620     albertel 6275:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 6276:                             &GDBM_READER(),0640)) {
1.510     www      6277:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      6278:         unless ($ids) { 
1.510     www      6279:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      6280:         }
                   6281:         if ($ids) {
                   6282: # ------------------------------------------------------------------- Has ID(s)
                   6283: 	    foreach (split(/\,/,$ids)) {
1.644     www      6284: 	       my ($mapid,$resid)=split(/\./,$_);
1.216     www      6285:                if (
                   6286:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   6287:    eq $symb) { 
1.620     albertel 6288: 		   if (($env{'request.role.adv'}) ||
                   6289: 		       $bighash{'encrypted_'.$_} eq $env{'request.enc'}) {
1.582     albertel 6290: 		       $okay=1; 
                   6291: 		   }
                   6292: 	       }
1.216     www      6293: 	   }
                   6294:         }
1.213     www      6295: 	untie(%bighash);
                   6296:     }
                   6297:     return $okay;
1.31      www      6298: }
                   6299: 
1.210     www      6300: # --------------------------------------------------------------- Clean-up symb
                   6301: 
                   6302: sub symbclean {
                   6303:     my $symb=shift;
1.568     albertel 6304:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      6305: # remove version from map
                   6306:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      6307: 
1.210     www      6308: # remove version from URL
                   6309:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      6310: 
1.507     www      6311: # remove wrapper
                   6312: 
1.510     www      6313:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 6314:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      6315:     return $symb;
1.409     www      6316: }
                   6317: 
                   6318: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 6319: 
                   6320: sub encode_symb {
                   6321:     my ($map,$resid,$url)=@_;
                   6322:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   6323: }
1.409     www      6324: 
                   6325: sub decode_symb {
1.568     albertel 6326:     my $symb=shift;
                   6327:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   6328:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      6329:     return (&fixversion($map),$resid,&fixversion($url));
                   6330: }
                   6331: 
                   6332: sub fixversion {
                   6333:     my $fn=shift;
1.609     banghart 6334:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      6335:     my %bighash;
                   6336:     my $uri=&clutter($fn);
1.620     albertel 6337:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      6338: # is this cached?
1.599     albertel 6339:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      6340:     if (defined($cached)) { return $result; }
                   6341: # unfortunately not cached, or expired
1.620     albertel 6342:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      6343: 	    &GDBM_READER(),0640)) {
                   6344:  	if ($bighash{'version_'.$uri}) {
                   6345:  	    my $version=$bighash{'version_'.$uri};
1.444     www      6346:  	    unless (($version eq 'mostrecent') || 
                   6347: 		    ($version==&getversion($uri))) {
1.440     www      6348:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   6349:  	    }
                   6350:  	}
                   6351:  	untie %bighash;
1.413     www      6352:     }
1.599     albertel 6353:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      6354: }
                   6355: 
                   6356: sub deversion {
                   6357:     my $url=shift;
                   6358:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   6359:     return $url;
1.210     www      6360: }
                   6361: 
1.31      www      6362: # ------------------------------------------------------ Return symb list entry
                   6363: 
                   6364: sub symbread {
1.249     www      6365:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 6366:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 6367:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      6368: # no filename provided? try from environment
1.44      www      6369:     unless ($thisfn) {
1.620     albertel 6370:         if ($env{'request.symb'}) {
                   6371: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 6372: 	}
1.620     albertel 6373: 	$thisfn=$env{'request.filename'};
1.44      www      6374:     }
1.569     albertel 6375:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      6376: # is that filename actually a symb? Verify, clean, and return
                   6377:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 6378: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 6379: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 6380: 	}
1.242     www      6381:     }
1.44      www      6382:     $thisfn=declutter($thisfn);
1.31      www      6383:     my %hash;
1.37      www      6384:     my %bighash;
                   6385:     my $syval='';
1.620     albertel 6386:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  6387:         my $targetfn = $thisfn;
1.609     banghart 6388:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  6389:             $targetfn = 'adm/wrapper/'.$thisfn;
                   6390:         }
1.687     albertel 6391: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   6392: 	    $targetfn=$1;
                   6393: 	}
1.620     albertel 6394:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 6395:                       &GDBM_READER(),0640)) {
1.481     raeburn  6396: 	    $syval=$hash{$targetfn};
1.37      www      6397:             untie(%hash);
                   6398:         }
                   6399: # ---------------------------------------------------------- There was an entry
                   6400:         if ($syval) {
1.601     albertel 6401: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 6402: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.601     albertel 6403: 		    #&appenv('request.ambiguous' => $thisfn);
1.620     albertel 6404: 		    #return $env{$cache_str}='';
1.601     albertel 6405: 		#}    
                   6406: 		#$syval.=$1;
                   6407: 	    #}
1.37      www      6408:         } else {
                   6409: # ------------------------------------------------------- Was not in symb table
1.620     albertel 6410:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 6411:                             &GDBM_READER(),0640)) {
1.37      www      6412: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      6413:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      6414:               unless ($ids) { 
                   6415:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      6416:               }
                   6417:               unless ($ids) {
                   6418: # alias?
                   6419: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      6420:               }
1.37      www      6421:               if ($ids) {
                   6422: # ------------------------------------------------------------------- Has ID(s)
                   6423:                  my @possibilities=split(/\,/,$ids);
1.39      www      6424:                  if ($#possibilities==0) {
                   6425: # ----------------------------------------------- There is only one possibility
1.37      www      6426: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 6427: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   6428: 						    $resid,$thisfn);
1.249     www      6429:                  } elsif (!$donotrecurse) {
1.39      www      6430: # ------------------------------------------ There is more than one possibility
                   6431:                      my $realpossible=0;
1.191     harris41 6432:                      foreach (@possibilities) {
1.39      www      6433: 			 my $file=$bighash{'src_'.$_};
                   6434:                          if (&allowed('bre',$file)) {
                   6435:          		    my ($mapid,$resid)=split(/\./,$_);
                   6436:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   6437: 				$realpossible++;
1.626     albertel 6438:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   6439: 						    $resid,$thisfn);
1.39      www      6440:                             }
                   6441: 			 }
1.191     harris41 6442:                      }
1.39      www      6443: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      6444:                  } else {
                   6445:                      $syval='';
1.37      www      6446:                  }
                   6447: 	      }
                   6448:               untie(%bighash)
1.481     raeburn  6449:            }
1.31      www      6450:         }
1.62      www      6451:         if ($syval) {
1.620     albertel 6452: 	    return $env{$cache_str}=$syval;
1.62      www      6453:         }
1.31      www      6454:     }
1.44      www      6455:     &appenv('request.ambiguous' => $thisfn);
1.620     albertel 6456:     return $env{$cache_str}='';
1.31      www      6457: }
                   6458: 
                   6459: # ---------------------------------------------------------- Return random seed
                   6460: 
1.32      www      6461: sub numval {
                   6462:     my $txt=shift;
                   6463:     $txt=~tr/A-J/0-9/;
                   6464:     $txt=~tr/a-j/0-9/;
                   6465:     $txt=~tr/K-T/0-9/;
                   6466:     $txt=~tr/k-t/0-9/;
                   6467:     $txt=~tr/U-Z/0-5/;
                   6468:     $txt=~tr/u-z/0-5/;
                   6469:     $txt=~s/\D//g;
1.564     albertel 6470:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      6471:     return int($txt);
1.368     albertel 6472: }
                   6473: 
1.484     albertel 6474: sub numval2 {
                   6475:     my $txt=shift;
                   6476:     $txt=~tr/A-J/0-9/;
                   6477:     $txt=~tr/a-j/0-9/;
                   6478:     $txt=~tr/K-T/0-9/;
                   6479:     $txt=~tr/k-t/0-9/;
                   6480:     $txt=~tr/U-Z/0-5/;
                   6481:     $txt=~tr/u-z/0-5/;
                   6482:     $txt=~s/\D//g;
                   6483:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   6484:     my $total;
                   6485:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 6486:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 6487:     return int($total);
                   6488: }
                   6489: 
1.575     albertel 6490: sub numval3 {
                   6491:     use integer;
                   6492:     my $txt=shift;
                   6493:     $txt=~tr/A-J/0-9/;
                   6494:     $txt=~tr/a-j/0-9/;
                   6495:     $txt=~tr/K-T/0-9/;
                   6496:     $txt=~tr/k-t/0-9/;
                   6497:     $txt=~tr/U-Z/0-5/;
                   6498:     $txt=~tr/u-z/0-5/;
                   6499:     $txt=~s/\D//g;
                   6500:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   6501:     my $total;
                   6502:     foreach my $val (@txts) { $total+=$val; }
                   6503:     if ($_64bit) { $total=(($total<<32)>>32); }
                   6504:     return $total;
                   6505: }
                   6506: 
1.675     albertel 6507: sub digest {
                   6508:     my ($data)=@_;
                   6509:     my $digest=&Digest::MD5::md5($data);
                   6510:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   6511:     my ($e,$f);
                   6512:     {
                   6513:         use integer;
                   6514:         $e=($a+$b);
                   6515:         $f=($c+$d);
                   6516:         if ($_64bit) {
                   6517:             $e=(($e<<32)>>32);
                   6518:             $f=(($f<<32)>>32);
                   6519:         }
                   6520:     }
                   6521:     if (wantarray) {
                   6522: 	return ($e,$f);
                   6523:     } else {
                   6524: 	my $g;
                   6525: 	{
                   6526: 	    use integer;
                   6527: 	    $g=($e+$f);
                   6528: 	    if ($_64bit) {
                   6529: 		$g=(($g<<32)>>32);
                   6530: 	    }
                   6531: 	}
                   6532: 	return $g;
                   6533:     }
                   6534: }
                   6535: 
1.368     albertel 6536: sub latest_rnd_algorithm_id {
1.675     albertel 6537:     return '64bit5';
1.366     albertel 6538: }
1.32      www      6539: 
1.503     albertel 6540: sub get_rand_alg {
                   6541:     my ($courseid)=@_;
                   6542:     if (!$courseid) { $courseid=(&Apache::lonxml::whichuser())[1]; }
                   6543:     if ($courseid) {
1.620     albertel 6544: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 6545:     }
                   6546:     return &latest_rnd_algorithm_id();
                   6547: }
                   6548: 
1.562     albertel 6549: sub validCODE {
                   6550:     my ($CODE)=@_;
                   6551:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   6552:     return 0;
                   6553: }
                   6554: 
1.491     albertel 6555: sub getCODE {
1.620     albertel 6556:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 6557:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   6558: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   6559: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 6560: 	return $Apache::lonhomework::history{'resource.CODE'};
                   6561:     }
                   6562:     return undef;
                   6563: }
                   6564: 
1.31      www      6565: sub rndseed {
1.155     albertel 6566:     my ($symb,$courseid,$domain,$username)=@_;
1.366     albertel 6567: 
                   6568:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&Apache::lonxml::whichuser();
1.155     albertel 6569:     if (!$symb) {
1.366     albertel 6570: 	unless ($symb=$wsymb) { return time; }
                   6571:     }
                   6572:     if (!$courseid) { $courseid=$wcourseid; }
                   6573:     if (!$domain) { $domain=$wdomain; }
                   6574:     if (!$username) { $username=$wusername }
1.503     albertel 6575:     my $which=&get_rand_alg();
1.491     albertel 6576:     if (defined(&getCODE())) {
1.675     albertel 6577: 	if ($which eq '64bit5') {
                   6578: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   6579: 	} elsif ($which eq '64bit4') {
1.575     albertel 6580: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   6581: 	} else {
                   6582: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   6583: 	}
1.675     albertel 6584:     } elsif ($which eq '64bit5') {
                   6585: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 6586:     } elsif ($which eq '64bit4') {
                   6587: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 6588:     } elsif ($which eq '64bit3') {
                   6589: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 6590:     } elsif ($which eq '64bit2') {
                   6591: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 6592:     } elsif ($which eq '64bit') {
                   6593: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   6594:     }
                   6595:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   6596: }
                   6597: 
                   6598: sub rndseed_32bit {
                   6599:     my ($symb,$courseid,$domain,$username)=@_;
                   6600:     {
                   6601: 	use integer;
                   6602: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   6603: 	my $symbseed=numval($symb) << 22;
                   6604: 	my $namechck=unpack("%32C*",$username) << 17;
                   6605: 	my $nameseed=numval($username) << 12;
                   6606: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   6607: 	my $courseseed=unpack("%32C*",$courseid);
                   6608: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
                   6609: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6610: 	#&Apache::lonxml::debug("rndseed :$num:$symb");
1.564     albertel 6611: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 6612: 	return $num;
                   6613:     }
                   6614: }
                   6615: 
                   6616: sub rndseed_64bit {
                   6617:     my ($symb,$courseid,$domain,$username)=@_;
                   6618:     {
                   6619: 	use integer;
                   6620: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   6621: 	my $symbseed=numval($symb) << 10;
                   6622: 	my $namechck=unpack("%32S*",$username);
                   6623: 	
                   6624: 	my $nameseed=numval($username) << 21;
                   6625: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   6626: 	my $courseseed=unpack("%32S*",$courseid);
                   6627: 	
                   6628: 	my $num1=$symbchck+$symbseed+$namechck;
                   6629: 	my $num2=$nameseed+$domainseed+$courseseed;
                   6630: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6631: 	#&Apache::lonxml::debug("rndseed :$num:$symb");
1.564     albertel 6632: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   6633: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 6634: 	return "$num1,$num2";
1.155     albertel 6635:     }
1.366     albertel 6636: }
                   6637: 
1.443     albertel 6638: sub rndseed_64bit2 {
                   6639:     my ($symb,$courseid,$domain,$username)=@_;
                   6640:     {
                   6641: 	use integer;
                   6642: 	# strings need to be an even # of cahracters long, it it is odd the
                   6643:         # last characters gets thrown away
                   6644: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6645: 	my $symbseed=numval($symb) << 10;
                   6646: 	my $namechck=unpack("%32S*",$username.' ');
                   6647: 	
                   6648: 	my $nameseed=numval($username) << 21;
1.501     albertel 6649: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   6650: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6651: 	
                   6652: 	my $num1=$symbchck+$symbseed+$namechck;
                   6653: 	my $num2=$nameseed+$domainseed+$courseseed;
                   6654: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6655: 	#&Apache::lonxml::debug("rndseed :$num:$symb");
                   6656: 	return "$num1,$num2";
                   6657:     }
                   6658: }
                   6659: 
                   6660: sub rndseed_64bit3 {
                   6661:     my ($symb,$courseid,$domain,$username)=@_;
                   6662:     {
                   6663: 	use integer;
                   6664: 	# strings need to be an even # of cahracters long, it it is odd the
                   6665:         # last characters gets thrown away
                   6666: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6667: 	my $symbseed=numval2($symb) << 10;
                   6668: 	my $namechck=unpack("%32S*",$username.' ');
                   6669: 	
                   6670: 	my $nameseed=numval2($username) << 21;
1.443     albertel 6671: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   6672: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6673: 	
                   6674: 	my $num1=$symbchck+$symbseed+$namechck;
                   6675: 	my $num2=$nameseed+$domainseed+$courseseed;
                   6676: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
1.564     albertel 6677: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$_64bit");
                   6678: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   6679: 	
1.503     albertel 6680: 	return "$num1:$num2";
1.443     albertel 6681:     }
                   6682: }
                   6683: 
1.575     albertel 6684: sub rndseed_64bit4 {
                   6685:     my ($symb,$courseid,$domain,$username)=@_;
                   6686:     {
                   6687: 	use integer;
                   6688: 	# strings need to be an even # of cahracters long, it it is odd the
                   6689:         # last characters gets thrown away
                   6690: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6691: 	my $symbseed=numval3($symb) << 10;
                   6692: 	my $namechck=unpack("%32S*",$username.' ');
                   6693: 	
                   6694: 	my $nameseed=numval3($username) << 21;
                   6695: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   6696: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6697: 	
                   6698: 	my $num1=$symbchck+$symbseed+$namechck;
                   6699: 	my $num2=$nameseed+$domainseed+$courseseed;
                   6700: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6701: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$_64bit");
                   6702: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   6703: 	
                   6704: 	return "$num1:$num2";
                   6705:     }
                   6706: }
                   6707: 
1.675     albertel 6708: sub rndseed_64bit5 {
                   6709:     my ($symb,$courseid,$domain,$username)=@_;
                   6710:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   6711:     return "$num1:$num2";
                   6712: }
                   6713: 
1.366     albertel 6714: sub rndseed_CODE_64bit {
                   6715:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 6716:     {
1.366     albertel 6717: 	use integer;
1.443     albertel 6718: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 6719: 	my $symbseed=numval2($symb);
1.491     albertel 6720: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   6721: 	my $CODEseed=numval(&getCODE());
1.443     albertel 6722: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 6723: 	my $num1=$symbseed+$CODEchck;
                   6724: 	my $num2=$CODEseed+$courseseed+$symbchck;
                   6725: 	#&Apache::lonxml::debug("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
1.366     albertel 6726: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$symb");
1.564     albertel 6727: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   6728: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 6729: 	return "$num1:$num2";
1.366     albertel 6730:     }
                   6731: }
                   6732: 
1.575     albertel 6733: sub rndseed_CODE_64bit4 {
                   6734:     my ($symb,$courseid,$domain,$username)=@_;
                   6735:     {
                   6736: 	use integer;
                   6737: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   6738: 	my $symbseed=numval3($symb);
                   6739: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   6740: 	my $CODEseed=numval3(&getCODE());
                   6741: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6742: 	my $num1=$symbseed+$CODEchck;
                   6743: 	my $num2=$CODEseed+$courseseed+$symbchck;
                   6744: 	#&Apache::lonxml::debug("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   6745: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$symb");
                   6746: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   6747: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   6748: 	return "$num1:$num2";
                   6749:     }
                   6750: }
                   6751: 
1.675     albertel 6752: sub rndseed_CODE_64bit5 {
                   6753:     my ($symb,$courseid,$domain,$username)=@_;
                   6754:     my $code = &getCODE();
                   6755:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   6756:     return "$num1:$num2";
                   6757: }
                   6758: 
1.366     albertel 6759: sub setup_random_from_rndseed {
                   6760:     my ($rndseed)=@_;
1.503     albertel 6761:     if ($rndseed =~/([,:])/) {
                   6762: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 6763: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   6764:     } else {
                   6765: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 6766:     }
1.36      albertel 6767: }
                   6768: 
1.474     albertel 6769: sub latest_receipt_algorithm_id {
                   6770:     return 'receipt2';
                   6771: }
                   6772: 
1.480     www      6773: sub recunique {
                   6774:     my $fucourseid=shift;
                   6775:     my $unique;
1.620     albertel 6776:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   6777: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      6778:     } else {
                   6779: 	$unique=$perlvar{'lonReceipt'};
                   6780:     }
                   6781:     return unpack("%32C*",$unique);
                   6782: }
                   6783: 
                   6784: sub recprefix {
                   6785:     my $fucourseid=shift;
                   6786:     my $prefix;
1.620     albertel 6787:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   6788: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      6789:     } else {
                   6790: 	$prefix=$perlvar{'lonHostID'};
                   6791:     }
                   6792:     return unpack("%32C*",$prefix);
                   6793: }
                   6794: 
1.76      www      6795: sub ireceipt {
1.474     albertel 6796:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.76      www      6797:     my $cuname=unpack("%32C*",$funame);
                   6798:     my $cudom=unpack("%32C*",$fudom);
                   6799:     my $cucourseid=unpack("%32C*",$fucourseid);
                   6800:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      6801:     my $cunique=&recunique($fucourseid);
1.474     albertel 6802:     my $cpart=unpack("%32S*",$part);
1.480     www      6803:     my $return =&recprefix($fucourseid).'-';
1.620     albertel 6804:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   6805: 	$env{'request.state'} eq 'construct') {
1.474     albertel 6806: 	&Apache::lonxml::debug("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname).
                   6807: 			       " and ".($cpart%$cudom));
                   6808: 			       
                   6809: 	$return.= ($cunique%$cuname+
                   6810: 		   $cunique%$cudom+
                   6811: 		   $cusymb%$cuname+
                   6812: 		   $cusymb%$cudom+
                   6813: 		   $cucourseid%$cuname+
                   6814: 		   $cucourseid%$cudom+
                   6815: 		   $cpart%$cuname+
                   6816: 		   $cpart%$cudom);
                   6817:     } else {
                   6818: 	$return.= ($cunique%$cuname+
                   6819: 		   $cunique%$cudom+
                   6820: 		   $cusymb%$cuname+
                   6821: 		   $cusymb%$cudom+
                   6822: 		   $cucourseid%$cuname+
                   6823: 		   $cucourseid%$cudom);
                   6824:     }
                   6825:     return $return;
1.76      www      6826: }
                   6827: 
                   6828: sub receipt {
1.474     albertel 6829:     my ($part)=@_;
                   6830:     my ($symb,$courseid,$domain,$name) = &Apache::lonxml::whichuser();
                   6831:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      6832: }
1.260     ng       6833: 
1.36      albertel 6834: # ------------------------------------------------------------ Serves up a file
1.472     albertel 6835: # returns either the contents of the file or 
                   6836: # -1 if the file doesn't exist
1.481     raeburn  6837: #
                   6838: # if the target is a file that was uploaded via DOCS, 
                   6839: # a check will be made to see if a current copy exists on the local server,
                   6840: # if it does this will be served, otherwise a copy will be retrieved from
                   6841: # the home server for the course and stored in /home/httpd/html/userfiles on
                   6842: # the local server.   
1.472     albertel 6843: 
1.36      albertel 6844: sub getfile {
1.538     albertel 6845:     my ($file) = @_;
1.609     banghart 6846:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 6847:     &repcopy($file);
                   6848:     return &readfile($file);
                   6849: }
                   6850: 
                   6851: sub repcopy_userfile {
                   6852:     my ($file)=@_;
1.609     banghart 6853:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 6854:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 6855:     my ($cdom,$cnum,$filename) = 
                   6856: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+([^/]+)/+([^/]+)/+(.*)|);
                   6857:     my ($info,$rtncode);
                   6858:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   6859:     if (-e "$file") {
                   6860: 	my @fileinfo = stat($file);
                   6861: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 6862: 	if ($lwpresp ne 'ok') {
                   6863: 	    if ($rtncode eq '404') {
1.538     albertel 6864: 		unlink($file);
1.482     albertel 6865: 	    }
1.517     albertel 6866: 	    #my $ua=new LWP::UserAgent;
1.538     albertel 6867: 	    #my $request=new HTTP::Request('GET',&tokenwrapper($uri));
1.517     albertel 6868: 	    #my $response=$ua->request($request);
                   6869: 	    #if ($response->is_success()) {
                   6870: 	#	return $response->content;
                   6871: 	#    } else {
                   6872: 	#	return -1;
                   6873: 	#    }
1.482     albertel 6874: 	    return -1;
                   6875: 	}
                   6876: 	if ($info < $fileinfo[9]) {
1.607     raeburn  6877: 	    return 'ok';
1.482     albertel 6878: 	}
                   6879: 	$info = '';
1.538     albertel 6880: 	$lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 6881: 	if ($lwpresp ne 'ok') {
                   6882: 	    return -1;
                   6883: 	}
                   6884:     } else {
1.538     albertel 6885: 	my $lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 6886: 	if ($lwpresp ne 'ok') {
1.517     albertel 6887: 	    my $ua=new LWP::UserAgent;
1.538     albertel 6888: 	    my $request=new HTTP::Request('GET',&tokenwrapper($uri));
1.517     albertel 6889: 	    my $response=$ua->request($request);
                   6890: 	    if ($response->is_success()) {
1.538     albertel 6891: 		$info=$response->content;
1.517     albertel 6892: 	    } else {
                   6893: 		return -1;
                   6894: 	    }
1.482     albertel 6895: 	}
                   6896: 	my @parts = ($cdom,$cnum); 
                   6897: 	if ($filename =~ m|^(.+)/[^/]+$|) {
                   6898: 	    push @parts, split(/\//,$1);
1.518     albertel 6899: 	}
1.538     albertel 6900: 	my $path = $perlvar{'lonDocRoot'}.'/userfiles';
1.482     albertel 6901: 	foreach my $part (@parts) {
                   6902: 	    $path .= '/'.$part;
                   6903: 	    if (!-e $path) {
                   6904: 		mkdir($path,0770);
                   6905: 	    }
                   6906: 	}
                   6907:     }
1.538     albertel 6908:     open(FILE,">$file");
1.482     albertel 6909:     print FILE $info;
                   6910:     close(FILE);
1.607     raeburn  6911:     return 'ok';
1.481     raeburn  6912: }
                   6913: 
1.517     albertel 6914: sub tokenwrapper {
                   6915:     my $uri=shift;
1.552     albertel 6916:     $uri=~s|^http\://([^/]+)||;
                   6917:     $uri=~s|^/||;
1.620     albertel 6918:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 6919:     my $token=$1;
1.552     albertel 6920:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   6921:     if ($udom && $uname && $file) {
                   6922: 	$file=~s|(\?\.*)*$||;
1.620     albertel 6923:         &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
1.552     albertel 6924:         return 'http://'.$hostname{ &homeserver($uname,$udom)}.'/'.$uri.
1.517     albertel 6925:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   6926:                                '&tokenissued='.$perlvar{'lonHostID'};
                   6927:     } else {
                   6928:         return '/adm/notfound.html';
                   6929:     }
                   6930: }
                   6931: 
1.481     raeburn  6932: sub getuploaded {
                   6933:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   6934:     $uri=~s/^\///;
                   6935:     $uri = 'http://'.$hostname{ &homeserver($cnum,$cdom)}.'/raw/'.$uri;
                   6936:     my $ua=new LWP::UserAgent;
                   6937:     my $request=new HTTP::Request($reqtype,$uri);
                   6938:     my $response=$ua->request($request);
                   6939:     $$rtncode = $response->code;
1.482     albertel 6940:     if (! $response->is_success()) {
                   6941: 	return 'failed';
                   6942:     }      
                   6943:     if ($reqtype eq 'HEAD') {
1.486     www      6944: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 6945:     } elsif ($reqtype eq 'GET') {
                   6946: 	$$info = $response->content;
1.472     albertel 6947:     }
1.482     albertel 6948:     return 'ok';
1.36      albertel 6949: }
                   6950: 
1.481     raeburn  6951: sub readfile {
                   6952:     my $file = shift;
                   6953:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   6954:     my $fh;
                   6955:     open($fh,"<$file");
                   6956:     my $a='';
                   6957:     while (<$fh>) { $a .=$_; }
                   6958:     return $a;
                   6959: }
                   6960: 
1.36      albertel 6961: sub filelocation {
1.590     banghart 6962:     my ($dir,$file) = @_;
                   6963:     my $location;
                   6964:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 6965: 
                   6966:     if ($file =~ m-^/adm/-) {
                   6967: 	$file=~s-^/adm/wrapper/-/-;
                   6968: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   6969:     }
1.590     banghart 6970:     if ($file=~m:^/~:) { # is a contruction space reference
                   6971:         $location = $file;
                   6972:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.649     albertel 6973:     } elsif ($file=~m:^/home/[^/]*/public_html/:) {
                   6974: 	# is a correct contruction space reference
                   6975:         $location = $file;
1.609     banghart 6976:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 6977:         my ($udom,$uname,$filename)=
1.609     banghart 6978:   	    ($file=~m -^/+(?:uploaded|editupload)/+([^/]+)/+([^/]+)/+(.*)$-);
1.590     banghart 6979:         my $home=&homeserver($uname,$udom);
                   6980:         my $is_me=0;
                   6981:         my @ids=&current_machine_ids();
                   6982:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   6983:         if ($is_me) {
1.740     www      6984:   	    $location=&propath($udom,$uname).
1.590     banghart 6985:   	      '/userfiles/'.$filename;
                   6986:         } else {
                   6987:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   6988:   	      $udom.'/'.$uname.'/'.$filename;
                   6989:         }
                   6990:     } else {
                   6991:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   6992:         $file=~s:^/res/:/:;
                   6993:         if ( !( $file =~ m:^/:) ) {
                   6994:             $location = $dir. '/'.$file;
                   6995:         } else {
                   6996:             $location = '/home/httpd/html/res'.$file;
                   6997:         }
1.59      albertel 6998:     }
1.590     banghart 6999:     $location=~s://+:/:g; # remove duplicate /
                   7000:     while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
                   7001:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   7002:     return $location;
1.46      www      7003: }
1.36      albertel 7004: 
1.46      www      7005: sub hreflocation {
                   7006:     my ($dir,$file)=@_;
1.460     albertel 7007:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
1.666     albertel 7008: 	$file=filelocation($dir,$file);
1.700     albertel 7009:     } elsif ($file=~m-^/adm/-) {
                   7010: 	$file=~s-^/adm/wrapper/-/-;
                   7011: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 7012:     }
                   7013:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   7014: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   7015:     } elsif ($file=~m-/home/(\w+)/public_html/-) {
1.462     albertel 7016: 	$file=~s-^/home/(\w+)/public_html/-/~$1/-;
1.666     albertel 7017:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
                   7018: 	$file=~s-^/home/httpd/lonUsers/([^/]*)/./././([^/]*)/userfiles/
                   7019: 	    -/uploaded/$1/$2/-x;
1.46      www      7020:     }
1.462     albertel 7021:     return $file;
1.465     albertel 7022: }
                   7023: 
                   7024: sub current_machine_domains {
                   7025:     my $hostname=$hostname{$perlvar{'lonHostID'}};
                   7026:     my @domains;
                   7027:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  7028: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 7029: 	if ($hostname eq $name) {
                   7030: 	    push(@domains,$hostdom{$id});
                   7031: 	}
                   7032:     }
                   7033:     return @domains;
                   7034: }
                   7035: 
                   7036: sub current_machine_ids {
                   7037:     my $hostname=$hostname{$perlvar{'lonHostID'}};
                   7038:     my @ids;
                   7039:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  7040: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 7041: 	if ($hostname eq $name) {
                   7042: 	    push(@ids,$id);
                   7043: 	}
                   7044:     }
                   7045:     return @ids;
1.31      www      7046: }
                   7047: 
                   7048: # ------------------------------------------------------------- Declutters URLs
                   7049: 
                   7050: sub declutter {
                   7051:     my $thisfn=shift;
1.569     albertel 7052:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 7053:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      7054:     $thisfn=~s/^\///;
1.697     albertel 7055:     $thisfn=~s|^adm/wrapper/||;
                   7056:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      7057:     $thisfn=~s/^res\///;
1.235     www      7058:     $thisfn=~s/\?.+$//;
1.268     www      7059:     return $thisfn;
                   7060: }
                   7061: 
                   7062: # ------------------------------------------------------------- Clutter up URLs
                   7063: 
                   7064: sub clutter {
                   7065:     my $thisfn='/'.&declutter(shift);
1.609     banghart 7066:     unless ($thisfn=~/^\/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)\//) { 
1.270     www      7067:        $thisfn='/res'.$thisfn; 
                   7068:     }
1.694     albertel 7069:     if ($thisfn !~m|/adm|) {
1.695     albertel 7070: 	if ($thisfn =~ m|/ext/|) {
1.694     albertel 7071: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 7072: 	} else {
                   7073: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   7074: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 7075: 	    if ($embstyle eq 'ssi'
                   7076: 		|| ($embstyle eq 'hdn')
                   7077: 		|| ($embstyle eq 'rat')
                   7078: 		|| ($embstyle eq 'prv')
                   7079: 		|| ($embstyle eq 'ign')) {
                   7080: 		#do nothing with these
                   7081: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 7082: 		|| ($embstyle eq 'emb')
                   7083: 		|| ($embstyle eq 'wrp')) {
                   7084: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 7085: 	    } elsif ($embstyle eq 'unk'
                   7086: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 7087: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 7088: 	    } else {
1.718     www      7089: #		&logthis("Got a blank emb style");
1.695     albertel 7090: 	    }
1.694     albertel 7091: 	}
                   7092:     }
1.31      www      7093:     return $thisfn;
1.12      www      7094: }
                   7095: 
1.557     albertel 7096: sub freeze_escape {
                   7097:     my ($value)=@_;
                   7098:     if (ref($value)) {
                   7099: 	$value=&nfreeze($value);
                   7100: 	return '__FROZEN__'.&escape($value);
                   7101:     }
                   7102:     return &escape($value);
                   7103: }
                   7104: 
1.11      www      7105: 
1.557     albertel 7106: sub thaw_unescape {
                   7107:     my ($value)=@_;
                   7108:     if ($value =~ /^__FROZEN__/) {
                   7109: 	substr($value,0,10,undef);
                   7110: 	$value=&unescape($value);
                   7111: 	return &thaw($value);
                   7112:     }
                   7113:     return &unescape($value);
                   7114: }
                   7115: 
1.436     albertel 7116: sub correct_line_ends {
                   7117:     my ($result)=@_;
                   7118:     $$result =~s/\r\n/\n/mg;
                   7119:     $$result =~s/\r/\n/mg;
1.415     albertel 7120: }
1.1       albertel 7121: # ================================================================ Main Program
                   7122: 
1.184     www      7123: sub goodbye {
1.204     albertel 7124:    &logthis("Starting Shut down");
1.443     albertel 7125: #not converted to using infrastruture and probably shouldn't be
1.599     albertel 7126:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&freeze(\%badServerCache))));
1.443     albertel 7127: #converted
1.599     albertel 7128: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
                   7129:    &logthis(sprintf("%-20s is %s",'%homecache',length(&freeze(\%homecache))));
                   7130: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&freeze(\%titlecache))));
                   7131: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&freeze(\%courseresdatacache))));
1.425     albertel 7132: #1.1 only
1.599     albertel 7133: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&freeze(\%userresdatacache))));
                   7134: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&freeze(\%getsectioncache))));
                   7135: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&freeze(\%courseresversioncache))));
                   7136: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&freeze(\%resversioncache))));
                   7137:    &logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
                   7138:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   7139:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      7140:    &flushcourselogs();
                   7141:    &logthis("Shutting down");
                   7142: }
                   7143: 
1.179     www      7144: BEGIN {
1.228     harris41 7145: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
1.195     www      7146:     unless ($readit) {
1.217     harris41 7147: {
1.781     raeburn  7148:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   7149:     %perlvar = (%perlvar,%{$configvars});
1.227     harris41 7150: }
1.1       albertel 7151: 
1.327     albertel 7152: # ------------------------------------------------------------ Read domain file
                   7153: {
                   7154:     %domaindescription = ();
                   7155:     %domain_auth_def = ();
                   7156:     %domain_auth_arg_def = ();
1.448     albertel 7157:     my $fh;
                   7158:     if (open($fh,"<".$Apache::lonnet::perlvar{'lonTabDir'}.'/domain.tab')) {
1.327     albertel 7159:        while (<$fh>) {
1.390     matthew  7160:            next if (/^(\#|\s*$)/);
                   7161: #           next if /^\#/;
1.327     albertel 7162:            chomp;
1.403     www      7163:            my ($domain, $domain_description, $def_auth, $def_auth_arg,
1.685     raeburn  7164: 	       $def_lang, $city, $longi, $lati, $primary) = split(/:/,$_);
1.403     www      7165: 	   $domain_auth_def{$domain}=$def_auth;
1.327     albertel 7166:            $domain_auth_arg_def{$domain}=$def_auth_arg;
1.403     www      7167: 	   $domaindescription{$domain}=$domain_description;
                   7168: 	   $domain_lang_def{$domain}=$def_lang;
                   7169: 	   $domain_city{$domain}=$city;
                   7170: 	   $domain_longi{$domain}=$longi;
                   7171: 	   $domain_lati{$domain}=$lati;
1.685     raeburn  7172:            $domain_primary{$domain}=$primary;
1.403     www      7173: 
1.448     albertel 7174:  #         &logthis("Domain.tab: $domain, $domain_auth_def{$domain}, $domain_auth_arg_def{$domain},$domaindescription{$domain}");
1.327     albertel 7175: #          &logthis("Domain.tab: $domain ".$domaindescription{$domain} );
1.448     albertel 7176: 	}
1.327     albertel 7177:     }
1.448     albertel 7178:     close ($fh);
1.327     albertel 7179: }
                   7180: 
                   7181: 
1.1       albertel 7182: # ------------------------------------------------------------- Read hosts file
                   7183: {
1.448     albertel 7184:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
1.1       albertel 7185: 
                   7186:     while (my $configline=<$config>) {
1.303     matthew  7187:        next if ($configline =~ /^(\#|\s*$)/);
1.154     www      7188:        chomp($configline);
1.595     albertel 7189:        my ($id,$domain,$role,$name)=split(/:/,$configline);
1.597     albertel 7190:        $name=~s/\s//g;
1.595     albertel 7191:        if ($id && $domain && $role && $name) {
1.252     albertel 7192: 	 $hostname{$id}=$name;
                   7193: 	 $hostdom{$id}=$domain;
                   7194: 	 if ($role eq 'library') { $libserv{$id}=$name; }
1.245     www      7195:        }
1.1       albertel 7196:     }
1.448     albertel 7197:     close($config);
1.619     albertel 7198:     # FIXME: dev server don't want this, production servers _do_ want this
1.654     albertel 7199:     #&get_iphost();
1.1       albertel 7200: }
                   7201: 
1.598     albertel 7202: sub get_iphost {
                   7203:     if (%iphost) { return %iphost; }
1.653     albertel 7204:     my %name_to_ip;
1.598     albertel 7205:     foreach my $id (keys(%hostname)) {
                   7206: 	my $name=$hostname{$id};
1.653     albertel 7207: 	my $ip;
                   7208: 	if (!exists($name_to_ip{$name})) {
                   7209: 	    $ip = gethostbyname($name);
                   7210: 	    if (!$ip || length($ip) ne 4) {
                   7211: 		&logthis("Skipping host $id name $name no IP found\n");
                   7212: 		next;
                   7213: 	    }
                   7214: 	    $ip=inet_ntoa($ip);
                   7215: 	    $name_to_ip{$name} = $ip;
                   7216: 	} else {
                   7217: 	    $ip = $name_to_ip{$name};
1.598     albertel 7218: 	}
                   7219: 	push(@{$iphost{$ip}},$id);
                   7220:     }
                   7221:     return %iphost;
                   7222: }
                   7223: 
1.1       albertel 7224: # ------------------------------------------------------ Read spare server file
                   7225: {
1.448     albertel 7226:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 7227: 
                   7228:     while (my $configline=<$config>) {
                   7229:        chomp($configline);
1.284     matthew  7230:        if ($configline) {
1.782.2.1  albertel 7231: 	   my ($host,$type) = split(':',$configline,2);
1.782.2.2  albertel 7232: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.782.2.1  albertel 7233: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 7234:        }
                   7235:     }
1.448     albertel 7236:     close($config);
1.1       albertel 7237: }
1.11      www      7238: # ------------------------------------------------------------ Read permissions
                   7239: {
1.448     albertel 7240:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      7241: 
                   7242:     while (my $configline=<$config>) {
1.448     albertel 7243: 	chomp($configline);
                   7244: 	if ($configline) {
                   7245: 	    my ($role,$perm)=split(/ /,$configline);
                   7246: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   7247: 	}
1.11      www      7248:     }
1.448     albertel 7249:     close($config);
1.11      www      7250: }
                   7251: 
                   7252: # -------------------------------------------- Read plain texts for permissions
                   7253: {
1.448     albertel 7254:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      7255: 
                   7256:     while (my $configline=<$config>) {
1.448     albertel 7257: 	chomp($configline);
                   7258: 	if ($configline) {
1.742     raeburn  7259: 	    my ($short,@plain)=split(/:/,$configline);
                   7260:             %{$prp{$short}} = ();
                   7261: 	    if (@plain > 0) {
                   7262:                 $prp{$short}{'std'} = $plain[0];
                   7263:                 for (my $i=1; $i<@plain; $i++) {
                   7264:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   7265:                 }
                   7266:             }
1.448     albertel 7267: 	}
1.135     www      7268:     }
1.448     albertel 7269:     close($config);
1.135     www      7270: }
                   7271: 
                   7272: # ---------------------------------------------------------- Read package table
                   7273: {
1.448     albertel 7274:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      7275: 
                   7276:     while (my $configline=<$config>) {
1.483     albertel 7277: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 7278: 	chomp($configline);
                   7279: 	my ($short,$plain)=split(/:/,$configline);
                   7280: 	my ($pack,$name)=split(/\&/,$short);
                   7281: 	if ($plain ne '') {
                   7282: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   7283: 	    $packagetab{$short}=$plain; 
                   7284: 	}
1.11      www      7285:     }
1.448     albertel 7286:     close($config);
1.329     matthew  7287: }
                   7288: 
                   7289: # ------------- set up temporary directory
                   7290: {
                   7291:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   7292: 
1.11      www      7293: }
                   7294: 
1.782.2.4! albertel 7295: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
        !          7296: 				'compress_threshold'=> 20_000,
        !          7297:  			        });
1.185     www      7298: 
1.281     www      7299: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      7300: $dumpcount=0;
1.22      www      7301: 
1.163     harris41 7302: &logtouch();
1.672     albertel 7303: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      7304: $readit=1;
1.564     albertel 7305:     {
                   7306: 	use integer;
                   7307: 	my $test=(2**32)+1;
1.568     albertel 7308: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 7309: 	&logthis(" Detected 64bit platform ($_64bit)");
                   7310:     }
1.195     www      7311: }
1.1       albertel 7312: }
1.179     www      7313: 
1.1       albertel 7314: 1;
1.191     harris41 7315: __END__
                   7316: 
1.243     albertel 7317: =pod
                   7318: 
1.191     harris41 7319: =head1 NAME
                   7320: 
1.243     albertel 7321: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 7322: 
                   7323: =head1 SYNOPSIS
                   7324: 
1.243     albertel 7325: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 7326: 
                   7327:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   7328: 
1.243     albertel 7329: Common parameters:
                   7330: 
                   7331: =over 4
                   7332: 
                   7333: =item *
                   7334: 
                   7335: $uname : an internal username (if $cname expecting a course Id specifically)
                   7336: 
                   7337: =item *
                   7338: 
                   7339: $udom : a domain (if $cdom expecting a course's domain specifically)
                   7340: 
                   7341: =item *
                   7342: 
                   7343: $symb : a resource instance identifier
                   7344: 
                   7345: =item *
                   7346: 
                   7347: $namespace : the name of a .db file that contains the data needed or
                   7348: being set.
                   7349: 
                   7350: =back
                   7351: 
1.394     bowersj2 7352: =head1 OVERVIEW
1.191     harris41 7353: 
1.394     bowersj2 7354: lonnet provides subroutines which interact with the
                   7355: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   7356: about classes, users, and resources.
1.243     albertel 7357: 
                   7358: For many of these objects you can also use this to store data about
                   7359: them or modify them in various ways.
1.191     harris41 7360: 
1.394     bowersj2 7361: =head2 Symbs
1.191     harris41 7362: 
1.394     bowersj2 7363: To identify a specific instance of a resource, LON-CAPA uses symbols
                   7364: or "symbs"X<symb>. These identifiers are built from the URL of the
                   7365: map, the resource number of the resource in the map, and the URL of
                   7366: the resource itself. The latter is somewhat redundant, but might help
                   7367: if maps change.
                   7368: 
                   7369: An example is
                   7370: 
                   7371:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   7372: 
                   7373: The respective map entry is
                   7374: 
                   7375:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   7376:   title="Problem 2">
                   7377:  </resource>
                   7378: 
                   7379: Symbs are used by the random number generator, as well as to store and
                   7380: restore data specific to a certain instance of for example a problem.
                   7381: 
                   7382: =head2 Storing And Retrieving Data
                   7383: 
                   7384: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   7385: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   7386: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   7387: is is the non-critical message twin of cstore. These functions are for
                   7388: handlers to store a perl hash to a user's permanent data space in an
                   7389: easy manner, and to retrieve it again on another call. It is expected
                   7390: that a handler would use this once at the beginning to retrieve data,
                   7391: and then again once at the end to send only the new data back.
                   7392: 
                   7393: The data is stored in the user's data directory on the user's
                   7394: homeserver under the ID of the course.
                   7395: 
                   7396: The hash that is returned by restore will have all of the previous
                   7397: value for all of the elements of the hash.
                   7398: 
                   7399: Example:
                   7400: 
                   7401:  #creating a hash
                   7402:  my %hash;
                   7403:  $hash{'foo'}='bar';
                   7404: 
                   7405:  #storing it
                   7406:  &Apache::lonnet::cstore(\%hash);
                   7407: 
                   7408:  #changing a value
                   7409:  $hash{'foo'}='notbar';
                   7410: 
                   7411:  #adding a new value
                   7412:  $hash{'bar'}='foo';
                   7413:  &Apache::lonnet::cstore(\%hash);
                   7414: 
                   7415:  #retrieving the hash
                   7416:  my %history=&Apache::lonnet::restore();
                   7417: 
                   7418:  #print the hash
                   7419:  foreach my $key (sort(keys(%history))) {
                   7420:    print("\%history{$key} = $history{$key}");
                   7421:  }
                   7422: 
                   7423: Will print out:
1.191     harris41 7424: 
1.394     bowersj2 7425:  %history{1:foo} = bar
                   7426:  %history{1:keys} = foo:timestamp
                   7427:  %history{1:timestamp} = 990455579
                   7428:  %history{2:bar} = foo
                   7429:  %history{2:foo} = notbar
                   7430:  %history{2:keys} = foo:bar:timestamp
                   7431:  %history{2:timestamp} = 990455580
                   7432:  %history{bar} = foo
                   7433:  %history{foo} = notbar
                   7434:  %history{timestamp} = 990455580
                   7435:  %history{version} = 2
                   7436: 
                   7437: Note that the special hash entries C<keys>, C<version> and
                   7438: C<timestamp> were added to the hash. C<version> will be equal to the
                   7439: total number of versions of the data that have been stored. The
                   7440: C<timestamp> attribute will be the UNIX time the hash was
                   7441: stored. C<keys> is available in every historical section to list which
                   7442: keys were added or changed at a specific historical revision of a
                   7443: hash.
                   7444: 
                   7445: B<Warning>: do not store the hash that restore returns directly. This
                   7446: will cause a mess since it will restore the historical keys as if the
                   7447: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 7448: 
1.394     bowersj2 7449: Calling convention:
1.191     harris41 7450: 
1.394     bowersj2 7451:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   7452:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 7453: 
1.394     bowersj2 7454: For more detailed information, see lonnet specific documentation.
1.191     harris41 7455: 
1.394     bowersj2 7456: =head1 RETURN MESSAGES
1.191     harris41 7457: 
1.394     bowersj2 7458: =over 4
1.191     harris41 7459: 
1.394     bowersj2 7460: =item * B<con_lost>: unable to contact remote host
1.191     harris41 7461: 
1.394     bowersj2 7462: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   7463: when the connection is brought back up
1.191     harris41 7464: 
1.394     bowersj2 7465: =item * B<con_failed>: unable to contact remote host and unable to save message
                   7466: for later delivery
1.191     harris41 7467: 
1.394     bowersj2 7468: =item * B<error:>: an error a occured, a description of the error follows the :
1.191     harris41 7469: 
1.394     bowersj2 7470: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 7471: that was requested
1.191     harris41 7472: 
1.243     albertel 7473: =back
1.191     harris41 7474: 
1.243     albertel 7475: =head1 PUBLIC SUBROUTINES
1.191     harris41 7476: 
1.243     albertel 7477: =head2 Session Environment Functions
1.191     harris41 7478: 
1.243     albertel 7479: =over 4
1.191     harris41 7480: 
1.394     bowersj2 7481: =item * 
                   7482: X<appenv()>
                   7483: B<appenv(%hash)>: the value of %hash is written to
                   7484: the user envirnoment file, and will be restored for each access this
1.620     albertel 7485: user makes during this session, also modifies the %env for the current
1.394     bowersj2 7486: process
1.191     harris41 7487: 
                   7488: =item *
1.394     bowersj2 7489: X<delenv()>
                   7490: B<delenv($regexp)>: removes all items from the session
                   7491: environment file that matches the regular expression in $regexp. The
1.620     albertel 7492: values are also delted from the current processes %env.
1.191     harris41 7493: 
1.243     albertel 7494: =back
                   7495: 
                   7496: =head2 User Information
1.191     harris41 7497: 
1.243     albertel 7498: =over 4
1.191     harris41 7499: 
                   7500: =item *
1.394     bowersj2 7501: X<queryauthenticate()>
                   7502: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 7503: authentication scheme
                   7504: 
                   7505: =item *
1.394     bowersj2 7506: X<authenticate()>
                   7507: B<authenticate($uname,$upass,$udom)>: try to
                   7508: authenticate user from domain's lib servers (first use the current
                   7509: one). C<$upass> should be the users password.
1.191     harris41 7510: 
                   7511: =item *
1.394     bowersj2 7512: X<homeserver()>
                   7513: B<homeserver($uname,$udom)>: find the server which has
                   7514: the user's directory and files (there must be only one), this caches
                   7515: the answer, and also caches if there is a borken connection.
1.191     harris41 7516: 
                   7517: =item *
1.394     bowersj2 7518: X<idget()>
                   7519: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   7520: (IDs are a unique resource in a domain, there must be only 1 ID per
                   7521: username, and only 1 username per ID in a specific domain) (returns
                   7522: hash: id=>name,id=>name)
1.191     harris41 7523: 
                   7524: =item *
1.394     bowersj2 7525: X<idrget()>
                   7526: B<idrget($udom,@unames)>: find the IDs behind a list of
                   7527: usernames (returns hash: name=>id,name=>id)
1.191     harris41 7528: 
                   7529: =item *
1.394     bowersj2 7530: X<idput()>
                   7531: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 7532: 
                   7533: =item *
1.394     bowersj2 7534: X<rolesinit()>
                   7535: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 7536: 
                   7537: =item *
1.551     albertel 7538: X<getsection()>
                   7539: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 7540: course $cname, return section name/number or '' for "not in course"
                   7541: and '-1' for "no section"
                   7542: 
                   7543: =item *
1.394     bowersj2 7544: X<userenvironment()>
                   7545: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 7546: passed in @what from the requested user's environment, returns a hash
                   7547: 
                   7548: =back
                   7549: 
                   7550: =head2 User Roles
                   7551: 
                   7552: =over 4
                   7553: 
                   7554: =item *
                   7555: 
                   7556: allowed($priv,$uri) : check for a user privilege; returns codes for allowed
                   7557: actions
                   7558:  F: full access
                   7559:  U,I,K: authentication modes (cxx only)
                   7560:  '': forbidden
                   7561:  1: user needs to choose course
                   7562:  2: browse allowed
1.766     albertel 7563:  A: passphrase authentication needed
1.243     albertel 7564: 
                   7565: =item *
                   7566: 
                   7567: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   7568: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   7569: and course level
                   7570: 
                   7571: =item *
                   7572: 
                   7573: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
                   7574: explanation of a user role term
                   7575: 
                   7576: =back
                   7577: 
                   7578: =head2 User Modification
                   7579: 
                   7580: =over 4
                   7581: 
                   7582: =item *
                   7583: 
                   7584: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
                   7585: user for the level given by URL.  Optional start and end dates (leave empty
                   7586: string or zero for "no date")
1.191     harris41 7587: 
                   7588: =item *
                   7589: 
1.243     albertel 7590: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   7591: change a users, password, possible return values are: ok,
                   7592: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   7593: refused
1.191     harris41 7594: 
                   7595: =item *
                   7596: 
1.243     albertel 7597: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 7598: 
                   7599: =item *
                   7600: 
1.243     albertel 7601: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
                   7602: modify user
1.191     harris41 7603: 
                   7604: =item *
                   7605: 
1.286     matthew  7606: modifystudent
                   7607: 
                   7608: modify a students enrollment and identification information.
                   7609: The course id is resolved based on the current users environment.  
                   7610: This means the envoking user must be a course coordinator or otherwise
                   7611: associated with a course.
                   7612: 
1.297     matthew  7613: This call is essentially a wrapper for lonnet::modifyuser and
                   7614: lonnet::modify_student_enrollment
1.286     matthew  7615: 
                   7616: Inputs: 
                   7617: 
                   7618: =over 4
                   7619: 
                   7620: =item B<$udom> Students loncapa domain
                   7621: 
                   7622: =item B<$uname> Students loncapa login name
                   7623: 
                   7624: =item B<$uid> Students id/student number
                   7625: 
                   7626: =item B<$umode> Students authentication mode
                   7627: 
                   7628: =item B<$upass> Students password
                   7629: 
                   7630: =item B<$first> Students first name
                   7631: 
                   7632: =item B<$middle> Students middle name
                   7633: 
                   7634: =item B<$last> Students last name
                   7635: 
                   7636: =item B<$gene> Students generation
                   7637: 
                   7638: =item B<$usec> Students section in course
                   7639: 
                   7640: =item B<$end> Unix time of the roles expiration
                   7641: 
                   7642: =item B<$start> Unix time of the roles start date
                   7643: 
                   7644: =item B<$forceid> If defined, allow $uid to be changed
                   7645: 
                   7646: =item B<$desiredhome> server to use as home server for student
                   7647: 
                   7648: =back
1.297     matthew  7649: 
                   7650: =item *
                   7651: 
                   7652: modify_student_enrollment
                   7653: 
                   7654: Change a students enrollment status in a class.  The environment variable
                   7655: 'role.request.course' must be defined for this function to proceed.
                   7656: 
                   7657: Inputs:
                   7658: 
                   7659: =over 4
                   7660: 
                   7661: =item $udom, students domain
                   7662: 
                   7663: =item $uname, students name
                   7664: 
                   7665: =item $uid, students user id
                   7666: 
                   7667: =item $first, students first name
                   7668: 
                   7669: =item $middle
                   7670: 
                   7671: =item $last
                   7672: 
                   7673: =item $gene
                   7674: 
                   7675: =item $usec
                   7676: 
                   7677: =item $end
                   7678: 
                   7679: =item $start
                   7680: 
                   7681: =back
                   7682: 
1.191     harris41 7683: 
                   7684: =item *
                   7685: 
1.243     albertel 7686: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   7687: custom role; give a custom role to a user for the level given by URL.  Specify
                   7688: name and domain of role author, and role name
1.191     harris41 7689: 
                   7690: =item *
                   7691: 
1.243     albertel 7692: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 7693: 
                   7694: =item *
                   7695: 
1.243     albertel 7696: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   7697: 
                   7698: =back
                   7699: 
                   7700: =head2 Course Infomation
                   7701: 
                   7702: =over 4
1.191     harris41 7703: 
                   7704: =item *
                   7705: 
1.631     albertel 7706: coursedescription($courseid) : returns a hash of information about the
                   7707: specified course id, including all environment settings for the
                   7708: course, the description of the course will be in the hash under the
                   7709: key 'description'
1.191     harris41 7710: 
                   7711: =item *
                   7712: 
1.624     albertel 7713: resdata($name,$domain,$type,@which) : request for current parameter
                   7714: setting for a specific $type, where $type is either 'course' or 'user',
                   7715: @what should be a list of parameters to ask about. This routine caches
                   7716: answers for 5 minutes.
1.243     albertel 7717: 
                   7718: =back
                   7719: 
                   7720: =head2 Course Modification
                   7721: 
                   7722: =over 4
1.191     harris41 7723: 
                   7724: =item *
                   7725: 
1.243     albertel 7726: writecoursepref($courseid,%prefs) : write preferences (environment
                   7727: database) for a course
1.191     harris41 7728: 
                   7729: =item *
                   7730: 
1.243     albertel 7731: createcourse($udom,$description,$url) : make/modify course
                   7732: 
                   7733: =back
                   7734: 
                   7735: =head2 Resource Subroutines
                   7736: 
                   7737: =over 4
1.191     harris41 7738: 
                   7739: =item *
                   7740: 
1.243     albertel 7741: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 7742: 
                   7743: =item *
                   7744: 
1.243     albertel 7745: repcopy($filename) : subscribes to the requested file, and attempts to
                   7746: replicate from the owning library server, Might return
1.607     raeburn  7747: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   7748: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 7749: resource. Expects the local filesystem pathname
                   7750: (/home/httpd/html/res/....)
                   7751: 
                   7752: =back
                   7753: 
                   7754: =head2 Resource Information
                   7755: 
                   7756: =over 4
1.191     harris41 7757: 
                   7758: =item *
                   7759: 
1.243     albertel 7760: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   7761: a vairety of different possible values, $varname should be a request
                   7762: string, and the other parameters can be used to specify who and what
                   7763: one is asking about.
                   7764: 
                   7765: Possible values for $varname are environment.lastname (or other item
                   7766: from the envirnment hash), user.name (or someother aspect about the
                   7767: user), resource.0.maxtries (or some other part and parameter of a
                   7768: resource)
1.204     albertel 7769: 
                   7770: =item *
                   7771: 
1.243     albertel 7772: directcondval($number) : get current value of a condition; reads from a state
                   7773: string
1.204     albertel 7774: 
                   7775: =item *
                   7776: 
1.243     albertel 7777: condval($condidx) : value of condition index based on state
1.204     albertel 7778: 
                   7779: =item *
                   7780: 
1.243     albertel 7781: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   7782: resource's metadata, $what should be either a specific key, or either
                   7783: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   7784: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   7785: 
                   7786: this function automatically caches all requests
1.191     harris41 7787: 
                   7788: =item *
                   7789: 
1.243     albertel 7790: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   7791: network of library servers; returns file handle of where SQL and regex results
                   7792: will be stored for query
1.191     harris41 7793: 
                   7794: =item *
                   7795: 
1.243     albertel 7796: symbread($filename) : return symbolic list entry (filename argument optional);
                   7797: returns the data handle
1.191     harris41 7798: 
                   7799: =item *
                   7800: 
1.243     albertel 7801: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 7802: a possible symb for the URL in $thisfn, and if is an encryypted
                   7803: resource that the user accessed using /enc/ returns a 1 on success, 0
                   7804: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 7805: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 7806: 
1.191     harris41 7807: 
                   7808: =item *
                   7809: 
1.243     albertel 7810: symbclean($symb) : removes versions numbers from a symb, returns the
                   7811: cleaned symb
1.191     harris41 7812: 
                   7813: =item *
                   7814: 
1.243     albertel 7815: is_on_map($uri) : checks if the $uri is somewhere on the current
                   7816: course map, user must be in a course for it to work.
1.191     harris41 7817: 
                   7818: =item *
                   7819: 
1.243     albertel 7820: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 7821: 
                   7822: =item *
                   7823: 
1.243     albertel 7824: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   7825: a random seed, all arguments are optional, if they aren't sent it uses the
                   7826: environment to derive them. Note: if symb isn't sent and it can't get one
                   7827: from &symbread it will use the current time as its return value
1.191     harris41 7828: 
                   7829: =item *
                   7830: 
1.243     albertel 7831: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   7832: unfakeable, receipt
1.191     harris41 7833: 
                   7834: =item *
                   7835: 
1.620     albertel 7836: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 7837: 
                   7838: =item *
                   7839: 
1.243     albertel 7840: countacc($url) : count the number of accesses to a given URL
1.191     harris41 7841: 
                   7842: =item *
                   7843: 
1.243     albertel 7844: 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 7845: 
                   7846: =item *
                   7847: 
1.243     albertel 7848: 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 7849: 
                   7850: =item *
                   7851: 
1.243     albertel 7852: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 7853: 
                   7854: =item *
                   7855: 
1.243     albertel 7856: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   7857: forcing spreadsheet to reevaluate the resource scores next time.
                   7858: 
                   7859: =back
                   7860: 
                   7861: =head2 Storing/Retreiving Data
                   7862: 
                   7863: =over 4
1.191     harris41 7864: 
                   7865: =item *
                   7866: 
1.243     albertel 7867: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   7868: for this url; hashref needs to be given and should be a \%hashname; the
                   7869: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 7870: be derived from the env
1.191     harris41 7871: 
                   7872: =item *
                   7873: 
1.243     albertel 7874: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   7875: uses critical subroutine
1.191     harris41 7876: 
                   7877: =item *
                   7878: 
1.243     albertel 7879: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   7880: all args are optional
1.191     harris41 7881: 
                   7882: =item *
                   7883: 
1.717     albertel 7884: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   7885: dumps the complete (or key matching regexp) namespace into a hash
                   7886: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   7887: normally &store()ed into
                   7888: 
                   7889: $range should be either an integer '100' (give me the first 100
                   7890:                                            matching records)
                   7891:               or be  two integers sperated by a - with no spaces
                   7892:                  '30-50' (give me the 30th through the 50th matching
                   7893:                           records)
                   7894: 
                   7895: 
                   7896: =item *
                   7897: 
                   7898: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   7899: replaces a &store() version of data with a replacement set of data
                   7900: for a particular resource in a namespace passed in the $storehash hash 
                   7901: reference
                   7902: 
                   7903: =item *
                   7904: 
1.243     albertel 7905: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   7906: works very similar to store/cstore, but all data is stored in a
                   7907: temporary location and can be reset using tmpreset, $storehash should
                   7908: be a hash reference, returns nothing on success
1.191     harris41 7909: 
                   7910: =item *
                   7911: 
1.243     albertel 7912: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   7913: similar to restore, but all data is stored in a temporary location and
                   7914: can be reset using tmpreset. Returns a hash of values on success,
                   7915: error string otherwise.
1.191     harris41 7916: 
                   7917: =item *
                   7918: 
1.243     albertel 7919: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   7920: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 7921: 
                   7922: =item *
                   7923: 
1.243     albertel 7924: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   7925: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 7926: 
                   7927: =item *
                   7928: 
1.243     albertel 7929: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   7930: namesp ($udom and $uname are optional)
1.191     harris41 7931: 
                   7932: =item *
                   7933: 
1.702     albertel 7934: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 7935: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 7936: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  7937: 
1.702     albertel 7938: $range should be either an integer '100' (give me the first 100
                   7939:                                            matching records)
                   7940:               or be  two integers sperated by a - with no spaces
                   7941:                  '30-50' (give me the 30th through the 50th matching
                   7942:                           records)
1.449     matthew  7943: =item *
                   7944: 
                   7945: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   7946: $store can be a scalar, an array reference, or if the amount to be 
                   7947: incremented is > 1, a hash reference.
                   7948: 
                   7949: ($udom and $uname are optional)
1.191     harris41 7950: 
                   7951: =item *
                   7952: 
1.243     albertel 7953: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   7954: ($udom and $uname are optional)
1.191     harris41 7955: 
                   7956: =item *
                   7957: 
1.243     albertel 7958: cput($namespace,$storehash,$udom,$uname) : critical put
                   7959: ($udom and $uname are optional)
1.191     harris41 7960: 
                   7961: =item *
                   7962: 
1.748     albertel 7963: newput($namespace,$storehash,$udom,$uname) :
                   7964: 
                   7965: Attempts to store the items in the $storehash, but only if they don't
                   7966: currently exist, if this succeeds you can be certain that you have 
                   7967: successfully created a new key value pair in the $namespace db.
                   7968: 
                   7969: 
                   7970: Args:
                   7971:  $namespace: name of database to store values to
                   7972:  $storehash: hashref to store to the db
                   7973:  $udom: (optional) domain of user containing the db
                   7974:  $uname: (optional) name of user caontaining the db
                   7975: 
                   7976: Returns:
                   7977:  'ok' -> succeeded in storing all keys of $storehash
                   7978:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   7979:                         least <key> already existed in the db (other
                   7980:                         requested keys may also already exist)
                   7981:  'error: <msg>' -> unable to tie the DB or other erorr occured
                   7982:  'con_lost' -> unable to contact request server
                   7983:  'refused' -> action was not allowed by remote machine
                   7984: 
                   7985: 
                   7986: =item *
                   7987: 
1.243     albertel 7988: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   7989: reference filled in from namesp (encrypts the return communication)
                   7990: ($udom and $uname are optional)
1.191     harris41 7991: 
                   7992: =item *
                   7993: 
1.243     albertel 7994: log($udom,$name,$home,$message) : write to permanent log for user; use
                   7995: critical subroutine
                   7996: 
                   7997: =back
                   7998: 
                   7999: =head2 Network Status Functions
                   8000: 
                   8001: =over 4
1.191     harris41 8002: 
                   8003: =item *
                   8004: 
                   8005: dirlist($uri) : return directory list based on URI
                   8006: 
                   8007: =item *
                   8008: 
1.243     albertel 8009: spareserver() : find server with least workload from spare.tab
                   8010: 
                   8011: =back
                   8012: 
                   8013: =head2 Apache Request
                   8014: 
                   8015: =over 4
1.191     harris41 8016: 
                   8017: =item *
                   8018: 
1.243     albertel 8019: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   8020: localhost, posts hash
                   8021: 
                   8022: =back
                   8023: 
                   8024: =head2 Data to String to Data
                   8025: 
                   8026: =over 4
1.191     harris41 8027: 
                   8028: =item *
                   8029: 
1.243     albertel 8030: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   8031: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 8032: 
                   8033: =item *
                   8034: 
1.243     albertel 8035: hashref2str($hashref) : convert a hashref into a string complete with
                   8036: escaping and '=' and '&' separators, supports elements that are
                   8037: arrayrefs and hashrefs
1.191     harris41 8038: 
                   8039: =item *
                   8040: 
1.243     albertel 8041: arrayref2str($arrayref) : convert an arrayref into a string complete
                   8042: with escaping and '&' separators, supports elements that are arrayrefs
                   8043: and hashrefs
1.191     harris41 8044: 
                   8045: =item *
                   8046: 
1.243     albertel 8047: str2hash($string) : convert string to hash using unescaping and
                   8048: splitting on '=' and '&', supports elements that are arrayrefs and
                   8049: hashrefs
1.191     harris41 8050: 
                   8051: =item *
                   8052: 
1.243     albertel 8053: str2array($string) : convert string to hash using unescaping and
                   8054: splitting on '&', supports elements that are arrayrefs and hashrefs
                   8055: 
                   8056: =back
                   8057: 
                   8058: =head2 Logging Routines
                   8059: 
                   8060: =over 4
                   8061: 
                   8062: These routines allow one to make log messages in the lonnet.log and
                   8063: lonnet.perm logfiles.
1.191     harris41 8064: 
                   8065: =item *
                   8066: 
1.243     albertel 8067: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 8068: 
                   8069: =item *
                   8070: 
1.243     albertel 8071: logthis() : append message to the normal lonnet.log file, it gets
                   8072: preiodically rolled over and deleted.
1.191     harris41 8073: 
                   8074: =item *
                   8075: 
1.243     albertel 8076: logperm() : append a permanent message to lonnet.perm.log, this log
                   8077: file never gets deleted by any automated portion of the system, only
                   8078: messages of critical importance should go in here.
                   8079: 
                   8080: =back
                   8081: 
                   8082: =head2 General File Helper Routines
                   8083: 
                   8084: =over 4
1.191     harris41 8085: 
                   8086: =item *
                   8087: 
1.481     raeburn  8088: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   8089: (a) files in /uploaded
                   8090:   (i) If a local copy of the file exists - 
                   8091:       compares modification date of local copy with last-modified date for 
                   8092:       definitive version stored on home server for course. If local copy is 
                   8093:       stale, requests a new version from the home server and stores it. 
                   8094:       If the original has been removed from the home server, then local copy 
                   8095:       is unlinked.
                   8096:   (ii) If local copy does not exist -
                   8097:       requests the file from the home server and stores it. 
                   8098:   
                   8099:   If $caller is 'uploadrep':  
                   8100:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   8101:     for request for files originally uploaded via DOCS. 
                   8102:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   8103:   
                   8104:   Otherwise:
                   8105:      This indicates a call from the content generation phase of the request.
                   8106:      -  returns the entire contents of the file or -1.
                   8107:      
                   8108: (b) files in /res
                   8109:    - returns the entire contents of a file or -1; 
                   8110:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 8111: 
1.712     albertel 8112: 
                   8113: =item *
                   8114: 
                   8115: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   8116:                   reference
                   8117: 
                   8118: returns either a stat() list of data about the file or an empty list
                   8119: if the file doesn't exist or couldn't find out about it (connection
                   8120: problems or user unknown)
                   8121: 
1.191     harris41 8122: =item *
                   8123: 
1.243     albertel 8124: filelocation($dir,$file) : returns file system location of a file
                   8125: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   8126: directory that relative $file lookups are to looked in ($dir of /a/dir
                   8127: and a file of ../bob will become /a/bob)
1.191     harris41 8128: 
                   8129: =item *
                   8130: 
                   8131: hreflocation($dir,$file) : returns file system location or a URL; same as
                   8132: filelocation except for hrefs
                   8133: 
                   8134: =item *
                   8135: 
                   8136: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   8137: 
1.243     albertel 8138: =back
                   8139: 
1.608     albertel 8140: =head2 Usererfile file routines (/uploaded*)
                   8141: 
                   8142: =over 4
                   8143: 
                   8144: =item *
                   8145: 
                   8146: userfileupload(): main rotine for putting a file in a user or course's
                   8147:                   filespace, arguments are,
                   8148: 
1.620     albertel 8149:  formname - required - this is the name of the element in $env where the
1.608     albertel 8150:            filename, and the contents of the file to create/modifed exist
1.620     albertel 8151:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   8152:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 8153:  coursedoc - if true, store the file in the course of the active role
                   8154:              of the current user
                   8155:  subdir - required - subdirectory to put the file in under ../userfiles/
                   8156:          if undefined, it will be placed in "unknown"
                   8157: 
                   8158:  (This routine calls clean_filename() to remove any dangerous
                   8159:  characters from the filename, and then calls finuserfileupload() to
                   8160:  complete the transaction)
                   8161: 
                   8162:  returns either the url of the uploaded file (/uploaded/....) if successful
                   8163:  and /adm/notfound.html if unsuccessful
                   8164: 
                   8165: =item *
                   8166: 
                   8167: clean_filename(): routine for cleaing a filename up for storage in
                   8168:                  userfile space, argument is:
                   8169: 
                   8170:  filename - proposed filename
                   8171: 
                   8172: returns: the new clean filename
                   8173: 
                   8174: =item *
                   8175: 
                   8176: finishuserfileupload(): routine that creaes and sends the file to
                   8177: userspace, probably shouldn't be called directly
                   8178: 
                   8179:   docuname: username or courseid of destination for the file
                   8180:   docudom: domain of user/course of destination for the file
                   8181:   formname: same as for userfileupload()
                   8182:   fname: filename (inculding subdirectories) for the file
                   8183: 
                   8184:  returns either the url of the uploaded file (/uploaded/....) if successful
                   8185:  and /adm/notfound.html if unsuccessful
                   8186: 
                   8187: =item *
                   8188: 
                   8189: renameuserfile(): renames an existing userfile to a new name
                   8190: 
                   8191:   Args:
                   8192:    docuname: username or courseid of destination for the file
                   8193:    docudom: domain of user/course of destination for the file
                   8194:    old: current file name (including any subdirs under userfiles)
                   8195:    new: desired file name (including any subdirs under userfiles)
                   8196: 
                   8197: =item *
                   8198: 
                   8199: mkdiruserfile(): creates a directory is a userfiles dir
                   8200: 
                   8201:   Args:
                   8202:    docuname: username or courseid of destination for the file
                   8203:    docudom: domain of user/course of destination for the file
                   8204:    dir: dir to create (including any subdirs under userfiles)
                   8205: 
                   8206: =item *
                   8207: 
                   8208: removeuserfile(): removes a file that exists in userfiles
                   8209: 
                   8210:   Args:
                   8211:    docuname: username or courseid of destination for the file
                   8212:    docudom: domain of user/course of destination for the file
                   8213:    fname: filname to delete (including any subdirs under userfiles)
                   8214: 
                   8215: =item *
                   8216: 
                   8217: removeuploadedurl(): convience function for removeuserfile()
                   8218: 
                   8219:   Args:
                   8220:    url:  a full /uploaded/... url to delete
                   8221: 
1.747     albertel 8222: =item * 
                   8223: 
                   8224: get_portfile_permissions():
                   8225:   Args:
                   8226:     domain: domain of user or course contain the portfolio files
                   8227:     user: name of user or num of course contain the portfolio files
                   8228:   Returns:
                   8229:     hashref of a dump of the proper file_permissions.db
                   8230:    
                   8231: 
                   8232: =item * 
                   8233: 
                   8234: get_access_controls():
                   8235: 
                   8236: Args:
                   8237:   current_permissions: the hash ref returned from get_portfile_permissions()
                   8238:   group: (optional) the group you want the files associated with
                   8239:   file: (optional) the file you want access info on
                   8240: 
                   8241: Returns:
1.749     raeburn  8242:     a hash (keys are file names) of hashes containing
                   8243:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   8244:         values are XML containing access control settings (see below) 
1.747     albertel 8245: 
                   8246: Internal notes:
                   8247: 
1.749     raeburn  8248:  access controls are stored in file_permissions.db as key=value pairs.
                   8249:     key -> path to file/file_name\0uniqueID:scope_end_start
                   8250:         where scope -> public,guest,course,group,domains or users.
                   8251:               end -> UNIX time for end of access (0 -> no end date)
                   8252:               start -> UNIX time for start of access
                   8253: 
                   8254:     value -> XML description of access control
                   8255:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   8256:             <start></start>
                   8257:             <end></end>
                   8258: 
                   8259:             <password></password>  for scope type = guest
                   8260: 
                   8261:             <domain></domain>     for scope type = course or group
                   8262:             <number></number>
                   8263:             <roles id="">
                   8264:              <role></role>
                   8265:              <access></access>
                   8266:              <section></section>
                   8267:              <group></group>
                   8268:             </roles>
                   8269: 
                   8270:             <dom></dom>         for scope type = domains
                   8271: 
                   8272:             <users>             for scope type = users
                   8273:              <user>
                   8274:               <uname></uname>
                   8275:               <udom></udom>
                   8276:              </user>
                   8277:             </users>
                   8278:            </scope> 
                   8279:               
                   8280:  Access data is also aggregated for each file in an additional key=value pair:
                   8281:  key -> path to file/file_name\0accesscontrol 
                   8282:  value -> reference to hash
                   8283:           hash contains key = value pairs
                   8284:           where key = uniqueID:scope_end_start
                   8285:                 value = UNIX time record was last updated
                   8286: 
                   8287:           Used to improve speed of look-ups of access controls for each file.  
                   8288:  
                   8289:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   8290: 
                   8291: modify_access_controls():
                   8292: 
                   8293: Modifies access controls for a portfolio file
                   8294: Args
                   8295: 1. file name
                   8296: 2. reference to hash of required changes,
                   8297: 3. domain
                   8298: 4. username
                   8299:   where domain,username are the domain of the portfolio owner 
                   8300:   (either a user or a course) 
                   8301: 
                   8302: Returns:
                   8303: 1. result of additions or updates ('ok' or 'error', with error message). 
                   8304: 2. result of deletions ('ok' or 'error', with error message).
                   8305: 3. reference to hash of any new or updated access controls.
                   8306: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   8307:    key = integer (inbound ID)
                   8308:    value = uniqueID  
1.747     albertel 8309: 
1.608     albertel 8310: =back
                   8311: 
1.243     albertel 8312: =head2 HTTP Helper Routines
                   8313: 
                   8314: =over 4
                   8315: 
1.191     harris41 8316: =item *
                   8317: 
                   8318: escape() : unpack non-word characters into CGI-compatible hex codes
                   8319: 
                   8320: =item *
                   8321: 
                   8322: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   8323: 
1.243     albertel 8324: =back
                   8325: 
                   8326: =head1 PRIVATE SUBROUTINES
                   8327: 
                   8328: =head2 Underlying communication routines (Shouldn't call)
                   8329: 
                   8330: =over 4
                   8331: 
                   8332: =item *
                   8333: 
                   8334: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   8335: 
                   8336: =item *
                   8337: 
                   8338: reply() : uses subreply to send a message to remote machine, logs all failures
                   8339: 
                   8340: =item *
                   8341: 
                   8342: critical() : passes a critical message to another server; if cannot
                   8343: get through then place message in connection buffer directory and
                   8344: returns con_delayed, if incapable of saving message, returns
                   8345: con_failed
                   8346: 
                   8347: =item *
                   8348: 
                   8349: reconlonc() : tries to reconnect lonc client processes.
                   8350: 
                   8351: =back
                   8352: 
                   8353: =head2 Resource Access Logging
                   8354: 
                   8355: =over 4
                   8356: 
                   8357: =item *
                   8358: 
                   8359: flushcourselogs() : flush (save) buffer logs and access logs
                   8360: 
                   8361: =item *
                   8362: 
                   8363: courselog($what) : save message for course in hash
                   8364: 
                   8365: =item *
                   8366: 
                   8367: courseacclog($what) : save message for course using &courselog().  Perform
                   8368: special processing for specific resource types (problems, exams, quizzes, etc).
                   8369: 
1.191     harris41 8370: =item *
                   8371: 
                   8372: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   8373: as a PerlChildExitHandler
1.243     albertel 8374: 
                   8375: =back
                   8376: 
                   8377: =head2 Other
                   8378: 
                   8379: =over 4
                   8380: 
                   8381: =item *
                   8382: 
                   8383: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 8384: 
                   8385: =back
                   8386: 
                   8387: =cut

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