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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.781   ! raeburn     4: # $Id: lonnet.pm,v 1.780 2006/09/15 07:55:05 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 {
                    298:     if ($env_loaded) { return; } 
1.374     www       299: 
                    300:     my ($lonidsdir,$handle)=@_;
1.720     albertel  301:     if (!defined($lonidsdir)) {
                    302: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    303:     }
                    304:     if (!defined($handle)) {
                    305:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    306:     }
                    307: 
1.374     www       308:     my @profile;
                    309:     {
1.448     albertel  310: 	open(my $idf,"$lonidsdir/$handle.id");
1.374     www       311: 	flock($idf,LOCK_SH);
                    312: 	@profile=<$idf>;
1.448     albertel  313: 	close($idf);
1.374     www       314:     }
                    315:     my $envi;
1.433     matthew   316:     my %Remove;
1.374     www       317:     for ($envi=0;$envi<=$#profile;$envi++) {
                    318: 	chomp($profile[$envi]);
1.690     albertel  319: 	my ($envname,$envvalue)=split(/=/,$profile[$envi],2);
1.726     albertel  320: 	$envname=&unescape($envname);
                    321: 	$envvalue=&unescape($envvalue);
1.619     albertel  322: 	$env{$envname} = $envvalue;
1.433     matthew   323:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    324:             if ($time < time-300) {
                    325:                 $Remove{$key}++;
                    326:             }
                    327:         }
                    328:     }
1.619     albertel  329:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  330:     $env_loaded=1;
1.433     matthew   331:     foreach my $expired_key (keys(%Remove)) {
                    332:         &delenv($expired_key);
1.374     www       333:     }
1.1       albertel  334: }
                    335: 
1.5       www       336: # ---------------------------------------------------------- Append Environment
                    337: 
                    338: sub appenv {
1.6       www       339:     my %newenv=@_;
1.692     albertel  340:     foreach my $key (keys(%newenv)) {
                    341: 	if (($newenv{$key}=~/^user\.role/) || ($newenv{$key}=~/^user\.priv/)) {
1.672     albertel  342:             &logthis("<font color=\"blue\">WARNING: ".
1.692     albertel  343:                 "Attempt to modify environment ".$key." to ".$newenv{$key}
1.151     www       344:                 .'</font>');
1.692     albertel  345: 	    delete($newenv{$key});
1.35      www       346:         } else {
1.692     albertel  347:             $env{$key}=$newenv{$key};
1.35      www       348:         }
1.191     harris41  349:     }
1.779     albertel  350:     foreach my $key (keys(%newenv)) {
                    351: 	my $value = &escape($newenv{$key});
                    352: 	delete($newenv{$key});
                    353: 	$newenv{&escape($key)}=$value;
                    354:     }
1.95      www       355: 
                    356:     my $lockfh;
1.620     albertel  357:     unless (open($lockfh,"$env{'user.environment'}")) {
1.448     albertel  358: 	return 'error: '.$!;
1.95      www       359:     }
                    360:     unless (flock($lockfh,LOCK_EX)) {
1.672     albertel  361:          &logthis("<font color=\"blue\">WARNING: ".
1.95      www       362:                   'Could not obtain exclusive lock in appenv: '.$!);
1.448     albertel  363:          close($lockfh);
1.95      www       364:          return 'error: '.$!;
                    365:     }
                    366: 
1.6       www       367:     my @oldenv;
                    368:     {
1.448     albertel  369: 	my $fh;
1.620     albertel  370: 	unless (open($fh,"$env{'user.environment'}")) {
1.448     albertel  371: 	    return 'error: '.$!;
                    372: 	}
                    373: 	@oldenv=<$fh>;
                    374: 	close($fh);
1.6       www       375:     }
                    376:     for (my $i=0; $i<=$#oldenv; $i++) {
                    377:         chomp($oldenv[$i]);
1.9       www       378:         if ($oldenv[$i] ne '') {
1.690     albertel  379: 	    my ($name,$value)=split(/=/,$oldenv[$i],2);
1.448     albertel  380: 	    unless (defined($newenv{$name})) {
                    381: 		$newenv{$name}=$value;
                    382: 	    }
1.9       www       383:         }
1.6       www       384:     }
                    385:     {
1.448     albertel  386: 	my $fh;
1.620     albertel  387: 	unless (open($fh,">$env{'user.environment'}")) {
1.448     albertel  388: 	    return 'error';
                    389: 	}
                    390: 	my $newname;
                    391: 	foreach $newname (keys %newenv) {
1.779     albertel  392: 	    print $fh $newname.'='.$newenv{$newname}."\n";
1.448     albertel  393: 	}
                    394: 	close($fh);
1.56      www       395:     }
1.448     albertel  396: 	
                    397:     close($lockfh);
1.56      www       398:     return 'ok';
                    399: }
                    400: # ----------------------------------------------------- Delete from Environment
                    401: 
                    402: sub delenv {
                    403:     my $delthis=shift;
                    404:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
1.672     albertel  405:         &logthis("<font color=\"blue\">WARNING: ".
1.56      www       406:                 "Attempt to delete from environment ".$delthis);
                    407:         return 'error';
                    408:     }
                    409:     my @oldenv;
                    410:     {
1.448     albertel  411: 	my $fh;
1.620     albertel  412: 	unless (open($fh,"$env{'user.environment'}")) {
1.448     albertel  413: 	    return 'error';
                    414: 	}
                    415: 	unless (flock($fh,LOCK_SH)) {
1.672     albertel  416: 	    &logthis("<font color=\"blue\">WARNING: ".
1.448     albertel  417: 		     'Could not obtain shared lock in delenv: '.$!);
                    418: 	    close($fh);
                    419: 	    return 'error: '.$!;
                    420: 	}
                    421: 	@oldenv=<$fh>;
                    422: 	close($fh);
1.56      www       423:     }
                    424:     {
1.448     albertel  425: 	my $fh;
1.620     albertel  426: 	unless (open($fh,">$env{'user.environment'}")) {
1.448     albertel  427: 	    return 'error';
                    428: 	}
                    429: 	unless (flock($fh,LOCK_EX)) {
1.672     albertel  430: 	    &logthis("<font color=\"blue\">WARNING: ".
1.448     albertel  431: 		     'Could not obtain exclusive lock in delenv: '.$!);
                    432: 	    close($fh);
                    433: 	    return 'error: '.$!;
                    434: 	}
1.692     albertel  435: 	foreach my $cur_key (@oldenv) {
1.726     albertel  436: 	    my $unescaped_cur_key = &unescape($cur_key);
                    437: 	    if ($unescaped_cur_key=~/^$delthis/) { 
                    438:                 my ($key) = split('=',$cur_key,2);
                    439: 		$key = &unescape($key);
1.619     albertel  440:                 delete($env{$key});
1.473     matthew   441:             } else {
1.692     albertel  442:                 print $fh $cur_key; 
1.473     matthew   443:             }
1.448     albertel  444: 	}
                    445: 	close($fh);
1.5       www       446:     }
                    447:     return 'ok';
1.369     albertel  448: }
                    449: 
                    450: # ------------------------------------------ Find out current server userload
                    451: # there is a copy in lond
                    452: sub userload {
                    453:     my $numusers=0;
                    454:     {
                    455: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    456: 	my $filename;
                    457: 	my $curtime=time;
                    458: 	while ($filename=readdir(LONIDS)) {
                    459: 	    if ($filename eq '.' || $filename eq '..') {next;}
1.404     albertel  460: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  461: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  462: 	}
                    463: 	closedir(LONIDS);
                    464:     }
                    465:     my $userloadpercent=0;
                    466:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    467:     if ($maxuserload) {
1.371     albertel  468: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  469:     }
1.372     albertel  470:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  471:     return $userloadpercent;
1.283     www       472: }
                    473: 
                    474: # ------------------------------------------ Fight off request when overloaded
                    475: 
                    476: sub overloaderror {
                    477:     my ($r,$checkserver)=@_;
                    478:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
                    479:     my $loadavg;
                    480:     if ($checkserver eq $perlvar{'lonHostID'}) {
1.448     albertel  481:        open(my $loadfile,'/proc/loadavg');
1.283     www       482:        $loadavg=<$loadfile>;
                    483:        $loadavg =~ s/\s.*//g;
1.285     matthew   484:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
1.448     albertel  485:        close($loadfile);
1.283     www       486:     } else {
                    487:        $loadavg=&reply('load',$checkserver);
                    488:     }
1.285     matthew   489:     my $overload=$loadavg-100;
1.283     www       490:     if ($overload>0) {
1.285     matthew   491: 	$r->err_headers_out->{'Retry-After'}=$overload;
1.283     www       492:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
1.554     www       493:         return 413;
1.283     www       494:     }    
                    495:     return '';
1.5       www       496: }
1.1       albertel  497: 
                    498: # ------------------------------ Find server with least workload from spare.tab
1.11      www       499: 
1.1       albertel  500: sub spareserver {
1.670     albertel  501:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
1.1       albertel  502:     my $tryserver;
                    503:     my $spareserver='';
1.370     albertel  504:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
                    505:     my $lowestserver=$loadpercent > $userloadpercent?
                    506: 	             $loadpercent :  $userloadpercent;
1.670     albertel  507:     foreach $tryserver (keys(%spareid)) {
                    508: 	my $loadans=&reply('load',$tryserver);
                    509: 	my $userloadans=&reply('userload',$tryserver);
1.411     albertel  510: 	if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
                    511: 	    next; #didn't get a number from the server
                    512: 	}
                    513: 	my $answer;
                    514: 	if ($loadans =~ /\d/) {
                    515: 	    if ($userloadans =~ /\d/) {
                    516: 		#both are numbers, pick the bigger one
                    517: 		$answer=$loadans > $userloadans?
                    518: 		    $loadans :  $userloadans;
                    519: 	    } else {
                    520: 		$answer = $loadans;
                    521: 	    }
                    522: 	} else {
                    523: 	    $answer = $userloadans;
                    524: 	}
                    525: 	if (($answer =~ /\d/) && ($answer<$lowestserver)) {
1.670     albertel  526: 	    if ($want_server_name) {
                    527: 		$spareserver=$tryserver;
                    528: 	    } else {
                    529: 		$spareserver="http://$hostname{$tryserver}";
                    530: 	    }
1.411     albertel  531: 	    $lowestserver=$answer;
                    532: 	}
1.370     albertel  533:     }
1.1       albertel  534:     return $spareserver;
1.202     matthew   535: }
                    536: 
                    537: # --------------------------------------------- Try to change a user's password
                    538: 
                    539: sub changepass {
                    540:     my ($uname,$udom,$currentpass,$newpass,$server)=@_;
                    541:     $currentpass = &escape($currentpass);
                    542:     $newpass     = &escape($newpass);
                    543:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass",
                    544: 		       $server);
                    545:     if (! $answer) {
                    546: 	&logthis("No reply on password change request to $server ".
                    547: 		 "by $uname in domain $udom.");
                    548:     } elsif ($answer =~ "^ok") {
                    549:         &logthis("$uname in $udom successfully changed their password ".
                    550: 		 "on $server.");
                    551:     } elsif ($answer =~ "^pwchange_failure") {
                    552: 	&logthis("$uname in $udom was unable to change their password ".
                    553: 		 "on $server.  The action was blocked by either lcpasswd ".
                    554: 		 "or pwchange");
                    555:     } elsif ($answer =~ "^non_authorized") {
                    556:         &logthis("$uname in $udom did not get their password correct when ".
                    557: 		 "attempting to change it on $server.");
                    558:     } elsif ($answer =~ "^auth_mode_error") {
                    559:         &logthis("$uname in $udom attempted to change their password despite ".
                    560: 		 "not being locally or internally authenticated on $server.");
                    561:     } elsif ($answer =~ "^unknown_user") {
                    562:         &logthis("$uname in $udom attempted to change their password ".
                    563: 		 "on $server but were unable to because $server is not ".
                    564: 		 "their home server.");
                    565:     } elsif ($answer =~ "^refused") {
                    566: 	&logthis("$server refused to change $uname in $udom password because ".
                    567: 		 "it was sent an unencrypted request to change the password.");
                    568:     }
                    569:     return $answer;
1.1       albertel  570: }
                    571: 
1.169     harris41  572: # ----------------------- Try to determine user's current authentication scheme
                    573: 
                    574: sub queryauthenticate {
                    575:     my ($uname,$udom)=@_;
1.456     albertel  576:     my $uhome=&homeserver($uname,$udom);
                    577:     if (!$uhome) {
                    578: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                    579: 	return 'no_host';
                    580:     }
                    581:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                    582:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                    583: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41  584:     }
1.456     albertel  585:     return $answer;
1.169     harris41  586: }
                    587: 
1.1       albertel  588: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www       589: 
1.1       albertel  590: sub authenticate {
                    591:     my ($uname,$upass,$udom)=@_;
1.12      www       592:     $upass=escape($upass);
1.199     www       593:     $uname=~s/\W//g;
1.471     albertel  594:     my $uhome=&homeserver($uname,$udom);
                    595:     if (!$uhome) {
                    596: 	&logthis("User $uname at $udom is unknown in authenticate");
                    597: 	return 'no_host';
1.1       albertel  598:     }
1.471     albertel  599:     my $answer=reply("encrypt:auth:$udom:$uname:$upass",$uhome);
                    600:     if ($answer eq 'authorized') {
                    601: 	&logthis("User $uname at $udom authorized by $uhome"); 
                    602: 	return $uhome; 
                    603:     }
                    604:     if ($answer eq 'non_authorized') {
                    605: 	&logthis("User $uname at $udom rejected by $uhome");
                    606: 	return 'no_host'; 
1.9       www       607:     }
1.471     albertel  608:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel  609:     return 'no_host';
                    610: }
                    611: 
                    612: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www       613: 
1.599     albertel  614: my %homecache;
1.1       albertel  615: sub homeserver {
1.230     stredwic  616:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel  617:     my $index="$uname:$udom";
1.426     albertel  618: 
1.599     albertel  619:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.1       albertel  620:     my $tryserver;
                    621:     foreach $tryserver (keys %libserv) {
1.230     stredwic  622:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic  623: 		 exists($badServerCache{$tryserver}));
1.1       albertel  624: 	if ($hostdom{$tryserver} eq $udom) {
                    625:            my $answer=reply("home:$udom:$uname",$tryserver);
                    626:            if ($answer eq 'found') { 
1.599     albertel  627: 	       return $homecache{$index}=$tryserver;
1.231     stredwic  628:            } elsif ($answer eq 'no_host') {
                    629: 	       $badServerCache{$tryserver}=1;
1.221     matthew   630:            }
1.1       albertel  631:        }
                    632:     }    
                    633:     return 'no_host';
1.70      www       634: }
                    635: 
                    636: # ------------------------------------- Find the usernames behind a list of IDs
                    637: 
                    638: sub idget {
                    639:     my ($udom,@ids)=@_;
                    640:     my %returnhash=();
                    641:     
                    642:     my $tryserver;
                    643:     foreach $tryserver (keys %libserv) {
                    644:        if ($hostdom{$tryserver} eq $udom) {
                    645: 	  my $idlist=join('&',@ids);
                    646:           $idlist=~tr/A-Z/a-z/; 
                    647: 	  my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                    648:           my @answer=();
1.76      www       649:           if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1.70      www       650: 	      @answer=split(/\&/,$reply);
                    651:           }                    ;
                    652:           my $i;
                    653:           for ($i=0;$i<=$#ids;$i++) {
                    654:               if ($answer[$i]) {
                    655: 		  $returnhash{$ids[$i]}=$answer[$i];
                    656:               } 
                    657:           }
                    658:        }
                    659:     }    
                    660:     return %returnhash;
                    661: }
                    662: 
                    663: # ------------------------------------- Find the IDs behind a list of usernames
                    664: 
                    665: sub idrget {
                    666:     my ($udom,@unames)=@_;
                    667:     my %returnhash=();
1.191     harris41  668:     foreach (@unames) {
1.70      www       669:         $returnhash{$_}=(&userenvironment($udom,$_,'id'))[1];
1.191     harris41  670:     }
1.70      www       671:     return %returnhash;
                    672: }
                    673: 
                    674: # ------------------------------- Store away a list of names and associated IDs
                    675: 
                    676: sub idput {
                    677:     my ($udom,%ids)=@_;
                    678:     my %servers=();
1.191     harris41  679:     foreach (keys %ids) {
1.487     albertel  680: 	&cput('environment',{'id'=>$ids{$_}},$udom,$_);
1.70      www       681:         my $uhom=&homeserver($_,$udom);
                    682:         if ($uhom ne 'no_host') {
                    683:             my $id=&escape($ids{$_});
                    684:             $id=~tr/A-Z/a-z/;
                    685:             my $unam=&escape($_);
                    686: 	    if ($servers{$uhom}) {
                    687: 		$servers{$uhom}.='&'.$id.'='.$unam;
                    688:             } else {
                    689:                 $servers{$uhom}=$id.'='.$unam;
                    690:             }
                    691:         }
1.191     harris41  692:     }
                    693:     foreach (keys %servers) {
1.70      www       694:         &critical('idput:'.$udom.':'.$servers{$_},$_);
1.191     harris41  695:     }
1.344     www       696: }
                    697: 
                    698: # --------------------------------------------------- Assign a key to a student
                    699: 
                    700: sub assign_access_key {
1.364     www       701: #
                    702: # a valid key looks like uname:udom#comments
                    703: # comments are being appended
                    704: #
1.498     www       705:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                    706:     $kdom=
1.620     albertel  707:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www       708:     $knum=
1.620     albertel  709:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www       710:     $cdom=
1.620     albertel  711:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       712:     $cnum=
1.620     albertel  713:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                    714:     $udom=$env{'user.name'} unless (defined($udom));
                    715:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www       716:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www       717:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel  718:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www       719:                                                   # assigned to this person
                    720:                                                   # - this should not happen,
1.345     www       721:                                                   # unless something went wrong
                    722:                                                   # the first time around
                    723: # ready to assign
1.364     www       724:         $logentry=$1.'; '.$logentry;
1.496     www       725:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www       726:                                                  $kdom,$knum) eq 'ok') {
1.345     www       727: # key now belongs to user
1.346     www       728: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www       729:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
                    730:                 &appenv('environment.'.$envkey => $ckey);
                    731:                 return 'ok';
                    732:             } else {
                    733:                 return 
                    734:   'error: Count not permanently assign key, will need to be re-entered later.';
                    735: 	    }
                    736:         } else {
                    737:             return 'error: Could not assign key, try again later.';
                    738:         }
1.364     www       739:     } elsif (!$existing{$ckey}) {
1.345     www       740: # the key does not exist
                    741: 	return 'error: The key does not exist';
                    742:     } else {
                    743: # the key is somebody else's
                    744: 	return 'error: The key is already in use';
                    745:     }
1.344     www       746: }
                    747: 
1.364     www       748: # ------------------------------------------ put an additional comment on a key
                    749: 
                    750: sub comment_access_key {
                    751: #
                    752: # a valid key looks like uname:udom#comments
                    753: # comments are being appended
                    754: #
                    755:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                    756:     $cdom=
1.620     albertel  757:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www       758:     $cnum=
1.620     albertel  759:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www       760:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                    761:     if ($existing{$ckey}) {
                    762:         $existing{$ckey}.='; '.$logentry;
                    763: # ready to assign
1.367     www       764:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www       765:                                                  $cdom,$cnum) eq 'ok') {
                    766: 	    return 'ok';
                    767:         } else {
                    768: 	    return 'error: Count not store comment.';
                    769:         }
                    770:     } else {
                    771: # the key does not exist
                    772: 	return 'error: The key does not exist';
                    773:     }
                    774: }
                    775: 
1.344     www       776: # ------------------------------------------------------ Generate a set of keys
                    777: 
                    778: sub generate_access_keys {
1.364     www       779:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www       780:     $cdom=
1.620     albertel  781:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       782:     $cnum=
1.620     albertel  783:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www       784:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www       785:     unless (($cdom) && ($cnum)) { return 0; }
                    786:     if ($number>10000) { return 0; }
                    787:     sleep(2); # make sure don't get same seed twice
                    788:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                    789:     my $total=0;
                    790:     for (my $i=1;$i<=$number;$i++) {
                    791:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                    792:                   sprintf("%lx",int(100000*rand)).'-'.
                    793:                   sprintf("%lx",int(100000*rand));
                    794:        $newkey=~s/1/g/g; # folks mix up 1 and l
                    795:        $newkey=~s/0/h/g; # and also 0 and O
                    796:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                    797:        if ($existing{$newkey}) {
                    798:            $i--;
                    799:        } else {
1.364     www       800: 	  if (&put('accesskeys',
                    801:               { $newkey => '# generated '.localtime().
1.620     albertel  802:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www       803:                            '; '.$logentry },
                    804: 		   $cdom,$cnum) eq 'ok') {
1.344     www       805:               $total++;
                    806: 	  }
                    807:        }
                    808:     }
1.620     albertel  809:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www       810:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                    811:     return $total;
                    812: }
                    813: 
                    814: # ------------------------------------------------------- Validate an accesskey
                    815: 
                    816: sub validate_access_key {
                    817:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                    818:     $cdom=
1.620     albertel  819:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       820:     $cnum=
1.620     albertel  821:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                    822:     $udom=$env{'user.domain'} unless (defined($udom));
                    823:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www       824:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel  825:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www       826: }
                    827: 
                    828: # ------------------------------------- Find the section of student in a course
1.652     albertel  829: sub devalidate_getsection_cache {
                    830:     my ($udom,$unam,$courseid)=@_;
                    831:     $courseid=~s/\_/\//g;
                    832:     $courseid=~s/^(\w)/\/$1/;
                    833:     my $hashid="$udom:$unam:$courseid";
                    834:     &devalidate_cache_new('getsection',$hashid);
                    835: }
1.298     matthew   836: 
                    837: sub getsection {
                    838:     my ($udom,$unam,$courseid)=@_;
1.599     albertel  839:     my $cachetime=1800;
1.298     matthew   840:     $courseid=~s/\_/\//g;
                    841:     $courseid=~s/^(\w)/\/$1/;
1.551     albertel  842: 
                    843:     my $hashid="$udom:$unam:$courseid";
1.599     albertel  844:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel  845:     if (defined($cached)) { return $result; }
                    846: 
1.298     matthew   847:     my %Pending; 
                    848:     my %Expired;
                    849:     #
                    850:     # Each role can either have not started yet (pending), be active, 
                    851:     #    or have expired.
                    852:     #
                    853:     # If there is an active role, we are done.
                    854:     #
                    855:     # If there is more than one role which has not started yet, 
                    856:     #     choose the one which will start sooner
                    857:     # If there is one role which has not started yet, return it.
                    858:     #
                    859:     # If there is more than one expired role, choose the one which ended last.
                    860:     # If there is a role which has expired, return it.
                    861:     #
                    862:     foreach (split(/\&/,&reply('dump:'.$udom.':'.$unam.':roles',
                    863:                         &homeserver($unam,$udom)))) {
                    864:         my ($key,$value)=split(/\=/,$_);
                    865:         $key=&unescape($key);
1.479     albertel  866:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew   867:         my $section=$1;
                    868:         if ($key eq $courseid.'_st') { $section=''; }
                    869:         my ($dummy,$end,$start)=split(/\_/,&unescape($value));
                    870:         my $now=time;
1.548     albertel  871:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew   872:             $Expired{$end}=$section;
                    873:             next;
                    874:         }
1.548     albertel  875:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew   876:             $Pending{$start}=$section;
                    877:             next;
                    878:         }
1.599     albertel  879:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew   880:     }
                    881:     #
                    882:     # Presumedly there will be few matching roles from the above
                    883:     # loop and the sorting time will be negligible.
                    884:     if (scalar(keys(%Pending))) {
                    885:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel  886:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew   887:     } 
                    888:     if (scalar(keys(%Expired))) {
                    889:         my @sorted = sort {$a <=> $b} keys(%Expired);
                    890:         my $time = pop(@sorted);
1.599     albertel  891:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew   892:     }
1.599     albertel  893:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew   894: }
1.70      www       895: 
1.599     albertel  896: sub save_cache {
                    897:     &purge_remembered();
1.722     albertel  898:     #&Apache::loncommon::validate_page();
1.620     albertel  899:     undef(%env);
1.780     albertel  900:     undef($env_loaded);
1.599     albertel  901: }
1.452     albertel  902: 
1.599     albertel  903: my $to_remember=-1;
                    904: my %remembered;
                    905: my %accessed;
                    906: my $kicks=0;
                    907: my $hits=0;
                    908: sub devalidate_cache_new {
                    909:     my ($name,$id,$debug) = @_;
                    910:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
                    911:     $id=&escape($name.':'.$id);
                    912:     $memcache->delete($id);
                    913:     delete($remembered{$id});
                    914:     delete($accessed{$id});
                    915: }
                    916: 
                    917: sub is_cached_new {
                    918:     my ($name,$id,$debug) = @_;
                    919:     $id=&escape($name.':'.$id);
                    920:     if (exists($remembered{$id})) {
                    921: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                    922: 	$accessed{$id}=[&gettimeofday()];
                    923: 	$hits++;
                    924: 	return ($remembered{$id},1);
                    925:     }
                    926:     my $value = $memcache->get($id);
                    927:     if (!(defined($value))) {
                    928: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel  929: 	return (undef,undef);
1.416     albertel  930:     }
1.599     albertel  931:     if ($value eq '__undef__') {
                    932: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                    933: 	$value=undef;
                    934:     }
                    935:     &make_room($id,$value,$debug);
                    936:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                    937:     return ($value,1);
                    938: }
                    939: 
                    940: sub do_cache_new {
                    941:     my ($name,$id,$value,$time,$debug) = @_;
                    942:     $id=&escape($name.':'.$id);
                    943:     my $setvalue=$value;
                    944:     if (!defined($setvalue)) {
                    945: 	$setvalue='__undef__';
                    946:     }
1.623     albertel  947:     if (!defined($time) ) {
                    948: 	$time=600;
                    949:     }
1.599     albertel  950:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.600     albertel  951:     $memcache->set($id,$setvalue,$time);
                    952:     # need to make a copy of $value
                    953:     #&make_room($id,$value,$debug);
1.599     albertel  954:     return $value;
                    955: }
                    956: 
                    957: sub make_room {
                    958:     my ($id,$value,$debug)=@_;
                    959:     $remembered{$id}=$value;
                    960:     if ($to_remember<0) { return; }
                    961:     $accessed{$id}=[&gettimeofday()];
                    962:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                    963:     my $to_kick;
                    964:     my $max_time=0;
                    965:     foreach my $other (keys(%accessed)) {
                    966: 	if (&tv_interval($accessed{$other}) > $max_time) {
                    967: 	    $to_kick=$other;
                    968: 	    $max_time=&tv_interval($accessed{$other});
                    969: 	}
                    970:     }
                    971:     delete($remembered{$to_kick});
                    972:     delete($accessed{$to_kick});
                    973:     $kicks++;
                    974:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel  975:     return;
                    976: }
                    977: 
1.599     albertel  978: sub purge_remembered {
1.604     albertel  979:     #&logthis("Tossing ".scalar(keys(%remembered)));
                    980:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel  981:     undef(%remembered);
                    982:     undef(%accessed);
1.428     albertel  983: }
1.70      www       984: # ------------------------------------- Read an entry from a user's environment
                    985: 
                    986: sub userenvironment {
                    987:     my ($udom,$unam,@what)=@_;
                    988:     my %returnhash=();
                    989:     my @answer=split(/\&/,
                    990:                 &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
                    991:                       &homeserver($unam,$udom)));
                    992:     my $i;
                    993:     for ($i=0;$i<=$#what;$i++) {
                    994: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
                    995:     }
                    996:     return %returnhash;
1.1       albertel  997: }
                    998: 
1.617     albertel  999: # ---------------------------------------------------------- Get a studentphoto
                   1000: sub studentphoto {
                   1001:     my ($udom,$unam,$ext) = @_;
                   1002:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  1003:     if (defined($env{'request.course.id'})) {
1.708     raeburn  1004:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  1005:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   1006:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   1007:             } else {
                   1008:                 my ($result,$perm_reqd)=
1.707     albertel 1009: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1010:                 if ($result eq 'ok') {
                   1011:                     if (!($perm_reqd eq 'yes')) {
                   1012:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   1013:                     }
                   1014:                 }
                   1015:             }
                   1016:         }
                   1017:     } else {
                   1018:         my ($result,$perm_reqd) = 
1.707     albertel 1019: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1020:         if ($result eq 'ok') {
                   1021:             if (!($perm_reqd eq 'yes')) {
                   1022:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   1023:             }
                   1024:         }
                   1025:     }
                   1026:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   1027: }
                   1028: 
                   1029: sub retrievestudentphoto {
                   1030:     my ($udom,$unam,$ext,$type) = @_;
                   1031:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   1032:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   1033:     if ($ret eq 'ok') {
                   1034:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   1035:         if ($type eq 'thumbnail') {
                   1036:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   1037:         }
                   1038:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   1039:         return $tokenurl;
                   1040:     } else {
                   1041:         if ($type eq 'thumbnail') {
                   1042:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   1043:         } else { 
                   1044:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   1045:         }
1.617     albertel 1046:     }
                   1047: }
                   1048: 
1.263     www      1049: # -------------------------------------------------------------------- New chat
                   1050: 
                   1051: sub chatsend {
1.724     raeburn  1052:     my ($newentry,$anon,$group)=@_;
1.620     albertel 1053:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1054:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1055:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      1056:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 1057: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  1058: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      1059: }
                   1060: 
                   1061: # ------------------------------------------ Find current version of a resource
                   1062: 
                   1063: sub getversion {
                   1064:     my $fname=&clutter(shift);
                   1065:     unless ($fname=~/^\/res\//) { return -1; }
                   1066:     return &currentversion(&filelocation('',$fname));
                   1067: }
                   1068: 
                   1069: sub currentversion {
                   1070:     my $fname=shift;
1.599     albertel 1071:     my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440     www      1072:     if (defined($cached)) { return $result; }
1.292     www      1073:     my $author=$fname;
                   1074:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1075:     my ($udom,$uname)=split(/\//,$author);
                   1076:     my $home=homeserver($uname,$udom);
                   1077:     if ($home eq 'no_host') { 
                   1078:         return -1; 
                   1079:     }
                   1080:     my $answer=reply("currentversion:$fname",$home);
                   1081:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1082: 	return -1;
                   1083:     }
1.599     albertel 1084:     return &do_cache_new('resversion',$fname,$answer,600);
1.263     www      1085: }
                   1086: 
1.1       albertel 1087: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      1088: 
1.1       albertel 1089: sub subscribe {
                   1090:     my $fname=shift;
1.761     raeburn  1091:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 1092:     $fname=~s/[\n\r]//g;
1.1       albertel 1093:     my $author=$fname;
                   1094:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1095:     my ($udom,$uname)=split(/\//,$author);
                   1096:     my $home=homeserver($uname,$udom);
1.335     albertel 1097:     if ($home eq 'no_host') {
                   1098:         return 'not_found';
1.1       albertel 1099:     }
                   1100:     my $answer=reply("sub:$fname",$home);
1.64      www      1101:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1102: 	$answer.=' by '.$home;
                   1103:     }
1.1       albertel 1104:     return $answer;
                   1105: }
                   1106:     
1.8       www      1107: # -------------------------------------------------------------- Replicate file
                   1108: 
                   1109: sub repcopy {
                   1110:     my $filename=shift;
1.23      www      1111:     $filename=~s/\/+/\//g;
1.607     raeburn  1112:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   1113:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 1114:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 1115: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 1116: 	return &repcopy_userfile($filename);
                   1117:     }
1.532     albertel 1118:     $filename=~s/[\n\r]//g;
1.8       www      1119:     my $transname="$filename.in.transfer";
1.607     raeburn  1120:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      1121:     my $remoteurl=subscribe($filename);
1.64      www      1122:     if ($remoteurl =~ /^con_lost by/) {
                   1123: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1124:            return 'unavailable';
1.8       www      1125:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 1126: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  1127: 	   return 'not_found';
1.64      www      1128:     } elsif ($remoteurl =~ /^rejected by/) {
                   1129: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1130:            return 'forbidden';
1.20      www      1131:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  1132:            return 'ok';
1.8       www      1133:     } else {
1.290     www      1134:         my $author=$filename;
                   1135:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1136:         my ($udom,$uname)=split(/\//,$author);
                   1137:         my $home=homeserver($uname,$udom);
                   1138:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      1139:            my @parts=split(/\//,$filename);
                   1140:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   1141:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   1142:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  1143: 	       return 'bad_request';
1.8       www      1144:            }
                   1145:            my $count;
                   1146:            for ($count=5;$count<$#parts;$count++) {
                   1147:                $path.="/$parts[$count]";
                   1148:                if ((-e $path)!=1) {
                   1149: 		   mkdir($path,0777);
                   1150:                }
                   1151:            }
                   1152:            my $ua=new LWP::UserAgent;
                   1153:            my $request=new HTTP::Request('GET',"$remoteurl");
                   1154:            my $response=$ua->request($request,$transname);
                   1155:            if ($response->is_error()) {
                   1156: 	       unlink($transname);
                   1157:                my $message=$response->status_line;
1.672     albertel 1158:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      1159:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  1160:                return 'unavailable';
1.8       www      1161:            } else {
1.16      www      1162: 	       if ($remoteurl!~/\.meta$/) {
                   1163:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   1164:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   1165:                   if ($mresponse->is_error()) {
                   1166: 		      unlink($filename.'.meta');
                   1167:                       &logthis(
1.672     albertel 1168:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      1169:                   }
                   1170: 	       }
1.8       www      1171:                rename($transname,$filename);
1.607     raeburn  1172:                return 'ok';
1.8       www      1173:            }
1.290     www      1174:        }
1.8       www      1175:     }
1.330     www      1176: }
                   1177: 
                   1178: # ------------------------------------------------ Get server side include body
                   1179: sub ssi_body {
1.381     albertel 1180:     my ($filelink,%form)=@_;
1.606     matthew  1181:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   1182:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   1183:     }
1.330     www      1184:     my $output=($filelink=~/^http\:/?&externalssi($filelink):
1.381     albertel 1185:                                      &ssi($filelink,%form));
1.778     albertel 1186:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 1187:     $output=~s/^.*?\<body[^\>]*\>//si;
                   1188:     $output=~s/(.*)\<\/body\s*\>.*?$/$1/si;
1.330     www      1189:     return $output;
1.8       www      1190: }
                   1191: 
1.15      www      1192: # --------------------------------------------------------- Server Side Include
                   1193: 
                   1194: sub ssi {
                   1195: 
1.23      www      1196:     my ($fn,%form)=@_;
1.15      www      1197: 
                   1198:     my $ua=new LWP::UserAgent;
1.23      www      1199:     
                   1200:     my $request;
1.711     albertel 1201: 
                   1202:     $form{'no_update_last_known'}=1;
                   1203: 
1.23      www      1204:     if (%form) {
                   1205:       $request=new HTTP::Request('POST',"http://".$ENV{'HTTP_HOST'}.$fn);
1.201     albertel 1206:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1.23      www      1207:     } else {
                   1208:       $request=new HTTP::Request('GET',"http://".$ENV{'HTTP_HOST'}.$fn);
                   1209:     }
                   1210: 
1.15      www      1211:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   1212:     my $response=$ua->request($request);
                   1213: 
1.324     www      1214:     return $response->content;
                   1215: }
                   1216: 
                   1217: sub externalssi {
                   1218:     my ($url)=@_;
                   1219:     my $ua=new LWP::UserAgent;
                   1220:     my $request=new HTTP::Request('GET',$url);
                   1221:     my $response=$ua->request($request);
1.15      www      1222:     return $response->content;
                   1223: }
1.254     www      1224: 
1.492     albertel 1225: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   1226: 
                   1227: sub allowuploaded {
                   1228:     my ($srcurl,$url)=@_;
                   1229:     $url=&clutter(&declutter($url));
                   1230:     my $dir=$url;
                   1231:     $dir=~s/\/[^\/]+$//;
                   1232:     my %httpref=();
                   1233:     my $httpurl=&hreflocation('',$url);
                   1234:     $httpref{'httpref.'.$httpurl}=$srcurl;
                   1235:     &Apache::lonnet::appenv(%httpref);
1.254     www      1236: }
1.477     raeburn  1237: 
1.478     albertel 1238: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 1239: # input: action, courseID, current domain, intended
1.637     raeburn  1240: #        path to file, source of file, instruction to parse file for objects,
                   1241: #        ref to hash for embedded objects,
                   1242: #        ref to hash for codebase of java objects.
                   1243: #
1.485     raeburn  1244: # output: url to file (if action was uploaddoc), 
                   1245: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  1246: #
1.478     albertel 1247: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   1248: # course.
1.477     raeburn  1249: #
1.478     albertel 1250: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1251: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   1252: #          course's home server.
1.477     raeburn  1253: #
1.478     albertel 1254: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   1255: #          be copied from $source (current location) to 
                   1256: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1257: #         and will then be copied to
                   1258: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   1259: #         course's home server.
1.485     raeburn  1260: #
1.481     raeburn  1261: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 1262: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  1263: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1264: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   1265: #         in course's home server.
1.637     raeburn  1266: #
1.477     raeburn  1267: 
                   1268: sub process_coursefile {
1.638     albertel 1269:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477     raeburn  1270:     my $fetchresult;
1.638     albertel 1271:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  1272:     if ($action eq 'propagate') {
1.638     albertel 1273:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   1274: 			     $home);
1.481     raeburn  1275:     } else {
1.477     raeburn  1276:         my $fpath = '';
                   1277:         my $fname = $file;
1.478     albertel 1278:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  1279:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  1280:         my $filepath = &build_filepath($fpath);
1.481     raeburn  1281:         if ($action eq 'copy') {
                   1282:             if ($source eq '') {
                   1283:                 $fetchresult = 'no source file';
                   1284:                 return $fetchresult;
                   1285:             } else {
                   1286:                 my $destination = $filepath.'/'.$fname;
                   1287:                 rename($source,$destination);
                   1288:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1289:                                  $home);
1.481     raeburn  1290:             }
                   1291:         } elsif ($action eq 'uploaddoc') {
                   1292:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 1293:             print $fh $env{'form.'.$source};
1.481     raeburn  1294:             close($fh);
1.637     raeburn  1295:             if ($parser eq 'parse') {
                   1296:                 my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
                   1297:                 unless ($parse_result eq 'ok') {
                   1298:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   1299:                 }
                   1300:             }
1.477     raeburn  1301:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1302:                                  $home);
1.481     raeburn  1303:             if ($fetchresult eq 'ok') {
                   1304:                 return '/uploaded/'.$fpath.'/'.$fname;
                   1305:             } else {
                   1306:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1307:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  1308:                 return '/adm/notfound.html';
                   1309:             }
1.477     raeburn  1310:         }
                   1311:     }
1.485     raeburn  1312:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  1313:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1314:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  1315:     }
                   1316:     return $fetchresult;
                   1317: }
                   1318: 
1.637     raeburn  1319: sub build_filepath {
                   1320:     my ($fpath) = @_;
                   1321:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   1322:     unless ($fpath eq '') {
                   1323:         my @parts=split('/',$fpath);
                   1324:         foreach my $part (@parts) {
                   1325:             $filepath.= '/'.$part;
                   1326:             if ((-e $filepath)!=1) {
                   1327:                 mkdir($filepath,0777);
                   1328:             }
                   1329:         }
                   1330:     }
                   1331:     return $filepath;
                   1332: }
                   1333: 
                   1334: sub store_edited_file {
1.638     albertel 1335:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  1336:     my $file = $primary_url;
                   1337:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   1338:     my $fpath = '';
                   1339:     my $fname = $file;
                   1340:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   1341:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   1342:     my $filepath = &build_filepath($fpath);
                   1343:     open(my $fh,'>'.$filepath.'/'.$fname);
                   1344:     print $fh $content;
                   1345:     close($fh);
1.638     albertel 1346:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  1347:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1348: 			  $home);
1.637     raeburn  1349:     if ($$fetchresult eq 'ok') {
                   1350:         return '/uploaded/'.$fpath.'/'.$fname;
                   1351:     } else {
1.638     albertel 1352:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   1353: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  1354:         return '/adm/notfound.html';
                   1355:     }
                   1356: }
                   1357: 
1.531     albertel 1358: sub clean_filename {
                   1359:     my ($fname)=@_;
1.315     www      1360: # Replace Windows backslashes by forward slashes
1.257     www      1361:     $fname=~s/\\/\//g;
1.315     www      1362: # Get rid of everything but the actual filename
1.257     www      1363:     $fname=~s/^.*\/([^\/]+)$/$1/;
1.315     www      1364: # Replace spaces by underscores
                   1365:     $fname=~s/\s+/\_/g;
                   1366: # Replace all other weird characters by nothing
1.317     www      1367:     $fname=~s/[^\w\.\-]//g;
1.540     albertel 1368: # Replace all .\d. sequences with _\d. so they no longer look like version
                   1369: # numbers
                   1370:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 1371:     return $fname;
                   1372: }
                   1373: 
1.608     albertel 1374: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 1375: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719     banghart 1376: #                    the desired filenam is in $env{"form.$formname.filename"}
1.686     albertel 1377: #        $coursedoc - if true up to the current course
                   1378: #                     if false
                   1379: #        $subdir - directory in userfile to store the file into
                   1380: #        $parser, $allfiles, $codebase - unknown
                   1381: #
                   1382: # output: url of file in userspace, or error: <message> 
                   1383: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 1384: 
                   1385: 
1.531     albertel 1386: sub userfileupload {
1.719     banghart 1387:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,$destudom)=@_;
1.531     albertel 1388:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 1389:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 1390:     $fname=&clean_filename($fname);
1.315     www      1391: # See if there is anything left
1.257     www      1392:     unless ($fname) { return 'error: no uploaded file'; }
1.620     albertel 1393:     chop($env{'form.'.$formname});
1.523     raeburn  1394:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
                   1395:         my $now = time;
                   1396:         my $filepath = 'tmp/helprequests/'.$now;
                   1397:         my @parts=split(/\//,$filepath);
                   1398:         my $fullpath = $perlvar{'lonDaemons'};
                   1399:         for (my $i=0;$i<@parts;$i++) {
                   1400:             $fullpath .= '/'.$parts[$i];
                   1401:             if ((-e $fullpath)!=1) {
                   1402:                 mkdir($fullpath,0777);
                   1403:             }
                   1404:         }
                   1405:         open(my $fh,'>'.$fullpath.'/'.$fname);
1.620     albertel 1406:         print $fh $env{'form.'.$formname};
1.523     raeburn  1407:         close($fh);
1.741     raeburn  1408:         return $fullpath.'/'.$fname;
                   1409:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
                   1410:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   1411:                        '_'.$env{'user.domain'}.'/pending';
                   1412:         my @parts=split(/\//,$filepath);
                   1413:         my $fullpath = $perlvar{'lonDaemons'};
                   1414:         for (my $i=0;$i<@parts;$i++) {
                   1415:             $fullpath .= '/'.$parts[$i];
                   1416:             if ((-e $fullpath)!=1) {
                   1417:                 mkdir($fullpath,0777);
                   1418:             }
                   1419:         }
                   1420:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   1421:         print $fh $env{'form.'.$formname};
                   1422:         close($fh);
                   1423:         return $fullpath.'/'.$fname;
1.523     raeburn  1424:     }
1.719     banghart 1425:     
1.258     www      1426: # Create the directory if not present
1.493     albertel 1427:     $fname="$subdir/$fname";
1.259     www      1428:     if ($coursedoc) {
1.638     albertel 1429: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1430: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  1431:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 1432:             return &finishuserfileupload($docuname,$docudom,
                   1433: 					 $formname,$fname,$parser,$allfiles,
                   1434: 					 $codebase);
1.481     raeburn  1435:         } else {
1.620     albertel 1436:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 1437:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   1438: 				       $fname,$formname,$parser,
                   1439: 				       $allfiles,$codebase);
1.481     raeburn  1440:         }
1.719     banghart 1441:     } elsif (defined($destuname)) {
                   1442:         my $docuname=$destuname;
                   1443:         my $docudom=$destudom;
                   1444: 	return &finishuserfileupload($docuname,$docudom,$formname,
                   1445: 				     $fname,$parser,$allfiles,$codebase);
                   1446:         
1.259     www      1447:     } else {
1.638     albertel 1448:         my $docuname=$env{'user.name'};
                   1449:         my $docudom=$env{'user.domain'};
1.714     raeburn  1450:         if (exists($env{'form.group'})) {
                   1451:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1452:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1453:         }
1.638     albertel 1454: 	return &finishuserfileupload($docuname,$docudom,$formname,
                   1455: 				     $fname,$parser,$allfiles,$codebase);
1.259     www      1456:     }
1.271     www      1457: }
                   1458: 
                   1459: sub finishuserfileupload {
1.638     albertel 1460:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase) = @_;
1.477     raeburn  1461:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      1462:     my $filepath=$perlvar{'lonDocRoot'};
1.494     albertel 1463:     my ($fnamepath,$file);
                   1464:     $file=$fname;
                   1465:     if ($fname=~m|/|) {
                   1466:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   1467: 	$path.=$fnamepath.'/';
                   1468:     }
1.259     www      1469:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      1470:     my $count;
                   1471:     for ($count=4;$count<=$#parts;$count++) {
                   1472:         $filepath.="/$parts[$count]";
                   1473:         if ((-e $filepath)!=1) {
                   1474: 	    mkdir($filepath,0777);
                   1475:         }
                   1476:     }
                   1477: # Save the file
                   1478:     {
1.701     albertel 1479: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   1480: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   1481: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   1482: 	    return '/adm/notfound.html';
                   1483: 	}
                   1484: 	if (!print FH ($env{'form.'.$formname})) {
                   1485: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   1486: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   1487: 	    return '/adm/notfound.html';
                   1488: 	}
1.570     albertel 1489: 	close(FH);
1.258     www      1490:     }
1.637     raeburn  1491:     if ($parser eq 'parse') {
1.638     albertel 1492:         my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
                   1493: 						   $codebase);
1.637     raeburn  1494:         unless ($parse_result eq 'ok') {
1.638     albertel 1495:             &logthis('Failed to parse '.$filepath.$file.
                   1496: 		     ' for embedded media: '.$parse_result); 
1.637     raeburn  1497:         }
                   1498:     }
1.259     www      1499: # Notify homeserver to grep it
                   1500: #
1.638     albertel 1501:     my $docuhome=&homeserver($docuname,$docudom);
1.494     albertel 1502:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      1503:     if ($fetchresult eq 'ok') {
1.259     www      1504: #
1.258     www      1505: # Return the URL to it
1.494     albertel 1506:         return '/uploaded/'.$path.$file;
1.263     www      1507:     } else {
1.494     albertel 1508:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   1509: 		 ': '.$fetchresult);
1.263     www      1510:         return '/adm/notfound.html';
                   1511:     }    
1.493     albertel 1512: }
                   1513: 
1.637     raeburn  1514: sub extract_embedded_items {
1.648     raeburn  1515:     my ($filepath,$file,$allfiles,$codebase,$content) = @_;
1.637     raeburn  1516:     my @state = ();
                   1517:     my %javafiles = (
                   1518:                       codebase => '',
                   1519:                       code => '',
                   1520:                       archive => ''
                   1521:                     );
                   1522:     my %mediafiles = (
                   1523:                       src => '',
                   1524:                       movie => '',
                   1525:                      );
1.648     raeburn  1526:     my $p;
                   1527:     if ($content) {
                   1528:         $p = HTML::LCParser->new($content);
                   1529:     } else {
                   1530:         $p = HTML::LCParser->new($filepath.'/'.$file);
                   1531:     }
1.641     albertel 1532:     while (my $t=$p->get_token()) {
1.640     albertel 1533: 	if ($t->[0] eq 'S') {
                   1534: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
                   1535: 	    push (@state, $tagname);
1.648     raeburn  1536:             if (lc($tagname) eq 'allow') {
                   1537:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   1538:             }
1.640     albertel 1539: 	    if (lc($tagname) eq 'img') {
                   1540: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   1541: 	    }
1.645     raeburn  1542:             if (lc($tagname) eq 'script') {
                   1543:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   1544:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   1545:                 } else {
                   1546:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   1547:                 }
                   1548:             }
                   1549:             if (lc($tagname) eq 'link') {
                   1550:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   1551:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   1552:                 }
                   1553:             }
1.640     albertel 1554: 	    if (lc($tagname) eq 'object' ||
                   1555: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   1556: 		foreach my $item (keys(%javafiles)) {
                   1557: 		    $javafiles{$item} = '';
                   1558: 		}
                   1559: 	    }
                   1560: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   1561: 		my $name = lc($attr->{'name'});
                   1562: 		foreach my $item (keys(%javafiles)) {
                   1563: 		    if ($name eq $item) {
                   1564: 			$javafiles{$item} = $attr->{'value'};
                   1565: 			last;
                   1566: 		    }
                   1567: 		}
                   1568: 		foreach my $item (keys(%mediafiles)) {
                   1569: 		    if ($name eq $item) {
                   1570: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   1571: 			last;
                   1572: 		    }
                   1573: 		}
                   1574: 	    }
                   1575: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   1576: 		foreach my $item (keys(%javafiles)) {
                   1577: 		    if ($attr->{$item}) {
                   1578: 			$javafiles{$item} = $attr->{$item};
                   1579: 			last;
                   1580: 		    }
                   1581: 		}
                   1582: 		foreach my $item (keys(%mediafiles)) {
                   1583: 		    if ($attr->{$item}) {
                   1584: 			&add_filetype($allfiles,$attr->{$item},$item);
                   1585: 			last;
                   1586: 		    }
                   1587: 		}
                   1588: 	    }
                   1589: 	} elsif ($t->[0] eq 'E') {
                   1590: 	    my ($tagname) = ($t->[1]);
                   1591: 	    if ($javafiles{'codebase'} ne '') {
                   1592: 		$javafiles{'codebase'} .= '/';
                   1593: 	    }  
                   1594: 	    if (lc($tagname) eq 'applet' ||
                   1595: 		lc($tagname) eq 'object' ||
                   1596: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   1597: 		) {
                   1598: 		foreach my $item (keys(%javafiles)) {
                   1599: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   1600: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   1601: 			&add_filetype($allfiles,$file,$item);
                   1602: 		    }
                   1603: 		}
                   1604: 	    } 
                   1605: 	    pop @state;
                   1606: 	}
                   1607:     }
1.637     raeburn  1608:     return 'ok';
                   1609: }
                   1610: 
1.639     albertel 1611: sub add_filetype {
                   1612:     my ($allfiles,$file,$type)=@_;
                   1613:     if (exists($allfiles->{$file})) {
                   1614: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   1615: 	    push(@{$allfiles->{$file}}, &escape($type));
                   1616: 	}
                   1617:     } else {
                   1618: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  1619:     }
                   1620: }
                   1621: 
1.493     albertel 1622: sub removeuploadedurl {
                   1623:     my ($url)=@_;
                   1624:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613     albertel 1625:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 1626: }
                   1627: 
                   1628: sub removeuserfile {
                   1629:     my ($docuname,$docudom,$fname)=@_;
                   1630:     my $home=&homeserver($docuname,$docudom);
                   1631:     return &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.257     www      1632: }
1.15      www      1633: 
1.530     albertel 1634: sub mkdiruserfile {
                   1635:     my ($docuname,$docudom,$dir)=@_;
                   1636:     my $home=&homeserver($docuname,$docudom);
                   1637:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   1638: }
                   1639: 
1.531     albertel 1640: sub renameuserfile {
                   1641:     my ($docuname,$docudom,$old,$new)=@_;
                   1642:     my $home=&homeserver($docuname,$docudom);
                   1643:     return &reply("renameuserfile:$docudom:$docuname:".&escape("$old").':'.
                   1644: 		  &escape("$new"),$home);
                   1645: }
                   1646: 
1.14      www      1647: # ------------------------------------------------------------------------- Log
                   1648: 
                   1649: sub log {
                   1650:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      1651:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      1652: }
                   1653: 
                   1654: # ------------------------------------------------------------------ Course Log
1.352     www      1655: #
                   1656: # This routine flushes several buffers of non-mission-critical nature
                   1657: #
1.157     www      1658: 
                   1659: sub flushcourselogs {
1.352     www      1660:     &logthis('Flushing log buffers');
                   1661: #
                   1662: # course logs
                   1663: # This is a log of all transactions in a course, which can be used
                   1664: # for data mining purposes
                   1665: #
                   1666: # It also collects the courseid database, which lists last transaction
                   1667: # times and course titles for all courseids
                   1668: #
                   1669:     my %courseidbuffer=();
1.191     harris41 1670:     foreach (keys %courselogs) {
1.157     www      1671:         my $crsid=$_;
1.352     www      1672:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      1673: 		          &escape($courselogs{$crsid}),
                   1674: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      1675: 	    delete $courselogs{$crsid};
                   1676:         } else {
                   1677:             &logthis('Failed to flush log buffer for '.$crsid);
                   1678:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 1679:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      1680:                         " exceeded maximum size, deleting.</font>");
                   1681:                delete $courselogs{$crsid};
                   1682:             }
1.352     www      1683:         }
                   1684:         if ($courseidbuffer{$coursehombuf{$crsid}}) {
                   1685:            $courseidbuffer{$coursehombuf{$crsid}}.='&'.
1.516     raeburn  1686: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.741     raeburn  1687:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1.352     www      1688:         } else {
                   1689:            $courseidbuffer{$coursehombuf{$crsid}}=
1.516     raeburn  1690: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.741     raeburn  1691:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1.571     raeburn  1692:         }
1.191     harris41 1693:     }
1.352     www      1694: #
                   1695: # Write course id database (reverse lookup) to homeserver of courses 
                   1696: # Is used in pickcourse
                   1697: #
                   1698:     foreach (keys %courseidbuffer) {
1.353     www      1699:         &courseidput($hostdom{$_},$courseidbuffer{$_},$_);
1.352     www      1700:     }
                   1701: #
                   1702: # File accesses
                   1703: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   1704: #
1.449     matthew  1705:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  1706:         if ($entry =~ /___count$/) {
                   1707:             my ($dom,$name);
                   1708:             ($dom,$name,undef)=($entry=~m:___(\w+)/(\w+)/(.*)___count$:);
                   1709:             if (! defined($dom) || $dom eq '' || 
                   1710:                 ! defined($name) || $name eq '') {
1.620     albertel 1711:                 my $cid = $env{'request.course.id'};
                   1712:                 $dom  = $env{'request.'.$cid.'.domain'};
                   1713:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  1714:             }
1.450     matthew  1715:             my $value = $accesshash{$entry};
                   1716:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   1717:             my %temphash=($url => $value);
1.449     matthew  1718:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   1719:             if ($result eq 'ok') {
                   1720:                 delete $accesshash{$entry};
                   1721:             } elsif ($result eq 'unknown_cmd') {
                   1722:                 # Target server has old code running on it.
1.450     matthew  1723:                 my %temphash=($entry => $value);
1.449     matthew  1724:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   1725:                     delete $accesshash{$entry};
                   1726:                 }
                   1727:             }
                   1728:         } else {
1.458     matthew  1729:             my ($dom,$name) = ($entry=~m:___(\w+)/(\w+)/(.*)___(\w+)$:);
1.450     matthew  1730:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  1731:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   1732:                 delete $accesshash{$entry};
                   1733:             }
1.185     www      1734:         }
1.191     harris41 1735:     }
1.352     www      1736: #
                   1737: # Roles
                   1738: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   1739: #
1.349     www      1740:     foreach (keys %userrolehash) {
                   1741:         my $entry=$_;
1.351     www      1742:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      1743: 	    split(/\:/,$entry);
                   1744:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      1745:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      1746:                 $rudom,$runame) eq 'ok') {
                   1747: 	    delete $userrolehash{$entry};
                   1748:         }
                   1749:     }
1.662     raeburn  1750: #
                   1751: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   1752: #
                   1753:     my %domrolebuffer = ();
                   1754:     foreach my $entry (keys %domainrolehash) {
                   1755:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split/:/,$entry;
                   1756:         if ($domrolebuffer{$rudom}) {
                   1757:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   1758:                       '='.&escape($domainrolehash{$entry});
                   1759:         } else {
                   1760:             $domrolebuffer{$rudom}.=&escape($entry).
                   1761:                       '='.&escape($domainrolehash{$entry});
                   1762:         }
                   1763:         delete $domainrolehash{$entry};
                   1764:     }
                   1765:     foreach my $dom (keys(%domrolebuffer)) {
                   1766:         foreach my $tryserver (keys %libserv) {
                   1767:             if ($hostdom{$tryserver} eq $dom) {
                   1768:                 unless (&reply('domroleput:'.$dom.':'.
                   1769:                   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   1770:                     &logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   1771:                 }
                   1772:             }
                   1773:         }
                   1774:     }
1.186     www      1775:     $dumpcount++;
1.157     www      1776: }
                   1777: 
                   1778: sub courselog {
                   1779:     my $what=shift;
1.158     www      1780:     $what=time.':'.$what;
1.620     albertel 1781:     unless ($env{'request.course.id'}) { return ''; }
                   1782:     $coursedombuf{$env{'request.course.id'}}=
                   1783:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   1784:     $coursenumbuf{$env{'request.course.id'}}=
                   1785:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   1786:     $coursehombuf{$env{'request.course.id'}}=
                   1787:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   1788:     $coursedescrbuf{$env{'request.course.id'}}=
                   1789:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   1790:     $courseinstcodebuf{$env{'request.course.id'}}=
                   1791:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   1792:     $courseownerbuf{$env{'request.course.id'}}=
                   1793:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  1794:     $coursetypebuf{$env{'request.course.id'}}=
                   1795:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 1796:     if (defined $courselogs{$env{'request.course.id'}}) {
                   1797: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      1798:     } else {
1.620     albertel 1799: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      1800:     }
1.620     albertel 1801:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      1802: 	&flushcourselogs();
                   1803:     }
1.158     www      1804: }
                   1805: 
                   1806: sub courseacclog {
                   1807:     my $fnsymb=shift;
1.620     albertel 1808:     unless ($env{'request.course.id'}) { return ''; }
                   1809:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 1810:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      1811:         $what.=':POST';
1.583     matthew  1812:         # FIXME: Probably ought to escape things....
1.620     albertel 1813: 	foreach (keys %env) {
1.158     www      1814:             if ($_=~/^form\.(.*)/) {
1.620     albertel 1815: 		$what.=':'.$1.'='.$env{$_};
1.158     www      1816:             }
1.191     harris41 1817:         }
1.583     matthew  1818:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   1819:         # FIXME: We should not be depending on a form parameter that someone
                   1820:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 1821:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  1822:             $what.= ':POST';
                   1823:             # FIXME: Probably ought to escape things....
                   1824:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   1825:                                  'crsdiscuss') {
1.620     albertel 1826:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  1827:             }
                   1828:         }
1.158     www      1829:     }
                   1830:     &courselog($what);
1.149     www      1831: }
                   1832: 
1.185     www      1833: sub countacc {
                   1834:     my $url=&declutter(shift);
1.458     matthew  1835:     return if (! defined($url) || $url eq '');
1.620     albertel 1836:     unless ($env{'request.course.id'}) { return ''; }
                   1837:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      1838:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  1839:     $accesshash{$key}++;
1.185     www      1840: }
1.349     www      1841: 
1.361     www      1842: sub linklog {
                   1843:     my ($from,$to)=@_;
                   1844:     $from=&declutter($from);
                   1845:     $to=&declutter($to);
                   1846:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   1847:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   1848: }
                   1849:   
1.349     www      1850: sub userrolelog {
                   1851:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  1852:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  1853:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  1854:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
                   1855:         ($trole=~/^ta/)) {
1.350     www      1856:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   1857:        $userrolehash
                   1858:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      1859:                     =$tend.':'.$tstart;
1.662     raeburn  1860:     }
                   1861:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   1862:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   1863:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   1864:         ($trole=~/^sc/)) {
                   1865:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   1866:        $domainrolehash
                   1867:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   1868:                     = $tend.':'.$tstart;
                   1869:     }
1.351     www      1870: }
                   1871: 
                   1872: sub get_course_adv_roles {
                   1873:     my $cid=shift;
1.620     albertel 1874:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      1875:     my %coursehash=&coursedescription($cid);
1.470     www      1876:     my %nothide=();
                   1877:     foreach (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   1878: 	$nothide{join(':',split(/[\@\:]/,$_))}=1;
                   1879:     }
1.351     www      1880:     my %returnhash=();
                   1881:     my %dumphash=
                   1882:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   1883:     my $now=time;
                   1884:     foreach (keys %dumphash) {
                   1885: 	my ($tend,$tstart)=split(/\:/,$dumphash{$_});
                   1886:         if (($tstart) && ($tstart<0)) { next; }
                   1887:         if (($tend) && ($tend<$now)) { next; }
                   1888:         if (($tstart) && ($now<$tstart)) { next; }
                   1889:         my ($role,$username,$domain,$section)=split(/\:/,$_);
1.576     albertel 1890: 	if ($username eq '' || $domain eq '') { next; }
1.470     www      1891: 	if ((&privileged($username,$domain)) && 
                   1892: 	    (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 1893: 	if ($role eq 'cr') { next; }
1.351     www      1894:         my $key=&plaintext($role);
                   1895:         if ($section) { $key.=' (Sec/Grp '.$section.')'; }
                   1896:         if ($returnhash{$key}) {
                   1897: 	    $returnhash{$key}.=','.$username.':'.$domain;
                   1898:         } else {
                   1899:             $returnhash{$key}=$username.':'.$domain;
                   1900:         }
1.400     www      1901:      }
                   1902:     return %returnhash;
                   1903: }
                   1904: 
                   1905: sub get_my_roles {
                   1906:     my ($uname,$udom)=@_;
1.620     albertel 1907:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   1908:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.400     www      1909:     my %dumphash=
                   1910:             &dump('nohist_userroles',$udom,$uname);
                   1911:     my %returnhash=();
                   1912:     my $now=time;
                   1913:     foreach (keys %dumphash) {
                   1914: 	my ($tend,$tstart)=split(/\:/,$dumphash{$_});
                   1915:         if (($tstart) && ($tstart<0)) { next; }
                   1916:         if (($tend) && ($tend<$now)) { next; }
                   1917:         if (($tstart) && ($now<$tstart)) { next; }
                   1918:         my ($role,$username,$domain,$section)=split(/\:/,$_);
                   1919: 	$returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
1.373     www      1920:      }
                   1921:     return %returnhash;
1.399     www      1922: }
                   1923: 
                   1924: # ----------------------------------------------------- Frontpage Announcements
                   1925: #
                   1926: #
                   1927: 
                   1928: sub postannounce {
                   1929:     my ($server,$text)=@_;
                   1930:     unless (&allowed('psa',$hostdom{$server})) { return 'refused'; }
                   1931:     unless ($text=~/\w/) { $text=''; }
                   1932:     return &reply('setannounce:'.&escape($text),$server);
                   1933: }
                   1934: 
                   1935: sub getannounce {
1.448     albertel 1936: 
                   1937:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      1938: 	my $announcement='';
                   1939: 	while (<$fh>) { $announcement .=$_; }
1.448     albertel 1940: 	close($fh);
1.399     www      1941: 	if ($announcement=~/\w/) { 
                   1942: 	    return 
                   1943:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 1944:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      1945: 	} else {
                   1946: 	    return '';
                   1947: 	}
                   1948:     } else {
                   1949: 	return '';
                   1950:     }
1.351     www      1951: }
1.353     www      1952: 
                   1953: # ---------------------------------------------------------- Course ID routines
                   1954: # Deal with domain's nohist_courseid.db files
                   1955: #
                   1956: 
                   1957: sub courseidput {
                   1958:     my ($domain,$what,$coursehome)=@_;
                   1959:     return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   1960: }
                   1961: 
                   1962: sub courseiddump {
1.741     raeburn  1963:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,$coursefilter,$hostidflag,$hostidref,$typefilter)=@_;
1.353     www      1964:     my %returnhash=();
1.355     www      1965:     unless ($domfilter) { $domfilter=''; }
1.353     www      1966:     foreach my $tryserver (keys %libserv) {
1.511     raeburn  1967:         if ( ($hostidflag == 1 && grep/^$tryserver$/,@{$hostidref}) || (!defined($hostidflag)) ) {
1.506     raeburn  1968: 	    if ((!$domfilter) || ($hostdom{$tryserver} eq $domfilter)) {
                   1969: 	        foreach (
                   1970:                  split(/\&/,&reply('courseiddump:'.$hostdom{$tryserver}.':'.
1.571     raeburn  1971: 			       $sincefilter.':'.&escape($descfilter).':'.
1.741     raeburn  1972:                                &escape($instcodefilter).':'.&escape($ownerfilter).':'.&escape($coursefilter).':'.&escape($typefilter),
1.354     www      1973:                                $tryserver))) {
1.506     raeburn  1974: 		    my ($key,$value)=split(/\=/,$_);
                   1975:                     if (($key) && ($value)) {
1.516     raeburn  1976: 		        $returnhash{&unescape($key)}=$value;
1.506     raeburn  1977:                     }
1.353     www      1978:                 }
                   1979:             }
                   1980:         }
                   1981:     }
                   1982:     return %returnhash;
                   1983: }
                   1984: 
1.658     raeburn  1985: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  1986: 
                   1987: sub dcmailput {
1.685     raeburn  1988:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  1989:     my $status = &Apache::lonnet::critical(
1.740     www      1990:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   1991:        &escape($message),$server);
1.662     raeburn  1992:     return $status;
                   1993: }
                   1994: 
1.658     raeburn  1995: sub dcmaildump {
                   1996:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  1997:     my %returnhash=();
                   1998:     if (exists($domain_primary{$dom})) {
                   1999:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   2000:                                                          &escape($enddate).':';
                   2001: 	my @esc_senders=map { &escape($_)} @$senders;
                   2002: 	$cmd.=&escape(join('&',@esc_senders));
                   2003: 	foreach (split(/\&/,&reply($cmd,$domain_primary{$dom}))) {
                   2004:             my ($key,$value) = split(/\=/,$_);
                   2005:             if (($key) && ($value)) {
                   2006:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  2007:             }
                   2008:         }
                   2009:     }
                   2010:     return %returnhash;
                   2011: }
1.662     raeburn  2012: # ---------------------------------------------------------- Domain roles
                   2013: 
                   2014: sub get_domain_roles {
                   2015:     my ($dom,$roles,$startdate,$enddate)=@_;
                   2016:     if (undef($startdate) || $startdate eq '') {
                   2017:         $startdate = '.';
                   2018:     }
                   2019:     if (undef($enddate) || $enddate eq '') {
                   2020:         $enddate = '.';
                   2021:     }
                   2022:     my $rolelist = join(':',@{$roles});
                   2023:     my %personnel = ();
                   2024:     foreach my $tryserver (keys(%libserv)) {
                   2025:         if ($hostdom{$tryserver} eq $dom) {
                   2026:             %{$personnel{$tryserver}}=();
                   2027:             foreach (
                   2028:                 split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   2029:                    &escape($startdate).':'.&escape($enddate).':'.
                   2030:                    &escape($rolelist), $tryserver))) {
                   2031:                 my($key,$value) = split(/\=/,$_);
                   2032:                 if (($key) && ($value)) {
                   2033:                     $personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   2034:                 }
                   2035:             }
                   2036:         }
                   2037:     }
                   2038:     return %personnel;
                   2039: }
1.658     raeburn  2040: 
1.149     www      2041: # ----------------------------------------------------------- Check out an item
                   2042: 
1.504     albertel 2043: sub get_first_access {
                   2044:     my ($type,$argsymb)=@_;
                   2045:     my ($symb,$courseid,$udom,$uname)=&Apache::lonxml::whichuser();
                   2046:     if ($argsymb) { $symb=$argsymb; }
                   2047:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 2048:     if ($type eq 'map') {
                   2049: 	$res=&symbread($map);
                   2050:     } else {
                   2051: 	$res=$symb;
                   2052:     }
                   2053:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   2054:     return $times{"$courseid\0$res"};
1.504     albertel 2055: }
                   2056: 
                   2057: sub set_first_access {
                   2058:     my ($type)=@_;
                   2059:     my ($symb,$courseid,$udom,$uname)=&Apache::lonxml::whichuser();
                   2060:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 2061:     if ($type eq 'map') {
                   2062: 	$res=&symbread($map);
                   2063:     } else {
                   2064: 	$res=$symb;
                   2065:     }
                   2066:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 2067:     if (!$firstaccess) {
1.588     albertel 2068: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 2069:     }
                   2070:     return 'already_set';
1.504     albertel 2071: }
                   2072: 
1.149     www      2073: sub checkout {
                   2074:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   2075:     my $now=time;
                   2076:     my $lonhost=$perlvar{'lonHostID'};
                   2077:     my $infostr=&escape(
1.234     www      2078:                  'CHECKOUTTOKEN&'.
1.149     www      2079:                  $tuname.'&'.
                   2080:                  $tudom.'&'.
                   2081:                  $tcrsid.'&'.
                   2082:                  $symb.'&'.
                   2083: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                   2084:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www      2085:     if ($token=~/^error\:/) { 
1.672     albertel 2086:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2087:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2088:                  "</font>");
                   2089:         return ''; 
                   2090:     }
                   2091: 
1.149     www      2092:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   2093:     $token=~tr/a-z/A-Z/;
                   2094: 
1.153     www      2095:     my %infohash=('resource.0.outtoken' => $token,
                   2096:                   'resource.0.checkouttime' => $now,
                   2097:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www      2098: 
                   2099:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2100:        return '';
1.151     www      2101:     } else {
1.672     albertel 2102:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2103:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2104:                  "</font>");
1.149     www      2105:     }    
                   2106: 
                   2107:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2108:                          &escape('Checkout '.$infostr.' - '.
                   2109:                                                  $token)) ne 'ok') {
                   2110: 	return '';
1.151     www      2111:     } else {
1.672     albertel 2112:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2113:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2114:                  "</font>");
1.149     www      2115:     }
1.151     www      2116:     return $token;
1.149     www      2117: }
                   2118: 
                   2119: # ------------------------------------------------------------ Check in an item
                   2120: 
                   2121: sub checkin {
                   2122:     my $token=shift;
1.150     www      2123:     my $now=time;
                   2124:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   2125:     $lonhost=~tr/A-Z/a-z/;
1.595     albertel 2126:     my $dtoken=$ta.'_'.$hostname{$lonhost}.'_'.$tb;
1.150     www      2127:     $dtoken=~s/\W/\_/g;
1.234     www      2128:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www      2129:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   2130: 
1.154     www      2131:     unless (($tuname) && ($tudom)) {
                   2132:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   2133:         return '';
                   2134:     }
                   2135:     
                   2136:     unless (&allowed('mgr',$tcrsid)) {
                   2137:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620     albertel 2138:                  $env{'user.name'}.' - '.$env{'user.domain'});
1.154     www      2139:         return '';
                   2140:     }
                   2141: 
1.153     www      2142:     my %infohash=('resource.0.intoken' => $token,
                   2143:                   'resource.0.checkintime' => $now,
                   2144:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      2145: 
                   2146:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2147:        return '';
                   2148:     }    
                   2149: 
                   2150:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2151:                          &escape('Checkin - '.$token)) ne 'ok') {
                   2152: 	return '';
                   2153:     }
                   2154: 
                   2155:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      2156: }
                   2157: 
                   2158: # --------------------------------------------- Set Expire Date for Spreadsheet
                   2159: 
                   2160: sub expirespread {
                   2161:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 2162:     my $cid=$env{'request.course.id'}; 
1.110     www      2163:     if ($cid) {
                   2164:        my $now=time;
                   2165:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 2166:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   2167:                             $env{'course.'.$cid.'.num'}.
1.110     www      2168: 	        	    ':nohist_expirationdates:'.
                   2169:                             &escape($key).'='.$now,
1.620     albertel 2170:                             $env{'course.'.$cid.'.home'})
1.110     www      2171:     }
                   2172:     return 'ok';
1.14      www      2173: }
                   2174: 
1.109     www      2175: # ----------------------------------------------------- Devalidate Spreadsheets
                   2176: 
                   2177: sub devalidate {
1.325     www      2178:     my ($symb,$uname,$udom)=@_;
1.620     albertel 2179:     my $cid=$env{'request.course.id'}; 
1.109     www      2180:     if ($cid) {
1.391     matthew  2181:         # delete the stored spreadsheets for
                   2182:         # - the student level sheet of this user in course's homespace
                   2183:         # - the assessment level sheet for this resource 
                   2184:         #   for this user in user's homespace
1.553     albertel 2185: 	# - current conditional state info
1.325     www      2186: 	my $key=$uname.':'.$udom.':';
1.109     www      2187:         my $status=
1.299     matthew  2188: 	    &del('nohist_calculatedsheets',
1.391     matthew  2189: 		 [$key.'studentcalc:'],
1.620     albertel 2190: 		 $env{'course.'.$cid.'.domain'},
                   2191: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 2192: 		.' '.
                   2193: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  2194: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      2195:         unless ($status eq 'ok ok') {
                   2196:            &logthis('Could not devalidate spreadsheet '.
1.325     www      2197:                     $uname.' at '.$udom.' for '.
1.109     www      2198: 		    $symb.': '.$status);
1.133     albertel 2199:         }
1.553     albertel 2200: 	&delenv('user.state.'.$cid);
1.109     www      2201:     }
                   2202: }
                   2203: 
1.265     albertel 2204: sub get_scalar {
                   2205:     my ($string,$end) = @_;
                   2206:     my $value;
                   2207:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   2208: 	$value = $1;
                   2209:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   2210: 	$value = $1;
                   2211:     }
                   2212:     return &unescape($value);
                   2213: }
                   2214: 
                   2215: sub array2str {
                   2216:   my (@array) = @_;
                   2217:   my $result=&arrayref2str(\@array);
                   2218:   $result=~s/^__ARRAY_REF__//;
                   2219:   $result=~s/__END_ARRAY_REF__$//;
                   2220:   return $result;
                   2221: }
                   2222: 
1.204     albertel 2223: sub arrayref2str {
                   2224:   my ($arrayref) = @_;
1.265     albertel 2225:   my $result='__ARRAY_REF__';
1.204     albertel 2226:   foreach my $elem (@$arrayref) {
1.265     albertel 2227:     if(ref($elem) eq 'ARRAY') {
                   2228:       $result.=&arrayref2str($elem).'&';
                   2229:     } elsif(ref($elem) eq 'HASH') {
                   2230:       $result.=&hashref2str($elem).'&';
                   2231:     } elsif(ref($elem)) {
                   2232:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 2233:     } else {
                   2234:       $result.=&escape($elem).'&';
                   2235:     }
                   2236:   }
                   2237:   $result=~s/\&$//;
1.265     albertel 2238:   $result .= '__END_ARRAY_REF__';
1.204     albertel 2239:   return $result;
                   2240: }
                   2241: 
1.168     albertel 2242: sub hash2str {
1.204     albertel 2243:   my (%hash) = @_;
                   2244:   my $result=&hashref2str(\%hash);
1.265     albertel 2245:   $result=~s/^__HASH_REF__//;
                   2246:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 2247:   return $result;
                   2248: }
                   2249: 
                   2250: sub hashref2str {
                   2251:   my ($hashref)=@_;
1.265     albertel 2252:   my $result='__HASH_REF__';
1.495     albertel 2253:   foreach (sort(keys(%$hashref))) {
1.204     albertel 2254:     if (ref($_) eq 'ARRAY') {
1.265     albertel 2255:       $result.=&arrayref2str($_).'=';
1.204     albertel 2256:     } elsif (ref($_) eq 'HASH') {
1.265     albertel 2257:       $result.=&hashref2str($_).'=';
1.204     albertel 2258:     } elsif (ref($_)) {
1.265     albertel 2259:       $result.='=';
                   2260:       #print("Got a ref of ".(ref($_))." skipping.");
1.204     albertel 2261:     } else {
1.265     albertel 2262: 	if ($_) {$result.=&escape($_).'=';} else { last; }
1.204     albertel 2263:     }
                   2264: 
1.265     albertel 2265:     if(ref($hashref->{$_}) eq 'ARRAY') {
                   2266:       $result.=&arrayref2str($hashref->{$_}).'&';
                   2267:     } elsif(ref($hashref->{$_}) eq 'HASH') {
                   2268:       $result.=&hashref2str($hashref->{$_}).'&';
                   2269:     } elsif(ref($hashref->{$_})) {
                   2270:        $result.='&';
                   2271:       #print("Got a ref of ".(ref($hashref->{$_}))." skipping.");
1.204     albertel 2272:     } else {
1.265     albertel 2273:       $result.=&escape($hashref->{$_}).'&';
1.204     albertel 2274:     }
                   2275:   }
1.168     albertel 2276:   $result=~s/\&$//;
1.265     albertel 2277:   $result .= '__END_HASH_REF__';
1.168     albertel 2278:   return $result;
                   2279: }
                   2280: 
                   2281: sub str2hash {
1.265     albertel 2282:     my ($string)=@_;
                   2283:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   2284:     return %$hash;
                   2285: }
                   2286: 
                   2287: sub str2hashref {
1.168     albertel 2288:   my ($string) = @_;
1.265     albertel 2289: 
                   2290:   my %hash;
                   2291: 
                   2292:   if($string !~ /^__HASH_REF__/) {
                   2293:       if (! ($string eq '' || !defined($string))) {
                   2294: 	  $hash{'error'}='Not hash reference';
                   2295:       }
                   2296:       return (\%hash, $string);
                   2297:   }
                   2298: 
                   2299:   $string =~ s/^__HASH_REF__//;
                   2300: 
                   2301:   while($string !~ /^__END_HASH_REF__/) {
                   2302:       #key
                   2303:       my $key='';
                   2304:       if($string =~ /^__HASH_REF__/) {
                   2305:           ($key, $string)=&str2hashref($string);
                   2306:           if(defined($key->{'error'})) {
                   2307:               $hash{'error'}='Bad data';
                   2308:               return (\%hash, $string);
                   2309:           }
                   2310:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2311:           ($key, $string)=&str2arrayref($string);
                   2312:           if($key->[0] eq 'Array reference error') {
                   2313:               $hash{'error'}='Bad data';
                   2314:               return (\%hash, $string);
                   2315:           }
                   2316:       } else {
                   2317:           $string =~ s/^(.*?)=//;
1.267     albertel 2318: 	  $key=&unescape($1);
1.265     albertel 2319:       }
                   2320:       $string =~ s/^=//;
                   2321: 
                   2322:       #value
                   2323:       my $value='';
                   2324:       if($string =~ /^__HASH_REF__/) {
                   2325:           ($value, $string)=&str2hashref($string);
                   2326:           if(defined($value->{'error'})) {
                   2327:               $hash{'error'}='Bad data';
                   2328:               return (\%hash, $string);
                   2329:           }
                   2330:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2331:           ($value, $string)=&str2arrayref($string);
                   2332:           if($value->[0] eq 'Array reference error') {
                   2333:               $hash{'error'}='Bad data';
                   2334:               return (\%hash, $string);
                   2335:           }
                   2336:       } else {
                   2337: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   2338:       }
                   2339:       $string =~ s/^&//;
                   2340: 
                   2341:       $hash{$key}=$value;
1.204     albertel 2342:   }
1.265     albertel 2343: 
                   2344:   $string =~ s/^__END_HASH_REF__//;
                   2345: 
                   2346:   return (\%hash, $string);
1.204     albertel 2347: }
                   2348: 
                   2349: sub str2array {
1.265     albertel 2350:     my ($string)=@_;
                   2351:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   2352:     return @$array;
                   2353: }
                   2354: 
                   2355: sub str2arrayref {
1.204     albertel 2356:   my ($string) = @_;
1.265     albertel 2357:   my @array;
                   2358: 
                   2359:   if($string !~ /^__ARRAY_REF__/) {
                   2360:       if (! ($string eq '' || !defined($string))) {
                   2361: 	  $array[0]='Array reference error';
                   2362:       }
                   2363:       return (\@array, $string);
                   2364:   }
                   2365: 
                   2366:   $string =~ s/^__ARRAY_REF__//;
                   2367: 
                   2368:   while($string !~ /^__END_ARRAY_REF__/) {
                   2369:       my $value='';
                   2370:       if($string =~ /^__HASH_REF__/) {
                   2371:           ($value, $string)=&str2hashref($string);
                   2372:           if(defined($value->{'error'})) {
                   2373:               $array[0] ='Array reference error';
                   2374:               return (\@array, $string);
                   2375:           }
                   2376:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2377:           ($value, $string)=&str2arrayref($string);
                   2378:           if($value->[0] eq 'Array reference error') {
                   2379:               $array[0] ='Array reference error';
                   2380:               return (\@array, $string);
                   2381:           }
                   2382:       } else {
                   2383: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   2384:       }
                   2385:       $string =~ s/^&//;
                   2386: 
                   2387:       push(@array, $value);
1.191     harris41 2388:   }
1.265     albertel 2389: 
                   2390:   $string =~ s/^__END_ARRAY_REF__//;
                   2391: 
                   2392:   return (\@array, $string);
1.168     albertel 2393: }
                   2394: 
1.167     albertel 2395: # -------------------------------------------------------------------Temp Store
                   2396: 
1.168     albertel 2397: sub tmpreset {
                   2398:   my ($symb,$namespace,$domain,$stuname) = @_;
                   2399:   if (!$symb) {
                   2400:     $symb=&symbread();
1.620     albertel 2401:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2402:   }
                   2403:   $symb=escape($symb);
                   2404: 
1.620     albertel 2405:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 2406:   $namespace=~s/\//\_/g;
                   2407:   $namespace=~s/\W//g;
                   2408: 
1.620     albertel 2409:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2410:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2411:   if ($domain eq 'public' && $stuname eq 'public') {
                   2412:       $stuname=$ENV{'REMOTE_ADDR'};
                   2413:   }
1.168     albertel 2414:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2415:   my %hash;
                   2416:   if (tie(%hash,'GDBM_File',
                   2417: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2418: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2419:     foreach my $key (keys %hash) {
1.180     albertel 2420:       if ($key=~ /:$symb/) {
1.168     albertel 2421: 	delete($hash{$key});
                   2422:       }
                   2423:     }
                   2424:   }
                   2425: }
                   2426: 
1.167     albertel 2427: sub tmpstore {
1.168     albertel 2428:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2429: 
                   2430:   if (!$symb) {
                   2431:     $symb=&symbread();
1.620     albertel 2432:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2433:   }
                   2434:   $symb=escape($symb);
                   2435: 
                   2436:   if (!$namespace) {
                   2437:     # I don't think we would ever want to store this for a course.
                   2438:     # it seems this will only be used if we don't have a course.
1.620     albertel 2439:     #$namespace=$env{'request.course.id'};
1.168     albertel 2440:     #if (!$namespace) {
1.620     albertel 2441:       $namespace=$env{'request.state'};
1.168     albertel 2442:     #}
                   2443:   }
                   2444:   $namespace=~s/\//\_/g;
                   2445:   $namespace=~s/\W//g;
1.620     albertel 2446:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2447:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2448:   if ($domain eq 'public' && $stuname eq 'public') {
                   2449:       $stuname=$ENV{'REMOTE_ADDR'};
                   2450:   }
1.168     albertel 2451:   my $now=time;
                   2452:   my %hash;
                   2453:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2454:   if (tie(%hash,'GDBM_File',
                   2455: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2456: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2457:     $hash{"version:$symb"}++;
                   2458:     my $version=$hash{"version:$symb"};
                   2459:     my $allkeys=''; 
                   2460:     foreach my $key (keys(%$storehash)) {
                   2461:       $allkeys.=$key.':';
1.591     albertel 2462:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 2463:     }
                   2464:     $hash{"$version:$symb:timestamp"}=$now;
                   2465:     $allkeys.='timestamp';
                   2466:     $hash{"$version:keys:$symb"}=$allkeys;
                   2467:     if (untie(%hash)) {
                   2468:       return 'ok';
                   2469:     } else {
                   2470:       return "error:$!";
                   2471:     }
                   2472:   } else {
                   2473:     return "error:$!";
                   2474:   }
                   2475: }
1.167     albertel 2476: 
1.168     albertel 2477: # -----------------------------------------------------------------Temp Restore
1.167     albertel 2478: 
1.168     albertel 2479: sub tmprestore {
                   2480:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 2481: 
1.168     albertel 2482:   if (!$symb) {
                   2483:     $symb=&symbread();
1.620     albertel 2484:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2485:   }
                   2486:   $symb=escape($symb);
                   2487: 
1.620     albertel 2488:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 2489: 
1.620     albertel 2490:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2491:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2492:   if ($domain eq 'public' && $stuname eq 'public') {
                   2493:       $stuname=$ENV{'REMOTE_ADDR'};
                   2494:   }
1.168     albertel 2495:   my %returnhash;
                   2496:   $namespace=~s/\//\_/g;
                   2497:   $namespace=~s/\W//g;
                   2498:   my %hash;
                   2499:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2500:   if (tie(%hash,'GDBM_File',
                   2501: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2502: 	  &GDBM_READER(),0640)) {
1.168     albertel 2503:     my $version=$hash{"version:$symb"};
                   2504:     $returnhash{'version'}=$version;
                   2505:     my $scope;
                   2506:     for ($scope=1;$scope<=$version;$scope++) {
                   2507:       my $vkeys=$hash{"$scope:keys:$symb"};
                   2508:       my @keys=split(/:/,$vkeys);
                   2509:       my $key;
                   2510:       $returnhash{"$scope:keys"}=$vkeys;
                   2511:       foreach $key (@keys) {
1.591     albertel 2512: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   2513: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 2514:       }
                   2515:     }
1.168     albertel 2516:     if (!(untie(%hash))) {
                   2517:       return "error:$!";
                   2518:     }
                   2519:   } else {
                   2520:     return "error:$!";
                   2521:   }
                   2522:   return %returnhash;
1.167     albertel 2523: }
                   2524: 
1.9       www      2525: # ----------------------------------------------------------------------- Store
                   2526: 
                   2527: sub store {
1.124     www      2528:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2529:     my $home='';
                   2530: 
1.168     albertel 2531:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2532: 
1.213     www      2533:     $symb=&symbclean($symb);
1.122     albertel 2534:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      2535: 
1.620     albertel 2536:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2537:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      2538: 
                   2539:     &devalidate($symb,$stuname,$domain);
1.109     www      2540: 
                   2541:     $symb=escape($symb);
1.187     www      2542:     if (!$namespace) { 
1.620     albertel 2543:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      2544:           return ''; 
                   2545:        } 
                   2546:     }
1.620     albertel 2547:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      2548: 
                   2549:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   2550:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   2551: 
1.12      www      2552:     my $namevalue='';
1.191     harris41 2553:     foreach (keys %$storehash) {
1.591     albertel 2554:         $namevalue.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
1.191     harris41 2555:     }
1.12      www      2556:     $namevalue=~s/\&$//;
1.187     www      2557:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      2558:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      2559: }
                   2560: 
1.47      www      2561: # -------------------------------------------------------------- Critical Store
                   2562: 
                   2563: sub cstore {
1.124     www      2564:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2565:     my $home='';
                   2566: 
1.168     albertel 2567:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2568: 
1.213     www      2569:     $symb=&symbclean($symb);
1.122     albertel 2570:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      2571: 
1.620     albertel 2572:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2573:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      2574: 
                   2575:     &devalidate($symb,$stuname,$domain);
1.109     www      2576: 
                   2577:     $symb=escape($symb);
1.187     www      2578:     if (!$namespace) { 
1.620     albertel 2579:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      2580:           return ''; 
                   2581:        } 
                   2582:     }
1.620     albertel 2583:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      2584: 
                   2585:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   2586:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 2587: 
1.47      www      2588:     my $namevalue='';
1.191     harris41 2589:     foreach (keys %$storehash) {
1.591     albertel 2590:         $namevalue.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
1.191     harris41 2591:     }
1.47      www      2592:     $namevalue=~s/\&$//;
1.187     www      2593:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      2594:     return critical
                   2595:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      2596: }
                   2597: 
1.9       www      2598: # --------------------------------------------------------------------- Restore
                   2599: 
                   2600: sub restore {
1.124     www      2601:     my ($symb,$namespace,$domain,$stuname) = @_;
                   2602:     my $home='';
                   2603: 
1.168     albertel 2604:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2605: 
1.122     albertel 2606:     if (!$symb) {
                   2607:       unless ($symb=escape(&symbread())) { return ''; }
                   2608:     } else {
1.213     www      2609:       $symb=&escape(&symbclean($symb));
1.122     albertel 2610:     }
1.188     www      2611:     if (!$namespace) { 
1.620     albertel 2612:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      2613:           return ''; 
                   2614:        } 
                   2615:     }
1.620     albertel 2616:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2617:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   2618:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 2619:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   2620: 
1.12      www      2621:     my %returnhash=();
1.191     harris41 2622:     foreach (split(/\&/,$answer)) {
1.12      www      2623: 	my ($name,$value)=split(/\=/,$_);
1.591     albertel 2624:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 2625:     }
1.75      www      2626:     my $version;
                   2627:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.191     harris41 2628:        foreach (split(/\:/,$returnhash{$version.':keys'})) {
1.75      www      2629:           $returnhash{$_}=$returnhash{$version.':'.$_};
1.191     harris41 2630:        }
1.75      www      2631:     }
1.13      www      2632:     return %returnhash;
1.34      www      2633: }
                   2634: 
                   2635: # ---------------------------------------------------------- Course Description
                   2636: 
                   2637: sub coursedescription {
1.731     albertel 2638:     my ($courseid,$args)=@_;
1.34      www      2639:     $courseid=~s/^\///;
1.49      www      2640:     $courseid=~s/\_/\//g;
1.34      www      2641:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 2642:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 2643:     my $normalid=$cdomain.'_'.$cnum;
                   2644:     # need to always cache even if we get errors otherwise we keep 
                   2645:     # trying and trying and trying to get the course description.
                   2646:     my %envhash=();
                   2647:     my %returnhash=();
1.731     albertel 2648:     
                   2649:     my $expiretime=600;
                   2650:     if ($env{'request.course.id'} eq $normalid) {
                   2651: 	$expiretime=120;
                   2652:     }
                   2653: 
                   2654:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   2655:     if (!$args->{'freshen_cache'}
                   2656: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   2657: 	foreach my $key (keys(%env)) {
                   2658: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   2659: 	    my ($setting) = $1;
                   2660: 	    $returnhash{$setting} = $env{$key};
                   2661: 	}
                   2662: 	return %returnhash;
                   2663:     }
                   2664: 
                   2665:     # get the data agin
                   2666:     if (!$args->{'one_time'}) {
                   2667: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   2668:     }
1.34      www      2669:     if ($chome ne 'no_host') {
1.302     albertel 2670:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 2671:        if (!exists($returnhash{'con_lost'})) {
                   2672:            $returnhash{'home'}= $chome;
                   2673: 	   $returnhash{'domain'} = $cdomain;
                   2674: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  2675:            if (!defined($returnhash{'type'})) {
                   2676:                $returnhash{'type'} = 'Course';
                   2677:            }
1.130     albertel 2678:            while (my ($name,$value) = each %returnhash) {
1.53      www      2679:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 2680:            }
1.270     www      2681:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      2682:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 2683: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      2684:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   2685:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   2686:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      2687:        }
                   2688:     }
1.731     albertel 2689:     if (!$args->{'one_time'}) {
                   2690: 	&appenv(%envhash);
                   2691:     }
1.302     albertel 2692:     return %returnhash;
1.461     www      2693: }
                   2694: 
                   2695: # -------------------------------------------------See if a user is privileged
                   2696: 
                   2697: sub privileged {
                   2698:     my ($username,$domain)=@_;
                   2699:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   2700: 			&homeserver($username,$domain));
                   2701:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
                   2702:     my $now=time;
                   2703:     if ($rolesdump ne '') {
                   2704:         foreach (split(/&/,$rolesdump)) {
1.586     albertel 2705: 	    if ($_!~/^rolesdef_/) {
1.461     www      2706: 		my ($area,$role)=split(/=/,$_);
                   2707: 		$area=~s/\_\w\w$//;
                   2708: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   2709: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   2710: 		    my $active=1;
                   2711: 		    if ($tend) {
                   2712: 			if ($tend<$now) { $active=0; }
                   2713: 		    }
                   2714: 		    if ($tstart) {
                   2715: 			if ($tstart>$now) { $active=0; }
                   2716: 		    }
                   2717: 		    if ($active) { return 1; }
                   2718: 		}
                   2719: 	    }
                   2720: 	}
                   2721:     }
                   2722:     return 0;
1.9       www      2723: }
1.1       albertel 2724: 
1.103     harris41 2725: # -------------------------------------------------------- Get user privileges
1.11      www      2726: 
                   2727: sub rolesinit {
                   2728:     my ($domain,$username,$authhost)=@_;
                   2729:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.12      www      2730:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
1.11      www      2731:     my %allroles=();
1.678     raeburn  2732:     my %allgroups=();   
1.11      www      2733:     my $now=time;
1.743     albertel 2734:     my %userroles = ('user.login.time' => $now);
1.678     raeburn  2735:     my $group_privs;
1.11      www      2736: 
                   2737:     if ($rolesdump ne '') {
1.191     harris41 2738:         foreach (split(/&/,$rolesdump)) {
1.586     albertel 2739: 	  if ($_!~/^rolesdef_/) {
1.11      www      2740:             my ($area,$role)=split(/=/,$_);
1.587     albertel 2741: 	    $area=~s/\_\w\w$//;
1.678     raeburn  2742:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 2743: 	    if ($role=~/^cr/) { 
1.655     albertel 2744: 		if ($role=~m|^(cr/\w+/\w+/[a-zA-Z0-9]+)_(.*)$|) {
                   2745: 		    ($trole,my $trest)=($role=~m|^(cr/\w+/\w+/[a-zA-Z0-9]+)_(.*)$|);
                   2746: 		    ($tend,$tstart)=split('_',$trest);
                   2747: 		} else {
                   2748: 		    $trole=$role;
                   2749: 		}
1.678     raeburn  2750:             } elsif ($role =~ m|^gr/|) {
                   2751:                 ($trole,$tend,$tstart) = split(/_/,$role);
                   2752:                 ($trole,$group_privs) = split(/\//,$trole);
                   2753:                 $group_privs = &unescape($group_privs);
1.587     albertel 2754: 	    } else {
                   2755: 		($trole,$tend,$tstart)=split(/_/,$role);
                   2756: 	    }
1.743     albertel 2757: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   2758: 					 $username);
                   2759: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  2760:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   2761:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      2762:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 2763: 		my $spec=$trole.'.'.$area;
                   2764: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   2765: 		if ($trole =~ /^cr\//) {
1.567     raeburn  2766:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  2767:                 } elsif ($trole eq 'gr') {
                   2768:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 2769: 		} else {
1.567     raeburn  2770:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 2771: 		}
1.12      www      2772:             }
1.662     raeburn  2773:           }
1.191     harris41 2774:         }
1.743     albertel 2775:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   2776:         $userroles{'user.adv'}    = $adv;
                   2777: 	$userroles{'user.author'} = $author;
1.620     albertel 2778:         $env{'user.adv'}=$adv;
1.11      www      2779:     }
1.743     albertel 2780:     return \%userroles;  
1.11      www      2781: }
                   2782: 
1.567     raeburn  2783: sub set_arearole {
                   2784:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   2785: # log the associated role with the area
                   2786:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 2787:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  2788: }
                   2789: 
                   2790: sub custom_roleprivs {
                   2791:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   2792:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   2793:     my $homsvr=homeserver($rauthor,$rdomain);
                   2794:     if ($hostname{$homsvr} ne '') {
                   2795:         my ($rdummy,$roledef)=
                   2796:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   2797:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   2798:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   2799:             if (defined($syspriv)) {
                   2800:                 $$allroles{'cm./'}.=':'.$syspriv;
                   2801:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   2802:             }
                   2803:             if ($tdomain ne '') {
                   2804:                 if (defined($dompriv)) {
                   2805:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   2806:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   2807:                 }
                   2808:                 if (($trest ne '') && (defined($coursepriv))) {
                   2809:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   2810:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   2811:                 }
                   2812:             }
                   2813:         }
                   2814:     }
                   2815: }
                   2816: 
1.678     raeburn  2817: sub group_roleprivs {
                   2818:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   2819:     my $access = 1;
                   2820:     my $now = time;
                   2821:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   2822:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   2823:     if ($access) {
                   2824:         my ($course,$group) = ($area =~ m|(/\w+/\w+)/([^/]+)$|);
                   2825:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   2826:     }
                   2827: }
1.567     raeburn  2828: 
                   2829: sub standard_roleprivs {
                   2830:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   2831:     if (defined($pr{$trole.':s'})) {
                   2832:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   2833:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   2834:     }
                   2835:     if ($tdomain ne '') {
                   2836:         if (defined($pr{$trole.':d'})) {
                   2837:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   2838:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   2839:         }
                   2840:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   2841:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   2842:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   2843:         }
                   2844:     }
                   2845: }
                   2846: 
                   2847: sub set_userprivs {
1.678     raeburn  2848:     my ($userroles,$allroles,$allgroups) = @_; 
1.567     raeburn  2849:     my $author=0;
                   2850:     my $adv=0;
1.678     raeburn  2851:     my %grouproles = ();
                   2852:     if (keys(%{$allgroups}) > 0) {
                   2853:         foreach my $role (keys %{$allroles}) {
1.681     raeburn  2854:             my ($trole,$area,$sec,$extendedarea);
1.771     raeburn  2855:             if ($role =~ m-^(\w+|cr/\w+/\w+/\w+)\.(/\w+/\w+)(/?\w*)-) {
1.678     raeburn  2856:                 $trole = $1;
                   2857:                 $area = $2;
1.681     raeburn  2858:                 $sec = $3;
                   2859:                 $extendedarea = $area.$sec;
                   2860:                 if (exists($$allgroups{$area})) {
                   2861:                     foreach my $group (keys(%{$$allgroups{$area}})) {
                   2862:                         my $spec = $trole.'.'.$extendedarea;
                   2863:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
                   2864:                                                 $$allgroups{$area}{$group};
1.678     raeburn  2865:                     }
                   2866:                 }
                   2867:             }
                   2868:         }
                   2869:     }
                   2870:     foreach (keys(%grouproles)) {
                   2871:         $$allroles{$_} = $grouproles{$_};
                   2872:     }
1.567     raeburn  2873:     foreach (keys %{$allroles}) {
                   2874:         my %thesepriv=();
                   2875:         if (($_=~/^au/) || ($_=~/^ca/)) { $author=1; }
                   2876:         foreach (split(/:/,$$allroles{$_})) {
                   2877:             if ($_ ne '') {
                   2878:                 my ($privilege,$restrictions)=split(/&/,$_);
                   2879:                 if ($restrictions eq '') {
                   2880:                     $thesepriv{$privilege}='F';
                   2881:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   2882:                     $thesepriv{$privilege}.=$restrictions;
                   2883:                 }
                   2884:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   2885:             }
                   2886:         }
                   2887:         my $thesestr='';
                   2888:         foreach (keys %thesepriv) { $thesestr.=':'.$_.'&'.$thesepriv{$_}; }
1.743     albertel 2889:         $userroles->{'user.priv.'.$_} = $thesestr;
1.567     raeburn  2890:     }
                   2891:     return ($author,$adv);
                   2892: }
                   2893: 
1.12      www      2894: # --------------------------------------------------------------- get interface
                   2895: 
                   2896: sub get {
1.131     albertel 2897:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      2898:    my $items='';
1.191     harris41 2899:    foreach (@$storearr) {
1.12      www      2900:        $items.=escape($_).'&';
1.191     harris41 2901:    }
1.12      www      2902:    $items=~s/\&$//;
1.620     albertel 2903:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2904:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 2905:    my $uhome=&homeserver($uname,$udomain);
                   2906: 
1.133     albertel 2907:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      2908:    my @pairs=split(/\&/,$rep);
1.273     albertel 2909:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   2910:      return @pairs;
                   2911:    }
1.15      www      2912:    my %returnhash=();
1.42      www      2913:    my $i=0;
1.191     harris41 2914:    foreach (@$storearr) {
1.557     albertel 2915:       $returnhash{$_}=&thaw_unescape($pairs[$i]);
1.42      www      2916:       $i++;
1.191     harris41 2917:    }
1.15      www      2918:    return %returnhash;
1.27      www      2919: }
                   2920: 
                   2921: # --------------------------------------------------------------- del interface
                   2922: 
                   2923: sub del {
1.133     albertel 2924:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      2925:    my $items='';
1.191     harris41 2926:    foreach (@$storearr) {
1.27      www      2927:        $items.=escape($_).'&';
1.191     harris41 2928:    }
1.27      www      2929:    $items=~s/\&$//;
1.620     albertel 2930:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2931:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 2932:    my $uhome=&homeserver($uname,$udomain);
                   2933: 
                   2934:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      2935: }
                   2936: 
                   2937: # -------------------------------------------------------------- dump interface
                   2938: 
                   2939: sub dump {
1.755     albertel 2940:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   2941:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2942:     if (!$uname) { $uname=$env{'user.name'}; }
                   2943:     my $uhome=&homeserver($uname,$udomain);
                   2944:     if ($regexp) {
                   2945: 	$regexp=&escape($regexp);
                   2946:     } else {
                   2947: 	$regexp='.';
                   2948:     }
                   2949:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   2950:     my @pairs=split(/\&/,$rep);
                   2951:     my %returnhash=();
                   2952:     foreach my $item (@pairs) {
                   2953: 	my ($key,$value)=split(/=/,$item,2);
                   2954: 	$key = &unescape($key);
                   2955: 	next if ($key =~ /^error: 2 /);
                   2956: 	$returnhash{$key}=&thaw_unescape($value);
                   2957:     }
                   2958:     return %returnhash;
1.407     www      2959: }
                   2960: 
1.717     albertel 2961: # --------------------------------------------------------- dumpstore interface
                   2962: 
                   2963: sub dumpstore {
                   2964:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   2965:    return &dump($namespace,$udomain,$uname,$regexp,$range);
                   2966: }
                   2967: 
1.407     www      2968: # -------------------------------------------------------------- keys interface
                   2969: 
                   2970: sub getkeys {
                   2971:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 2972:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2973:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      2974:    my $uhome=&homeserver($uname,$udomain);
                   2975:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   2976:    my @keyarray=();
                   2977:    foreach (split(/\&/,$rep)) {
                   2978:       push (@keyarray,&unescape($_));
                   2979:    }
                   2980:    return @keyarray;
1.318     matthew  2981: }
                   2982: 
1.319     matthew  2983: # --------------------------------------------------------------- currentdump
                   2984: sub currentdump {
1.328     matthew  2985:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 2986:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   2987:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   2988:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  2989:    my $uhome = &homeserver($sname,$sdom);
                   2990:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  2991:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  2992:    #
1.318     matthew  2993:    my %returnhash=();
1.319     matthew  2994:    #
                   2995:    if ($rep eq "unknown_cmd") { 
                   2996:        # an old lond will not know currentdump
                   2997:        # Do a dump and make it look like a currentdump
1.326     matthew  2998:        my @tmp = &dump($courseid,$sdom,$sname,'.');
1.319     matthew  2999:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   3000:        my %hash = @tmp;
                   3001:        @tmp=();
1.424     matthew  3002:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  3003:    } else {
                   3004:        my @pairs=split(/\&/,$rep);
                   3005:        foreach (@pairs) {
                   3006:            my ($key,$value)=split(/=/,$_);
                   3007:            my ($symb,$param) = split(/:/,$key);
                   3008:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 3009:                                                         &thaw_unescape($value);
1.319     matthew  3010:        }
1.191     harris41 3011:    }
1.12      www      3012:    return %returnhash;
1.424     matthew  3013: }
                   3014: 
                   3015: sub convert_dump_to_currentdump{
                   3016:     my %hash = %{shift()};
                   3017:     my %returnhash;
                   3018:     # Code ripped from lond, essentially.  The only difference
                   3019:     # here is the unescaping done by lonnet::dump().  Conceivably
                   3020:     # we might run in to problems with parameter names =~ /^v\./
                   3021:     while (my ($key,$value) = each(%hash)) {
                   3022:         my ($v,$symb,$param) = split(/:/,$key);
                   3023:         next if ($v eq 'version' || $symb eq 'keys');
                   3024:         next if (exists($returnhash{$symb}) &&
                   3025:                  exists($returnhash{$symb}->{$param}) &&
                   3026:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   3027:         $returnhash{$symb}->{$param}=$value;
                   3028:         $returnhash{$symb}->{'v.'.$param}=$v;
                   3029:     }
                   3030:     #
                   3031:     # Remove all of the keys in the hashes which keep track of
                   3032:     # the version of the parameter.
                   3033:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   3034:         # use a foreach because we are going to delete from the hash.
                   3035:         foreach my $key (keys(%$param_hash)) {
                   3036:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   3037:         }
                   3038:     }
                   3039:     return \%returnhash;
1.12      www      3040: }
                   3041: 
1.627     albertel 3042: # ------------------------------------------------------ critical inc interface
                   3043: 
                   3044: sub cinc {
                   3045:     return &inc(@_,'critical');
                   3046: }
                   3047: 
1.449     matthew  3048: # --------------------------------------------------------------- inc interface
                   3049: 
                   3050: sub inc {
1.627     albertel 3051:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 3052:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3053:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  3054:     my $uhome=&homeserver($uname,$udomain);
                   3055:     my $items='';
                   3056:     if (! ref($store)) {
                   3057:         # got a single value, so use that instead
                   3058:         $items = &escape($store).'=&';
                   3059:     } elsif (ref($store) eq 'SCALAR') {
                   3060:         $items = &escape($$store).'=&';        
                   3061:     } elsif (ref($store) eq 'ARRAY') {
                   3062:         $items = join('=&',map {&escape($_);} @{$store});
                   3063:     } elsif (ref($store) eq 'HASH') {
                   3064:         while (my($key,$value) = each(%{$store})) {
                   3065:             $items.= &escape($key).'='.&escape($value).'&';
                   3066:         }
                   3067:     }
                   3068:     $items=~s/\&$//;
1.627     albertel 3069:     if ($critical) {
                   3070: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3071:     } else {
                   3072: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3073:     }
1.449     matthew  3074: }
                   3075: 
1.12      www      3076: # --------------------------------------------------------------- put interface
                   3077: 
                   3078: sub put {
1.134     albertel 3079:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3080:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3081:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3082:    my $uhome=&homeserver($uname,$udomain);
1.12      www      3083:    my $items='';
1.191     harris41 3084:    foreach (keys %$storehash) {
1.557     albertel 3085:        $items.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
1.191     harris41 3086:    }
1.12      www      3087:    $items=~s/\&$//;
1.134     albertel 3088:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      3089: }
                   3090: 
1.631     albertel 3091: # ------------------------------------------------------------ newput interface
                   3092: 
                   3093: sub newput {
                   3094:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   3095:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3096:    if (!$uname) { $uname=$env{'user.name'}; }
                   3097:    my $uhome=&homeserver($uname,$udomain);
                   3098:    my $items='';
                   3099:    foreach my $key (keys(%$storehash)) {
                   3100:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   3101:    }
                   3102:    $items=~s/\&$//;
                   3103:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   3104: }
                   3105: 
                   3106: # ---------------------------------------------------------  putstore interface
                   3107: 
1.524     raeburn  3108: sub putstore {
1.715     albertel 3109:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 3110:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3111:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  3112:    my $uhome=&homeserver($uname,$udomain);
                   3113:    my $items='';
1.715     albertel 3114:    foreach my $key (keys(%$storehash)) {
                   3115:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  3116:    }
1.715     albertel 3117:    $items=~s/\&$//;
1.716     albertel 3118:    my $esc_symb=&escape($symb);
                   3119:    my $esc_v=&escape($version);
1.715     albertel 3120:    my $reply =
1.716     albertel 3121:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 3122: 	      $uhome);
                   3123:    if ($reply eq 'unknown_cmd') {
1.716     albertel 3124:        # gfall back to way things use to be done
1.715     albertel 3125:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   3126: 			    $uname);
1.524     raeburn  3127:    }
1.715     albertel 3128:    return $reply;
                   3129: }
                   3130: 
                   3131: sub old_putstore {
1.716     albertel 3132:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   3133:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3134:     if (!$uname) { $uname=$env{'user.name'}; }
                   3135:     my $uhome=&homeserver($uname,$udomain);
                   3136:     my %newstorehash;
                   3137:     foreach (keys %$storehash) {
                   3138: 	my $key = $version.':'.&escape($symb).':'.$_;
                   3139: 	$newstorehash{$key} = $storehash->{$_};
                   3140:     }
                   3141:     my $items='';
                   3142:     my %allitems = ();
                   3143:     foreach (keys %newstorehash) {
                   3144: 	if ($_ =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
                   3145: 	    my $key = $1.':keys:'.$2;
                   3146: 	    $allitems{$key} .= $3.':';
                   3147: 	}
                   3148: 	$items.=$_.'='.&freeze_escape($newstorehash{$_}).'&';
                   3149:     }
                   3150:     foreach (keys %allitems) {
                   3151: 	$allitems{$_} =~ s/\:$//;
                   3152: 	$items.= $_.'='.$allitems{$_}.'&';
                   3153:     }
                   3154:     $items=~s/\&$//;
                   3155:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  3156: }
                   3157: 
1.47      www      3158: # ------------------------------------------------------ critical put interface
                   3159: 
                   3160: sub cput {
1.134     albertel 3161:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3162:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3163:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3164:    my $uhome=&homeserver($uname,$udomain);
1.47      www      3165:    my $items='';
1.191     harris41 3166:    foreach (keys %$storehash) {
1.715     albertel 3167:        $items.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
1.191     harris41 3168:    }
1.47      www      3169:    $items=~s/\&$//;
1.134     albertel 3170:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3171: }
                   3172: 
                   3173: # -------------------------------------------------------------- eget interface
                   3174: 
                   3175: sub eget {
1.133     albertel 3176:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3177:    my $items='';
1.191     harris41 3178:    foreach (@$storearr) {
1.12      www      3179:        $items.=escape($_).'&';
1.191     harris41 3180:    }
1.12      www      3181:    $items=~s/\&$//;
1.620     albertel 3182:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3183:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3184:    my $uhome=&homeserver($uname,$udomain);
                   3185:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3186:    my @pairs=split(/\&/,$rep);
                   3187:    my %returnhash=();
1.42      www      3188:    my $i=0;
1.191     harris41 3189:    foreach (@$storearr) {
1.557     albertel 3190:       $returnhash{$_}=&thaw_unescape($pairs[$i]);
1.42      www      3191:       $i++;
1.191     harris41 3192:    }
1.12      www      3193:    return %returnhash;
                   3194: }
                   3195: 
1.667     albertel 3196: # ------------------------------------------------------------ tmpput interface
                   3197: sub tmpput {
                   3198:     my ($storehash,$server)=@_;
                   3199:     my $items='';
                   3200:     foreach (keys(%$storehash)) {
                   3201: 	$items.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
                   3202:     }
                   3203:     $items=~s/\&$//;
                   3204:     return &reply("tmpput:$items",$server);
                   3205: }
                   3206: 
                   3207: # ------------------------------------------------------------ tmpget interface
                   3208: sub tmpget {
1.688     albertel 3209:     my ($token,$server)=@_;
                   3210:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3211:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 3212:     my %returnhash;
                   3213:     foreach my $item (split(/\&/,$rep)) {
                   3214: 	my ($key,$value)=split(/=/,$item);
                   3215: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   3216:     }
                   3217:     return %returnhash;
                   3218: }
                   3219: 
1.688     albertel 3220: # ------------------------------------------------------------ tmpget interface
                   3221: sub tmpdel {
                   3222:     my ($token,$server)=@_;
                   3223:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3224:     return &reply("tmpdel:$token",$server);
                   3225: }
                   3226: 
1.765     albertel 3227: # -------------------------------------------------- portfolio access checking
                   3228: 
                   3229: sub portfolio_access {
1.766     albertel 3230:     my ($requrl) = @_;
1.765     albertel 3231:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   3232:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
                   3233:     if ($result eq 'ok') {
1.766     albertel 3234:        return 'F';
1.765     albertel 3235:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 3236:        return 'A';
1.765     albertel 3237:     }
1.766     albertel 3238:     return '';
1.765     albertel 3239: }
                   3240: 
                   3241: sub get_portfolio_access {
1.767     albertel 3242:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   3243: 
                   3244:     if (!ref($access_hash)) {
                   3245: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   3246: 	my %access_controls = &get_access_controls($current_perms,$group,
                   3247: 						   $file_name);
                   3248: 	$access_hash = $access_controls{$file_name};
                   3249:     }
                   3250: 
1.765     albertel 3251:     my ($public,$guest,@domains,@users,@courses,@groups);
                   3252:     my $now = time;
                   3253:     if (ref($access_hash) eq 'HASH') {
                   3254:         foreach my $key (keys(%{$access_hash})) {
                   3255:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   3256:             if ($start > $now) {
                   3257:                 next;
                   3258:             }
                   3259:             if ($end && $end<$now) {
                   3260:                 next;
                   3261:             }
                   3262:             if ($scope eq 'public') {
                   3263:                 $public = $key;
                   3264:                 last;
                   3265:             } elsif ($scope eq 'guest') {
                   3266:                 $guest = $key;
                   3267:             } elsif ($scope eq 'domains') {
                   3268:                 push(@domains,$key);
                   3269:             } elsif ($scope eq 'users') {
                   3270:                 push(@users,$key);
                   3271:             } elsif ($scope eq 'course') {
                   3272:                 push(@courses,$key);
                   3273:             } elsif ($scope eq 'group') {
                   3274:                 push(@groups,$key);
                   3275:             }
                   3276:         }
                   3277:         if ($public) {
                   3278:             return 'ok';
                   3279:         }
                   3280:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   3281:             if ($guest) {
                   3282:                 return $guest;
                   3283:             }
                   3284:         } else {
                   3285:             if (@domains > 0) {
                   3286:                 foreach my $domkey (@domains) {
                   3287:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   3288:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   3289:                             return 'ok';
                   3290:                         }
                   3291:                     }
                   3292:                 }
                   3293:             }
                   3294:             if (@users > 0) {
                   3295:                 foreach my $userkey (@users) {
                   3296:                     if (exists($access_hash->{$userkey}{'users'}{$env{'user.name'}.':'.$env{'user.domain'}})) {
                   3297:                         return 'ok';
                   3298:                     }
                   3299:                 }
                   3300:             }
                   3301:             my %roleshash;
                   3302:             my @courses_and_groups = @courses;
                   3303:             push(@courses_and_groups,@groups); 
                   3304:             if (@courses_and_groups > 0) {
                   3305:                 my (%allgroups,%allroles); 
                   3306:                 my ($start,$end,$role,$sec,$group);
                   3307:                 foreach my $envkey (%env) {
                   3308:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./([^/]+)/([^/]+)/?([^/]*)$-) {
                   3309:                         my $cid = $2.'_'.$3; 
                   3310:                         if ($1 eq 'gr') {
                   3311:                             $group = $4;
                   3312:                             $allgroups{$cid}{$group} = $env{$envkey};
                   3313:                         } else {
                   3314:                             if ($4 eq '') {
                   3315:                                 $sec = 'none';
                   3316:                             } else {
                   3317:                                 $sec = $4;
                   3318:                             }
                   3319:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   3320:                         }
                   3321:                     } elsif ($envkey =~ m-^user\.role\./cr/(\w+/\w+/\w*)./([^/]+)/([^/]+)/?([^/]*)$-) {
                   3322:                         my $cid = $2.'_'.$3;
                   3323:                         if ($4 eq '') {
                   3324:                             $sec = 'none';
                   3325:                         } else {
                   3326:                             $sec = $4;
                   3327:                         }
                   3328:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   3329:                     }
                   3330:                 }
                   3331:                 if (keys(%allroles) == 0) {
                   3332:                     return;
                   3333:                 }
                   3334:                 foreach my $key (@courses_and_groups) {
                   3335:                     my %content = %{$$access_hash{$key}};
                   3336:                     my $cnum = $content{'number'};
                   3337:                     my $cdom = $content{'domain'};
                   3338:                     my $cid = $cdom.'_'.$cnum;
                   3339:                     if (!exists($allroles{$cid})) {
                   3340:                         next;
                   3341:                     }    
                   3342:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   3343:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   3344:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   3345:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   3346:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   3347:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   3348:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   3349:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   3350:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   3351:                                         if (grep/^all$/,@sections) {
                   3352:                                             return 'ok';
                   3353:                                         } else {
                   3354:                                             if (grep/^$sec$/,@sections) {
                   3355:                                                 return 'ok';
                   3356:                                             }
                   3357:                                         }
                   3358:                                     }
                   3359:                                 }
                   3360:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   3361:                                     if (grep/^none$/,@groups) {
                   3362:                                         return 'ok';
                   3363:                                     }
                   3364:                                 } else {
                   3365:                                     if (grep/^all$/,@groups) {
                   3366:                                         return 'ok';
                   3367:                                     } 
                   3368:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   3369:                                         if (grep/^$group$/,@groups) {
                   3370:                                             return 'ok';
                   3371:                                         }
                   3372:                                     }
                   3373:                                 } 
                   3374:                             }
                   3375:                         }
                   3376:                     }
                   3377:                 }
                   3378:             }
                   3379:             if ($guest) {
                   3380:                 return $guest;
                   3381:             }
                   3382:         }
                   3383:     }
                   3384:     return;
                   3385: }
                   3386: 
                   3387: sub course_group_datechecker {
                   3388:     my ($dates,$now,$status) = @_;
                   3389:     my ($start,$end) = split(/\./,$dates);
                   3390:     if (!$start && !$end) {
                   3391:         return 'ok';
                   3392:     }
                   3393:     if (grep/^active$/,@{$status}) {
                   3394:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   3395:             return 'ok';
                   3396:         }
                   3397:     }
                   3398:     if (grep/^previous$/,@{$status}) {
                   3399:         if ($end > $now ) {
                   3400:             return 'ok';
                   3401:         }
                   3402:     }
                   3403:     if (grep/^future$/,@{$status}) {
                   3404:         if ($start > $now) {
                   3405:             return 'ok';
                   3406:         }
                   3407:     }
                   3408:     return; 
                   3409: }
                   3410: 
                   3411: sub parse_portfolio_url {
                   3412:     my ($url) = @_;
                   3413: 
                   3414:     my ($type,$udom,$unum,$group,$file_name);
                   3415:     
                   3416:     if ($url =~  m-^/*uploaded/([^/]+)/([^/]+)/portfolio(/.+)$-) {
                   3417: 	$type = 1;
                   3418:         $udom = $1;
                   3419:         $unum = $2;
                   3420:         $file_name = $3;
                   3421:     } elsif ($url =~ m-^/*uploaded/([^/]+)/([^/]+)/groups/([^/]+)/portfolio/(.+)$-) {
                   3422: 	$type = 2;
                   3423:         $udom = $1;
                   3424:         $unum = $2;
                   3425:         $group = $3;
                   3426:         $file_name = $3.'/'.$4;
                   3427:     }
                   3428:     if (wantarray) {
                   3429: 	return ($type,$udom,$unum,$file_name,$group);
                   3430:     }
                   3431:     return $type;
                   3432: }
                   3433: 
                   3434: sub is_portfolio_url {
                   3435:     my ($url) = @_;
                   3436:     return scalar(&parse_portfolio_url($url));
                   3437: }
                   3438: 
1.341     www      3439: # ---------------------------------------------- Custom access rule evaluation
                   3440: 
                   3441: sub customaccess {
                   3442:     my ($priv,$uri)=@_;
1.620     albertel 3443:     my ($urole,$urealm)=split(/\./,$env{'request.role'});
1.343     www      3444:     $urealm=~s/^\W//;
                   3445:     my ($udom,$ucrs,$usec)=split(/\//,$urealm);
1.341     www      3446:     my $access=0;
                   3447:     foreach (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.342     www      3448: 	my ($effect,$realm,$role)=split(/\:/,$_);
1.343     www      3449:         if ($role) {
                   3450: 	   if ($role ne $urole) { next; }
                   3451:         }
                   3452:         foreach (split(/\s*\,\s*/,$realm)) {
                   3453:             my ($tdom,$tcrs,$tsec)=split(/\_/,$_);
                   3454:             if ($tdom) {
                   3455: 		if ($tdom ne $udom) { next; }
                   3456:             }
                   3457:             if ($tcrs) {
                   3458: 		if ($tcrs ne $ucrs) { next; }
                   3459:             }
                   3460:             if ($tsec) {
                   3461: 		if ($tsec ne $usec) { next; }
                   3462:             }
                   3463:             $access=($effect eq 'allow');
                   3464:             last;
1.342     www      3465:         }
1.402     bowersj2 3466: 	if ($realm eq '' && $role eq '') {
                   3467:             $access=($effect eq 'allow');
                   3468: 	}
1.341     www      3469:     }
                   3470:     return $access;
                   3471: }
                   3472: 
1.103     harris41 3473: # ------------------------------------------------- Check for a user privilege
1.12      www      3474: 
                   3475: sub allowed {
1.579     albertel 3476:     my ($priv,$uri,$symb)=@_;
1.705     albertel 3477:     my $ver_orguri=$uri;
1.439     www      3478:     $uri=&deversion($uri);
1.152     www      3479:     my $orguri=$uri;
1.52      www      3480:     $uri=&declutter($uri);
1.545     banghart 3481:     
1.620     albertel 3482:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      3483: # Free bre access to adm and meta resources
1.775     albertel 3484:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 3485: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   3486: 	&& ($priv eq 'bre')) {
1.14      www      3487: 	return 'F';
1.159     www      3488:     }
                   3489: 
1.545     banghart 3490: # Free bre access to user's own portfolio contents
1.714     raeburn  3491:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  3492:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  3493: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.545     banghart 3494:         return 'F';
                   3495:     }
                   3496: 
1.762     raeburn  3497: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  3498:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   3499:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   3500:         if (exists($env{'request.course.id'})) {
                   3501:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3502:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3503:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   3504:                 my $courseprivid=$env{'request.course.id'};
                   3505:                 $courseprivid=~s/\_/\//;
                   3506:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   3507:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   3508:                     return $1; 
1.762     raeburn  3509:                 } else {
                   3510:                     if ($env{'request.course.sec'}) {
                   3511:                         $courseprivid.='/'.$env{'request.course.sec'};
                   3512:                     }
                   3513:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   3514:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   3515:                         return $2;
                   3516:                     }
1.714     raeburn  3517:                 }
                   3518:             }
                   3519:         }
                   3520:     }
                   3521: 
1.159     www      3522: # Free bre to public access
                   3523: 
                   3524:     if ($priv eq 'bre') {
1.238     www      3525:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 3526: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      3527:            return 'F'; 
                   3528:         }
1.238     www      3529:         if ($copyright eq 'priv') {
                   3530:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 3531: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      3532: 		return '';
                   3533:             }
                   3534:         }
                   3535:         if ($copyright eq 'domain') {
                   3536:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 3537: 	    unless (($env{'user.domain'} eq $1) ||
                   3538:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      3539: 		return '';
                   3540:             }
1.262     matthew  3541:         }
1.620     albertel 3542:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  3543:             # Library role, so allow browsing of resources in this domain.
                   3544:             return 'F';
1.238     www      3545:         }
1.341     www      3546:         if ($copyright eq 'custom') {
                   3547: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   3548:         }
1.14      www      3549:     }
1.264     matthew  3550:     # Domain coordinator is trying to create a course
1.620     albertel 3551:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  3552:         # uri is the requested domain in this case.
                   3553:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  3554:         # a role of dc for the domain in question.
1.620     albertel 3555:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  3556:     }
1.29      www      3557: 
1.52      www      3558:     my $thisallowed='';
                   3559:     my $statecond=0;
                   3560:     my $courseprivid='';
                   3561: 
                   3562: # Course
                   3563: 
1.620     albertel 3564:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3565:        $thisallowed.=$1;
                   3566:     }
1.29      www      3567: 
1.52      www      3568: # Domain
                   3569: 
1.620     albertel 3570:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 3571:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      3572:        $thisallowed.=$1;
                   3573:     }
1.52      www      3574: 
                   3575: # Course: uri itself is a course
1.66      www      3576:     my $courseuri=$uri;
                   3577:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      3578:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      3579: 
1.620     albertel 3580:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 3581:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      3582:        $thisallowed.=$1;
                   3583:     }
1.29      www      3584: 
1.665     albertel 3585: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 3586: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 3587:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 3588: 	$thisallowed='';
1.671     raeburn  3589:         my ($match)=&is_on_map($uri);
                   3590:         if ($match) {
                   3591:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   3592:                   =~/\Q$priv\E\&([^\:]*)/) {
                   3593:                 $thisallowed.=$1;
                   3594:             }
                   3595:         } else {
1.705     albertel 3596:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  3597:             if ($refuri) {
                   3598:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  3599:                     $thisallowed='F';
1.671     raeburn  3600:                 } else {
                   3601:                     $refuri=&declutter($refuri);
                   3602:                     my ($match) = &is_on_map($refuri);
                   3603:                     if ($match) {
                   3604:                         $thisallowed='F';
                   3605:                     }
1.669     raeburn  3606:                 }
1.671     raeburn  3607:             }
                   3608:         }
1.314     www      3609:     }
1.492     albertel 3610: 
1.766     albertel 3611:     if ($priv eq 'bre'
                   3612: 	&& $thisallowed ne 'F' 
                   3613: 	&& $thisallowed ne '2'
                   3614: 	&& &is_portfolio_url($uri)) {
                   3615: 	$thisallowed = &portfolio_access($uri);
                   3616:     }
                   3617:     
1.52      www      3618: # Full access at system, domain or course-wide level? Exit.
1.29      www      3619: 
                   3620:     if ($thisallowed=~/F/) {
                   3621: 	return 'F';
                   3622:     }
                   3623: 
1.52      www      3624: # If this is generating or modifying users, exit with special codes
1.29      www      3625: 
1.643     www      3626:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   3627: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 3628: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      3629: # no author name given, so this just checks on the general right to make a co-author in this domain
                   3630: 	    unless ($auname) { return $thisallowed; }
                   3631: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 3632: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   3633: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   3634: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   3635: 	}
1.52      www      3636: 	return $thisallowed;
                   3637:     }
                   3638: #
1.103     harris41 3639: # Gathered so far: system, domain and course wide privileges
1.52      www      3640: #
                   3641: # Course: See if uri or referer is an individual resource that is part of 
                   3642: # the course
                   3643: 
1.620     albertel 3644:     if ($env{'request.course.id'}) {
1.232     www      3645: 
1.620     albertel 3646:        $courseprivid=$env{'request.course.id'};
                   3647:        if ($env{'request.course.sec'}) {
                   3648:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      3649:        }
                   3650:        $courseprivid=~s/\_/\//;
                   3651:        my $checkreferer=1;
1.232     www      3652:        my ($match,$cond)=&is_on_map($uri);
                   3653:        if ($match) {
                   3654:            $statecond=$cond;
1.620     albertel 3655:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 3656:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3657:                $thisallowed.=$1;
                   3658:                $checkreferer=0;
                   3659:            }
1.29      www      3660:        }
1.83      www      3661:        
1.148     www      3662:        if ($checkreferer) {
1.620     albertel 3663: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      3664:             unless ($refuri) {
1.620     albertel 3665:                 foreach (keys %env) {
1.148     www      3666: 		    if ($_=~/^httpref\..*\*/) {
                   3667: 			my $pattern=$_;
1.156     www      3668:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      3669:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   3670:                         $pattern=~s/\//\\\//g;
1.152     www      3671:                         if ($orguri=~/$pattern/) {
1.620     albertel 3672: 			    $refuri=$env{$_};
1.148     www      3673:                         }
                   3674:                     }
1.191     harris41 3675:                 }
1.148     www      3676:             }
1.232     www      3677: 
1.148     www      3678:          if ($refuri) { 
1.152     www      3679: 	  $refuri=&declutter($refuri);
1.232     www      3680:           my ($match,$cond)=&is_on_map($refuri);
                   3681:             if ($match) {
                   3682:               my $refstatecond=$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;
1.53      www      3686:                   $uri=$refuri;
                   3687:                   $statecond=$refstatecond;
1.52      www      3688:               }
                   3689:           }
1.148     www      3690:         }
1.29      www      3691:        }
1.52      www      3692:    }
1.29      www      3693: 
1.52      www      3694: #
1.103     harris41 3695: # Gathered now: all privileges that could apply, and condition number
1.52      www      3696: # 
                   3697: #
                   3698: # Full or no access?
                   3699: #
1.29      www      3700: 
1.52      www      3701:     if ($thisallowed=~/F/) {
                   3702: 	return 'F';
                   3703:     }
1.29      www      3704: 
1.52      www      3705:     unless ($thisallowed) {
                   3706:         return '';
                   3707:     }
1.29      www      3708: 
1.52      www      3709: # Restrictions exist, deal with them
                   3710: #
                   3711: #   C:according to course preferences
                   3712: #   R:according to resource settings
                   3713: #   L:unless locked
                   3714: #   X:according to user session state
                   3715: #
                   3716: 
                   3717: # Possibly locked functionality, check all courses
1.54      www      3718: # Locks might take effect only after 10 minutes cache expiration for other
                   3719: # courses, and 2 minutes for current course
1.52      www      3720: 
                   3721:     my $envkey;
                   3722:     if ($thisallowed=~/L/) {
1.620     albertel 3723:         foreach $envkey (keys %env) {
1.54      www      3724:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   3725:                my $courseid=$2;
                   3726:                my $roleid=$1.'.'.$2;
1.92      www      3727:                $courseid=~s/^\///;
1.54      www      3728:                my $expiretime=600;
1.620     albertel 3729:                if ($env{'request.role'} eq $roleid) {
1.54      www      3730: 		  $expiretime=120;
                   3731:                }
                   3732: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   3733:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 3734:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 3735: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      3736:                }
1.620     albertel 3737:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   3738:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   3739: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   3740:                        &log($env{'user.domain'},$env{'user.name'},
                   3741:                             $env{'user.home'},
1.57      www      3742:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      3743:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 3744:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      3745: 		       return '';
                   3746:                    }
                   3747:                }
1.620     albertel 3748:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   3749:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   3750: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   3751:                        &log($env{'user.domain'},$env{'user.name'},
                   3752:                             $env{'user.home'},
1.57      www      3753:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      3754:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 3755:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      3756: 		       return '';
                   3757:                    }
                   3758:                }
                   3759: 	   }
1.29      www      3760:        }
1.52      www      3761:     }
                   3762:    
                   3763: #
                   3764: # Rest of the restrictions depend on selected course
                   3765: #
                   3766: 
1.620     albertel 3767:     unless ($env{'request.course.id'}) {
1.766     albertel 3768: 	if ($thisallowed eq 'A') {
                   3769: 	    return 'A';
                   3770: 	} else {
                   3771: 	    return '1';
                   3772: 	}
1.52      www      3773:     }
1.29      www      3774: 
1.52      www      3775: #
                   3776: # Now user is definitely in a course
                   3777: #
1.53      www      3778: 
                   3779: 
                   3780: # Course preferences
                   3781: 
                   3782:    if ($thisallowed=~/C/) {
1.620     albertel 3783:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   3784:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   3785:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 3786: 	   =~/\Q$rolecode\E/) {
1.689     albertel 3787: 	   if ($priv ne 'pch') { 
                   3788: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   3789: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   3790: 			$env{'request.course.id'});
                   3791: 	   }
1.237     www      3792:            return '';
                   3793:        }
                   3794: 
1.620     albertel 3795:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 3796: 	   =~/\Q$unamedom\E/) {
1.689     albertel 3797: 	   if ($priv ne 'pch') { 
                   3798: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   3799: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   3800: 			$env{'request.course.id'});
                   3801: 	   }
1.54      www      3802:            return '';
                   3803:        }
1.53      www      3804:    }
                   3805: 
                   3806: # Resource preferences
                   3807: 
                   3808:    if ($thisallowed=~/R/) {
1.620     albertel 3809:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 3810:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689     albertel 3811: 	   if ($priv ne 'pch') { 
                   3812: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   3813: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   3814: 	   }
                   3815: 	   return '';
1.54      www      3816:        }
1.53      www      3817:    }
1.30      www      3818: 
1.246     www      3819: # Restricted by state or randomout?
1.30      www      3820: 
1.52      www      3821:    if ($thisallowed=~/X/) {
1.620     albertel 3822:       if ($env{'acc.randomout'}) {
1.579     albertel 3823: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 3824:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      3825:             return ''; 
                   3826:          }
1.247     www      3827:       }
                   3828:       if (&condval($statecond)) {
1.52      www      3829: 	 return '2';
                   3830:       } else {
                   3831:          return '';
                   3832:       }
                   3833:    }
1.30      www      3834: 
1.766     albertel 3835:     if ($thisallowed eq 'A') {
                   3836: 	return 'A';
                   3837:     }
1.52      www      3838:    return 'F';
1.232     www      3839: }
                   3840: 
1.710     albertel 3841: sub split_uri_for_cond {
                   3842:     my $uri=&deversion(&declutter(shift));
                   3843:     my @uriparts=split(/\//,$uri);
                   3844:     my $filename=pop(@uriparts);
                   3845:     my $pathname=join('/',@uriparts);
                   3846:     return ($pathname,$filename);
                   3847: }
1.232     www      3848: # --------------------------------------------------- Is a resource on the map?
                   3849: 
                   3850: sub is_on_map {
1.710     albertel 3851:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 3852:     #Trying to find the conditional for the file
1.620     albertel 3853:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 3854: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      3855:     if ($match) {
1.289     bowersj2 3856: 	return (1,$1);
                   3857:     } else {
1.434     www      3858: 	return (0,0);
1.289     bowersj2 3859:     }
1.12      www      3860: }
                   3861: 
1.427     www      3862: # --------------------------------------------------------- Get symb from alias
                   3863: 
                   3864: sub get_symb_from_alias {
                   3865:     my $symb=shift;
                   3866:     my ($map,$resid,$url)=&decode_symb($symb);
                   3867: # Already is a symb
                   3868:     if ($url) { return $symb; }
                   3869: # Must be an alias
                   3870:     my $aliassymb='';
                   3871:     my %bighash;
1.620     albertel 3872:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      3873:                             &GDBM_READER(),0640)) {
                   3874:         my $rid=$bighash{'mapalias_'.$symb};
                   3875: 	if ($rid) {
                   3876: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 3877: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   3878: 				    $resid,$bighash{'src_'.$rid});
1.427     www      3879: 	}
                   3880:         untie %bighash;
                   3881:     }
                   3882:     return $aliassymb;
                   3883: }
                   3884: 
1.12      www      3885: # ----------------------------------------------------------------- Define Role
                   3886: 
                   3887: sub definerole {
                   3888:   if (allowed('mcr','/')) {
                   3889:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.392     www      3890:     foreach (split(':',$sysrole)) {
1.21      www      3891: 	my ($crole,$cqual)=split(/\&/,$_);
1.479     albertel 3892:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   3893:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   3894: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      3895:                return "refused:s:$crole&$cqual"; 
                   3896:             }
                   3897:         }
1.191     harris41 3898:     }
1.392     www      3899:     foreach (split(':',$domrole)) {
1.21      www      3900: 	my ($crole,$cqual)=split(/\&/,$_);
1.479     albertel 3901:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   3902:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   3903: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      3904:                return "refused:d:$crole&$cqual"; 
                   3905:             }
                   3906:         }
1.191     harris41 3907:     }
1.392     www      3908:     foreach (split(':',$courole)) {
1.21      www      3909: 	my ($crole,$cqual)=split(/\&/,$_);
1.479     albertel 3910:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   3911:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   3912: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      3913:                return "refused:c:$crole&$cqual"; 
                   3914:             }
                   3915:         }
1.191     harris41 3916:     }
1.620     albertel 3917:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   3918:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      3919: 	        "rolesdef_$rolename=".
                   3920:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 3921:     return reply($command,$env{'user.home'});
1.12      www      3922:   } else {
                   3923:     return 'refused';
                   3924:   }
1.105     harris41 3925: }
                   3926: 
                   3927: # ---------------- Make a metadata query against the network of library servers
                   3928: 
                   3929: sub metadata_query {
1.244     matthew  3930:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 3931:     my %rhash;
1.244     matthew  3932:     my @server_list = (defined($server_array) ? @$server_array
                   3933:                                               : keys(%libserv) );
                   3934:     for my $server (@server_list) {
1.118     harris41 3935: 	unless ($custom or $customshow) {
                   3936: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   3937: 	    $rhash{$server}=$reply;
                   3938: 	}
                   3939: 	else {
                   3940: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   3941: 			     &escape($custom).':'.&escape($customshow),
                   3942: 			     $server);
                   3943: 	    $rhash{$server}=$reply;
                   3944: 	}
1.112     harris41 3945:     }
1.118     harris41 3946:     return \%rhash;
1.240     www      3947: }
                   3948: 
                   3949: # ----------------------------------------- Send log queries and wait for reply
                   3950: 
                   3951: sub log_query {
                   3952:     my ($uname,$udom,$query,%filters)=@_;
                   3953:     my $uhome=&homeserver($uname,$udom);
                   3954:     if ($uhome eq 'no_host') { return 'error: no_host'; }
                   3955:     my $uhost=$hostname{$uhome};
1.241     www      3956:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys %filters));
1.240     www      3957:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   3958:                        $uhome);
1.479     albertel 3959:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      3960:     return get_query_reply($queryid);
                   3961: }
                   3962: 
1.508     raeburn  3963: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  3964: 
                   3965: sub fetch_enrollment_query {
1.511     raeburn  3966:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  3967:     my $homeserver;
1.547     raeburn  3968:     my $maxtries = 1;
1.508     raeburn  3969:     if ($context eq 'automated') {
                   3970:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  3971:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  3972:     } else {
                   3973:         $homeserver = &homeserver($cnum,$dom);
                   3974:     }
1.506     raeburn  3975:     my $host=$hostname{$homeserver};
                   3976:     my $cmd = '';
                   3977:     foreach (keys %{$affiliatesref}) {
1.508     raeburn  3978:         $cmd .= $_.'='.join(",",@{$$affiliatesref{$_}}).'%%';
1.506     raeburn  3979:     }
                   3980:     $cmd =~ s/%%$//;
                   3981:     $cmd = &escape($cmd);
                   3982:     my $query = 'fetchenrollment';
1.620     albertel 3983:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  3984:     unless ($queryid=~/^\Q$host\E\_/) { 
                   3985:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   3986:         return 'error: '.$queryid;
                   3987:     }
1.506     raeburn  3988:     my $reply = &get_query_reply($queryid);
1.547     raeburn  3989:     my $tries = 1;
                   3990:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   3991:         $reply = &get_query_reply($queryid);
                   3992:         $tries ++;
                   3993:     }
1.526     raeburn  3994:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 3995:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  3996:     } else {
1.515     raeburn  3997:         my @responses = split/:/,$reply;
                   3998:         if ($homeserver eq $perlvar{'lonHostID'}) {
                   3999:             foreach (@responses) {
                   4000:                 my ($key,$value) = split/=/,$_;
                   4001:                 $$replyref{$key} = $value;
                   4002:             }
                   4003:         } else {
1.506     raeburn  4004:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
                   4005:             foreach (@responses) {
                   4006:                 my ($key,$value) = split/=/,$_;
                   4007:                 $$replyref{$key} = $value;
                   4008:                 if ($value > 0) {
                   4009:                     foreach (@{$$affiliatesref{$key}}) {
                   4010:                         my $filename = $dom.'_'.$key.'_'.$_.'_classlist.xml';
                   4011:                         my $destname = $pathname.'/'.$filename;
                   4012:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  4013:                         if ($xml_classlist =~ /^error/) {
                   4014:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   4015:                         } else {
1.506     raeburn  4016:                             if ( open(FILE,">$destname") ) {
                   4017:                                 print FILE &unescape($xml_classlist);
                   4018:                                 close(FILE);
1.526     raeburn  4019:                             } else {
                   4020:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  4021:                             }
                   4022:                         }
                   4023:                     }
                   4024:                 }
                   4025:             }
                   4026:         }
                   4027:         return 'ok';
                   4028:     }
                   4029:     return 'error';
                   4030: }
                   4031: 
1.242     www      4032: sub get_query_reply {
                   4033:     my $queryid=shift;
1.240     www      4034:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   4035:     my $reply='';
                   4036:     for (1..100) {
                   4037: 	sleep 2;
                   4038:         if (-e $replyfile.'.end') {
1.448     albertel 4039: 	    if (open(my $fh,$replyfile)) {
1.240     www      4040:                $reply.=<$fh>;
1.448     albertel 4041:                close($fh);
1.240     www      4042: 	   } else { return 'error: reply_file_error'; }
1.242     www      4043:            return &unescape($reply);
                   4044: 	}
1.240     www      4045:     }
1.242     www      4046:     return 'timeout:'.$queryid;
1.240     www      4047: }
                   4048: 
                   4049: sub courselog_query {
1.241     www      4050: #
                   4051: # possible filters:
                   4052: # url: url or symb
                   4053: # username
                   4054: # domain
                   4055: # action: view, submit, grade
                   4056: # start: timestamp
                   4057: # end: timestamp
                   4058: #
1.240     www      4059:     my (%filters)=@_;
1.620     albertel 4060:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      4061:     if ($filters{'url'}) {
                   4062: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   4063:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   4064:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   4065:     }
1.620     albertel 4066:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4067:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      4068:     return &log_query($cname,$cdom,'courselog',%filters);
                   4069: }
                   4070: 
                   4071: sub userlog_query {
                   4072:     my ($uname,$udom,%filters)=@_;
                   4073:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      4074: }
                   4075: 
1.506     raeburn  4076: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   4077: 
                   4078: sub auto_run {
1.508     raeburn  4079:     my ($cnum,$cdom) = @_;
                   4080:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  4081:     my $response = &reply('autorun:'.$cdom,$homeserver);
1.506     raeburn  4082:     return $response;
                   4083: }
1.776     albertel 4084: 
1.506     raeburn  4085: sub auto_get_sections {
1.508     raeburn  4086:     my ($cnum,$cdom,$inst_coursecode) = @_;
                   4087:     my $homeserver = &homeserver($cnum,$cdom);
1.506     raeburn  4088:     my @secs = ();
1.511     raeburn  4089:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506     raeburn  4090:     unless ($response eq 'refused') {
                   4091:         @secs = split/:/,$response;
                   4092:     }
                   4093:     return @secs;
                   4094: }
1.776     albertel 4095: 
1.506     raeburn  4096: sub auto_new_course {
1.508     raeburn  4097:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
                   4098:     my $homeserver = &homeserver($cnum,$cdom);
1.515     raeburn  4099:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506     raeburn  4100:     return $response;
                   4101: }
1.776     albertel 4102: 
1.506     raeburn  4103: sub auto_validate_courseID {
1.508     raeburn  4104:     my ($cnum,$cdom,$inst_course_id) = @_;
                   4105:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  4106:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  4107:     return $response;
                   4108: }
1.776     albertel 4109: 
1.506     raeburn  4110: sub auto_create_password {
1.508     raeburn  4111:     my ($cnum,$cdom,$authparam) = @_;
                   4112:     my $homeserver = &homeserver($cnum,$cdom); 
1.506     raeburn  4113:     my $create_passwd = 0;
                   4114:     my $authchk = '';
1.511     raeburn  4115:     my $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
1.506     raeburn  4116:     if ($response eq 'refused') {
                   4117:         $authchk = 'refused';
                   4118:     } else {
                   4119:         ($authparam,$create_passwd,$authchk) = split/:/,$response;
                   4120:     }
                   4121:     return ($authparam,$create_passwd,$authchk);
                   4122: }
                   4123: 
1.706     raeburn  4124: sub auto_photo_permission {
                   4125:     my ($cnum,$cdom,$students) = @_;
                   4126:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 4127:     my ($outcome,$perm_reqd,$conditions) = 
                   4128: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 4129:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4130: 	return (undef,undef);
                   4131:     }
1.706     raeburn  4132:     return ($outcome,$perm_reqd,$conditions);
                   4133: }
                   4134: 
                   4135: sub auto_checkphotos {
                   4136:     my ($uname,$udom,$pid) = @_;
                   4137:     my $homeserver = &homeserver($uname,$udom);
                   4138:     my ($result,$resulttype);
                   4139:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 4140: 				   &escape($uname).':'.&escape($pid),
                   4141: 				   $homeserver));
1.709     albertel 4142:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4143: 	return (undef,undef);
                   4144:     }
1.706     raeburn  4145:     if ($outcome) {
                   4146:         ($result,$resulttype) = split(/:/,$outcome);
                   4147:     } 
                   4148:     return ($result,$resulttype);
                   4149: }
                   4150: 
                   4151: sub auto_photochoice {
                   4152:     my ($cnum,$cdom) = @_;
                   4153:     my $homeserver = &homeserver($cnum,$cdom);
                   4154:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 4155: 						       &escape($cdom),
                   4156: 						       $homeserver)));
1.709     albertel 4157:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4158: 	return (undef,undef);
                   4159:     }
1.706     raeburn  4160:     return ($update,$comment);
                   4161: }
                   4162: 
                   4163: sub auto_photoupdate {
                   4164:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   4165:     my $homeserver = &homeserver($cnum,$dom);
                   4166:     my $host=$hostname{$homeserver};
                   4167:     my $cmd = '';
                   4168:     my $maxtries = 1;
                   4169:     foreach (keys %{$affiliatesref}) {
                   4170:         $cmd .= $_.'='.join(",",@{$$affiliatesref{$_}}).'%%';
                   4171:     }
                   4172:     $cmd =~ s/%%$//;
                   4173:     $cmd = &escape($cmd);
                   4174:     my $query = 'institutionalphotos';
                   4175:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   4176:     unless ($queryid=~/^\Q$host\E\_/) {
                   4177:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   4178:         return 'error: '.$queryid;
                   4179:     }
                   4180:     my $reply = &get_query_reply($queryid);
                   4181:     my $tries = 1;
                   4182:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   4183:         $reply = &get_query_reply($queryid);
                   4184:         $tries ++;
                   4185:     }
                   4186:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   4187:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   4188:     } else {
                   4189:         my @responses = split(/:/,$reply);
                   4190:         my $outcome = shift(@responses); 
                   4191:         foreach my $item (@responses) {
                   4192:             my ($key,$value) = split(/=/,$item);
                   4193:             $$photo{$key} = $value;
                   4194:         }
                   4195:         return $outcome;
                   4196:     }
                   4197:     return 'error';
                   4198: }
                   4199: 
1.521     raeburn  4200: sub auto_instcode_format {
                   4201:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,$cat_order) = @_;
                   4202:     my $courses = '';
1.772     raeburn  4203:     my @homeservers;
1.521     raeburn  4204:     if ($caller eq 'global') {
1.584     raeburn  4205:         foreach my $tryserver (keys %libserv) {
                   4206:             if ($hostdom{$tryserver} eq $codedom) {
1.772     raeburn  4207:                 if (!grep/^\Q$tryserver\E$/,@homeservers) {
                   4208:                     push(@homeservers,$tryserver);
                   4209:                 }
1.584     raeburn  4210:             }
                   4211:         }
1.521     raeburn  4212:     } else {
1.772     raeburn  4213:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  4214:     }
                   4215:     foreach (keys %{$instcodes}) {
                   4216:         $courses .= &escape($_).'='.&escape($$instcodes{$_}).'&';
                   4217:     }
                   4218:     chop($courses);
1.772     raeburn  4219:     my $ok_response = 0;
                   4220:     my $response;
                   4221:     while (@homeservers > 0 && $ok_response == 0) {
                   4222:         my $server = shift(@homeservers); 
                   4223:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   4224:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   4225:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
                   4226:                                                             split/:/,$response;
                   4227:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   4228:             push(@{$codetitles},&str2array($codetitles_str));
                   4229:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   4230:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   4231:             $ok_response = 1;
                   4232:         }
                   4233:     }
                   4234:     if ($ok_response) {
1.521     raeburn  4235:         return 'ok';
1.772     raeburn  4236:     } else {
                   4237:         return $response;
1.521     raeburn  4238:     }
                   4239: }
                   4240: 
1.777     albertel 4241: sub auto_validate_class_sec {
1.773     raeburn  4242:     my ($cdom,$cnum,$owner,$inst_class) = @_;
                   4243:     my $homeserver = &homeserver($cnum,$cdom);
                   4244:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.774     banghart 4245:                         &escape($owner).':'.$cdom,$homeserver);
1.773     raeburn  4246:     return $response;
                   4247: }
                   4248: 
1.679     raeburn  4249: # ------------------------------------------------------- Course Group routines
                   4250: 
                   4251: sub get_coursegroups {
1.683     raeburn  4252:     my ($cdom,$cnum,$group) = @_;
                   4253:     return(&dump('coursegroups',$cdom,$cnum,$group));
1.679     raeburn  4254: }
                   4255: 
                   4256: sub modify_coursegroup {
                   4257:     my ($cdom,$cnum,$groupsettings) = @_;
                   4258:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   4259: }
                   4260: 
                   4261: sub modify_group_roles {
                   4262:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
                   4263:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   4264:     my $role = 'gr/'.&escape($userprivs);
                   4265:     my ($uname,$udom) = split(/:/,$user);
                   4266:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
1.684     raeburn  4267:     if ($result eq 'ok') {
                   4268:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   4269:     }
1.679     raeburn  4270:     return $result;
                   4271: }
                   4272: 
                   4273: sub modify_coursegroup_membership {
                   4274:     my ($cdom,$cnum,$membership) = @_;
                   4275:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   4276:     return $result;
                   4277: }
                   4278: 
1.682     raeburn  4279: sub get_active_groups {
                   4280:     my ($udom,$uname,$cdom,$cnum) = @_;
                   4281:     my $now = time;
                   4282:     my %groups = ();
                   4283:     foreach my $key (keys(%env)) {
                   4284:         if ($key =~ m-user\.role\.gr\./([^/]+)/([^/]+)/(\w+)$-) {
                   4285:             my ($start,$end) = split(/\./,$env{$key});
                   4286:             if (($end!=0) && ($end<$now)) { next; }
                   4287:             if (($start!=0) && ($start>$now)) { next; }
                   4288:             if ($1 eq $cdom && $2 eq $cnum) {
                   4289:                 $groups{$3} = $env{$key} ;
                   4290:             }
                   4291:         }
                   4292:     }
                   4293:     return %groups;
                   4294: }
                   4295: 
1.683     raeburn  4296: sub get_group_membership {
                   4297:     my ($cdom,$cnum,$group) = @_;
                   4298:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   4299: }
                   4300: 
                   4301: sub get_users_groups {
                   4302:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  4303:     my @usersgroups;
1.683     raeburn  4304:     my $cachetime=1800;
                   4305:     $courseid=~s/\_/\//g;
                   4306:     $courseid=~s/^(\w)/\/$1/;
                   4307: 
                   4308:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  4309:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   4310:     if (defined($cached)) {
1.734     albertel 4311:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  4312:     } else {  
                   4313:         $grouplist = '';
                   4314:         my %roleshash = &dump('roles',$udom,$uname,$courseid);
                   4315:         my ($tmp) = keys(%roleshash);
                   4316:         if ($tmp=~/^error:/) {
                   4317:             &logthis('Error retrieving roles: '.$tmp.' for '.$uname.':'.$udom);
                   4318:         } else {
                   4319:             my $access_end = $env{'course.'.$courseid.
                   4320:                                   '.default_enrollment_end_date'};
                   4321:             my $now = time;
1.734     albertel 4322:             foreach my $key (keys(%roleshash)) {
1.733     raeburn  4323:                 if ($key =~ /^\Q$courseid\E\/(\w+)\_gr$/) {
                   4324:                     my $group = $1;
                   4325:                     if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   4326:                         my $start = $2;
                   4327:                         my $end = $1;
                   4328:                         if ($start == -1) { next; } # deleted from group
                   4329:                         if (($start!=0) && ($start>$now)) { next; }
                   4330:                         if (($end!=0) && ($end<$now)) {
                   4331:                             if ($access_end && $access_end < $now) {
                   4332:                                 if ($access_end - $end < 86400) {
                   4333:                                     push(@usersgroups,$group);
                   4334:                                 }
                   4335:                             }
                   4336:                             next;
                   4337:                         }
                   4338:                         push(@usersgroups,$group);
                   4339:                     }
1.683     raeburn  4340:                 }
                   4341:             }
1.733     raeburn  4342:             @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   4343:             $grouplist = join(':',@usersgroups);
                   4344:             &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  4345:         }
                   4346:     }
1.733     raeburn  4347:     return @usersgroups;
1.683     raeburn  4348: }
                   4349: 
                   4350: sub devalidate_getgroups_cache {
                   4351:     my ($udom,$uname,$cdom,$cnum)=@_;
                   4352:     my $courseid = $cdom.'_'.$cnum;
                   4353:     $courseid=~s/\_/\//g;
                   4354:     $courseid=~s/^(\w)/\/$1/;
                   4355:     my $hashid="$udom:$uname:$courseid";
                   4356:     &devalidate_cache_new('getgroups',$hashid);
                   4357: }
                   4358: 
1.12      www      4359: # ------------------------------------------------------------------ Plain Text
                   4360: 
                   4361: sub plaintext {
1.742     raeburn  4362:     my ($short,$type,$cid) = @_;
1.758     albertel 4363:     if ($short =~ /^cr/) {
                   4364: 	return (split('/',$short))[-1];
                   4365:     }
1.742     raeburn  4366:     if (!defined($cid)) {
                   4367:         $cid = $env{'request.course.id'};
                   4368:     }
                   4369:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
                   4370:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
                   4371:                                           '.plaintext'});
                   4372:     }
                   4373:     my %rolenames = (
                   4374:                       Course => 'std',
                   4375:                       Group => 'alt1',
                   4376:                     );
                   4377:     if (defined($type) && 
                   4378:          defined($rolenames{$type}) && 
                   4379:          defined($prp{$short}{$rolenames{$type}})) {
                   4380:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
                   4381:     } else {
                   4382:         return &Apache::lonlocal::mt($prp{$short}{'std'});
                   4383:     }
1.12      www      4384: }
                   4385: 
                   4386: # ----------------------------------------------------------------- Assign Role
                   4387: 
                   4388: sub assignrole {
1.357     www      4389:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
1.21      www      4390:     my $mrole;
                   4391:     if ($role =~ /^cr\//) {
1.393     www      4392:         my $cwosec=$url;
                   4393:         $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
                   4394: 	unless (&allowed('ccr',$cwosec)) {
1.104     www      4395:            &logthis('Refused custom assignrole: '.
                   4396:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 4397: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      4398:            return 'refused'; 
                   4399:         }
1.21      www      4400:         $mrole='cr';
1.678     raeburn  4401:     } elsif ($role =~ /^gr\//) {
                   4402:         my $cwogrp=$url;
                   4403:         $cwogrp=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
                   4404:         unless (&allowed('mdg',$cwogrp)) {
                   4405:             &logthis('Refused group assignrole: '.
                   4406:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   4407:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   4408:             return 'refused';
                   4409:         }
                   4410:         $mrole='gr';
1.21      www      4411:     } else {
1.82      www      4412:         my $cwosec=$url;
1.83      www      4413:         $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
1.373     www      4414:         unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) { 
1.104     www      4415:            &logthis('Refused assignrole: '.
                   4416:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 4417: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      4418:            return 'refused'; 
                   4419:         }
1.21      www      4420:         $mrole=$role;
                   4421:     }
1.620     albertel 4422:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      4423:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      4424:     if ($end) { $command.='_'.$end; }
1.21      www      4425:     if ($start) {
                   4426: 	if ($end) { 
1.81      www      4427:            $command.='_'.$start; 
1.21      www      4428:         } else {
1.81      www      4429:            $command.='_0_'.$start;
1.21      www      4430:         }
                   4431:     }
1.739     raeburn  4432:     my $origstart = $start;
                   4433:     my $origend = $end;
1.357     www      4434: # actually delete
                   4435:     if ($deleteflag) {
1.373     www      4436: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      4437: # modify command to delete the role
1.620     albertel 4438:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      4439:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 4440: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      4441: # set start and finish to negative values for userrolelog
                   4442:            $start=-1;
                   4443:            $end=-1;
                   4444:         }
                   4445:     }
                   4446: # send command
1.349     www      4447:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      4448: # log new user role if status is ok
1.349     www      4449:     if ($answer eq 'ok') {
1.663     raeburn  4450: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  4451: # for course roles, perform group memberships changes triggered by role change.
                   4452:         unless ($role =~ /^gr/) {
                   4453:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   4454:                                              $origstart);
                   4455:         }
1.349     www      4456:     }
                   4457:     return $answer;
1.169     harris41 4458: }
                   4459: 
                   4460: # -------------------------------------------------- Modify user authentication
1.197     www      4461: # Overrides without validation
                   4462: 
1.169     harris41 4463: sub modifyuserauth {
                   4464:     my ($udom,$uname,$umode,$upass)=@_;
                   4465:     my $uhome=&homeserver($uname,$udom);
1.197     www      4466:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   4467:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 4468:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   4469:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 4470:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   4471: 		     &escape($upass),$uhome);
1.620     albertel 4472:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      4473:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   4474:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   4475:     &log($udom,,$uname,$uhome,
1.620     albertel 4476:         'Authentication changed by '.$env{'user.domain'}.', '.
                   4477:                                      $env{'user.name'}.', '.$umode.
1.197     www      4478:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 4479:     unless ($reply eq 'ok') {
1.197     www      4480:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 4481: 	return 'error: '.$reply;
                   4482:     }   
1.170     harris41 4483:     return 'ok';
1.80      www      4484: }
                   4485: 
1.81      www      4486: # --------------------------------------------------------------- Modify a user
1.80      www      4487: 
1.81      www      4488: sub modifyuser {
1.206     matthew  4489:     my ($udom,    $uname, $uid,
                   4490:         $umode,   $upass, $first,
                   4491:         $middle,  $last,  $gene,
1.387     www      4492:         $forceid, $desiredhome, $email)=@_;
1.198     www      4493:     $udom=~s/\W//g;
                   4494:     $uname=~s/\W//g;
1.81      www      4495:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      4496:              $umode.', '.$first.', '.$middle.', '.
1.206     matthew  4497: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
                   4498:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   4499:                                      ' desiredhome not specified'). 
1.620     albertel 4500:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   4501:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 4502:     my $uhome=&homeserver($uname,$udom,'true');
1.80      www      4503: # ----------------------------------------------------------------- Create User
1.406     albertel 4504:     if (($uhome eq 'no_host') && 
                   4505: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      4506:         my $unhome='';
1.209     matthew  4507:         if (defined($desiredhome) && $hostdom{$desiredhome} eq $udom) { 
                   4508:             $unhome = $desiredhome;
1.620     albertel 4509: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   4510: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  4511:         } else { # load balancing routine for determining $unhome
1.80      www      4512:             my $tryserver;
1.81      www      4513:             my $loadm=10000000;
1.80      www      4514:             foreach $tryserver (keys %libserv) {
                   4515: 	       if ($hostdom{$tryserver} eq $udom) {
                   4516:                   my $answer=reply('load',$tryserver);
                   4517:                   if (($answer=~/\d+/) && ($answer<$loadm)) {
                   4518: 		      $loadm=$answer;
                   4519:                       $unhome=$tryserver;
                   4520:                   }
                   4521: 	       }
                   4522: 	    }
                   4523:         }
                   4524:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  4525: 	    return 'error: unable to find a home server for '.$uname.
                   4526:                    ' in domain '.$udom;
1.80      www      4527:         }
                   4528:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   4529:                          &escape($upass),$unhome);
                   4530: 	unless ($reply eq 'ok') {
                   4531:             return 'error: '.$reply;
                   4532:         }   
1.230     stredwic 4533:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      4534:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  4535: 	    return 'error: unable verify users home machine.';
1.80      www      4536:         }
1.209     matthew  4537:     }   # End of creation of new user
1.80      www      4538: # ---------------------------------------------------------------------- Add ID
                   4539:     if ($uid) {
                   4540:        $uid=~tr/A-Z/a-z/;
                   4541:        my %uidhash=&idrget($udom,$uname);
1.196     www      4542:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   4543:          && (!$forceid)) {
1.80      www      4544: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  4545: 	      return 'error: user id "'.$uid.'" does not match '.
                   4546:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      4547:           }
                   4548:        } else {
                   4549: 	  &idput($udom,($uname => $uid));
                   4550:        }
                   4551:     }
                   4552: # -------------------------------------------------------------- Add names, etc
1.313     matthew  4553:     my @tmp=&get('environment',
1.134     albertel 4554: 		   ['firstname','middlename','lastname','generation'],
                   4555: 		   $udom,$uname);
1.313     matthew  4556:     my %names;
                   4557:     if ($tmp[0] =~ m/^error:.*/) { 
                   4558:         %names=(); 
                   4559:     } else {
                   4560:         %names = @tmp;
                   4561:     }
1.388     www      4562: #
                   4563: # Make sure to not trash student environment if instructor does not bother
                   4564: # to supply name and email information
                   4565: #
                   4566:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  4567:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      4568:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  4569:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      4570:     if ($email) {
                   4571:        $email=~s/[^\w\@\.\-\,]//gs;
                   4572:        if ($email=~/\@/) { $names{'notification'} = $email;
                   4573: 			   $names{'critnotification'} = $email;
                   4574: 			   $names{'permanentemail'} = $email; }
                   4575:     }
1.134     albertel 4576:     my $reply = &put('environment', \%names, $udom,$uname);
                   4577:     if ($reply ne 'ok') { return 'error: '.$reply; }
1.680     www      4578:     &devalidate_cache_new('namescache',$uname.':'.$udom);
1.81      www      4579:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      4580:              $umode.', '.$first.', '.$middle.', '.
                   4581: 	     $last.', '.$gene.' by '.
1.620     albertel 4582:              $env{'user.name'}.' at '.$env{'user.domain'});
1.134     albertel 4583:     return 'ok';
1.80      www      4584: }
                   4585: 
1.81      www      4586: # -------------------------------------------------------------- Modify student
1.80      www      4587: 
1.81      www      4588: sub modifystudent {
                   4589:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.515     raeburn  4590:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
1.455     albertel 4591:     if (!$cid) {
1.620     albertel 4592: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 4593: 	    return 'not_in_class';
                   4594: 	}
1.80      www      4595:     }
                   4596: # --------------------------------------------------------------- Make the user
1.81      www      4597:     my $reply=&modifyuser
1.209     matthew  4598: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387     www      4599:          $desiredhome,$email);
1.80      www      4600:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  4601:     # This will cause &modify_student_enrollment to get the uid from the
                   4602:     # students environment
                   4603:     $uid = undef if (!$forceid);
1.455     albertel 4604:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.515     raeburn  4605: 					$gene,$usec,$end,$start,$type,$locktype,$cid);
1.297     matthew  4606:     return $reply;
                   4607: }
                   4608: 
                   4609: sub modify_student_enrollment {
1.515     raeburn  4610:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
1.455     albertel 4611:     my ($cdom,$cnum,$chome);
                   4612:     if (!$cid) {
1.620     albertel 4613: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 4614: 	    return 'not_in_class';
                   4615: 	}
1.620     albertel 4616: 	$cdom=$env{'course.'.$cid.'.domain'};
                   4617: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 4618:     } else {
                   4619: 	($cdom,$cnum)=split(/_/,$cid);
                   4620:     }
1.620     albertel 4621:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 4622:     if (!$chome) {
1.457     raeburn  4623: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  4624:     }
1.455     albertel 4625:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  4626:     # Make sure the user exists
1.81      www      4627:     my $uhome=&homeserver($uname,$udom);
                   4628:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   4629: 	return 'error: no such user';
                   4630:     }
1.297     matthew  4631:     # Get student data if we were not given enough information
                   4632:     if (!defined($first)  || $first  eq '' || 
                   4633:         !defined($last)   || $last   eq '' || 
                   4634:         !defined($uid)    || $uid    eq '' || 
                   4635:         !defined($middle) || $middle eq '' || 
                   4636:         !defined($gene)   || $gene   eq '') {
1.294     matthew  4637:         # They did not supply us with enough data to enroll the student, so
                   4638:         # we need to pick up more information.
1.297     matthew  4639:         my %tmp = &get('environment',
1.294     matthew  4640:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  4641:                        ,$udom,$uname);
                   4642: 
1.455     albertel 4643:         #foreach (keys(%tmp)) {
                   4644:         #    &logthis("key $_ = ".$tmp{$_});
                   4645:         #}
1.294     matthew  4646:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   4647:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   4648:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  4649:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  4650:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   4651:     }
1.556     albertel 4652:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 4653:     my $reply=cput('classlist',
                   4654: 		   {"$uname:$udom" => 
1.515     raeburn  4655: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 4656: 		   $cdom,$cnum);
1.81      www      4657:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   4658: 	return 'error: '.$reply;
1.652     albertel 4659:     } else {
                   4660: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      4661:     }
1.297     matthew  4662:     # Add student role to user
1.83      www      4663:     my $uurl='/'.$cid;
1.81      www      4664:     $uurl=~s/\_/\//g;
                   4665:     if ($usec) {
                   4666: 	$uurl.='/'.$usec;
                   4667:     }
                   4668:     return &assignrole($udom,$uname,$uurl,'st',$end,$start);
1.21      www      4669: }
                   4670: 
1.556     albertel 4671: sub format_name {
                   4672:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   4673:     my $name;
                   4674:     if ($first ne 'lastname') {
                   4675: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   4676:     } else {
                   4677: 	if ($lastname=~/\S/) {
                   4678: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   4679: 	    $name=~s/\s+,/,/;
                   4680: 	} else {
                   4681: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   4682: 	}
                   4683:     }
                   4684:     $name=~s/^\s+//;
                   4685:     $name=~s/\s+$//;
                   4686:     $name=~s/\s+/ /g;
                   4687:     return $name;
                   4688: }
                   4689: 
1.84      www      4690: # ------------------------------------------------- Write to course preferences
                   4691: 
                   4692: sub writecoursepref {
                   4693:     my ($courseid,%prefs)=@_;
                   4694:     $courseid=~s/^\///;
                   4695:     $courseid=~s/\_/\//g;
                   4696:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   4697:     my $chome=homeserver($cnum,$cdomain);
                   4698:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   4699: 	return 'error: no such course';
                   4700:     }
                   4701:     my $cstring='';
1.191     harris41 4702:     foreach (keys %prefs) {
1.84      www      4703: 	$cstring.=escape($_).'='.escape($prefs{$_}).'&';
1.191     harris41 4704:     }
1.84      www      4705:     $cstring=~s/\&$//;
                   4706:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   4707: }
                   4708: 
                   4709: # ---------------------------------------------------------- Make/modify course
                   4710: 
                   4711: sub createcourse {
1.741     raeburn  4712:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
                   4713:         $course_owner,$crstype)=@_;
1.84      www      4714:     $url=&declutter($url);
                   4715:     my $cid='';
1.264     matthew  4716:     unless (&allowed('ccc',$udom)) {
1.84      www      4717:         return 'refused';
                   4718:     }
                   4719: # ------------------------------------------------------------------- Create ID
1.674     www      4720:    my $uname=int(1+rand(9)).
                   4721:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   4722:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
1.84      www      4723:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   4724: # ----------------------------------------------- Make sure that does not exist
1.230     stredwic 4725:    my $uhome=&homeserver($uname,$udom,'true');
1.84      www      4726:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   4727:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   4728:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230     stredwic 4729:        $uhome=&homeserver($uname,$udom,'true');       
1.84      www      4730:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   4731:            return 'error: unable to generate unique course-ID';
                   4732:        } 
                   4733:    }
1.264     matthew  4734: # ------------------------------------------------ Check supplied server name
1.620     albertel 4735:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.264     matthew  4736:     if (! exists($libserv{$course_server})) {
                   4737:         return 'error:bad server name '.$course_server;
                   4738:     }
1.84      www      4739: # ------------------------------------------------------------- Make the course
                   4740:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  4741:                       $course_server);
1.84      www      4742:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230     stredwic 4743:     $uhome=&homeserver($uname,$udom,'true');
1.84      www      4744:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   4745: 	return 'error: no such course';
                   4746:     }
1.271     www      4747: # ----------------------------------------------------------------- Course made
1.516     raeburn  4748: # log existence
                   4749:     &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description).
1.741     raeburn  4750:                  ':'.&escape($inst_code).':'.&escape($course_owner).':'.
                   4751:                   &escape($crstype),$uhome);
1.358     www      4752:     &flushcourselogs();
                   4753: # set toplevel url
1.271     www      4754:     my $topurl=$url;
                   4755:     unless ($nonstandard) {
                   4756: # ------------------------------------------ For standard courses, make top url
                   4757:         my $mapurl=&clutter($url);
1.278     www      4758:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 4759:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      4760: <map>
                   4761: <resource id="1" type="start"></resource>
                   4762: <resource id="2" src="$mapurl"></resource>
                   4763: <resource id="3" type="finish"></resource>
                   4764: <link index="1" from="1" to="2"></link>
                   4765: <link index="2" from="2" to="3"></link>
                   4766: </map>
                   4767: ENDINITMAP
                   4768:         $topurl=&declutter(
1.638     albertel 4769:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      4770:                           );
                   4771:     }
                   4772: # ----------------------------------------------------------- Write preferences
1.84      www      4773:     &writecoursepref($udom.'_'.$uname,
                   4774:                      ('description' => $description,
1.271     www      4775:                       'url'         => $topurl));
1.84      www      4776:     return '/'.$udom.'/'.$uname;
                   4777: }
                   4778: 
1.21      www      4779: # ---------------------------------------------------------- Assign Custom Role
                   4780: 
                   4781: sub assigncustomrole {
1.357     www      4782:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
1.21      www      4783:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.357     www      4784:                        $end,$start,$deleteflag);
1.21      www      4785: }
                   4786: 
                   4787: # ----------------------------------------------------------------- Revoke Role
                   4788: 
                   4789: sub revokerole {
1.357     www      4790:     my ($udom,$uname,$url,$role,$deleteflag)=@_;
1.21      www      4791:     my $now=time;
1.357     www      4792:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
1.21      www      4793: }
                   4794: 
                   4795: # ---------------------------------------------------------- Revoke Custom Role
                   4796: 
                   4797: sub revokecustomrole {
1.357     www      4798:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
1.21      www      4799:     my $now=time;
1.357     www      4800:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
                   4801:            $deleteflag);
1.17      www      4802: }
                   4803: 
1.533     banghart 4804: # ------------------------------------------------------------ Disk usage
1.535     albertel 4805: sub diskusage {
1.533     banghart 4806:     my ($udom,$uname,$directoryRoot)=@_;
                   4807:     $directoryRoot =~ s/\/$//;
1.535     albertel 4808:     my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
1.514     albertel 4809:     return $listing;
1.512     banghart 4810: }
                   4811: 
1.566     banghart 4812: sub is_locked {
                   4813:     my ($file_name, $domain, $user) = @_;
                   4814:     my @check;
                   4815:     my $is_locked;
                   4816:     push @check, $file_name;
1.613     albertel 4817:     my %locked = &get('file_permissions',\@check,
1.620     albertel 4818: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 4819:     my ($tmp)=keys(%locked);
                   4820:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  4821:     
1.566     banghart 4822:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  4823:         $is_locked = 'false';
                   4824:         foreach my $entry (@{$locked{$file_name}}) {
                   4825:            if (ref($entry) eq 'ARRAY') { 
1.746     raeburn  4826:                $is_locked = 'true';
                   4827:                last;
1.745     raeburn  4828:            }
                   4829:        }
1.566     banghart 4830:     } else {
                   4831:         $is_locked = 'false';
                   4832:     }
                   4833: }
                   4834: 
1.759     albertel 4835: sub declutter_portfile {
                   4836:     my ($file) = @_;
                   4837:     &logthis("got $file");
                   4838:     $file =~ s-^(/portfolio/|portfolio/)-/-;
                   4839:     &logthis("ret $file");
                   4840:     return $file;
                   4841: }
                   4842: 
1.559     banghart 4843: # ------------------------------------------------------------- Mark as Read Only
                   4844: 
                   4845: sub mark_as_readonly {
                   4846:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 4847:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 4848:     my ($tmp)=keys(%current_permissions);
                   4849:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 4850:     foreach my $file (@{$files}) {
1.759     albertel 4851: 	$file = &declutter_portfile($file);
1.561     banghart 4852:         push(@{$current_permissions{$file}},$what);
1.559     banghart 4853:     }
1.613     albertel 4854:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 4855:     return;
                   4856: }
                   4857: 
1.572     banghart 4858: # ------------------------------------------------------------Save Selected Files
                   4859: 
                   4860: sub save_selected_files {
                   4861:     my ($user, $path, @files) = @_;
                   4862:     my $filename = $user."savedfiles";
1.573     banghart 4863:     my @other_files = &files_not_in_path($user, $path);
1.574     banghart 4864:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 4865:     foreach my $file (@files) {
1.620     albertel 4866:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 4867:     }
                   4868:     foreach my $file (@other_files) {
1.574     banghart 4869:         print (OUT $file."\n");
1.572     banghart 4870:     }
1.574     banghart 4871:     close (OUT);
1.572     banghart 4872:     return 'ok';
                   4873: }
                   4874: 
1.574     banghart 4875: sub clear_selected_files {
                   4876:     my ($user) = @_;
                   4877:     my $filename = $user."savedfiles";
                   4878:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   4879:     print (OUT undef);
                   4880:     close (OUT);
                   4881:     return ("ok");    
                   4882: }
                   4883: 
1.572     banghart 4884: sub files_in_path {
                   4885:     my ($user, $path) = @_;
                   4886:     my $filename = $user."savedfiles";
                   4887:     my %return_files;
1.574     banghart 4888:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 4889:     while (my $line_in = <IN>) {
1.574     banghart 4890:         chomp ($line_in);
                   4891:         my @paths_and_file = split (m!/!, $line_in);
                   4892:         my $file_part = pop (@paths_and_file);
                   4893:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 4894:         $path_part.='/';
                   4895:         my $path_and_file = $path_part.$file_part;
                   4896:         if ($path_part eq $path) {
                   4897:             $return_files{$file_part}= 'selected';
                   4898:         }
                   4899:     }
1.574     banghart 4900:     close (IN);
                   4901:     return (\%return_files);
1.572     banghart 4902: }
                   4903: 
                   4904: # called in portfolio select mode, to show files selected NOT in current directory
                   4905: sub files_not_in_path {
                   4906:     my ($user, $path) = @_;
                   4907:     my $filename = $user."savedfiles";
                   4908:     my @return_files;
                   4909:     my $path_part;
1.574     banghart 4910:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.572     banghart 4911:     while (<IN>) {
                   4912:         #ok, I know it's clunky, but I want it to work
                   4913:         my @paths_and_file = split m!/!, $_;
1.574     banghart 4914:         my $file_part = pop (@paths_and_file);
                   4915:         chomp ($file_part);
                   4916:         my $path_part = join ('/', @paths_and_file);
1.572     banghart 4917:         $path_part .= '/';
                   4918:         my $path_and_file = $path_part.$file_part;
                   4919:         if ($path_part ne $path) {
1.574     banghart 4920:             push (@return_files, ($path_and_file));
1.572     banghart 4921:         }
                   4922:     }
1.574     banghart 4923:     close (OUT);
                   4924:     return (@return_files);
1.572     banghart 4925: }
                   4926: 
1.745     raeburn  4927: #----------------------------------------------Get portfolio file permissions
1.629     banghart 4928: 
1.745     raeburn  4929: sub get_portfile_permissions {
                   4930:     my ($domain,$user) = @_;
1.613     albertel 4931:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 4932:     my ($tmp)=keys(%current_permissions);
                   4933:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  4934:     return \%current_permissions;
                   4935: }
                   4936: 
                   4937: #---------------------------------------------Get portfolio file access controls
                   4938: 
1.749     raeburn  4939: sub get_access_controls {
1.745     raeburn  4940:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 4941:     my %access;
                   4942:     my $real_file = $file;
                   4943:     $file =~ s/\.meta$//;
1.745     raeburn  4944:     if (defined($file)) {
1.749     raeburn  4945:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   4946:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 4947:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  4948:             }
                   4949:         }
1.745     raeburn  4950:     } else {
1.749     raeburn  4951:         foreach my $key (keys(%{$current_permissions})) {
                   4952:             if ($key =~ /\0accesscontrol$/) {
                   4953:                 if (defined($group)) {
                   4954:                     if ($key !~ m-^\Q$group\E/-) {
                   4955:                         next;
                   4956:                     }
                   4957:                 }
                   4958:                 my ($fullpath) = split(/\0/,$key);
                   4959:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   4960:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   4961:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   4962:                     }
                   4963:                 }
                   4964:             }
                   4965:         }
                   4966:     }
                   4967:     return %access;
                   4968: }
                   4969: 
                   4970: sub modify_access_controls {
                   4971:     my ($file_name,$changes,$domain,$user)=@_;
                   4972:     my ($outcome,$deloutcome);
                   4973:     my %store_permissions;
                   4974:     my %new_values;
                   4975:     my %new_control;
                   4976:     my %translation;
                   4977:     my @deletions = ();
                   4978:     my $now = time;
                   4979:     if (exists($$changes{'activate'})) {
                   4980:         if (ref($$changes{'activate'}) eq 'HASH') {
                   4981:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   4982:             my $numnew = scalar(@newitems);
                   4983:             for (my $i=0; $i<$numnew; $i++) {
                   4984:                 my $newkey = $newitems[$i];
                   4985:                 my $newid = &Apache::loncommon::get_cgi_id();
                   4986:                 $newkey =~ s/^(\d+)/$newid/;
                   4987:                 $translation{$1} = $newid;
                   4988:                 $new_values{$file_name."\0".$newkey} = 
                   4989:                                           $$changes{'activate'}{$newitems[$i]};
                   4990:                 $new_control{$newkey} = $now;
                   4991:             }
                   4992:         }
                   4993:     }
                   4994:     my %todelete;
                   4995:     my %changed_items;
                   4996:     foreach my $action ('delete','update') {
                   4997:         if (exists($$changes{$action})) {
                   4998:             if (ref($$changes{$action}) eq 'HASH') {
                   4999:                 foreach my $key (keys(%{$$changes{$action}})) {
                   5000:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   5001:                     if ($action eq 'delete') { 
                   5002:                         $todelete{$itemnum} = 1;
                   5003:                     } else {
                   5004:                         $changed_items{$itemnum} = $key;
                   5005:                     }
                   5006:                 }
1.745     raeburn  5007:             }
                   5008:         }
1.749     raeburn  5009:     }
                   5010:     # get lock on access controls for file.
                   5011:     my $lockhash = {
                   5012:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   5013:                                                        ':'.$env{'user.domain'},
                   5014:                    }; 
                   5015:     my $tries = 0;
                   5016:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   5017:    
                   5018:     while (($gotlock ne 'ok') && $tries <3) {
                   5019:         $tries ++;
                   5020:         sleep 1;
                   5021:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   5022:     }
                   5023:     if ($gotlock eq 'ok') {
                   5024:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   5025:         my ($tmp)=keys(%curr_permissions);
                   5026:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   5027:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   5028:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   5029:             if (ref($curr_controls) eq 'HASH') {
                   5030:                 foreach my $control_item (keys(%{$curr_controls})) {
                   5031:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   5032:                     if (defined($todelete{$itemnum})) {
                   5033:                         push(@deletions,$file_name."\0".$control_item);
                   5034:                     } else {
                   5035:                         if (defined($changed_items{$itemnum})) {
                   5036:                             $new_control{$changed_items{$itemnum}} = $now;
                   5037:                             push(@deletions,$file_name."\0".$control_item);
                   5038:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   5039:                         } else {
                   5040:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   5041:                         }
                   5042:                     }
1.745     raeburn  5043:                 }
                   5044:             }
                   5045:         }
1.749     raeburn  5046:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   5047:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   5048:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   5049:         #  remove lock
                   5050:         my @del_lock = ($file_name."\0".'locked_access_records');
                   5051:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
                   5052:     } else {
                   5053:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  5054:     }
1.749     raeburn  5055:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  5056: }
                   5057: 
                   5058: #------------------------------------------------------Get Marked as Read Only
                   5059: 
                   5060: sub get_marked_as_readonly {
                   5061:     my ($domain,$user,$what,$group) = @_;
                   5062:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 5063:     my @readonly_files;
1.629     banghart 5064:     my $cmp1=$what;
                   5065:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  5066:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   5067:         if (defined($group)) {
                   5068:             if ($file_name !~ m-^\Q$group\E/-) {
                   5069:                 next;
                   5070:             }
                   5071:         }
1.561     banghart 5072:         if (ref($value) eq "ARRAY"){
                   5073:             foreach my $stored_what (@{$value}) {
1.629     banghart 5074:                 my $cmp2=$stored_what;
1.759     albertel 5075:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  5076:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  5077:                 }
1.629     banghart 5078:                 if ($cmp1 eq $cmp2) {
1.561     banghart 5079:                     push(@readonly_files, $file_name);
1.745     raeburn  5080:                     last;
1.563     banghart 5081:                 } elsif (!defined($what)) {
                   5082:                     push(@readonly_files, $file_name);
1.745     raeburn  5083:                     last;
1.561     banghart 5084:                 }
                   5085:             }
1.745     raeburn  5086:         }
1.561     banghart 5087:     }
                   5088:     return @readonly_files;
                   5089: }
1.577     banghart 5090: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 5091: 
1.577     banghart 5092: sub get_marked_as_readonly_hash {
1.745     raeburn  5093:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 5094:     my %readonly_files;
1.745     raeburn  5095:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   5096:         if (defined($group)) {
                   5097:             if ($file_name !~ m-^\Q$group\E/-) {
                   5098:                 next;
                   5099:             }
                   5100:         }
1.577     banghart 5101:         if (ref($value) eq "ARRAY"){
                   5102:             foreach my $stored_what (@{$value}) {
1.745     raeburn  5103:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 5104:                     foreach my $lock_descriptor(@{$stored_what}) {
                   5105:                         if ($lock_descriptor eq 'graded') {
                   5106:                             $readonly_files{$file_name} = 'graded';
                   5107:                         } elsif ($lock_descriptor eq 'handback') {
                   5108:                             $readonly_files{$file_name} = 'handback';
                   5109:                         } else {
                   5110:                             if (!exists($readonly_files{$file_name})) {
                   5111:                                 $readonly_files{$file_name} = 'locked';
                   5112:                             }
                   5113:                         }
1.745     raeburn  5114:                     }
1.750     banghart 5115:                 } 
1.577     banghart 5116:             }
                   5117:         } 
                   5118:     }
                   5119:     return %readonly_files;
                   5120: }
1.559     banghart 5121: # ------------------------------------------------------------ Unmark as Read Only
                   5122: 
                   5123: sub unmark_as_readonly {
1.629     banghart 5124:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   5125:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  5126:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 5127:     $file_name = &declutter_portfile($file_name);
1.634     albertel 5128:     my $symb_crs = $what;
                   5129:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  5130:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 5131:     my ($tmp)=keys(%current_permissions);
                   5132:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  5133:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 5134:     foreach my $file (@readonly_files) {
1.759     albertel 5135: 	my $clean_file = &declutter_portfile($file);
                   5136: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 5137: 	my $current_locks = $current_permissions{$file};
1.563     banghart 5138:         my @new_locks;
                   5139:         my @del_keys;
                   5140:         if (ref($current_locks) eq "ARRAY"){
                   5141:             foreach my $locker (@{$current_locks}) {
1.632     albertel 5142:                 my $compare=$locker;
1.749     raeburn  5143:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  5144:                     $compare=join('',@{$locker});
1.746     raeburn  5145:                     if ($compare ne $symb_crs) {
                   5146:                         push(@new_locks, $locker);
                   5147:                     }
1.563     banghart 5148:                 }
                   5149:             }
1.650     albertel 5150:             if (scalar(@new_locks) > 0) {
1.563     banghart 5151:                 $current_permissions{$file} = \@new_locks;
                   5152:             } else {
                   5153:                 push(@del_keys, $file);
1.613     albertel 5154:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 5155:                 delete($current_permissions{$file});
1.563     banghart 5156:             }
                   5157:         }
1.561     banghart 5158:     }
1.613     albertel 5159:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 5160:     return;
                   5161: }
1.512     banghart 5162: 
1.17      www      5163: # ------------------------------------------------------------ Directory lister
                   5164: 
                   5165: sub dirlist {
1.253     stredwic 5166:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
                   5167: 
1.18      www      5168:     $uri=~s/^\///;
                   5169:     $uri=~s/\/$//;
1.253     stredwic 5170:     my ($udom, $uname);
                   5171:     (undef,$udom,$uname)=split(/\//,$uri);
                   5172:     if(defined($userdomain)) {
                   5173:         $udom = $userdomain;
                   5174:     }
                   5175:     if(defined($username)) {
                   5176:         $uname = $username;
                   5177:     }
                   5178: 
                   5179:     my $dirRoot = $perlvar{'lonDocRoot'};
                   5180:     if(defined($alternateDirectoryRoot)) {
                   5181:         $dirRoot = $alternateDirectoryRoot;
                   5182:         $dirRoot =~ s/\/$//;
1.751     banghart 5183:     }
1.253     stredwic 5184: 
                   5185:     if($udom) {
                   5186:         if($uname) {
1.605     matthew  5187:             my $listing=reply('ls2:'.$dirRoot.'/'.$uri,
1.253     stredwic 5188:                               homeserver($uname,$udom));
1.605     matthew  5189:             my @listing_results;
                   5190:             if ($listing eq 'unknown_cmd') {
                   5191:                 $listing=reply('ls:'.$dirRoot.'/'.$uri,
                   5192:                                homeserver($uname,$udom));
                   5193:                 @listing_results = split(/:/,$listing);
                   5194:             } else {
                   5195:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   5196:             }
                   5197:             return @listing_results;
1.253     stredwic 5198:         } elsif(!defined($alternateDirectoryRoot)) {
                   5199:             my $tryserver;
                   5200:             my %allusers=();
                   5201:             foreach $tryserver (keys %libserv) {
                   5202:                 if($hostdom{$tryserver} eq $udom) {
1.605     matthew  5203:                     my $listing=reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
1.253     stredwic 5204:                                       $udom, $tryserver);
1.605     matthew  5205:                     my @listing_results;
                   5206:                     if ($listing eq 'unknown_cmd') {
                   5207:                         $listing=reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   5208:                                        $udom, $tryserver);
                   5209:                         @listing_results = split(/:/,$listing);
                   5210:                     } else {
                   5211:                         @listing_results =
                   5212:                             map { &unescape($_); } split(/:/,$listing);
                   5213:                     }
                   5214:                     if ($listing_results[0] ne 'no_such_dir' && 
                   5215:                         $listing_results[0] ne 'empty'       &&
                   5216:                         $listing_results[0] ne 'con_lost') {
                   5217:                         foreach (@listing_results) {
1.253     stredwic 5218:                             my ($entry,@stat)=split(/&/,$_);
                   5219:                             $allusers{$entry}=1;
                   5220:                         }
                   5221:                     }
1.191     harris41 5222:                 }
1.253     stredwic 5223:             }
                   5224:             my $alluserstr='';
                   5225:             foreach (sort keys %allusers) {
                   5226:                 $alluserstr.=$_.'&user:';
                   5227:             }
                   5228:             $alluserstr=~s/:$//;
                   5229:             return split(/:/,$alluserstr);
                   5230:         } else {
                   5231:             my @emptyResults = ();
                   5232:             push(@emptyResults, 'missing user name');
                   5233:             return split(':',@emptyResults);
                   5234:         }
                   5235:     } elsif(!defined($alternateDirectoryRoot)) {
                   5236:         my $tryserver;
                   5237:         my %alldom=();
                   5238:         foreach $tryserver (keys %libserv) {
                   5239:             $alldom{$hostdom{$tryserver}}=1;
                   5240:         }
                   5241:         my $alldomstr='';
                   5242:         foreach (sort keys %alldom) {
1.397     albertel 5243:             $alldomstr.=$perlvar{'lonDocRoot'}.'/res/'.$_.'/&domain:';
1.253     stredwic 5244:         }
                   5245:         $alldomstr=~s/:$//;
                   5246:         return split(/:/,$alldomstr);       
                   5247:     } else {
                   5248:         my @emptyResults = ();
                   5249:         push(@emptyResults, 'missing domain');
                   5250:         return split(':',@emptyResults);
1.275     stredwic 5251:     }
                   5252: }
                   5253: 
                   5254: # --------------------------------------------- GetFileTimestamp
                   5255: # This function utilizes dirlist and returns the date stamp for
                   5256: # when it was last modified.  It will also return an error of -1
                   5257: # if an error occurs
                   5258: 
1.410     matthew  5259: ##
                   5260: ## FIXME: This subroutine assumes its caller knows something about the
                   5261: ## directory structure of the home server for the student ($root).
                   5262: ## Not a good assumption to make.  Since this is for looking up files
                   5263: ## in user directories, the full path should be constructed by lond, not
                   5264: ## whatever machine we request data from.
                   5265: ##
1.275     stredwic 5266: sub GetFileTimestamp {
                   5267:     my ($studentDomain,$studentName,$filename,$root)=@_;
                   5268:     $studentDomain=~s/\W//g;
                   5269:     $studentName=~s/\W//g;
                   5270:     my $subdir=$studentName.'__';
                   5271:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   5272:     my $proname="$studentDomain/$subdir/$studentName";
                   5273:     $proname .= '/'.$filename;
1.375     matthew  5274:     my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain, 
                   5275:                                               $studentName, $root);
1.275     stredwic 5276:     my @stats = split('&', $fileStat);
                   5277:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  5278:         # @stats contains first the filename, then the stat output
                   5279:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 5280:     } else {
                   5281:         return -1;
1.253     stredwic 5282:     }
1.26      www      5283: }
                   5284: 
1.712     albertel 5285: sub stat_file {
                   5286:     my ($uri) = @_;
1.722     albertel 5287:     $uri = &clutter($uri);
                   5288: 
                   5289:     # we want just the url part without the unneeded accessor url bits
1.723     banghart 5290:     if ($uri =~ m-^/adm/-) {
                   5291: 	$uri=~s-^/adm/wrapper/-/-;
                   5292: 	$uri=~s-^/adm/coursedocs/showdoc/-/-;
1.722     albertel 5293:     }
1.712     albertel 5294:     my ($udom,$uname,$file,$dir);
                   5295:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   5296: 	($udom,$uname,$file) =
                   5297: 	    ($uri =~ m-/(?:uploaded|editupload)/?([^/]*)/?([^/]*)/?(.*)-);
                   5298: 	$file = 'userfiles/'.$file;
1.740     www      5299: 	$dir = &propath($udom,$uname);
1.712     albertel 5300:     }
                   5301:     if ($uri =~ m-^/res/-) {
                   5302: 	($udom,$uname) = 
                   5303: 	    ($uri =~ m-/(?:res)/?([^/]*)/?([^/]*)/-);
                   5304: 	$file = $uri;
                   5305:     }
                   5306: 
                   5307:     if (!$udom || !$uname || !$file) {
                   5308: 	# unable to handle the uri
                   5309: 	return ();
                   5310:     }
                   5311: 
                   5312:     my ($result) = &dirlist($file,$udom,$uname,$dir);
                   5313:     my @stats = split('&', $result);
1.721     banghart 5314:     
1.712     albertel 5315:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   5316: 	shift(@stats); #filename is first
                   5317: 	return @stats;
                   5318:     }
                   5319:     return ();
                   5320: }
                   5321: 
1.26      www      5322: # -------------------------------------------------------- Value of a Condition
                   5323: 
1.713     albertel 5324: # gets the value of a specific preevaluated condition
                   5325: #    stored in the string  $env{user.state.<cid>}
                   5326: # or looks up a condition reference in the bighash and if if hasn't
                   5327: # already been evaluated recurses into docondval to get the value of
                   5328: # the condition, then memoizing it to 
                   5329: #   $env{user.state.<cid>.<condition>}
1.40      www      5330: sub directcondval {
                   5331:     my $number=shift;
1.620     albertel 5332:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 5333: 	&Apache::lonuserstate::evalstate();
                   5334:     }
1.713     albertel 5335:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   5336: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   5337:     } elsif ($number =~ /^_/) {
                   5338: 	my $sub_condition;
                   5339: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   5340: 		&GDBM_READER(),0640)) {
                   5341: 	    $sub_condition=$bighash{'conditions'.$number};
                   5342: 	    untie(%bighash);
                   5343: 	}
                   5344: 	my $value = &docondval($sub_condition);
                   5345: 	&appenv('user.state.'.$env{'request.course.id'}.".$number" => $value);
                   5346: 	return $value;
                   5347:     }
1.620     albertel 5348:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   5349:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      5350:     } else {
                   5351:        return 2;
                   5352:     }
                   5353: }
                   5354: 
1.713     albertel 5355: # get the collection of conditions for this resource
1.26      www      5356: sub condval {
                   5357:     my $condidx=shift;
1.54      www      5358:     my $allpathcond='';
1.713     albertel 5359:     foreach my $cond (split(/\|/,$condidx)) {
                   5360: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   5361: 	    $allpathcond.=
                   5362: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   5363: 	}
1.191     harris41 5364:     }
1.54      www      5365:     $allpathcond=~s/\|$//;
1.713     albertel 5366:     return &docondval($allpathcond);
                   5367: }
                   5368: 
                   5369: #evaluates an expression of conditions
                   5370: sub docondval {
                   5371:     my ($allpathcond) = @_;
                   5372:     my $result=0;
                   5373:     if ($env{'request.course.id'}
                   5374: 	&& defined($allpathcond)) {
                   5375: 	my $operand='|';
                   5376: 	my @stack;
                   5377: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   5378: 	    if ($chunk eq '(') {
                   5379: 		push @stack,($operand,$result);
                   5380: 	    } elsif ($chunk eq ')') {
                   5381: 		my $before=pop @stack;
                   5382: 		if (pop @stack eq '&') {
                   5383: 		    $result=$result>$before?$before:$result;
                   5384: 		} else {
                   5385: 		    $result=$result>$before?$result:$before;
                   5386: 		}
                   5387: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   5388: 		$operand=$chunk;
                   5389: 	    } else {
                   5390: 		my $new=directcondval($chunk);
                   5391: 		if ($operand eq '&') {
                   5392: 		    $result=$result>$new?$new:$result;
                   5393: 		} else {
                   5394: 		    $result=$result>$new?$result:$new;
                   5395: 		}
                   5396: 	    }
                   5397: 	}
1.26      www      5398:     }
                   5399:     return $result;
1.421     albertel 5400: }
                   5401: 
                   5402: # ---------------------------------------------------- Devalidate courseresdata
                   5403: 
                   5404: sub devalidatecourseresdata {
                   5405:     my ($coursenum,$coursedomain)=@_;
                   5406:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 5407:     &devalidate_cache_new('courseres',$hashid);
1.28      www      5408: }
                   5409: 
1.763     www      5410: 
1.200     www      5411: # --------------------------------------------------- Course Resourcedata Query
                   5412: 
1.624     albertel 5413: sub get_courseresdata {
                   5414:     my ($coursenum,$coursedomain)=@_;
1.200     www      5415:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   5416:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 5417:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 5418:     my %dumpreply;
1.417     albertel 5419:     unless (defined($cached)) {
1.624     albertel 5420: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 5421: 	$result=\%dumpreply;
1.251     albertel 5422: 	my ($tmp) = keys(%dumpreply);
                   5423: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 5424: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 5425: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   5426: 	    return $tmp;
1.416     albertel 5427: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 5428: 	    $result=undef;
1.599     albertel 5429: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 5430: 	}
                   5431:     }
1.624     albertel 5432:     return $result;
                   5433: }
                   5434: 
1.633     albertel 5435: sub devalidateuserresdata {
                   5436:     my ($uname,$udom)=@_;
                   5437:     my $hashid="$udom:$uname";
                   5438:     &devalidate_cache_new('userres',$hashid);
                   5439: }
                   5440: 
1.624     albertel 5441: sub get_userresdata {
                   5442:     my ($uname,$udom)=@_;
                   5443:     #most student don\'t have any data set, check if there is some data
                   5444:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   5445: 
                   5446:     my $hashid="$udom:$uname";
                   5447:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   5448:     if (!defined($cached)) {
                   5449: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   5450: 	$result=\%resourcedata;
                   5451: 	&do_cache_new('userres',$hashid,$result,600);
                   5452:     }
                   5453:     my ($tmp)=keys(%$result);
                   5454:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   5455: 	return $result;
                   5456:     }
                   5457:     #error 2 occurs when the .db doesn't exist
                   5458:     if ($tmp!~/error: 2 /) {
1.672     albertel 5459: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 5460: 		 " Trying to get resource data for ".
                   5461: 		 $uname." at ".$udom.": ".
                   5462: 		 $tmp."</font>");
                   5463:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 5464: 	#&EXT_cache_set($udom,$uname);
                   5465: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 5466: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 5467:     }
                   5468:     return $tmp;
                   5469: }
                   5470: 
                   5471: sub resdata {
                   5472:     my ($name,$domain,$type,@which)=@_;
                   5473:     my $result;
                   5474:     if ($type eq 'course') {
                   5475: 	$result=&get_courseresdata($name,$domain);
                   5476:     } elsif ($type eq 'user') {
                   5477: 	$result=&get_userresdata($name,$domain);
                   5478:     }
                   5479:     if (!ref($result)) { return $result; }    
1.251     albertel 5480:     foreach my $item (@which) {
1.417     albertel 5481: 	if (defined($result->{$item})) {
                   5482: 	    return $result->{$item};
1.251     albertel 5483: 	}
1.250     albertel 5484:     }
1.291     albertel 5485:     return undef;
1.200     www      5486: }
                   5487: 
1.379     matthew  5488: #
                   5489: # EXT resource caching routines
                   5490: #
                   5491: 
                   5492: sub clear_EXT_cache_status {
1.383     albertel 5493:     &delenv('cache.EXT.');
1.379     matthew  5494: }
                   5495: 
                   5496: sub EXT_cache_status {
                   5497:     my ($target_domain,$target_user) = @_;
1.383     albertel 5498:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 5499:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  5500:         # We know already the user has no data
                   5501:         return 1;
                   5502:     } else {
                   5503:         return 0;
                   5504:     }
                   5505: }
                   5506: 
                   5507: sub EXT_cache_set {
                   5508:     my ($target_domain,$target_user) = @_;
1.383     albertel 5509:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.633     albertel 5510:     #&appenv($cachename => time);
1.379     matthew  5511: }
                   5512: 
1.28      www      5513: # --------------------------------------------------------- Value of a Variable
1.58      www      5514: sub EXT {
1.715     albertel 5515: 
1.395     albertel 5516:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      5517:     unless ($varname) { return ''; }
1.218     albertel 5518:     #get real user name/domain, courseid and symb
                   5519:     my $courseid;
1.359     albertel 5520:     my $publicuser;
1.427     www      5521:     if ($symbparm) {
                   5522: 	$symbparm=&get_symb_from_alias($symbparm);
                   5523:     }
1.218     albertel 5524:     if (!($uname && $udom)) {
1.360     albertel 5525:       (my $cursymb,$courseid,$udom,$uname,$publicuser)=
1.378     matthew  5526: 	  &Apache::lonxml::whichuser($symbparm);
1.218     albertel 5527:       if (!$symbparm) {	$symbparm=$cursymb; }
                   5528:     } else {
1.620     albertel 5529: 	$courseid=$env{'request.course.id'};
1.218     albertel 5530:     }
1.48      www      5531:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   5532:     my $rest;
1.320     albertel 5533:     if (defined($therest[0])) {
1.48      www      5534:        $rest=join('.',@therest);
                   5535:     } else {
                   5536:        $rest='';
                   5537:     }
1.320     albertel 5538: 
1.57      www      5539:     my $qualifierrest=$qualifier;
                   5540:     if ($rest) { $qualifierrest.='.'.$rest; }
                   5541:     my $spacequalifierrest=$space;
                   5542:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      5543:     if ($realm eq 'user') {
1.48      www      5544: # --------------------------------------------------------------- user.resource
                   5545: 	if ($space eq 'resource') {
1.651     albertel 5546: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   5547: 		  || defined($Apache::lonhomework::parsing_a_task))
                   5548: 		 &&
1.744     albertel 5549: 		 ($symbparm eq &symbread()) ) {	
                   5550: 		# if we are in the middle of processing the resource the
                   5551: 		# get the value we are planning on committing
                   5552:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   5553:                     return $Apache::lonhomework::results{$qualifierrest};
                   5554:                 } else {
                   5555:                     return $Apache::lonhomework::history{$qualifierrest};
                   5556:                 }
1.335     albertel 5557: 	    } else {
1.359     albertel 5558: 		my %restored;
1.620     albertel 5559: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 5560: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   5561: 		} else {
                   5562: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   5563: 		}
1.335     albertel 5564: 		return $restored{$qualifierrest};
                   5565: 	    }
1.48      www      5566: # ----------------------------------------------------------------- user.access
                   5567:         } elsif ($space eq 'access') {
1.218     albertel 5568: 	    # FIXME - not supporting calls for a specific user
1.48      www      5569:             return &allowed($qualifier,$rest);
                   5570: # ------------------------------------------ user.preferences, user.environment
                   5571:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 5572: 	    if (($uname eq $env{'user.name'}) &&
                   5573: 		($udom eq $env{'user.domain'})) {
                   5574: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 5575: 	    } else {
1.359     albertel 5576: 		my %returnhash;
                   5577: 		if (!$publicuser) {
                   5578: 		    %returnhash=&userenvironment($udom,$uname,
                   5579: 						 $qualifierrest);
                   5580: 		}
1.218     albertel 5581: 		return $returnhash{$qualifierrest};
                   5582: 	    }
1.48      www      5583: # ----------------------------------------------------------------- user.course
                   5584:         } elsif ($space eq 'course') {
1.218     albertel 5585: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 5586:             return $env{join('.',('request.course',$qualifier))};
1.48      www      5587: # ------------------------------------------------------------------- user.role
                   5588:         } elsif ($space eq 'role') {
1.218     albertel 5589: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 5590:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      5591:             if ($qualifier eq 'value') {
                   5592: 		return $role;
                   5593:             } elsif ($qualifier eq 'extent') {
                   5594:                 return $where;
                   5595:             }
                   5596: # ----------------------------------------------------------------- user.domain
                   5597:         } elsif ($space eq 'domain') {
1.218     albertel 5598:             return $udom;
1.48      www      5599: # ------------------------------------------------------------------- user.name
                   5600:         } elsif ($space eq 'name') {
1.218     albertel 5601:             return $uname;
1.48      www      5602: # ---------------------------------------------------- Any other user namespace
1.29      www      5603:         } else {
1.359     albertel 5604: 	    my %reply;
                   5605: 	    if (!$publicuser) {
                   5606: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   5607: 	    }
                   5608: 	    return $reply{$qualifierrest};
1.48      www      5609:         }
1.236     www      5610:     } elsif ($realm eq 'query') {
                   5611: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 5612:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   5613: 						[$spacequalifierrest]);
1.620     albertel 5614: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      5615:    } elsif ($realm eq 'request') {
1.48      www      5616: # ------------------------------------------------------------- request.browser
                   5617:         if ($space eq 'browser') {
1.430     www      5618: 	    if ($qualifier eq 'textremote') {
1.676     albertel 5619: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      5620: 		    return 1;
                   5621: 		} else {
                   5622: 		    return 0;
                   5623: 		}
                   5624: 	    } else {
1.620     albertel 5625: 		return $env{'browser.'.$qualifier};
1.430     www      5626: 	    }
1.57      www      5627: # ------------------------------------------------------------ request.filename
                   5628:         } else {
1.620     albertel 5629:             return $env{'request.'.$spacequalifierrest};
1.29      www      5630:         }
1.28      www      5631:     } elsif ($realm eq 'course') {
1.48      www      5632: # ---------------------------------------------------------- course.description
1.620     albertel 5633:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      5634:     } elsif ($realm eq 'resource') {
1.165     www      5635: 
1.620     albertel 5636: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 5637: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   5638: 	}
1.693     albertel 5639: 
                   5640: 	if ($space eq 'title') {
                   5641: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   5642: 	    return &gettitle($symbparm);
                   5643: 	}
                   5644: 	
                   5645: 	if ($space eq 'map') {
                   5646: 	    my ($map) = &decode_symb($symbparm);
                   5647: 	    return &symbread($map);
                   5648: 	}
                   5649: 
                   5650: 	my ($section, $group, @groups);
1.593     albertel 5651: 	my ($courselevelm,$courselevel);
1.539     albertel 5652: 	if ($symbparm && defined($courseid) && 
1.620     albertel 5653: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      5654: 
1.218     albertel 5655: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      5656: 
1.60      www      5657: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 5658: 	    my $symbp=$symbparm;
1.735     albertel 5659: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 5660: 
                   5661: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   5662: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   5663: 
1.620     albertel 5664: 	    if (($env{'user.name'} eq $uname) &&
                   5665: 		($env{'user.domain'} eq $udom)) {
                   5666: 		$section=$env{'request.course.sec'};
1.733     raeburn  5667:                 @groups = split(/:/,$env{'request.course.groups'});  
                   5668:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 5669: 	    } else {
1.539     albertel 5670: 		if (! defined($usection)) {
1.551     albertel 5671: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 5672: 		} else {
                   5673: 		    $section = $usection;
                   5674: 		}
1.733     raeburn  5675:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 5676: 	    }
                   5677: 
                   5678: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   5679: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   5680: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   5681: 
1.593     albertel 5682: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 5683: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 5684: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      5685: 
1.60      www      5686: # ----------------------------------------------------------- first, check user
1.624     albertel 5687: 
                   5688: 	    my $userreply=&resdata($uname,$udom,'user',
                   5689: 				       ($courselevelr,$courselevelm,
                   5690: 					$courselevel));
                   5691: 	    if (defined($userreply)) { return $userreply; }
1.95      www      5692: 
1.594     albertel 5693: # ------------------------------------------------ second, check some of course
1.684     raeburn  5694:             my $coursereply;
1.691     raeburn  5695:             if (@groups > 0) {
                   5696:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   5697:                                        $mapparm,$spacequalifierrest);
1.684     raeburn  5698:                 if (defined($coursereply)) { return $coursereply; }
                   5699:             }
1.96      www      5700: 
1.684     raeburn  5701: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.624     albertel 5702: 				     $env{'course.'.$courseid.'.domain'},
                   5703: 				     'course',
                   5704: 				     ($seclevelr,$seclevelm,$seclevel,
                   5705: 				      $courselevelr));
1.287     albertel 5706: 	    if (defined($coursereply)) { return $coursereply; }
1.200     www      5707: 
1.60      www      5708: # ------------------------------------------------------ third, check map parms
1.218     albertel 5709: 	    my %parmhash=();
                   5710: 	    my $thisparm='';
                   5711: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 5712: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 5713: 		    &GDBM_READER(),0640)) {
1.218     albertel 5714: 		$thisparm=$parmhash{$symbparm};
                   5715: 		untie(%parmhash);
                   5716: 	    }
                   5717: 	    if ($thisparm) { return $thisparm; }
                   5718: 	}
1.594     albertel 5719: # ------------------------------------------ fourth, look in resource metadata
1.71      www      5720: 
1.218     albertel 5721: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 5722: 	my $filename;
                   5723: 	if (!$symbparm) { $symbparm=&symbread(); }
                   5724: 	if ($symbparm) {
1.409     www      5725: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 5726: 	} else {
1.620     albertel 5727: 	    $filename=$env{'request.filename'};
1.282     albertel 5728: 	}
                   5729: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.288     albertel 5730: 	if (defined($metadata)) { return $metadata; }
1.282     albertel 5731: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.288     albertel 5732: 	if (defined($metadata)) { return $metadata; }
1.142     www      5733: 
1.594     albertel 5734: # ---------------------------------------------- fourth, look in rest pf course
1.593     albertel 5735: 	if ($symbparm && defined($courseid) && 
1.620     albertel 5736: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 5737: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   5738: 				     $env{'course.'.$courseid.'.domain'},
                   5739: 				     'course',
                   5740: 				     ($courselevelm,$courselevel));
1.593     albertel 5741: 	    if (defined($coursereply)) { return $coursereply; }
                   5742: 	}
1.145     www      5743: # ------------------------------------------------------------------ Cascade up
1.218     albertel 5744: 	unless ($space eq '0') {
1.336     albertel 5745: 	    my @parts=split(/_/,$space);
                   5746: 	    my $id=pop(@parts);
                   5747: 	    my $part=join('_',@parts);
                   5748: 	    if ($part eq '') { $part='0'; }
                   5749: 	    my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 5750: 				 $symbparm,$udom,$uname,$section,1);
1.337     albertel 5751: 	    if (defined($partgeneral)) { return $partgeneral; }
1.218     albertel 5752: 	}
1.395     albertel 5753: 	if ($recurse) { return undef; }
                   5754: 	my $pack_def=&packages_tab_default($filename,$varname);
                   5755: 	if (defined($pack_def)) { return $pack_def; }
1.71      www      5756: 
1.48      www      5757: # ---------------------------------------------------- Any other user namespace
                   5758:     } elsif ($realm eq 'environment') {
                   5759: # ----------------------------------------------------------------- environment
1.620     albertel 5760: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   5761: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 5762: 	} else {
1.770     albertel 5763: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   5764: 		return '';
                   5765: 	    }
1.219     albertel 5766: 	    my %returnhash=&userenvironment($udom,$uname,
                   5767: 					    $spacequalifierrest);
                   5768: 	    return $returnhash{$spacequalifierrest};
                   5769: 	}
1.28      www      5770:     } elsif ($realm eq 'system') {
1.48      www      5771: # ----------------------------------------------------------------- system.time
                   5772: 	if ($space eq 'time') {
                   5773: 	    return time;
                   5774:         }
1.696     albertel 5775:     } elsif ($realm eq 'server') {
                   5776: # ----------------------------------------------------------------- system.time
                   5777: 	if ($space eq 'name') {
                   5778: 	    return $ENV{'SERVER_NAME'};
                   5779:         }
1.28      www      5780:     }
1.48      www      5781:     return '';
1.61      www      5782: }
                   5783: 
1.691     raeburn  5784: sub check_group_parms {
                   5785:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   5786:     my @groupitems = ();
                   5787:     my $resultitem;
                   5788:     my @levels = ($symbparm,$mapparm,$what);
                   5789:     foreach my $group (@{$groups}) {
                   5790:         foreach my $level (@levels) {
                   5791:              my $item = $courseid.'.['.$group.'].'.$level;
                   5792:              push(@groupitems,$item);
                   5793:         }
                   5794:     }
                   5795:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   5796:                             $env{'course.'.$courseid.'.domain'},
                   5797:                                      'course',@groupitems);
                   5798:     return $coursereply;
                   5799: }
                   5800: 
                   5801: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  5802:     my ($courseid,@groups) = @_;
                   5803:     @groups = sort(@groups);
1.691     raeburn  5804:     return @groups;
                   5805: }
                   5806: 
1.395     albertel 5807: sub packages_tab_default {
                   5808:     my ($uri,$varname)=@_;
                   5809:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 5810: 
                   5811:     my (@extension,@specifics,$do_default);
                   5812:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 5813: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 5814: 	if ($pack_type eq 'default') {
                   5815: 	    $do_default=1;
                   5816: 	} elsif ($pack_type eq 'extension') {
                   5817: 	    push(@extension,[$package,$pack_type,$pack_part]);
                   5818: 	} else {
                   5819: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   5820: 	}
                   5821:     }
                   5822:     # first look for a package that matches the requested part id
                   5823:     foreach my $package (@specifics) {
                   5824: 	my (undef,$pack_type,$pack_part)=@{$package};
                   5825: 	next if ($pack_part ne $part);
                   5826: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   5827: 	    return $packagetab{"$pack_type&$name&default"};
                   5828: 	}
                   5829:     }
                   5830:     # look for any possible matching non extension_ package
                   5831:     foreach my $package (@specifics) {
                   5832: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 5833: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   5834: 	    return $packagetab{"$pack_type&$name&default"};
                   5835: 	}
1.585     albertel 5836: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 5837: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   5838: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 5839: 	}
                   5840:     }
1.738     albertel 5841:     # look for any posible extension_ match
                   5842:     foreach my $package (@extension) {
                   5843: 	my ($package,$pack_type)=@{$package};
                   5844: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   5845: 	    return $packagetab{"$pack_type&$name&default"};
                   5846: 	}
                   5847: 	if (defined($packagetab{$package."&$name&default"})) {
                   5848: 	    return $packagetab{$package."&$name&default"};
                   5849: 	}
                   5850:     }
                   5851:     # look for a global default setting
                   5852:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   5853: 	return $packagetab{"default&$name&default"};
                   5854:     }
1.395     albertel 5855:     return undef;
                   5856: }
                   5857: 
1.334     albertel 5858: sub add_prefix_and_part {
                   5859:     my ($prefix,$part)=@_;
                   5860:     my $keyroot;
                   5861:     if (defined($prefix) && $prefix !~ /^__/) {
                   5862: 	# prefix that has a part already
                   5863: 	$keyroot=$prefix;
                   5864:     } elsif (defined($prefix)) {
                   5865: 	# prefix that is missing a part
                   5866: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   5867:     } else {
                   5868: 	# no prefix at all
                   5869: 	if (defined($part)) { $keyroot='_'.$part; }
                   5870:     }
                   5871:     return $keyroot;
                   5872: }
                   5873: 
1.71      www      5874: # ---------------------------------------------------------------- Get metadata
                   5875: 
1.599     albertel 5876: my %metaentry;
1.71      www      5877: sub metadata {
1.176     www      5878:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      5879:     $uri=&declutter($uri);
1.288     albertel 5880:     # if it is a non metadata possible uri return quickly
1.529     albertel 5881:     if (($uri eq '') || 
                   5882: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 5883: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.423     albertel 5884:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) ||
1.489     albertel 5885: 	($uri =~ m|home/[^/]+/public_html/|)) {
1.468     albertel 5886: 	return undef;
1.288     albertel 5887:     }
1.73      www      5888:     my $filename=$uri;
                   5889:     $uri=~s/\.meta$//;
1.172     www      5890: #
                   5891: # Is the metadata already cached?
1.177     www      5892: # Look at timestamp of caching
1.172     www      5893: # Everything is cached by the main uri, libraries are never directly cached
                   5894: #
1.428     albertel 5895:     if (!defined($liburi)) {
1.599     albertel 5896: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 5897: 	if (defined($cached)) { return $result->{':'.$what}; }
                   5898:     }
                   5899:     {
1.172     www      5900: #
                   5901: # Is this a recursive call for a library?
                   5902: #
1.599     albertel 5903: #	if (! exists($metacache{$uri})) {
                   5904: #	    $metacache{$uri}={};
                   5905: #	}
1.171     www      5906:         if ($liburi) {
                   5907: 	    $liburi=&declutter($liburi);
                   5908:             $filename=$liburi;
1.401     bowersj2 5909:         } else {
1.599     albertel 5910: 	    &devalidate_cache_new('meta',$uri);
                   5911: 	    undef(%metaentry);
1.401     bowersj2 5912: 	}
1.140     www      5913:         my %metathesekeys=();
1.73      www      5914:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 5915: 	my $metastring;
1.768     albertel 5916: 	if ($uri !~ m -^(editupload)/-) {
1.543     albertel 5917: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 5918: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 5919: 	    $metastring=&getfile($file);
1.489     albertel 5920: 	}
1.208     albertel 5921:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      5922:         my $token;
1.140     www      5923:         undef %metathesekeys;
1.71      www      5924:         while ($token=$parser->get_token) {
1.339     albertel 5925: 	    if ($token->[0] eq 'S') {
                   5926: 		if (defined($token->[2]->{'package'})) {
1.172     www      5927: #
                   5928: # This is a package - get package info
                   5929: #
1.339     albertel 5930: 		    my $package=$token->[2]->{'package'};
                   5931: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   5932: 		    if (defined($token->[2]->{'id'})) { 
                   5933: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   5934: 		    }
1.599     albertel 5935: 		    if ($metaentry{':packages'}) {
                   5936: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 5937: 		    } else {
1.599     albertel 5938: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 5939: 		    }
1.736     albertel 5940: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 5941: 			my $part=$keyroot;
                   5942: 			$part=~s/^\_//;
1.736     albertel 5943: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   5944: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   5945: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 5946: 			    # ignore package.tab specified default values
                   5947:                             # here &package_tab_default() will fetch those
                   5948: 			    if ($subp eq 'default') { next; }
1.736     albertel 5949: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 5950: 			    my $unikey;
                   5951: 			    if ($pack =~ /_0$/) {
                   5952: 				$unikey='parameter_0_'.$name;
                   5953: 				$part=0;
                   5954: 			    } else {
                   5955: 				$unikey='parameter'.$keyroot.'_'.$name;
                   5956: 			    }
1.339     albertel 5957: 			    if ($subp eq 'display') {
                   5958: 				$value.=' [Part: '.$part.']';
                   5959: 			    }
1.599     albertel 5960: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 5961: 			    $metathesekeys{$unikey}=1;
1.599     albertel 5962: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   5963: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 5964: 			    }
1.599     albertel 5965: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   5966: 				$metaentry{':'.$unikey}=
                   5967: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 5968: 			    }
1.339     albertel 5969: 			}
                   5970: 		    }
                   5971: 		} else {
1.172     www      5972: #
                   5973: # This is not a package - some other kind of start tag
1.339     albertel 5974: #
                   5975: 		    my $entry=$token->[1];
                   5976: 		    my $unikey;
                   5977: 		    if ($entry eq 'import') {
                   5978: 			$unikey='';
                   5979: 		    } else {
                   5980: 			$unikey=$entry;
                   5981: 		    }
                   5982: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   5983: 
                   5984: 		    if (defined($token->[2]->{'id'})) { 
                   5985: 			$unikey.='_'.$token->[2]->{'id'}; 
                   5986: 		    }
1.175     www      5987: 
1.339     albertel 5988: 		    if ($entry eq 'import') {
1.175     www      5989: #
                   5990: # Importing a library here
1.339     albertel 5991: #
                   5992: 			if ($depthcount<20) {
                   5993: 			    my $location=$parser->get_text('/import');
                   5994: 			    my $dir=$filename;
                   5995: 			    $dir=~s|[^/]*$||;
                   5996: 			    $location=&filelocation($dir,$location);
1.736     albertel 5997: 			    my $metadata = 
                   5998: 				&metadata($uri,'keys', $location,$unikey,
                   5999: 					  $depthcount+1);
                   6000: 			    foreach my $meta (split(',',$metadata)) {
                   6001: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   6002: 				$metathesekeys{$meta}=1;
1.339     albertel 6003: 			    }
                   6004: 			}
                   6005: 		    } else { 
                   6006: 			
                   6007: 			if (defined($token->[2]->{'name'})) { 
                   6008: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   6009: 			}
                   6010: 			$metathesekeys{$unikey}=1;
1.736     albertel 6011: 			foreach my $param (@{$token->[3]}) {
                   6012: 			    $metaentry{':'.$unikey.'.'.$param} =
                   6013: 				$token->[2]->{$param};
1.339     albertel 6014: 			}
                   6015: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 6016: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 6017: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   6018: 		 # only ws inside the tag, and not in default, so use default
                   6019: 		 # as value
1.599     albertel 6020: 			    $metaentry{':'.$unikey}=$default;
1.339     albertel 6021: 			} else {
1.321     albertel 6022: 		  # either something interesting inside the tag or default
                   6023:                   # uninteresting
1.599     albertel 6024: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 6025: 			}
1.172     www      6026: # end of not-a-package not-a-library import
1.339     albertel 6027: 		    }
1.172     www      6028: # end of not-a-package start tag
1.339     albertel 6029: 		}
1.172     www      6030: # the next is the end of "start tag"
1.339     albertel 6031: 	    }
                   6032: 	}
1.483     albertel 6033: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.737     albertel 6034: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 6035: 	    #no specific packages #how's our extension
                   6036: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 6037: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 6038: 					 \%metathesekeys);
                   6039: 	}
1.599     albertel 6040: 	if (!exists($metaentry{':packages'})) {
1.737     albertel 6041: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 6042: 		#no specific packages well let's get default then
                   6043: 		if ($key!~/^default&/) { next; }
1.488     albertel 6044: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 6045: 					     \%metathesekeys);
                   6046: 	    }
                   6047: 	}
1.338     www      6048: # are there custom rights to evaluate
1.599     albertel 6049: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 6050: 
1.338     www      6051:     #
                   6052:     # Importing a rights file here
1.339     albertel 6053:     #
                   6054: 	    unless ($depthcount) {
1.599     albertel 6055: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 6056: 		my $dir=$filename;
                   6057: 		$dir=~s|[^/]*$||;
                   6058: 		$location=&filelocation($dir,$location);
1.736     albertel 6059: 		my $rights_metadata =
                   6060: 		    &metadata($uri,'keys',$location,'_rights',
                   6061: 			      $depthcount+1);
                   6062: 		foreach my $rights (split(',',$rights_metadata)) {
                   6063: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   6064: 		    $metathesekeys{$rights}=1;
1.339     albertel 6065: 		}
                   6066: 	    }
                   6067: 	}
1.737     albertel 6068: 	# uniqifiy package listing
                   6069: 	my %seen;
                   6070: 	my @uniq_packages =
                   6071: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   6072: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   6073: 
                   6074: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 6075: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   6076: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.699     albertel 6077: 	&do_cache_new('meta',$uri,\%metaentry,60*60);
1.177     www      6078: # this is the end of "was not already recently cached
1.71      www      6079:     }
1.599     albertel 6080:     return $metaentry{':'.$what};
1.261     albertel 6081: }
                   6082: 
1.488     albertel 6083: sub metadata_create_package_def {
1.483     albertel 6084:     my ($uri,$key,$package,$metathesekeys)=@_;
                   6085:     my ($pack,$name,$subp)=split(/\&/,$key);
                   6086:     if ($subp eq 'default') { next; }
                   6087:     
1.599     albertel 6088:     if (defined($metaentry{':packages'})) {
                   6089: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 6090:     } else {
1.599     albertel 6091: 	$metaentry{':packages'}=$package;
1.483     albertel 6092:     }
                   6093:     my $value=$packagetab{$key};
                   6094:     my $unikey;
                   6095:     $unikey='parameter_0_'.$name;
1.599     albertel 6096:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 6097:     $$metathesekeys{$unikey}=1;
1.599     albertel 6098:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   6099: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 6100:     }
1.599     albertel 6101:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   6102: 	$metaentry{':'.$unikey}=
                   6103: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 6104:     }
                   6105: }
                   6106: 
1.261     albertel 6107: sub metadata_generate_part0 {
                   6108:     my ($metadata,$metacache,$uri) = @_;
                   6109:     my %allnames;
1.737     albertel 6110:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 6111: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 6112: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   6113: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 6114: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 6115: 	    $allnames{$name}=$part;
                   6116: 	  }
                   6117: 	}
                   6118:     }
                   6119:     foreach my $name (keys(%allnames)) {
                   6120:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 6121:       my $key=":parameter_0_$name";
1.261     albertel 6122:       $$metacache{"$key.part"}='0';
                   6123:       $$metacache{"$key.name"}=$name;
1.428     albertel 6124:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 6125: 					   $allnames{$name}.'_'.$name.
                   6126: 					   '.type'};
1.428     albertel 6127:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 6128: 			     '.display'};
1.644     www      6129:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 6130:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 6131:       $$metacache{"$key.display"}=$olddis;
                   6132:     }
1.71      www      6133: }
                   6134: 
1.764     albertel 6135: # ------------------------------------------------------ Devalidate title cache
                   6136: 
                   6137: sub devalidate_title_cache {
                   6138:     my ($url)=@_;
                   6139:     if (!$env{'request.course.id'}) { return; }
                   6140:     my $symb=&symbread($url);
                   6141:     if (!$symb) { return; }
                   6142:     my $key=$env{'request.course.id'}."\0".$symb;
                   6143:     &devalidate_cache_new('title',$key);
                   6144: }
                   6145: 
1.301     www      6146: # ------------------------------------------------- Get the title of a resource
                   6147: 
                   6148: sub gettitle {
                   6149:     my $urlsymb=shift;
                   6150:     my $symb=&symbread($urlsymb);
1.534     albertel 6151:     if ($symb) {
1.620     albertel 6152: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 6153: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 6154: 	if (defined($cached)) { 
                   6155: 	    return $result;
                   6156: 	}
1.534     albertel 6157: 	my ($map,$resid,$url)=&decode_symb($symb);
                   6158: 	my $title='';
                   6159: 	my %bighash;
1.620     albertel 6160: 	if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.534     albertel 6161: 		&GDBM_READER(),0640)) {
                   6162: 	    my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   6163: 	    $title=$bighash{'title_'.$mapid.'.'.$resid};
                   6164: 	    untie %bighash;
                   6165: 	}
                   6166: 	$title=~s/\&colon\;/\:/gs;
                   6167: 	if ($title) {
1.599     albertel 6168: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 6169: 	}
                   6170: 	$urlsymb=$url;
                   6171:     }
                   6172:     my $title=&metadata($urlsymb,'title');
                   6173:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   6174:     return $title;
1.301     www      6175: }
1.613     albertel 6176: 
1.614     albertel 6177: sub get_slot {
                   6178:     my ($which,$cnum,$cdom)=@_;
                   6179:     if (!$cnum || !$cdom) {
                   6180: 	(undef,my $courseid)=&Apache::lonxml::whichuser();
1.620     albertel 6181: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   6182: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 6183:     }
1.703     albertel 6184:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   6185:     my %slotinfo;
                   6186:     if (exists($remembered{$key})) {
                   6187: 	$slotinfo{$which} = $remembered{$key};
                   6188:     } else {
                   6189: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   6190: 	&Apache::lonhomework::showhash(%slotinfo);
                   6191: 	my ($tmp)=keys(%slotinfo);
                   6192: 	if ($tmp=~/^error:/) { return (); }
                   6193: 	$remembered{$key} = $slotinfo{$which};
                   6194:     }
1.616     albertel 6195:     if (ref($slotinfo{$which}) eq 'HASH') {
                   6196: 	return %{$slotinfo{$which}};
                   6197:     }
                   6198:     return $slotinfo{$which};
1.614     albertel 6199: }
1.31      www      6200: # ------------------------------------------------- Update symbolic store links
                   6201: 
                   6202: sub symblist {
                   6203:     my ($mapname,%newhash)=@_;
1.438     www      6204:     $mapname=&deversion(&declutter($mapname));
1.31      www      6205:     my %hash;
1.620     albertel 6206:     if (($env{'request.course.fn'}) && (%newhash)) {
                   6207:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 6208:                       &GDBM_WRCREAT(),0640)) {
1.711     albertel 6209: 	    foreach my $url (keys %newhash) {
                   6210: 		next if ($url eq 'last_known'
                   6211: 			 && $env{'form.no_update_last_known'});
                   6212: 		$hash{declutter($url)}=&encode_symb($mapname,
                   6213: 						    $newhash{$url}->[1],
                   6214: 						    $newhash{$url}->[0]);
1.191     harris41 6215:             }
1.31      www      6216:             if (untie(%hash)) {
                   6217: 		return 'ok';
                   6218:             }
                   6219:         }
                   6220:     }
                   6221:     return 'error';
1.212     www      6222: }
                   6223: 
                   6224: # --------------------------------------------------------------- Verify a symb
                   6225: 
                   6226: sub symbverify {
1.510     www      6227:     my ($symb,$thisurl)=@_;
                   6228:     my $thisfn=$thisurl;
                   6229: # wrapper not part of symbs
                   6230:     $thisfn=~s/^\/adm\/wrapper//;
1.694     albertel 6231:     $thisfn=~s/^\/adm\/coursedocs\/showdoc\///;
1.439     www      6232:     $thisfn=&declutter($thisfn);
1.215     www      6233: # direct jump to resource in page or to a sequence - will construct own symbs
                   6234:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   6235: # check URL part
1.409     www      6236:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      6237: 
1.431     www      6238:     unless ($url eq $thisfn) { return 0; }
1.213     www      6239: 
1.216     www      6240:     $symb=&symbclean($symb);
1.510     www      6241:     $thisurl=&deversion($thisurl);
1.439     www      6242:     $thisfn=&deversion($thisfn);
1.213     www      6243: 
                   6244:     my %bighash;
                   6245:     my $okay=0;
1.431     www      6246: 
1.620     albertel 6247:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 6248:                             &GDBM_READER(),0640)) {
1.510     www      6249:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      6250:         unless ($ids) { 
1.510     www      6251:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      6252:         }
                   6253:         if ($ids) {
                   6254: # ------------------------------------------------------------------- Has ID(s)
                   6255: 	    foreach (split(/\,/,$ids)) {
1.644     www      6256: 	       my ($mapid,$resid)=split(/\./,$_);
1.216     www      6257:                if (
                   6258:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   6259:    eq $symb) { 
1.620     albertel 6260: 		   if (($env{'request.role.adv'}) ||
                   6261: 		       $bighash{'encrypted_'.$_} eq $env{'request.enc'}) {
1.582     albertel 6262: 		       $okay=1; 
                   6263: 		   }
                   6264: 	       }
1.216     www      6265: 	   }
                   6266:         }
1.213     www      6267: 	untie(%bighash);
                   6268:     }
                   6269:     return $okay;
1.31      www      6270: }
                   6271: 
1.210     www      6272: # --------------------------------------------------------------- Clean-up symb
                   6273: 
                   6274: sub symbclean {
                   6275:     my $symb=shift;
1.568     albertel 6276:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      6277: # remove version from map
                   6278:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      6279: 
1.210     www      6280: # remove version from URL
                   6281:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      6282: 
1.507     www      6283: # remove wrapper
                   6284: 
1.510     www      6285:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 6286:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      6287:     return $symb;
1.409     www      6288: }
                   6289: 
                   6290: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 6291: 
                   6292: sub encode_symb {
                   6293:     my ($map,$resid,$url)=@_;
                   6294:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   6295: }
1.409     www      6296: 
                   6297: sub decode_symb {
1.568     albertel 6298:     my $symb=shift;
                   6299:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   6300:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      6301:     return (&fixversion($map),$resid,&fixversion($url));
                   6302: }
                   6303: 
                   6304: sub fixversion {
                   6305:     my $fn=shift;
1.609     banghart 6306:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      6307:     my %bighash;
                   6308:     my $uri=&clutter($fn);
1.620     albertel 6309:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      6310: # is this cached?
1.599     albertel 6311:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      6312:     if (defined($cached)) { return $result; }
                   6313: # unfortunately not cached, or expired
1.620     albertel 6314:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      6315: 	    &GDBM_READER(),0640)) {
                   6316:  	if ($bighash{'version_'.$uri}) {
                   6317:  	    my $version=$bighash{'version_'.$uri};
1.444     www      6318:  	    unless (($version eq 'mostrecent') || 
                   6319: 		    ($version==&getversion($uri))) {
1.440     www      6320:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   6321:  	    }
                   6322:  	}
                   6323:  	untie %bighash;
1.413     www      6324:     }
1.599     albertel 6325:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      6326: }
                   6327: 
                   6328: sub deversion {
                   6329:     my $url=shift;
                   6330:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   6331:     return $url;
1.210     www      6332: }
                   6333: 
1.31      www      6334: # ------------------------------------------------------ Return symb list entry
                   6335: 
                   6336: sub symbread {
1.249     www      6337:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 6338:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 6339:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      6340: # no filename provided? try from environment
1.44      www      6341:     unless ($thisfn) {
1.620     albertel 6342:         if ($env{'request.symb'}) {
                   6343: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 6344: 	}
1.620     albertel 6345: 	$thisfn=$env{'request.filename'};
1.44      www      6346:     }
1.569     albertel 6347:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      6348: # is that filename actually a symb? Verify, clean, and return
                   6349:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 6350: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 6351: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 6352: 	}
1.242     www      6353:     }
1.44      www      6354:     $thisfn=declutter($thisfn);
1.31      www      6355:     my %hash;
1.37      www      6356:     my %bighash;
                   6357:     my $syval='';
1.620     albertel 6358:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  6359:         my $targetfn = $thisfn;
1.609     banghart 6360:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  6361:             $targetfn = 'adm/wrapper/'.$thisfn;
                   6362:         }
1.687     albertel 6363: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   6364: 	    $targetfn=$1;
                   6365: 	}
1.620     albertel 6366:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 6367:                       &GDBM_READER(),0640)) {
1.481     raeburn  6368: 	    $syval=$hash{$targetfn};
1.37      www      6369:             untie(%hash);
                   6370:         }
                   6371: # ---------------------------------------------------------- There was an entry
                   6372:         if ($syval) {
1.601     albertel 6373: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 6374: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.601     albertel 6375: 		    #&appenv('request.ambiguous' => $thisfn);
1.620     albertel 6376: 		    #return $env{$cache_str}='';
1.601     albertel 6377: 		#}    
                   6378: 		#$syval.=$1;
                   6379: 	    #}
1.37      www      6380:         } else {
                   6381: # ------------------------------------------------------- Was not in symb table
1.620     albertel 6382:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 6383:                             &GDBM_READER(),0640)) {
1.37      www      6384: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      6385:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      6386:               unless ($ids) { 
                   6387:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      6388:               }
                   6389:               unless ($ids) {
                   6390: # alias?
                   6391: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      6392:               }
1.37      www      6393:               if ($ids) {
                   6394: # ------------------------------------------------------------------- Has ID(s)
                   6395:                  my @possibilities=split(/\,/,$ids);
1.39      www      6396:                  if ($#possibilities==0) {
                   6397: # ----------------------------------------------- There is only one possibility
1.37      www      6398: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 6399: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   6400: 						    $resid,$thisfn);
1.249     www      6401:                  } elsif (!$donotrecurse) {
1.39      www      6402: # ------------------------------------------ There is more than one possibility
                   6403:                      my $realpossible=0;
1.191     harris41 6404:                      foreach (@possibilities) {
1.39      www      6405: 			 my $file=$bighash{'src_'.$_};
                   6406:                          if (&allowed('bre',$file)) {
                   6407:          		    my ($mapid,$resid)=split(/\./,$_);
                   6408:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   6409: 				$realpossible++;
1.626     albertel 6410:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   6411: 						    $resid,$thisfn);
1.39      www      6412:                             }
                   6413: 			 }
1.191     harris41 6414:                      }
1.39      www      6415: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      6416:                  } else {
                   6417:                      $syval='';
1.37      www      6418:                  }
                   6419: 	      }
                   6420:               untie(%bighash)
1.481     raeburn  6421:            }
1.31      www      6422:         }
1.62      www      6423:         if ($syval) {
1.620     albertel 6424: 	    return $env{$cache_str}=$syval;
1.62      www      6425:         }
1.31      www      6426:     }
1.44      www      6427:     &appenv('request.ambiguous' => $thisfn);
1.620     albertel 6428:     return $env{$cache_str}='';
1.31      www      6429: }
                   6430: 
                   6431: # ---------------------------------------------------------- Return random seed
                   6432: 
1.32      www      6433: sub numval {
                   6434:     my $txt=shift;
                   6435:     $txt=~tr/A-J/0-9/;
                   6436:     $txt=~tr/a-j/0-9/;
                   6437:     $txt=~tr/K-T/0-9/;
                   6438:     $txt=~tr/k-t/0-9/;
                   6439:     $txt=~tr/U-Z/0-5/;
                   6440:     $txt=~tr/u-z/0-5/;
                   6441:     $txt=~s/\D//g;
1.564     albertel 6442:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      6443:     return int($txt);
1.368     albertel 6444: }
                   6445: 
1.484     albertel 6446: sub numval2 {
                   6447:     my $txt=shift;
                   6448:     $txt=~tr/A-J/0-9/;
                   6449:     $txt=~tr/a-j/0-9/;
                   6450:     $txt=~tr/K-T/0-9/;
                   6451:     $txt=~tr/k-t/0-9/;
                   6452:     $txt=~tr/U-Z/0-5/;
                   6453:     $txt=~tr/u-z/0-5/;
                   6454:     $txt=~s/\D//g;
                   6455:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   6456:     my $total;
                   6457:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 6458:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 6459:     return int($total);
                   6460: }
                   6461: 
1.575     albertel 6462: sub numval3 {
                   6463:     use integer;
                   6464:     my $txt=shift;
                   6465:     $txt=~tr/A-J/0-9/;
                   6466:     $txt=~tr/a-j/0-9/;
                   6467:     $txt=~tr/K-T/0-9/;
                   6468:     $txt=~tr/k-t/0-9/;
                   6469:     $txt=~tr/U-Z/0-5/;
                   6470:     $txt=~tr/u-z/0-5/;
                   6471:     $txt=~s/\D//g;
                   6472:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   6473:     my $total;
                   6474:     foreach my $val (@txts) { $total+=$val; }
                   6475:     if ($_64bit) { $total=(($total<<32)>>32); }
                   6476:     return $total;
                   6477: }
                   6478: 
1.675     albertel 6479: sub digest {
                   6480:     my ($data)=@_;
                   6481:     my $digest=&Digest::MD5::md5($data);
                   6482:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   6483:     my ($e,$f);
                   6484:     {
                   6485:         use integer;
                   6486:         $e=($a+$b);
                   6487:         $f=($c+$d);
                   6488:         if ($_64bit) {
                   6489:             $e=(($e<<32)>>32);
                   6490:             $f=(($f<<32)>>32);
                   6491:         }
                   6492:     }
                   6493:     if (wantarray) {
                   6494: 	return ($e,$f);
                   6495:     } else {
                   6496: 	my $g;
                   6497: 	{
                   6498: 	    use integer;
                   6499: 	    $g=($e+$f);
                   6500: 	    if ($_64bit) {
                   6501: 		$g=(($g<<32)>>32);
                   6502: 	    }
                   6503: 	}
                   6504: 	return $g;
                   6505:     }
                   6506: }
                   6507: 
1.368     albertel 6508: sub latest_rnd_algorithm_id {
1.675     albertel 6509:     return '64bit5';
1.366     albertel 6510: }
1.32      www      6511: 
1.503     albertel 6512: sub get_rand_alg {
                   6513:     my ($courseid)=@_;
                   6514:     if (!$courseid) { $courseid=(&Apache::lonxml::whichuser())[1]; }
                   6515:     if ($courseid) {
1.620     albertel 6516: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 6517:     }
                   6518:     return &latest_rnd_algorithm_id();
                   6519: }
                   6520: 
1.562     albertel 6521: sub validCODE {
                   6522:     my ($CODE)=@_;
                   6523:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   6524:     return 0;
                   6525: }
                   6526: 
1.491     albertel 6527: sub getCODE {
1.620     albertel 6528:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 6529:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   6530: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   6531: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 6532: 	return $Apache::lonhomework::history{'resource.CODE'};
                   6533:     }
                   6534:     return undef;
                   6535: }
                   6536: 
1.31      www      6537: sub rndseed {
1.155     albertel 6538:     my ($symb,$courseid,$domain,$username)=@_;
1.366     albertel 6539: 
                   6540:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&Apache::lonxml::whichuser();
1.155     albertel 6541:     if (!$symb) {
1.366     albertel 6542: 	unless ($symb=$wsymb) { return time; }
                   6543:     }
                   6544:     if (!$courseid) { $courseid=$wcourseid; }
                   6545:     if (!$domain) { $domain=$wdomain; }
                   6546:     if (!$username) { $username=$wusername }
1.503     albertel 6547:     my $which=&get_rand_alg();
1.491     albertel 6548:     if (defined(&getCODE())) {
1.675     albertel 6549: 	if ($which eq '64bit5') {
                   6550: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   6551: 	} elsif ($which eq '64bit4') {
1.575     albertel 6552: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   6553: 	} else {
                   6554: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   6555: 	}
1.675     albertel 6556:     } elsif ($which eq '64bit5') {
                   6557: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 6558:     } elsif ($which eq '64bit4') {
                   6559: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 6560:     } elsif ($which eq '64bit3') {
                   6561: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 6562:     } elsif ($which eq '64bit2') {
                   6563: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 6564:     } elsif ($which eq '64bit') {
                   6565: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   6566:     }
                   6567:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   6568: }
                   6569: 
                   6570: sub rndseed_32bit {
                   6571:     my ($symb,$courseid,$domain,$username)=@_;
                   6572:     {
                   6573: 	use integer;
                   6574: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   6575: 	my $symbseed=numval($symb) << 22;
                   6576: 	my $namechck=unpack("%32C*",$username) << 17;
                   6577: 	my $nameseed=numval($username) << 12;
                   6578: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   6579: 	my $courseseed=unpack("%32C*",$courseid);
                   6580: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
                   6581: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6582: 	#&Apache::lonxml::debug("rndseed :$num:$symb");
1.564     albertel 6583: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 6584: 	return $num;
                   6585:     }
                   6586: }
                   6587: 
                   6588: sub rndseed_64bit {
                   6589:     my ($symb,$courseid,$domain,$username)=@_;
                   6590:     {
                   6591: 	use integer;
                   6592: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   6593: 	my $symbseed=numval($symb) << 10;
                   6594: 	my $namechck=unpack("%32S*",$username);
                   6595: 	
                   6596: 	my $nameseed=numval($username) << 21;
                   6597: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   6598: 	my $courseseed=unpack("%32S*",$courseid);
                   6599: 	
                   6600: 	my $num1=$symbchck+$symbseed+$namechck;
                   6601: 	my $num2=$nameseed+$domainseed+$courseseed;
                   6602: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6603: 	#&Apache::lonxml::debug("rndseed :$num:$symb");
1.564     albertel 6604: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   6605: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 6606: 	return "$num1,$num2";
1.155     albertel 6607:     }
1.366     albertel 6608: }
                   6609: 
1.443     albertel 6610: sub rndseed_64bit2 {
                   6611:     my ($symb,$courseid,$domain,$username)=@_;
                   6612:     {
                   6613: 	use integer;
                   6614: 	# strings need to be an even # of cahracters long, it it is odd the
                   6615:         # last characters gets thrown away
                   6616: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6617: 	my $symbseed=numval($symb) << 10;
                   6618: 	my $namechck=unpack("%32S*",$username.' ');
                   6619: 	
                   6620: 	my $nameseed=numval($username) << 21;
1.501     albertel 6621: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   6622: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6623: 	
                   6624: 	my $num1=$symbchck+$symbseed+$namechck;
                   6625: 	my $num2=$nameseed+$domainseed+$courseseed;
                   6626: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6627: 	#&Apache::lonxml::debug("rndseed :$num:$symb");
                   6628: 	return "$num1,$num2";
                   6629:     }
                   6630: }
                   6631: 
                   6632: sub rndseed_64bit3 {
                   6633:     my ($symb,$courseid,$domain,$username)=@_;
                   6634:     {
                   6635: 	use integer;
                   6636: 	# strings need to be an even # of cahracters long, it it is odd the
                   6637:         # last characters gets thrown away
                   6638: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6639: 	my $symbseed=numval2($symb) << 10;
                   6640: 	my $namechck=unpack("%32S*",$username.' ');
                   6641: 	
                   6642: 	my $nameseed=numval2($username) << 21;
1.443     albertel 6643: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   6644: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6645: 	
                   6646: 	my $num1=$symbchck+$symbseed+$namechck;
                   6647: 	my $num2=$nameseed+$domainseed+$courseseed;
                   6648: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
1.564     albertel 6649: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$_64bit");
                   6650: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   6651: 	
1.503     albertel 6652: 	return "$num1:$num2";
1.443     albertel 6653:     }
                   6654: }
                   6655: 
1.575     albertel 6656: sub rndseed_64bit4 {
                   6657:     my ($symb,$courseid,$domain,$username)=@_;
                   6658:     {
                   6659: 	use integer;
                   6660: 	# strings need to be an even # of cahracters long, it it is odd the
                   6661:         # last characters gets thrown away
                   6662: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6663: 	my $symbseed=numval3($symb) << 10;
                   6664: 	my $namechck=unpack("%32S*",$username.' ');
                   6665: 	
                   6666: 	my $nameseed=numval3($username) << 21;
                   6667: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   6668: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6669: 	
                   6670: 	my $num1=$symbchck+$symbseed+$namechck;
                   6671: 	my $num2=$nameseed+$domainseed+$courseseed;
                   6672: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6673: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$_64bit");
                   6674: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   6675: 	
                   6676: 	return "$num1:$num2";
                   6677:     }
                   6678: }
                   6679: 
1.675     albertel 6680: sub rndseed_64bit5 {
                   6681:     my ($symb,$courseid,$domain,$username)=@_;
                   6682:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   6683:     return "$num1:$num2";
                   6684: }
                   6685: 
1.366     albertel 6686: sub rndseed_CODE_64bit {
                   6687:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 6688:     {
1.366     albertel 6689: 	use integer;
1.443     albertel 6690: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 6691: 	my $symbseed=numval2($symb);
1.491     albertel 6692: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   6693: 	my $CODEseed=numval(&getCODE());
1.443     albertel 6694: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 6695: 	my $num1=$symbseed+$CODEchck;
                   6696: 	my $num2=$CODEseed+$courseseed+$symbchck;
                   6697: 	#&Apache::lonxml::debug("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
1.366     albertel 6698: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$symb");
1.564     albertel 6699: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   6700: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 6701: 	return "$num1:$num2";
1.366     albertel 6702:     }
                   6703: }
                   6704: 
1.575     albertel 6705: sub rndseed_CODE_64bit4 {
                   6706:     my ($symb,$courseid,$domain,$username)=@_;
                   6707:     {
                   6708: 	use integer;
                   6709: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   6710: 	my $symbseed=numval3($symb);
                   6711: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   6712: 	my $CODEseed=numval3(&getCODE());
                   6713: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6714: 	my $num1=$symbseed+$CODEchck;
                   6715: 	my $num2=$CODEseed+$courseseed+$symbchck;
                   6716: 	#&Apache::lonxml::debug("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   6717: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$symb");
                   6718: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   6719: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   6720: 	return "$num1:$num2";
                   6721:     }
                   6722: }
                   6723: 
1.675     albertel 6724: sub rndseed_CODE_64bit5 {
                   6725:     my ($symb,$courseid,$domain,$username)=@_;
                   6726:     my $code = &getCODE();
                   6727:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   6728:     return "$num1:$num2";
                   6729: }
                   6730: 
1.366     albertel 6731: sub setup_random_from_rndseed {
                   6732:     my ($rndseed)=@_;
1.503     albertel 6733:     if ($rndseed =~/([,:])/) {
                   6734: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 6735: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   6736:     } else {
                   6737: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 6738:     }
1.36      albertel 6739: }
                   6740: 
1.474     albertel 6741: sub latest_receipt_algorithm_id {
                   6742:     return 'receipt2';
                   6743: }
                   6744: 
1.480     www      6745: sub recunique {
                   6746:     my $fucourseid=shift;
                   6747:     my $unique;
1.620     albertel 6748:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   6749: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      6750:     } else {
                   6751: 	$unique=$perlvar{'lonReceipt'};
                   6752:     }
                   6753:     return unpack("%32C*",$unique);
                   6754: }
                   6755: 
                   6756: sub recprefix {
                   6757:     my $fucourseid=shift;
                   6758:     my $prefix;
1.620     albertel 6759:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   6760: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      6761:     } else {
                   6762: 	$prefix=$perlvar{'lonHostID'};
                   6763:     }
                   6764:     return unpack("%32C*",$prefix);
                   6765: }
                   6766: 
1.76      www      6767: sub ireceipt {
1.474     albertel 6768:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.76      www      6769:     my $cuname=unpack("%32C*",$funame);
                   6770:     my $cudom=unpack("%32C*",$fudom);
                   6771:     my $cucourseid=unpack("%32C*",$fucourseid);
                   6772:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      6773:     my $cunique=&recunique($fucourseid);
1.474     albertel 6774:     my $cpart=unpack("%32S*",$part);
1.480     www      6775:     my $return =&recprefix($fucourseid).'-';
1.620     albertel 6776:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   6777: 	$env{'request.state'} eq 'construct') {
1.474     albertel 6778: 	&Apache::lonxml::debug("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname).
                   6779: 			       " and ".($cpart%$cudom));
                   6780: 			       
                   6781: 	$return.= ($cunique%$cuname+
                   6782: 		   $cunique%$cudom+
                   6783: 		   $cusymb%$cuname+
                   6784: 		   $cusymb%$cudom+
                   6785: 		   $cucourseid%$cuname+
                   6786: 		   $cucourseid%$cudom+
                   6787: 		   $cpart%$cuname+
                   6788: 		   $cpart%$cudom);
                   6789:     } else {
                   6790: 	$return.= ($cunique%$cuname+
                   6791: 		   $cunique%$cudom+
                   6792: 		   $cusymb%$cuname+
                   6793: 		   $cusymb%$cudom+
                   6794: 		   $cucourseid%$cuname+
                   6795: 		   $cucourseid%$cudom);
                   6796:     }
                   6797:     return $return;
1.76      www      6798: }
                   6799: 
                   6800: sub receipt {
1.474     albertel 6801:     my ($part)=@_;
                   6802:     my ($symb,$courseid,$domain,$name) = &Apache::lonxml::whichuser();
                   6803:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      6804: }
1.260     ng       6805: 
1.36      albertel 6806: # ------------------------------------------------------------ Serves up a file
1.472     albertel 6807: # returns either the contents of the file or 
                   6808: # -1 if the file doesn't exist
1.481     raeburn  6809: #
                   6810: # if the target is a file that was uploaded via DOCS, 
                   6811: # a check will be made to see if a current copy exists on the local server,
                   6812: # if it does this will be served, otherwise a copy will be retrieved from
                   6813: # the home server for the course and stored in /home/httpd/html/userfiles on
                   6814: # the local server.   
1.472     albertel 6815: 
1.36      albertel 6816: sub getfile {
1.538     albertel 6817:     my ($file) = @_;
1.609     banghart 6818:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 6819:     &repcopy($file);
                   6820:     return &readfile($file);
                   6821: }
                   6822: 
                   6823: sub repcopy_userfile {
                   6824:     my ($file)=@_;
1.609     banghart 6825:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 6826:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 6827:     my ($cdom,$cnum,$filename) = 
                   6828: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+([^/]+)/+([^/]+)/+(.*)|);
                   6829:     my ($info,$rtncode);
                   6830:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   6831:     if (-e "$file") {
                   6832: 	my @fileinfo = stat($file);
                   6833: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 6834: 	if ($lwpresp ne 'ok') {
                   6835: 	    if ($rtncode eq '404') {
1.538     albertel 6836: 		unlink($file);
1.482     albertel 6837: 	    }
1.517     albertel 6838: 	    #my $ua=new LWP::UserAgent;
1.538     albertel 6839: 	    #my $request=new HTTP::Request('GET',&tokenwrapper($uri));
1.517     albertel 6840: 	    #my $response=$ua->request($request);
                   6841: 	    #if ($response->is_success()) {
                   6842: 	#	return $response->content;
                   6843: 	#    } else {
                   6844: 	#	return -1;
                   6845: 	#    }
1.482     albertel 6846: 	    return -1;
                   6847: 	}
                   6848: 	if ($info < $fileinfo[9]) {
1.607     raeburn  6849: 	    return 'ok';
1.482     albertel 6850: 	}
                   6851: 	$info = '';
1.538     albertel 6852: 	$lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 6853: 	if ($lwpresp ne 'ok') {
                   6854: 	    return -1;
                   6855: 	}
                   6856:     } else {
1.538     albertel 6857: 	my $lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 6858: 	if ($lwpresp ne 'ok') {
1.517     albertel 6859: 	    my $ua=new LWP::UserAgent;
1.538     albertel 6860: 	    my $request=new HTTP::Request('GET',&tokenwrapper($uri));
1.517     albertel 6861: 	    my $response=$ua->request($request);
                   6862: 	    if ($response->is_success()) {
1.538     albertel 6863: 		$info=$response->content;
1.517     albertel 6864: 	    } else {
                   6865: 		return -1;
                   6866: 	    }
1.482     albertel 6867: 	}
                   6868: 	my @parts = ($cdom,$cnum); 
                   6869: 	if ($filename =~ m|^(.+)/[^/]+$|) {
                   6870: 	    push @parts, split(/\//,$1);
1.518     albertel 6871: 	}
1.538     albertel 6872: 	my $path = $perlvar{'lonDocRoot'}.'/userfiles';
1.482     albertel 6873: 	foreach my $part (@parts) {
                   6874: 	    $path .= '/'.$part;
                   6875: 	    if (!-e $path) {
                   6876: 		mkdir($path,0770);
                   6877: 	    }
                   6878: 	}
                   6879:     }
1.538     albertel 6880:     open(FILE,">$file");
1.482     albertel 6881:     print FILE $info;
                   6882:     close(FILE);
1.607     raeburn  6883:     return 'ok';
1.481     raeburn  6884: }
                   6885: 
1.517     albertel 6886: sub tokenwrapper {
                   6887:     my $uri=shift;
1.552     albertel 6888:     $uri=~s|^http\://([^/]+)||;
                   6889:     $uri=~s|^/||;
1.620     albertel 6890:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 6891:     my $token=$1;
1.552     albertel 6892:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   6893:     if ($udom && $uname && $file) {
                   6894: 	$file=~s|(\?\.*)*$||;
1.620     albertel 6895:         &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
1.552     albertel 6896:         return 'http://'.$hostname{ &homeserver($uname,$udom)}.'/'.$uri.
1.517     albertel 6897:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   6898:                                '&tokenissued='.$perlvar{'lonHostID'};
                   6899:     } else {
                   6900:         return '/adm/notfound.html';
                   6901:     }
                   6902: }
                   6903: 
1.481     raeburn  6904: sub getuploaded {
                   6905:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   6906:     $uri=~s/^\///;
                   6907:     $uri = 'http://'.$hostname{ &homeserver($cnum,$cdom)}.'/raw/'.$uri;
                   6908:     my $ua=new LWP::UserAgent;
                   6909:     my $request=new HTTP::Request($reqtype,$uri);
                   6910:     my $response=$ua->request($request);
                   6911:     $$rtncode = $response->code;
1.482     albertel 6912:     if (! $response->is_success()) {
                   6913: 	return 'failed';
                   6914:     }      
                   6915:     if ($reqtype eq 'HEAD') {
1.486     www      6916: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 6917:     } elsif ($reqtype eq 'GET') {
                   6918: 	$$info = $response->content;
1.472     albertel 6919:     }
1.482     albertel 6920:     return 'ok';
1.36      albertel 6921: }
                   6922: 
1.481     raeburn  6923: sub readfile {
                   6924:     my $file = shift;
                   6925:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   6926:     my $fh;
                   6927:     open($fh,"<$file");
                   6928:     my $a='';
                   6929:     while (<$fh>) { $a .=$_; }
                   6930:     return $a;
                   6931: }
                   6932: 
1.36      albertel 6933: sub filelocation {
1.590     banghart 6934:     my ($dir,$file) = @_;
                   6935:     my $location;
                   6936:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 6937: 
                   6938:     if ($file =~ m-^/adm/-) {
                   6939: 	$file=~s-^/adm/wrapper/-/-;
                   6940: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   6941:     }
1.590     banghart 6942:     if ($file=~m:^/~:) { # is a contruction space reference
                   6943:         $location = $file;
                   6944:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.649     albertel 6945:     } elsif ($file=~m:^/home/[^/]*/public_html/:) {
                   6946: 	# is a correct contruction space reference
                   6947:         $location = $file;
1.609     banghart 6948:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 6949:         my ($udom,$uname,$filename)=
1.609     banghart 6950:   	    ($file=~m -^/+(?:uploaded|editupload)/+([^/]+)/+([^/]+)/+(.*)$-);
1.590     banghart 6951:         my $home=&homeserver($uname,$udom);
                   6952:         my $is_me=0;
                   6953:         my @ids=&current_machine_ids();
                   6954:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   6955:         if ($is_me) {
1.740     www      6956:   	    $location=&propath($udom,$uname).
1.590     banghart 6957:   	      '/userfiles/'.$filename;
                   6958:         } else {
                   6959:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   6960:   	      $udom.'/'.$uname.'/'.$filename;
                   6961:         }
                   6962:     } else {
                   6963:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   6964:         $file=~s:^/res/:/:;
                   6965:         if ( !( $file =~ m:^/:) ) {
                   6966:             $location = $dir. '/'.$file;
                   6967:         } else {
                   6968:             $location = '/home/httpd/html/res'.$file;
                   6969:         }
1.59      albertel 6970:     }
1.590     banghart 6971:     $location=~s://+:/:g; # remove duplicate /
                   6972:     while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
                   6973:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   6974:     return $location;
1.46      www      6975: }
1.36      albertel 6976: 
1.46      www      6977: sub hreflocation {
                   6978:     my ($dir,$file)=@_;
1.460     albertel 6979:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
1.666     albertel 6980: 	$file=filelocation($dir,$file);
1.700     albertel 6981:     } elsif ($file=~m-^/adm/-) {
                   6982: 	$file=~s-^/adm/wrapper/-/-;
                   6983: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 6984:     }
                   6985:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   6986: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   6987:     } elsif ($file=~m-/home/(\w+)/public_html/-) {
1.462     albertel 6988: 	$file=~s-^/home/(\w+)/public_html/-/~$1/-;
1.666     albertel 6989:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
                   6990: 	$file=~s-^/home/httpd/lonUsers/([^/]*)/./././([^/]*)/userfiles/
                   6991: 	    -/uploaded/$1/$2/-x;
1.46      www      6992:     }
1.462     albertel 6993:     return $file;
1.465     albertel 6994: }
                   6995: 
                   6996: sub current_machine_domains {
                   6997:     my $hostname=$hostname{$perlvar{'lonHostID'}};
                   6998:     my @domains;
                   6999:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  7000: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 7001: 	if ($hostname eq $name) {
                   7002: 	    push(@domains,$hostdom{$id});
                   7003: 	}
                   7004:     }
                   7005:     return @domains;
                   7006: }
                   7007: 
                   7008: sub current_machine_ids {
                   7009:     my $hostname=$hostname{$perlvar{'lonHostID'}};
                   7010:     my @ids;
                   7011:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  7012: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 7013: 	if ($hostname eq $name) {
                   7014: 	    push(@ids,$id);
                   7015: 	}
                   7016:     }
                   7017:     return @ids;
1.31      www      7018: }
                   7019: 
                   7020: # ------------------------------------------------------------- Declutters URLs
                   7021: 
                   7022: sub declutter {
                   7023:     my $thisfn=shift;
1.569     albertel 7024:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 7025:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      7026:     $thisfn=~s/^\///;
1.697     albertel 7027:     $thisfn=~s|^adm/wrapper/||;
                   7028:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      7029:     $thisfn=~s/^res\///;
1.235     www      7030:     $thisfn=~s/\?.+$//;
1.268     www      7031:     return $thisfn;
                   7032: }
                   7033: 
                   7034: # ------------------------------------------------------------- Clutter up URLs
                   7035: 
                   7036: sub clutter {
                   7037:     my $thisfn='/'.&declutter(shift);
1.609     banghart 7038:     unless ($thisfn=~/^\/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)\//) { 
1.270     www      7039:        $thisfn='/res'.$thisfn; 
                   7040:     }
1.694     albertel 7041:     if ($thisfn !~m|/adm|) {
1.695     albertel 7042: 	if ($thisfn =~ m|/ext/|) {
1.694     albertel 7043: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 7044: 	} else {
                   7045: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   7046: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 7047: 	    if ($embstyle eq 'ssi'
                   7048: 		|| ($embstyle eq 'hdn')
                   7049: 		|| ($embstyle eq 'rat')
                   7050: 		|| ($embstyle eq 'prv')
                   7051: 		|| ($embstyle eq 'ign')) {
                   7052: 		#do nothing with these
                   7053: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 7054: 		|| ($embstyle eq 'emb')
                   7055: 		|| ($embstyle eq 'wrp')) {
                   7056: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 7057: 	    } elsif ($embstyle eq 'unk'
                   7058: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 7059: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 7060: 	    } else {
1.718     www      7061: #		&logthis("Got a blank emb style");
1.695     albertel 7062: 	    }
1.694     albertel 7063: 	}
                   7064:     }
1.31      www      7065:     return $thisfn;
1.12      www      7066: }
                   7067: 
1.557     albertel 7068: sub freeze_escape {
                   7069:     my ($value)=@_;
                   7070:     if (ref($value)) {
                   7071: 	$value=&nfreeze($value);
                   7072: 	return '__FROZEN__'.&escape($value);
                   7073:     }
                   7074:     return &escape($value);
                   7075: }
                   7076: 
1.11      www      7077: 
1.557     albertel 7078: sub thaw_unescape {
                   7079:     my ($value)=@_;
                   7080:     if ($value =~ /^__FROZEN__/) {
                   7081: 	substr($value,0,10,undef);
                   7082: 	$value=&unescape($value);
                   7083: 	return &thaw($value);
                   7084:     }
                   7085:     return &unescape($value);
                   7086: }
                   7087: 
1.436     albertel 7088: sub correct_line_ends {
                   7089:     my ($result)=@_;
                   7090:     $$result =~s/\r\n/\n/mg;
                   7091:     $$result =~s/\r/\n/mg;
1.415     albertel 7092: }
1.1       albertel 7093: # ================================================================ Main Program
                   7094: 
1.184     www      7095: sub goodbye {
1.204     albertel 7096:    &logthis("Starting Shut down");
1.443     albertel 7097: #not converted to using infrastruture and probably shouldn't be
1.599     albertel 7098:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&freeze(\%badServerCache))));
1.443     albertel 7099: #converted
1.599     albertel 7100: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
                   7101:    &logthis(sprintf("%-20s is %s",'%homecache',length(&freeze(\%homecache))));
                   7102: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&freeze(\%titlecache))));
                   7103: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&freeze(\%courseresdatacache))));
1.425     albertel 7104: #1.1 only
1.599     albertel 7105: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&freeze(\%userresdatacache))));
                   7106: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&freeze(\%getsectioncache))));
                   7107: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&freeze(\%courseresversioncache))));
                   7108: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&freeze(\%resversioncache))));
                   7109:    &logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
                   7110:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   7111:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      7112:    &flushcourselogs();
                   7113:    &logthis("Shutting down");
                   7114: }
                   7115: 
1.179     www      7116: BEGIN {
1.228     harris41 7117: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
1.195     www      7118:     unless ($readit) {
1.217     harris41 7119: {
1.781   ! raeburn  7120:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
        !          7121:     %perlvar = (%perlvar,%{$configvars});
1.227     harris41 7122: }
1.1       albertel 7123: 
1.327     albertel 7124: # ------------------------------------------------------------ Read domain file
                   7125: {
                   7126:     %domaindescription = ();
                   7127:     %domain_auth_def = ();
                   7128:     %domain_auth_arg_def = ();
1.448     albertel 7129:     my $fh;
                   7130:     if (open($fh,"<".$Apache::lonnet::perlvar{'lonTabDir'}.'/domain.tab')) {
1.327     albertel 7131:        while (<$fh>) {
1.390     matthew  7132:            next if (/^(\#|\s*$)/);
                   7133: #           next if /^\#/;
1.327     albertel 7134:            chomp;
1.403     www      7135:            my ($domain, $domain_description, $def_auth, $def_auth_arg,
1.685     raeburn  7136: 	       $def_lang, $city, $longi, $lati, $primary) = split(/:/,$_);
1.403     www      7137: 	   $domain_auth_def{$domain}=$def_auth;
1.327     albertel 7138:            $domain_auth_arg_def{$domain}=$def_auth_arg;
1.403     www      7139: 	   $domaindescription{$domain}=$domain_description;
                   7140: 	   $domain_lang_def{$domain}=$def_lang;
                   7141: 	   $domain_city{$domain}=$city;
                   7142: 	   $domain_longi{$domain}=$longi;
                   7143: 	   $domain_lati{$domain}=$lati;
1.685     raeburn  7144:            $domain_primary{$domain}=$primary;
1.403     www      7145: 
1.448     albertel 7146:  #         &logthis("Domain.tab: $domain, $domain_auth_def{$domain}, $domain_auth_arg_def{$domain},$domaindescription{$domain}");
1.327     albertel 7147: #          &logthis("Domain.tab: $domain ".$domaindescription{$domain} );
1.448     albertel 7148: 	}
1.327     albertel 7149:     }
1.448     albertel 7150:     close ($fh);
1.327     albertel 7151: }
                   7152: 
                   7153: 
1.1       albertel 7154: # ------------------------------------------------------------- Read hosts file
                   7155: {
1.448     albertel 7156:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
1.1       albertel 7157: 
                   7158:     while (my $configline=<$config>) {
1.303     matthew  7159:        next if ($configline =~ /^(\#|\s*$)/);
1.154     www      7160:        chomp($configline);
1.595     albertel 7161:        my ($id,$domain,$role,$name)=split(/:/,$configline);
1.597     albertel 7162:        $name=~s/\s//g;
1.595     albertel 7163:        if ($id && $domain && $role && $name) {
1.252     albertel 7164: 	 $hostname{$id}=$name;
                   7165: 	 $hostdom{$id}=$domain;
                   7166: 	 if ($role eq 'library') { $libserv{$id}=$name; }
1.245     www      7167:        }
1.1       albertel 7168:     }
1.448     albertel 7169:     close($config);
1.619     albertel 7170:     # FIXME: dev server don't want this, production servers _do_ want this
1.654     albertel 7171:     #&get_iphost();
1.1       albertel 7172: }
                   7173: 
1.598     albertel 7174: sub get_iphost {
                   7175:     if (%iphost) { return %iphost; }
1.653     albertel 7176:     my %name_to_ip;
1.598     albertel 7177:     foreach my $id (keys(%hostname)) {
                   7178: 	my $name=$hostname{$id};
1.653     albertel 7179: 	my $ip;
                   7180: 	if (!exists($name_to_ip{$name})) {
                   7181: 	    $ip = gethostbyname($name);
                   7182: 	    if (!$ip || length($ip) ne 4) {
                   7183: 		&logthis("Skipping host $id name $name no IP found\n");
                   7184: 		next;
                   7185: 	    }
                   7186: 	    $ip=inet_ntoa($ip);
                   7187: 	    $name_to_ip{$name} = $ip;
                   7188: 	} else {
                   7189: 	    $ip = $name_to_ip{$name};
1.598     albertel 7190: 	}
                   7191: 	push(@{$iphost{$ip}},$id);
                   7192:     }
                   7193:     return %iphost;
                   7194: }
                   7195: 
1.1       albertel 7196: # ------------------------------------------------------ Read spare server file
                   7197: {
1.448     albertel 7198:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 7199: 
                   7200:     while (my $configline=<$config>) {
                   7201:        chomp($configline);
1.284     matthew  7202:        if ($configline) {
1.1       albertel 7203:           $spareid{$configline}=1;
                   7204:        }
                   7205:     }
1.448     albertel 7206:     close($config);
1.1       albertel 7207: }
1.11      www      7208: # ------------------------------------------------------------ Read permissions
                   7209: {
1.448     albertel 7210:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      7211: 
                   7212:     while (my $configline=<$config>) {
1.448     albertel 7213: 	chomp($configline);
                   7214: 	if ($configline) {
                   7215: 	    my ($role,$perm)=split(/ /,$configline);
                   7216: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   7217: 	}
1.11      www      7218:     }
1.448     albertel 7219:     close($config);
1.11      www      7220: }
                   7221: 
                   7222: # -------------------------------------------- Read plain texts for permissions
                   7223: {
1.448     albertel 7224:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      7225: 
                   7226:     while (my $configline=<$config>) {
1.448     albertel 7227: 	chomp($configline);
                   7228: 	if ($configline) {
1.742     raeburn  7229: 	    my ($short,@plain)=split(/:/,$configline);
                   7230:             %{$prp{$short}} = ();
                   7231: 	    if (@plain > 0) {
                   7232:                 $prp{$short}{'std'} = $plain[0];
                   7233:                 for (my $i=1; $i<@plain; $i++) {
                   7234:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   7235:                 }
                   7236:             }
1.448     albertel 7237: 	}
1.135     www      7238:     }
1.448     albertel 7239:     close($config);
1.135     www      7240: }
                   7241: 
                   7242: # ---------------------------------------------------------- Read package table
                   7243: {
1.448     albertel 7244:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      7245: 
                   7246:     while (my $configline=<$config>) {
1.483     albertel 7247: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 7248: 	chomp($configline);
                   7249: 	my ($short,$plain)=split(/:/,$configline);
                   7250: 	my ($pack,$name)=split(/\&/,$short);
                   7251: 	if ($plain ne '') {
                   7252: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   7253: 	    $packagetab{$short}=$plain; 
                   7254: 	}
1.11      www      7255:     }
1.448     albertel 7256:     close($config);
1.329     matthew  7257: }
                   7258: 
                   7259: # ------------- set up temporary directory
                   7260: {
                   7261:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   7262: 
1.11      www      7263: }
                   7264: 
1.599     albertel 7265: $memcache=new Cache::Memcached({'servers'=>['127.0.0.1:11211']});
1.185     www      7266: 
1.281     www      7267: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      7268: $dumpcount=0;
1.22      www      7269: 
1.163     harris41 7270: &logtouch();
1.672     albertel 7271: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      7272: $readit=1;
1.564     albertel 7273:     {
                   7274: 	use integer;
                   7275: 	my $test=(2**32)+1;
1.568     albertel 7276: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 7277: 	&logthis(" Detected 64bit platform ($_64bit)");
                   7278:     }
1.195     www      7279: }
1.1       albertel 7280: }
1.179     www      7281: 
1.1       albertel 7282: 1;
1.191     harris41 7283: __END__
                   7284: 
1.243     albertel 7285: =pod
                   7286: 
1.191     harris41 7287: =head1 NAME
                   7288: 
1.243     albertel 7289: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 7290: 
                   7291: =head1 SYNOPSIS
                   7292: 
1.243     albertel 7293: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 7294: 
                   7295:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   7296: 
1.243     albertel 7297: Common parameters:
                   7298: 
                   7299: =over 4
                   7300: 
                   7301: =item *
                   7302: 
                   7303: $uname : an internal username (if $cname expecting a course Id specifically)
                   7304: 
                   7305: =item *
                   7306: 
                   7307: $udom : a domain (if $cdom expecting a course's domain specifically)
                   7308: 
                   7309: =item *
                   7310: 
                   7311: $symb : a resource instance identifier
                   7312: 
                   7313: =item *
                   7314: 
                   7315: $namespace : the name of a .db file that contains the data needed or
                   7316: being set.
                   7317: 
                   7318: =back
                   7319: 
1.394     bowersj2 7320: =head1 OVERVIEW
1.191     harris41 7321: 
1.394     bowersj2 7322: lonnet provides subroutines which interact with the
                   7323: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   7324: about classes, users, and resources.
1.243     albertel 7325: 
                   7326: For many of these objects you can also use this to store data about
                   7327: them or modify them in various ways.
1.191     harris41 7328: 
1.394     bowersj2 7329: =head2 Symbs
1.191     harris41 7330: 
1.394     bowersj2 7331: To identify a specific instance of a resource, LON-CAPA uses symbols
                   7332: or "symbs"X<symb>. These identifiers are built from the URL of the
                   7333: map, the resource number of the resource in the map, and the URL of
                   7334: the resource itself. The latter is somewhat redundant, but might help
                   7335: if maps change.
                   7336: 
                   7337: An example is
                   7338: 
                   7339:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   7340: 
                   7341: The respective map entry is
                   7342: 
                   7343:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   7344:   title="Problem 2">
                   7345:  </resource>
                   7346: 
                   7347: Symbs are used by the random number generator, as well as to store and
                   7348: restore data specific to a certain instance of for example a problem.
                   7349: 
                   7350: =head2 Storing And Retrieving Data
                   7351: 
                   7352: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   7353: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   7354: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   7355: is is the non-critical message twin of cstore. These functions are for
                   7356: handlers to store a perl hash to a user's permanent data space in an
                   7357: easy manner, and to retrieve it again on another call. It is expected
                   7358: that a handler would use this once at the beginning to retrieve data,
                   7359: and then again once at the end to send only the new data back.
                   7360: 
                   7361: The data is stored in the user's data directory on the user's
                   7362: homeserver under the ID of the course.
                   7363: 
                   7364: The hash that is returned by restore will have all of the previous
                   7365: value for all of the elements of the hash.
                   7366: 
                   7367: Example:
                   7368: 
                   7369:  #creating a hash
                   7370:  my %hash;
                   7371:  $hash{'foo'}='bar';
                   7372: 
                   7373:  #storing it
                   7374:  &Apache::lonnet::cstore(\%hash);
                   7375: 
                   7376:  #changing a value
                   7377:  $hash{'foo'}='notbar';
                   7378: 
                   7379:  #adding a new value
                   7380:  $hash{'bar'}='foo';
                   7381:  &Apache::lonnet::cstore(\%hash);
                   7382: 
                   7383:  #retrieving the hash
                   7384:  my %history=&Apache::lonnet::restore();
                   7385: 
                   7386:  #print the hash
                   7387:  foreach my $key (sort(keys(%history))) {
                   7388:    print("\%history{$key} = $history{$key}");
                   7389:  }
                   7390: 
                   7391: Will print out:
1.191     harris41 7392: 
1.394     bowersj2 7393:  %history{1:foo} = bar
                   7394:  %history{1:keys} = foo:timestamp
                   7395:  %history{1:timestamp} = 990455579
                   7396:  %history{2:bar} = foo
                   7397:  %history{2:foo} = notbar
                   7398:  %history{2:keys} = foo:bar:timestamp
                   7399:  %history{2:timestamp} = 990455580
                   7400:  %history{bar} = foo
                   7401:  %history{foo} = notbar
                   7402:  %history{timestamp} = 990455580
                   7403:  %history{version} = 2
                   7404: 
                   7405: Note that the special hash entries C<keys>, C<version> and
                   7406: C<timestamp> were added to the hash. C<version> will be equal to the
                   7407: total number of versions of the data that have been stored. The
                   7408: C<timestamp> attribute will be the UNIX time the hash was
                   7409: stored. C<keys> is available in every historical section to list which
                   7410: keys were added or changed at a specific historical revision of a
                   7411: hash.
                   7412: 
                   7413: B<Warning>: do not store the hash that restore returns directly. This
                   7414: will cause a mess since it will restore the historical keys as if the
                   7415: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 7416: 
1.394     bowersj2 7417: Calling convention:
1.191     harris41 7418: 
1.394     bowersj2 7419:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   7420:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 7421: 
1.394     bowersj2 7422: For more detailed information, see lonnet specific documentation.
1.191     harris41 7423: 
1.394     bowersj2 7424: =head1 RETURN MESSAGES
1.191     harris41 7425: 
1.394     bowersj2 7426: =over 4
1.191     harris41 7427: 
1.394     bowersj2 7428: =item * B<con_lost>: unable to contact remote host
1.191     harris41 7429: 
1.394     bowersj2 7430: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   7431: when the connection is brought back up
1.191     harris41 7432: 
1.394     bowersj2 7433: =item * B<con_failed>: unable to contact remote host and unable to save message
                   7434: for later delivery
1.191     harris41 7435: 
1.394     bowersj2 7436: =item * B<error:>: an error a occured, a description of the error follows the :
1.191     harris41 7437: 
1.394     bowersj2 7438: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 7439: that was requested
1.191     harris41 7440: 
1.243     albertel 7441: =back
1.191     harris41 7442: 
1.243     albertel 7443: =head1 PUBLIC SUBROUTINES
1.191     harris41 7444: 
1.243     albertel 7445: =head2 Session Environment Functions
1.191     harris41 7446: 
1.243     albertel 7447: =over 4
1.191     harris41 7448: 
1.394     bowersj2 7449: =item * 
                   7450: X<appenv()>
                   7451: B<appenv(%hash)>: the value of %hash is written to
                   7452: the user envirnoment file, and will be restored for each access this
1.620     albertel 7453: user makes during this session, also modifies the %env for the current
1.394     bowersj2 7454: process
1.191     harris41 7455: 
                   7456: =item *
1.394     bowersj2 7457: X<delenv()>
                   7458: B<delenv($regexp)>: removes all items from the session
                   7459: environment file that matches the regular expression in $regexp. The
1.620     albertel 7460: values are also delted from the current processes %env.
1.191     harris41 7461: 
1.243     albertel 7462: =back
                   7463: 
                   7464: =head2 User Information
1.191     harris41 7465: 
1.243     albertel 7466: =over 4
1.191     harris41 7467: 
                   7468: =item *
1.394     bowersj2 7469: X<queryauthenticate()>
                   7470: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 7471: authentication scheme
                   7472: 
                   7473: =item *
1.394     bowersj2 7474: X<authenticate()>
                   7475: B<authenticate($uname,$upass,$udom)>: try to
                   7476: authenticate user from domain's lib servers (first use the current
                   7477: one). C<$upass> should be the users password.
1.191     harris41 7478: 
                   7479: =item *
1.394     bowersj2 7480: X<homeserver()>
                   7481: B<homeserver($uname,$udom)>: find the server which has
                   7482: the user's directory and files (there must be only one), this caches
                   7483: the answer, and also caches if there is a borken connection.
1.191     harris41 7484: 
                   7485: =item *
1.394     bowersj2 7486: X<idget()>
                   7487: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   7488: (IDs are a unique resource in a domain, there must be only 1 ID per
                   7489: username, and only 1 username per ID in a specific domain) (returns
                   7490: hash: id=>name,id=>name)
1.191     harris41 7491: 
                   7492: =item *
1.394     bowersj2 7493: X<idrget()>
                   7494: B<idrget($udom,@unames)>: find the IDs behind a list of
                   7495: usernames (returns hash: name=>id,name=>id)
1.191     harris41 7496: 
                   7497: =item *
1.394     bowersj2 7498: X<idput()>
                   7499: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 7500: 
                   7501: =item *
1.394     bowersj2 7502: X<rolesinit()>
                   7503: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 7504: 
                   7505: =item *
1.551     albertel 7506: X<getsection()>
                   7507: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 7508: course $cname, return section name/number or '' for "not in course"
                   7509: and '-1' for "no section"
                   7510: 
                   7511: =item *
1.394     bowersj2 7512: X<userenvironment()>
                   7513: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 7514: passed in @what from the requested user's environment, returns a hash
                   7515: 
                   7516: =back
                   7517: 
                   7518: =head2 User Roles
                   7519: 
                   7520: =over 4
                   7521: 
                   7522: =item *
                   7523: 
                   7524: allowed($priv,$uri) : check for a user privilege; returns codes for allowed
                   7525: actions
                   7526:  F: full access
                   7527:  U,I,K: authentication modes (cxx only)
                   7528:  '': forbidden
                   7529:  1: user needs to choose course
                   7530:  2: browse allowed
1.766     albertel 7531:  A: passphrase authentication needed
1.243     albertel 7532: 
                   7533: =item *
                   7534: 
                   7535: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   7536: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   7537: and course level
                   7538: 
                   7539: =item *
                   7540: 
                   7541: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
                   7542: explanation of a user role term
                   7543: 
                   7544: =back
                   7545: 
                   7546: =head2 User Modification
                   7547: 
                   7548: =over 4
                   7549: 
                   7550: =item *
                   7551: 
                   7552: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
                   7553: user for the level given by URL.  Optional start and end dates (leave empty
                   7554: string or zero for "no date")
1.191     harris41 7555: 
                   7556: =item *
                   7557: 
1.243     albertel 7558: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   7559: change a users, password, possible return values are: ok,
                   7560: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   7561: refused
1.191     harris41 7562: 
                   7563: =item *
                   7564: 
1.243     albertel 7565: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 7566: 
                   7567: =item *
                   7568: 
1.243     albertel 7569: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
                   7570: modify user
1.191     harris41 7571: 
                   7572: =item *
                   7573: 
1.286     matthew  7574: modifystudent
                   7575: 
                   7576: modify a students enrollment and identification information.
                   7577: The course id is resolved based on the current users environment.  
                   7578: This means the envoking user must be a course coordinator or otherwise
                   7579: associated with a course.
                   7580: 
1.297     matthew  7581: This call is essentially a wrapper for lonnet::modifyuser and
                   7582: lonnet::modify_student_enrollment
1.286     matthew  7583: 
                   7584: Inputs: 
                   7585: 
                   7586: =over 4
                   7587: 
                   7588: =item B<$udom> Students loncapa domain
                   7589: 
                   7590: =item B<$uname> Students loncapa login name
                   7591: 
                   7592: =item B<$uid> Students id/student number
                   7593: 
                   7594: =item B<$umode> Students authentication mode
                   7595: 
                   7596: =item B<$upass> Students password
                   7597: 
                   7598: =item B<$first> Students first name
                   7599: 
                   7600: =item B<$middle> Students middle name
                   7601: 
                   7602: =item B<$last> Students last name
                   7603: 
                   7604: =item B<$gene> Students generation
                   7605: 
                   7606: =item B<$usec> Students section in course
                   7607: 
                   7608: =item B<$end> Unix time of the roles expiration
                   7609: 
                   7610: =item B<$start> Unix time of the roles start date
                   7611: 
                   7612: =item B<$forceid> If defined, allow $uid to be changed
                   7613: 
                   7614: =item B<$desiredhome> server to use as home server for student
                   7615: 
                   7616: =back
1.297     matthew  7617: 
                   7618: =item *
                   7619: 
                   7620: modify_student_enrollment
                   7621: 
                   7622: Change a students enrollment status in a class.  The environment variable
                   7623: 'role.request.course' must be defined for this function to proceed.
                   7624: 
                   7625: Inputs:
                   7626: 
                   7627: =over 4
                   7628: 
                   7629: =item $udom, students domain
                   7630: 
                   7631: =item $uname, students name
                   7632: 
                   7633: =item $uid, students user id
                   7634: 
                   7635: =item $first, students first name
                   7636: 
                   7637: =item $middle
                   7638: 
                   7639: =item $last
                   7640: 
                   7641: =item $gene
                   7642: 
                   7643: =item $usec
                   7644: 
                   7645: =item $end
                   7646: 
                   7647: =item $start
                   7648: 
                   7649: =back
                   7650: 
1.191     harris41 7651: 
                   7652: =item *
                   7653: 
1.243     albertel 7654: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   7655: custom role; give a custom role to a user for the level given by URL.  Specify
                   7656: name and domain of role author, and role name
1.191     harris41 7657: 
                   7658: =item *
                   7659: 
1.243     albertel 7660: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 7661: 
                   7662: =item *
                   7663: 
1.243     albertel 7664: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   7665: 
                   7666: =back
                   7667: 
                   7668: =head2 Course Infomation
                   7669: 
                   7670: =over 4
1.191     harris41 7671: 
                   7672: =item *
                   7673: 
1.631     albertel 7674: coursedescription($courseid) : returns a hash of information about the
                   7675: specified course id, including all environment settings for the
                   7676: course, the description of the course will be in the hash under the
                   7677: key 'description'
1.191     harris41 7678: 
                   7679: =item *
                   7680: 
1.624     albertel 7681: resdata($name,$domain,$type,@which) : request for current parameter
                   7682: setting for a specific $type, where $type is either 'course' or 'user',
                   7683: @what should be a list of parameters to ask about. This routine caches
                   7684: answers for 5 minutes.
1.243     albertel 7685: 
                   7686: =back
                   7687: 
                   7688: =head2 Course Modification
                   7689: 
                   7690: =over 4
1.191     harris41 7691: 
                   7692: =item *
                   7693: 
1.243     albertel 7694: writecoursepref($courseid,%prefs) : write preferences (environment
                   7695: database) for a course
1.191     harris41 7696: 
                   7697: =item *
                   7698: 
1.243     albertel 7699: createcourse($udom,$description,$url) : make/modify course
                   7700: 
                   7701: =back
                   7702: 
                   7703: =head2 Resource Subroutines
                   7704: 
                   7705: =over 4
1.191     harris41 7706: 
                   7707: =item *
                   7708: 
1.243     albertel 7709: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 7710: 
                   7711: =item *
                   7712: 
1.243     albertel 7713: repcopy($filename) : subscribes to the requested file, and attempts to
                   7714: replicate from the owning library server, Might return
1.607     raeburn  7715: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   7716: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 7717: resource. Expects the local filesystem pathname
                   7718: (/home/httpd/html/res/....)
                   7719: 
                   7720: =back
                   7721: 
                   7722: =head2 Resource Information
                   7723: 
                   7724: =over 4
1.191     harris41 7725: 
                   7726: =item *
                   7727: 
1.243     albertel 7728: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   7729: a vairety of different possible values, $varname should be a request
                   7730: string, and the other parameters can be used to specify who and what
                   7731: one is asking about.
                   7732: 
                   7733: Possible values for $varname are environment.lastname (or other item
                   7734: from the envirnment hash), user.name (or someother aspect about the
                   7735: user), resource.0.maxtries (or some other part and parameter of a
                   7736: resource)
1.204     albertel 7737: 
                   7738: =item *
                   7739: 
1.243     albertel 7740: directcondval($number) : get current value of a condition; reads from a state
                   7741: string
1.204     albertel 7742: 
                   7743: =item *
                   7744: 
1.243     albertel 7745: condval($condidx) : value of condition index based on state
1.204     albertel 7746: 
                   7747: =item *
                   7748: 
1.243     albertel 7749: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   7750: resource's metadata, $what should be either a specific key, or either
                   7751: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   7752: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   7753: 
                   7754: this function automatically caches all requests
1.191     harris41 7755: 
                   7756: =item *
                   7757: 
1.243     albertel 7758: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   7759: network of library servers; returns file handle of where SQL and regex results
                   7760: will be stored for query
1.191     harris41 7761: 
                   7762: =item *
                   7763: 
1.243     albertel 7764: symbread($filename) : return symbolic list entry (filename argument optional);
                   7765: returns the data handle
1.191     harris41 7766: 
                   7767: =item *
                   7768: 
1.243     albertel 7769: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 7770: a possible symb for the URL in $thisfn, and if is an encryypted
                   7771: resource that the user accessed using /enc/ returns a 1 on success, 0
                   7772: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 7773: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 7774: 
1.191     harris41 7775: 
                   7776: =item *
                   7777: 
1.243     albertel 7778: symbclean($symb) : removes versions numbers from a symb, returns the
                   7779: cleaned symb
1.191     harris41 7780: 
                   7781: =item *
                   7782: 
1.243     albertel 7783: is_on_map($uri) : checks if the $uri is somewhere on the current
                   7784: course map, user must be in a course for it to work.
1.191     harris41 7785: 
                   7786: =item *
                   7787: 
1.243     albertel 7788: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 7789: 
                   7790: =item *
                   7791: 
1.243     albertel 7792: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   7793: a random seed, all arguments are optional, if they aren't sent it uses the
                   7794: environment to derive them. Note: if symb isn't sent and it can't get one
                   7795: from &symbread it will use the current time as its return value
1.191     harris41 7796: 
                   7797: =item *
                   7798: 
1.243     albertel 7799: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   7800: unfakeable, receipt
1.191     harris41 7801: 
                   7802: =item *
                   7803: 
1.620     albertel 7804: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 7805: 
                   7806: =item *
                   7807: 
1.243     albertel 7808: countacc($url) : count the number of accesses to a given URL
1.191     harris41 7809: 
                   7810: =item *
                   7811: 
1.243     albertel 7812: 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 7813: 
                   7814: =item *
                   7815: 
1.243     albertel 7816: 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 7817: 
                   7818: =item *
                   7819: 
1.243     albertel 7820: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 7821: 
                   7822: =item *
                   7823: 
1.243     albertel 7824: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   7825: forcing spreadsheet to reevaluate the resource scores next time.
                   7826: 
                   7827: =back
                   7828: 
                   7829: =head2 Storing/Retreiving Data
                   7830: 
                   7831: =over 4
1.191     harris41 7832: 
                   7833: =item *
                   7834: 
1.243     albertel 7835: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   7836: for this url; hashref needs to be given and should be a \%hashname; the
                   7837: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 7838: be derived from the env
1.191     harris41 7839: 
                   7840: =item *
                   7841: 
1.243     albertel 7842: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   7843: uses critical subroutine
1.191     harris41 7844: 
                   7845: =item *
                   7846: 
1.243     albertel 7847: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   7848: all args are optional
1.191     harris41 7849: 
                   7850: =item *
                   7851: 
1.717     albertel 7852: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   7853: dumps the complete (or key matching regexp) namespace into a hash
                   7854: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   7855: normally &store()ed into
                   7856: 
                   7857: $range should be either an integer '100' (give me the first 100
                   7858:                                            matching records)
                   7859:               or be  two integers sperated by a - with no spaces
                   7860:                  '30-50' (give me the 30th through the 50th matching
                   7861:                           records)
                   7862: 
                   7863: 
                   7864: =item *
                   7865: 
                   7866: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   7867: replaces a &store() version of data with a replacement set of data
                   7868: for a particular resource in a namespace passed in the $storehash hash 
                   7869: reference
                   7870: 
                   7871: =item *
                   7872: 
1.243     albertel 7873: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   7874: works very similar to store/cstore, but all data is stored in a
                   7875: temporary location and can be reset using tmpreset, $storehash should
                   7876: be a hash reference, returns nothing on success
1.191     harris41 7877: 
                   7878: =item *
                   7879: 
1.243     albertel 7880: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   7881: similar to restore, but all data is stored in a temporary location and
                   7882: can be reset using tmpreset. Returns a hash of values on success,
                   7883: error string otherwise.
1.191     harris41 7884: 
                   7885: =item *
                   7886: 
1.243     albertel 7887: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   7888: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 7889: 
                   7890: =item *
                   7891: 
1.243     albertel 7892: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   7893: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 7894: 
                   7895: =item *
                   7896: 
1.243     albertel 7897: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   7898: namesp ($udom and $uname are optional)
1.191     harris41 7899: 
                   7900: =item *
                   7901: 
1.702     albertel 7902: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 7903: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 7904: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  7905: 
1.702     albertel 7906: $range should be either an integer '100' (give me the first 100
                   7907:                                            matching records)
                   7908:               or be  two integers sperated by a - with no spaces
                   7909:                  '30-50' (give me the 30th through the 50th matching
                   7910:                           records)
1.449     matthew  7911: =item *
                   7912: 
                   7913: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   7914: $store can be a scalar, an array reference, or if the amount to be 
                   7915: incremented is > 1, a hash reference.
                   7916: 
                   7917: ($udom and $uname are optional)
1.191     harris41 7918: 
                   7919: =item *
                   7920: 
1.243     albertel 7921: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   7922: ($udom and $uname are optional)
1.191     harris41 7923: 
                   7924: =item *
                   7925: 
1.243     albertel 7926: cput($namespace,$storehash,$udom,$uname) : critical put
                   7927: ($udom and $uname are optional)
1.191     harris41 7928: 
                   7929: =item *
                   7930: 
1.748     albertel 7931: newput($namespace,$storehash,$udom,$uname) :
                   7932: 
                   7933: Attempts to store the items in the $storehash, but only if they don't
                   7934: currently exist, if this succeeds you can be certain that you have 
                   7935: successfully created a new key value pair in the $namespace db.
                   7936: 
                   7937: 
                   7938: Args:
                   7939:  $namespace: name of database to store values to
                   7940:  $storehash: hashref to store to the db
                   7941:  $udom: (optional) domain of user containing the db
                   7942:  $uname: (optional) name of user caontaining the db
                   7943: 
                   7944: Returns:
                   7945:  'ok' -> succeeded in storing all keys of $storehash
                   7946:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   7947:                         least <key> already existed in the db (other
                   7948:                         requested keys may also already exist)
                   7949:  'error: <msg>' -> unable to tie the DB or other erorr occured
                   7950:  'con_lost' -> unable to contact request server
                   7951:  'refused' -> action was not allowed by remote machine
                   7952: 
                   7953: 
                   7954: =item *
                   7955: 
1.243     albertel 7956: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   7957: reference filled in from namesp (encrypts the return communication)
                   7958: ($udom and $uname are optional)
1.191     harris41 7959: 
                   7960: =item *
                   7961: 
1.243     albertel 7962: log($udom,$name,$home,$message) : write to permanent log for user; use
                   7963: critical subroutine
                   7964: 
                   7965: =back
                   7966: 
                   7967: =head2 Network Status Functions
                   7968: 
                   7969: =over 4
1.191     harris41 7970: 
                   7971: =item *
                   7972: 
                   7973: dirlist($uri) : return directory list based on URI
                   7974: 
                   7975: =item *
                   7976: 
1.243     albertel 7977: spareserver() : find server with least workload from spare.tab
                   7978: 
                   7979: =back
                   7980: 
                   7981: =head2 Apache Request
                   7982: 
                   7983: =over 4
1.191     harris41 7984: 
                   7985: =item *
                   7986: 
1.243     albertel 7987: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   7988: localhost, posts hash
                   7989: 
                   7990: =back
                   7991: 
                   7992: =head2 Data to String to Data
                   7993: 
                   7994: =over 4
1.191     harris41 7995: 
                   7996: =item *
                   7997: 
1.243     albertel 7998: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   7999: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 8000: 
                   8001: =item *
                   8002: 
1.243     albertel 8003: hashref2str($hashref) : convert a hashref into a string complete with
                   8004: escaping and '=' and '&' separators, supports elements that are
                   8005: arrayrefs and hashrefs
1.191     harris41 8006: 
                   8007: =item *
                   8008: 
1.243     albertel 8009: arrayref2str($arrayref) : convert an arrayref into a string complete
                   8010: with escaping and '&' separators, supports elements that are arrayrefs
                   8011: and hashrefs
1.191     harris41 8012: 
                   8013: =item *
                   8014: 
1.243     albertel 8015: str2hash($string) : convert string to hash using unescaping and
                   8016: splitting on '=' and '&', supports elements that are arrayrefs and
                   8017: hashrefs
1.191     harris41 8018: 
                   8019: =item *
                   8020: 
1.243     albertel 8021: str2array($string) : convert string to hash using unescaping and
                   8022: splitting on '&', supports elements that are arrayrefs and hashrefs
                   8023: 
                   8024: =back
                   8025: 
                   8026: =head2 Logging Routines
                   8027: 
                   8028: =over 4
                   8029: 
                   8030: These routines allow one to make log messages in the lonnet.log and
                   8031: lonnet.perm logfiles.
1.191     harris41 8032: 
                   8033: =item *
                   8034: 
1.243     albertel 8035: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 8036: 
                   8037: =item *
                   8038: 
1.243     albertel 8039: logthis() : append message to the normal lonnet.log file, it gets
                   8040: preiodically rolled over and deleted.
1.191     harris41 8041: 
                   8042: =item *
                   8043: 
1.243     albertel 8044: logperm() : append a permanent message to lonnet.perm.log, this log
                   8045: file never gets deleted by any automated portion of the system, only
                   8046: messages of critical importance should go in here.
                   8047: 
                   8048: =back
                   8049: 
                   8050: =head2 General File Helper Routines
                   8051: 
                   8052: =over 4
1.191     harris41 8053: 
                   8054: =item *
                   8055: 
1.481     raeburn  8056: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   8057: (a) files in /uploaded
                   8058:   (i) If a local copy of the file exists - 
                   8059:       compares modification date of local copy with last-modified date for 
                   8060:       definitive version stored on home server for course. If local copy is 
                   8061:       stale, requests a new version from the home server and stores it. 
                   8062:       If the original has been removed from the home server, then local copy 
                   8063:       is unlinked.
                   8064:   (ii) If local copy does not exist -
                   8065:       requests the file from the home server and stores it. 
                   8066:   
                   8067:   If $caller is 'uploadrep':  
                   8068:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   8069:     for request for files originally uploaded via DOCS. 
                   8070:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   8071:   
                   8072:   Otherwise:
                   8073:      This indicates a call from the content generation phase of the request.
                   8074:      -  returns the entire contents of the file or -1.
                   8075:      
                   8076: (b) files in /res
                   8077:    - returns the entire contents of a file or -1; 
                   8078:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 8079: 
1.712     albertel 8080: 
                   8081: =item *
                   8082: 
                   8083: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   8084:                   reference
                   8085: 
                   8086: returns either a stat() list of data about the file or an empty list
                   8087: if the file doesn't exist or couldn't find out about it (connection
                   8088: problems or user unknown)
                   8089: 
1.191     harris41 8090: =item *
                   8091: 
1.243     albertel 8092: filelocation($dir,$file) : returns file system location of a file
                   8093: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   8094: directory that relative $file lookups are to looked in ($dir of /a/dir
                   8095: and a file of ../bob will become /a/bob)
1.191     harris41 8096: 
                   8097: =item *
                   8098: 
                   8099: hreflocation($dir,$file) : returns file system location or a URL; same as
                   8100: filelocation except for hrefs
                   8101: 
                   8102: =item *
                   8103: 
                   8104: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   8105: 
1.243     albertel 8106: =back
                   8107: 
1.608     albertel 8108: =head2 Usererfile file routines (/uploaded*)
                   8109: 
                   8110: =over 4
                   8111: 
                   8112: =item *
                   8113: 
                   8114: userfileupload(): main rotine for putting a file in a user or course's
                   8115:                   filespace, arguments are,
                   8116: 
1.620     albertel 8117:  formname - required - this is the name of the element in $env where the
1.608     albertel 8118:            filename, and the contents of the file to create/modifed exist
1.620     albertel 8119:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   8120:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 8121:  coursedoc - if true, store the file in the course of the active role
                   8122:              of the current user
                   8123:  subdir - required - subdirectory to put the file in under ../userfiles/
                   8124:          if undefined, it will be placed in "unknown"
                   8125: 
                   8126:  (This routine calls clean_filename() to remove any dangerous
                   8127:  characters from the filename, and then calls finuserfileupload() to
                   8128:  complete the transaction)
                   8129: 
                   8130:  returns either the url of the uploaded file (/uploaded/....) if successful
                   8131:  and /adm/notfound.html if unsuccessful
                   8132: 
                   8133: =item *
                   8134: 
                   8135: clean_filename(): routine for cleaing a filename up for storage in
                   8136:                  userfile space, argument is:
                   8137: 
                   8138:  filename - proposed filename
                   8139: 
                   8140: returns: the new clean filename
                   8141: 
                   8142: =item *
                   8143: 
                   8144: finishuserfileupload(): routine that creaes and sends the file to
                   8145: userspace, probably shouldn't be called directly
                   8146: 
                   8147:   docuname: username or courseid of destination for the file
                   8148:   docudom: domain of user/course of destination for the file
                   8149:   formname: same as for userfileupload()
                   8150:   fname: filename (inculding subdirectories) for the file
                   8151: 
                   8152:  returns either the url of the uploaded file (/uploaded/....) if successful
                   8153:  and /adm/notfound.html if unsuccessful
                   8154: 
                   8155: =item *
                   8156: 
                   8157: renameuserfile(): renames an existing userfile to a new name
                   8158: 
                   8159:   Args:
                   8160:    docuname: username or courseid of destination for the file
                   8161:    docudom: domain of user/course of destination for the file
                   8162:    old: current file name (including any subdirs under userfiles)
                   8163:    new: desired file name (including any subdirs under userfiles)
                   8164: 
                   8165: =item *
                   8166: 
                   8167: mkdiruserfile(): creates a directory is a userfiles dir
                   8168: 
                   8169:   Args:
                   8170:    docuname: username or courseid of destination for the file
                   8171:    docudom: domain of user/course of destination for the file
                   8172:    dir: dir to create (including any subdirs under userfiles)
                   8173: 
                   8174: =item *
                   8175: 
                   8176: removeuserfile(): removes a file that exists in userfiles
                   8177: 
                   8178:   Args:
                   8179:    docuname: username or courseid of destination for the file
                   8180:    docudom: domain of user/course of destination for the file
                   8181:    fname: filname to delete (including any subdirs under userfiles)
                   8182: 
                   8183: =item *
                   8184: 
                   8185: removeuploadedurl(): convience function for removeuserfile()
                   8186: 
                   8187:   Args:
                   8188:    url:  a full /uploaded/... url to delete
                   8189: 
1.747     albertel 8190: =item * 
                   8191: 
                   8192: get_portfile_permissions():
                   8193:   Args:
                   8194:     domain: domain of user or course contain the portfolio files
                   8195:     user: name of user or num of course contain the portfolio files
                   8196:   Returns:
                   8197:     hashref of a dump of the proper file_permissions.db
                   8198:    
                   8199: 
                   8200: =item * 
                   8201: 
                   8202: get_access_controls():
                   8203: 
                   8204: Args:
                   8205:   current_permissions: the hash ref returned from get_portfile_permissions()
                   8206:   group: (optional) the group you want the files associated with
                   8207:   file: (optional) the file you want access info on
                   8208: 
                   8209: Returns:
1.749     raeburn  8210:     a hash (keys are file names) of hashes containing
                   8211:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   8212:         values are XML containing access control settings (see below) 
1.747     albertel 8213: 
                   8214: Internal notes:
                   8215: 
1.749     raeburn  8216:  access controls are stored in file_permissions.db as key=value pairs.
                   8217:     key -> path to file/file_name\0uniqueID:scope_end_start
                   8218:         where scope -> public,guest,course,group,domains or users.
                   8219:               end -> UNIX time for end of access (0 -> no end date)
                   8220:               start -> UNIX time for start of access
                   8221: 
                   8222:     value -> XML description of access control
                   8223:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   8224:             <start></start>
                   8225:             <end></end>
                   8226: 
                   8227:             <password></password>  for scope type = guest
                   8228: 
                   8229:             <domain></domain>     for scope type = course or group
                   8230:             <number></number>
                   8231:             <roles id="">
                   8232:              <role></role>
                   8233:              <access></access>
                   8234:              <section></section>
                   8235:              <group></group>
                   8236:             </roles>
                   8237: 
                   8238:             <dom></dom>         for scope type = domains
                   8239: 
                   8240:             <users>             for scope type = users
                   8241:              <user>
                   8242:               <uname></uname>
                   8243:               <udom></udom>
                   8244:              </user>
                   8245:             </users>
                   8246:            </scope> 
                   8247:               
                   8248:  Access data is also aggregated for each file in an additional key=value pair:
                   8249:  key -> path to file/file_name\0accesscontrol 
                   8250:  value -> reference to hash
                   8251:           hash contains key = value pairs
                   8252:           where key = uniqueID:scope_end_start
                   8253:                 value = UNIX time record was last updated
                   8254: 
                   8255:           Used to improve speed of look-ups of access controls for each file.  
                   8256:  
                   8257:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   8258: 
                   8259: modify_access_controls():
                   8260: 
                   8261: Modifies access controls for a portfolio file
                   8262: Args
                   8263: 1. file name
                   8264: 2. reference to hash of required changes,
                   8265: 3. domain
                   8266: 4. username
                   8267:   where domain,username are the domain of the portfolio owner 
                   8268:   (either a user or a course) 
                   8269: 
                   8270: Returns:
                   8271: 1. result of additions or updates ('ok' or 'error', with error message). 
                   8272: 2. result of deletions ('ok' or 'error', with error message).
                   8273: 3. reference to hash of any new or updated access controls.
                   8274: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   8275:    key = integer (inbound ID)
                   8276:    value = uniqueID  
1.747     albertel 8277: 
1.608     albertel 8278: =back
                   8279: 
1.243     albertel 8280: =head2 HTTP Helper Routines
                   8281: 
                   8282: =over 4
                   8283: 
1.191     harris41 8284: =item *
                   8285: 
                   8286: escape() : unpack non-word characters into CGI-compatible hex codes
                   8287: 
                   8288: =item *
                   8289: 
                   8290: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   8291: 
1.243     albertel 8292: =back
                   8293: 
                   8294: =head1 PRIVATE SUBROUTINES
                   8295: 
                   8296: =head2 Underlying communication routines (Shouldn't call)
                   8297: 
                   8298: =over 4
                   8299: 
                   8300: =item *
                   8301: 
                   8302: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   8303: 
                   8304: =item *
                   8305: 
                   8306: reply() : uses subreply to send a message to remote machine, logs all failures
                   8307: 
                   8308: =item *
                   8309: 
                   8310: critical() : passes a critical message to another server; if cannot
                   8311: get through then place message in connection buffer directory and
                   8312: returns con_delayed, if incapable of saving message, returns
                   8313: con_failed
                   8314: 
                   8315: =item *
                   8316: 
                   8317: reconlonc() : tries to reconnect lonc client processes.
                   8318: 
                   8319: =back
                   8320: 
                   8321: =head2 Resource Access Logging
                   8322: 
                   8323: =over 4
                   8324: 
                   8325: =item *
                   8326: 
                   8327: flushcourselogs() : flush (save) buffer logs and access logs
                   8328: 
                   8329: =item *
                   8330: 
                   8331: courselog($what) : save message for course in hash
                   8332: 
                   8333: =item *
                   8334: 
                   8335: courseacclog($what) : save message for course using &courselog().  Perform
                   8336: special processing for specific resource types (problems, exams, quizzes, etc).
                   8337: 
1.191     harris41 8338: =item *
                   8339: 
                   8340: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   8341: as a PerlChildExitHandler
1.243     albertel 8342: 
                   8343: =back
                   8344: 
                   8345: =head2 Other
                   8346: 
                   8347: =over 4
                   8348: 
                   8349: =item *
                   8350: 
                   8351: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 8352: 
                   8353: =back
                   8354: 
                   8355: =cut

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