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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.785   ! albertel    4: # $Id: lonnet.pm,v 1.784 2006/09/28 01:38:59 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.783     albertel  295: sub convert_and_load_session_env {
                    296:     my ($lonidsdir,$handle)=@_;
                    297:     my @profile;
                    298:     {
                    299: 	open(my $idf,"$lonidsdir/$handle.id");
                    300: 	flock($idf,LOCK_SH);
                    301: 	@profile=<$idf>;
                    302: 	close($idf);
                    303:     }
                    304:     my %temp_env;
                    305:     foreach my $line (@profile) {
                    306: 	chomp($line);
                    307: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    308: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    309:     }
                    310:     unlink("$lonidsdir/$handle.id");
                    311:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    312: 	    0640)) {
                    313: 	%disk_env = %temp_env;
                    314: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    315: 	untie(%disk_env);
                    316:     }
                    317: }
                    318: 
1.374     www       319: # ------------------------------------------- Transfer profile into environment
1.780     albertel  320: my $env_loaded;
                    321: sub transfer_profile_to_env {
                    322:     if ($env_loaded) { return; } 
1.374     www       323: 
                    324:     my ($lonidsdir,$handle)=@_;
1.720     albertel  325:     if (!defined($lonidsdir)) {
                    326: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    327:     }
                    328:     if (!defined($handle)) {
                    329:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    330:     }
                    331: 
1.783     albertel  332:     my %remove;
                    333:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_READER(),
                    334: 	    0640)) {
                    335: 	@env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    336: 	untie(%disk_env);
                    337:     } else {
                    338: 	&convert_and_load_session_env($lonidsdir,$handle);
1.374     www       339:     }
1.783     albertel  340: 
                    341:     while ( my $envname = each(%env) ) {
1.433     matthew   342:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    343:             if ($time < time-300) {
1.783     albertel  344:                 $remove{$key}++;
1.433     matthew   345:             }
                    346:         }
                    347:     }
1.783     albertel  348: 
1.619     albertel  349:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  350:     $env_loaded=1;
1.783     albertel  351:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   352:         &delenv($expired_key);
1.374     www       353:     }
1.1       albertel  354: }
                    355: 
1.5       www       356: # ---------------------------------------------------------- Append Environment
                    357: 
                    358: sub appenv {
1.6       www       359:     my %newenv=@_;
1.692     albertel  360:     foreach my $key (keys(%newenv)) {
                    361: 	if (($newenv{$key}=~/^user\.role/) || ($newenv{$key}=~/^user\.priv/)) {
1.672     albertel  362:             &logthis("<font color=\"blue\">WARNING: ".
1.692     albertel  363:                 "Attempt to modify environment ".$key." to ".$newenv{$key}
1.151     www       364:                 .'</font>');
1.692     albertel  365: 	    delete($newenv{$key});
1.35      www       366:         } else {
1.692     albertel  367:             $env{$key}=$newenv{$key};
1.35      www       368:         }
1.191     harris41  369:     }
1.783     albertel  370:     if (tie(my %disk_env,'GDBM_File',$env{'user.environment'},&GDBM_WRITER(),
                    371: 	    0640)) {
                    372: 	while (my ($key,$value) = each(%newenv)) {
                    373: 	    $disk_env{$key} = $value;
1.448     albertel  374: 	}
1.783     albertel  375: 	untie(%disk_env);
1.56      www       376:     }
                    377:     return 'ok';
                    378: }
                    379: # ----------------------------------------------------- Delete from Environment
                    380: 
                    381: sub delenv {
                    382:     my $delthis=shift;
                    383:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
1.672     albertel  384:         &logthis("<font color=\"blue\">WARNING: ".
1.56      www       385:                 "Attempt to delete from environment ".$delthis);
                    386:         return 'error';
                    387:     }
1.783     albertel  388:     if (tie(my %disk_env,'GDBM_File',$env{'user.environment'},&GDBM_WRITER(),
                    389: 	    0640)) {
                    390: 	foreach my $key (keys(%disk_env)) {
                    391: 	    if ($key=~/^$delthis/) { 
1.619     albertel  392:                 delete($env{$key});
1.783     albertel  393:                 delete($disk_env{$key});
1.473     matthew   394:             }
1.448     albertel  395: 	}
1.783     albertel  396: 	untie(%disk_env);
1.5       www       397:     }
                    398:     return 'ok';
1.369     albertel  399: }
                    400: 
                    401: # ------------------------------------------ Find out current server userload
                    402: # there is a copy in lond
                    403: sub userload {
                    404:     my $numusers=0;
                    405:     {
                    406: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    407: 	my $filename;
                    408: 	my $curtime=time;
                    409: 	while ($filename=readdir(LONIDS)) {
                    410: 	    if ($filename eq '.' || $filename eq '..') {next;}
1.404     albertel  411: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  412: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  413: 	}
                    414: 	closedir(LONIDS);
                    415:     }
                    416:     my $userloadpercent=0;
                    417:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    418:     if ($maxuserload) {
1.371     albertel  419: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  420:     }
1.372     albertel  421:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  422:     return $userloadpercent;
1.283     www       423: }
                    424: 
                    425: # ------------------------------------------ Fight off request when overloaded
                    426: 
                    427: sub overloaderror {
                    428:     my ($r,$checkserver)=@_;
                    429:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
                    430:     my $loadavg;
                    431:     if ($checkserver eq $perlvar{'lonHostID'}) {
1.448     albertel  432:        open(my $loadfile,'/proc/loadavg');
1.283     www       433:        $loadavg=<$loadfile>;
                    434:        $loadavg =~ s/\s.*//g;
1.285     matthew   435:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
1.448     albertel  436:        close($loadfile);
1.283     www       437:     } else {
                    438:        $loadavg=&reply('load',$checkserver);
                    439:     }
1.285     matthew   440:     my $overload=$loadavg-100;
1.283     www       441:     if ($overload>0) {
1.285     matthew   442: 	$r->err_headers_out->{'Retry-After'}=$overload;
1.283     www       443:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
1.554     www       444:         return 413;
1.283     www       445:     }    
                    446:     return '';
1.5       www       447: }
1.1       albertel  448: 
                    449: # ------------------------------ Find server with least workload from spare.tab
1.11      www       450: 
1.1       albertel  451: sub spareserver {
1.670     albertel  452:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
1.784     albertel  453:     my $spare_server;
1.370     albertel  454:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  455:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    456:                                                      :  $userloadpercent;
                    457:     
                    458:     foreach my $try_server (@{ $spareid{'primary'} }) {
                    459: 	($spare_server, $lowest_load) =
                    460: 	    &compare_server_load($try_server, $spare_server, $lowest_load);
                    461:     }
                    462: 
                    463:     my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    464: 
                    465:     if (!$found_server) {
                    466: 	foreach my $try_server (@{ $spareid{'default'} }) {
                    467: 	    ($spare_server, $lowest_load) =
                    468: 		&compare_server_load($try_server, $spare_server, $lowest_load);
                    469: 	}
                    470:     }
                    471: 
                    472:     if (!$want_server_name) {
                    473: 	$spare_server="http://$hostname{$spare_server}";
                    474:     }
                    475:     return $spare_server;
                    476: }
                    477: 
                    478: sub compare_server_load {
                    479:     my ($try_server, $spare_server, $lowest_load) = @_;
                    480: 
                    481:     my $loadans     = &reply('load',    $try_server);
                    482:     my $userloadans = &reply('userload',$try_server);
                    483: 
                    484:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
                    485: 	next; #didn't get a number from the server
                    486:     }
                    487: 
                    488:     my $load;
                    489:     if ($loadans =~ /\d/) {
                    490: 	if ($userloadans =~ /\d/) {
                    491: 	    #both are numbers, pick the bigger one
                    492: 	    $load = ($loadans > $userloadans) ? $loadans 
                    493: 		                              : $userloadans;
1.411     albertel  494: 	} else {
1.784     albertel  495: 	    $load = $loadans;
1.411     albertel  496: 	}
1.784     albertel  497:     } else {
                    498: 	$load = $userloadans;
                    499:     }
                    500: 
                    501:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    502: 	$spare_server = $try_server;
                    503: 	$lowest_load  = $load;
1.370     albertel  504:     }
1.784     albertel  505:     return ($spare_server,$lowest_load);
1.202     matthew   506: }
                    507: # --------------------------------------------- Try to change a user's password
                    508: 
                    509: sub changepass {
                    510:     my ($uname,$udom,$currentpass,$newpass,$server)=@_;
                    511:     $currentpass = &escape($currentpass);
                    512:     $newpass     = &escape($newpass);
                    513:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass",
                    514: 		       $server);
                    515:     if (! $answer) {
                    516: 	&logthis("No reply on password change request to $server ".
                    517: 		 "by $uname in domain $udom.");
                    518:     } elsif ($answer =~ "^ok") {
                    519:         &logthis("$uname in $udom successfully changed their password ".
                    520: 		 "on $server.");
                    521:     } elsif ($answer =~ "^pwchange_failure") {
                    522: 	&logthis("$uname in $udom was unable to change their password ".
                    523: 		 "on $server.  The action was blocked by either lcpasswd ".
                    524: 		 "or pwchange");
                    525:     } elsif ($answer =~ "^non_authorized") {
                    526:         &logthis("$uname in $udom did not get their password correct when ".
                    527: 		 "attempting to change it on $server.");
                    528:     } elsif ($answer =~ "^auth_mode_error") {
                    529:         &logthis("$uname in $udom attempted to change their password despite ".
                    530: 		 "not being locally or internally authenticated on $server.");
                    531:     } elsif ($answer =~ "^unknown_user") {
                    532:         &logthis("$uname in $udom attempted to change their password ".
                    533: 		 "on $server but were unable to because $server is not ".
                    534: 		 "their home server.");
                    535:     } elsif ($answer =~ "^refused") {
                    536: 	&logthis("$server refused to change $uname in $udom password because ".
                    537: 		 "it was sent an unencrypted request to change the password.");
                    538:     }
                    539:     return $answer;
1.1       albertel  540: }
                    541: 
1.169     harris41  542: # ----------------------- Try to determine user's current authentication scheme
                    543: 
                    544: sub queryauthenticate {
                    545:     my ($uname,$udom)=@_;
1.456     albertel  546:     my $uhome=&homeserver($uname,$udom);
                    547:     if (!$uhome) {
                    548: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                    549: 	return 'no_host';
                    550:     }
                    551:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                    552:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                    553: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41  554:     }
1.456     albertel  555:     return $answer;
1.169     harris41  556: }
                    557: 
1.1       albertel  558: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www       559: 
1.1       albertel  560: sub authenticate {
                    561:     my ($uname,$upass,$udom)=@_;
1.12      www       562:     $upass=escape($upass);
1.199     www       563:     $uname=~s/\W//g;
1.471     albertel  564:     my $uhome=&homeserver($uname,$udom);
                    565:     if (!$uhome) {
                    566: 	&logthis("User $uname at $udom is unknown in authenticate");
                    567: 	return 'no_host';
1.1       albertel  568:     }
1.471     albertel  569:     my $answer=reply("encrypt:auth:$udom:$uname:$upass",$uhome);
                    570:     if ($answer eq 'authorized') {
                    571: 	&logthis("User $uname at $udom authorized by $uhome"); 
                    572: 	return $uhome; 
                    573:     }
                    574:     if ($answer eq 'non_authorized') {
                    575: 	&logthis("User $uname at $udom rejected by $uhome");
                    576: 	return 'no_host'; 
1.9       www       577:     }
1.471     albertel  578:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel  579:     return 'no_host';
                    580: }
                    581: 
                    582: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www       583: 
1.599     albertel  584: my %homecache;
1.1       albertel  585: sub homeserver {
1.230     stredwic  586:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel  587:     my $index="$uname:$udom";
1.426     albertel  588: 
1.599     albertel  589:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.1       albertel  590:     my $tryserver;
                    591:     foreach $tryserver (keys %libserv) {
1.230     stredwic  592:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic  593: 		 exists($badServerCache{$tryserver}));
1.1       albertel  594: 	if ($hostdom{$tryserver} eq $udom) {
                    595:            my $answer=reply("home:$udom:$uname",$tryserver);
                    596:            if ($answer eq 'found') { 
1.599     albertel  597: 	       return $homecache{$index}=$tryserver;
1.231     stredwic  598:            } elsif ($answer eq 'no_host') {
                    599: 	       $badServerCache{$tryserver}=1;
1.221     matthew   600:            }
1.1       albertel  601:        }
                    602:     }    
                    603:     return 'no_host';
1.70      www       604: }
                    605: 
                    606: # ------------------------------------- Find the usernames behind a list of IDs
                    607: 
                    608: sub idget {
                    609:     my ($udom,@ids)=@_;
                    610:     my %returnhash=();
                    611:     
                    612:     my $tryserver;
                    613:     foreach $tryserver (keys %libserv) {
                    614:        if ($hostdom{$tryserver} eq $udom) {
                    615: 	  my $idlist=join('&',@ids);
                    616:           $idlist=~tr/A-Z/a-z/; 
                    617: 	  my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                    618:           my @answer=();
1.76      www       619:           if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1.70      www       620: 	      @answer=split(/\&/,$reply);
                    621:           }                    ;
                    622:           my $i;
                    623:           for ($i=0;$i<=$#ids;$i++) {
                    624:               if ($answer[$i]) {
                    625: 		  $returnhash{$ids[$i]}=$answer[$i];
                    626:               } 
                    627:           }
                    628:        }
                    629:     }    
                    630:     return %returnhash;
                    631: }
                    632: 
                    633: # ------------------------------------- Find the IDs behind a list of usernames
                    634: 
                    635: sub idrget {
                    636:     my ($udom,@unames)=@_;
                    637:     my %returnhash=();
1.191     harris41  638:     foreach (@unames) {
1.70      www       639:         $returnhash{$_}=(&userenvironment($udom,$_,'id'))[1];
1.191     harris41  640:     }
1.70      www       641:     return %returnhash;
                    642: }
                    643: 
                    644: # ------------------------------- Store away a list of names and associated IDs
                    645: 
                    646: sub idput {
                    647:     my ($udom,%ids)=@_;
                    648:     my %servers=();
1.191     harris41  649:     foreach (keys %ids) {
1.487     albertel  650: 	&cput('environment',{'id'=>$ids{$_}},$udom,$_);
1.70      www       651:         my $uhom=&homeserver($_,$udom);
                    652:         if ($uhom ne 'no_host') {
                    653:             my $id=&escape($ids{$_});
                    654:             $id=~tr/A-Z/a-z/;
                    655:             my $unam=&escape($_);
                    656: 	    if ($servers{$uhom}) {
                    657: 		$servers{$uhom}.='&'.$id.'='.$unam;
                    658:             } else {
                    659:                 $servers{$uhom}=$id.'='.$unam;
                    660:             }
                    661:         }
1.191     harris41  662:     }
                    663:     foreach (keys %servers) {
1.70      www       664:         &critical('idput:'.$udom.':'.$servers{$_},$_);
1.191     harris41  665:     }
1.344     www       666: }
                    667: 
                    668: # --------------------------------------------------- Assign a key to a student
                    669: 
                    670: sub assign_access_key {
1.364     www       671: #
                    672: # a valid key looks like uname:udom#comments
                    673: # comments are being appended
                    674: #
1.498     www       675:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                    676:     $kdom=
1.620     albertel  677:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www       678:     $knum=
1.620     albertel  679:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www       680:     $cdom=
1.620     albertel  681:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       682:     $cnum=
1.620     albertel  683:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                    684:     $udom=$env{'user.name'} unless (defined($udom));
                    685:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www       686:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www       687:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel  688:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www       689:                                                   # assigned to this person
                    690:                                                   # - this should not happen,
1.345     www       691:                                                   # unless something went wrong
                    692:                                                   # the first time around
                    693: # ready to assign
1.364     www       694:         $logentry=$1.'; '.$logentry;
1.496     www       695:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www       696:                                                  $kdom,$knum) eq 'ok') {
1.345     www       697: # key now belongs to user
1.346     www       698: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www       699:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
                    700:                 &appenv('environment.'.$envkey => $ckey);
                    701:                 return 'ok';
                    702:             } else {
                    703:                 return 
                    704:   'error: Count not permanently assign key, will need to be re-entered later.';
                    705: 	    }
                    706:         } else {
                    707:             return 'error: Could not assign key, try again later.';
                    708:         }
1.364     www       709:     } elsif (!$existing{$ckey}) {
1.345     www       710: # the key does not exist
                    711: 	return 'error: The key does not exist';
                    712:     } else {
                    713: # the key is somebody else's
                    714: 	return 'error: The key is already in use';
                    715:     }
1.344     www       716: }
                    717: 
1.364     www       718: # ------------------------------------------ put an additional comment on a key
                    719: 
                    720: sub comment_access_key {
                    721: #
                    722: # a valid key looks like uname:udom#comments
                    723: # comments are being appended
                    724: #
                    725:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                    726:     $cdom=
1.620     albertel  727:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www       728:     $cnum=
1.620     albertel  729:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www       730:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                    731:     if ($existing{$ckey}) {
                    732:         $existing{$ckey}.='; '.$logentry;
                    733: # ready to assign
1.367     www       734:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www       735:                                                  $cdom,$cnum) eq 'ok') {
                    736: 	    return 'ok';
                    737:         } else {
                    738: 	    return 'error: Count not store comment.';
                    739:         }
                    740:     } else {
                    741: # the key does not exist
                    742: 	return 'error: The key does not exist';
                    743:     }
                    744: }
                    745: 
1.344     www       746: # ------------------------------------------------------ Generate a set of keys
                    747: 
                    748: sub generate_access_keys {
1.364     www       749:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www       750:     $cdom=
1.620     albertel  751:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       752:     $cnum=
1.620     albertel  753:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www       754:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www       755:     unless (($cdom) && ($cnum)) { return 0; }
                    756:     if ($number>10000) { return 0; }
                    757:     sleep(2); # make sure don't get same seed twice
                    758:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                    759:     my $total=0;
                    760:     for (my $i=1;$i<=$number;$i++) {
                    761:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                    762:                   sprintf("%lx",int(100000*rand)).'-'.
                    763:                   sprintf("%lx",int(100000*rand));
                    764:        $newkey=~s/1/g/g; # folks mix up 1 and l
                    765:        $newkey=~s/0/h/g; # and also 0 and O
                    766:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                    767:        if ($existing{$newkey}) {
                    768:            $i--;
                    769:        } else {
1.364     www       770: 	  if (&put('accesskeys',
                    771:               { $newkey => '# generated '.localtime().
1.620     albertel  772:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www       773:                            '; '.$logentry },
                    774: 		   $cdom,$cnum) eq 'ok') {
1.344     www       775:               $total++;
                    776: 	  }
                    777:        }
                    778:     }
1.620     albertel  779:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www       780:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                    781:     return $total;
                    782: }
                    783: 
                    784: # ------------------------------------------------------- Validate an accesskey
                    785: 
                    786: sub validate_access_key {
                    787:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                    788:     $cdom=
1.620     albertel  789:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       790:     $cnum=
1.620     albertel  791:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                    792:     $udom=$env{'user.domain'} unless (defined($udom));
                    793:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www       794:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel  795:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www       796: }
                    797: 
                    798: # ------------------------------------- Find the section of student in a course
1.652     albertel  799: sub devalidate_getsection_cache {
                    800:     my ($udom,$unam,$courseid)=@_;
                    801:     $courseid=~s/\_/\//g;
                    802:     $courseid=~s/^(\w)/\/$1/;
                    803:     my $hashid="$udom:$unam:$courseid";
                    804:     &devalidate_cache_new('getsection',$hashid);
                    805: }
1.298     matthew   806: 
                    807: sub getsection {
                    808:     my ($udom,$unam,$courseid)=@_;
1.599     albertel  809:     my $cachetime=1800;
1.298     matthew   810:     $courseid=~s/\_/\//g;
                    811:     $courseid=~s/^(\w)/\/$1/;
1.551     albertel  812: 
                    813:     my $hashid="$udom:$unam:$courseid";
1.599     albertel  814:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel  815:     if (defined($cached)) { return $result; }
                    816: 
1.298     matthew   817:     my %Pending; 
                    818:     my %Expired;
                    819:     #
                    820:     # Each role can either have not started yet (pending), be active, 
                    821:     #    or have expired.
                    822:     #
                    823:     # If there is an active role, we are done.
                    824:     #
                    825:     # If there is more than one role which has not started yet, 
                    826:     #     choose the one which will start sooner
                    827:     # If there is one role which has not started yet, return it.
                    828:     #
                    829:     # If there is more than one expired role, choose the one which ended last.
                    830:     # If there is a role which has expired, return it.
                    831:     #
                    832:     foreach (split(/\&/,&reply('dump:'.$udom.':'.$unam.':roles',
                    833:                         &homeserver($unam,$udom)))) {
                    834:         my ($key,$value)=split(/\=/,$_);
                    835:         $key=&unescape($key);
1.479     albertel  836:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew   837:         my $section=$1;
                    838:         if ($key eq $courseid.'_st') { $section=''; }
                    839:         my ($dummy,$end,$start)=split(/\_/,&unescape($value));
                    840:         my $now=time;
1.548     albertel  841:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew   842:             $Expired{$end}=$section;
                    843:             next;
                    844:         }
1.548     albertel  845:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew   846:             $Pending{$start}=$section;
                    847:             next;
                    848:         }
1.599     albertel  849:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew   850:     }
                    851:     #
                    852:     # Presumedly there will be few matching roles from the above
                    853:     # loop and the sorting time will be negligible.
                    854:     if (scalar(keys(%Pending))) {
                    855:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel  856:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew   857:     } 
                    858:     if (scalar(keys(%Expired))) {
                    859:         my @sorted = sort {$a <=> $b} keys(%Expired);
                    860:         my $time = pop(@sorted);
1.599     albertel  861:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew   862:     }
1.599     albertel  863:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew   864: }
1.70      www       865: 
1.599     albertel  866: sub save_cache {
                    867:     &purge_remembered();
1.722     albertel  868:     #&Apache::loncommon::validate_page();
1.620     albertel  869:     undef(%env);
1.780     albertel  870:     undef($env_loaded);
1.599     albertel  871: }
1.452     albertel  872: 
1.599     albertel  873: my $to_remember=-1;
                    874: my %remembered;
                    875: my %accessed;
                    876: my $kicks=0;
                    877: my $hits=0;
                    878: sub devalidate_cache_new {
                    879:     my ($name,$id,$debug) = @_;
                    880:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
                    881:     $id=&escape($name.':'.$id);
                    882:     $memcache->delete($id);
                    883:     delete($remembered{$id});
                    884:     delete($accessed{$id});
                    885: }
                    886: 
                    887: sub is_cached_new {
                    888:     my ($name,$id,$debug) = @_;
                    889:     $id=&escape($name.':'.$id);
                    890:     if (exists($remembered{$id})) {
                    891: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                    892: 	$accessed{$id}=[&gettimeofday()];
                    893: 	$hits++;
                    894: 	return ($remembered{$id},1);
                    895:     }
                    896:     my $value = $memcache->get($id);
                    897:     if (!(defined($value))) {
                    898: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel  899: 	return (undef,undef);
1.416     albertel  900:     }
1.599     albertel  901:     if ($value eq '__undef__') {
                    902: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                    903: 	$value=undef;
                    904:     }
                    905:     &make_room($id,$value,$debug);
                    906:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                    907:     return ($value,1);
                    908: }
                    909: 
                    910: sub do_cache_new {
                    911:     my ($name,$id,$value,$time,$debug) = @_;
                    912:     $id=&escape($name.':'.$id);
                    913:     my $setvalue=$value;
                    914:     if (!defined($setvalue)) {
                    915: 	$setvalue='__undef__';
                    916:     }
1.623     albertel  917:     if (!defined($time) ) {
                    918: 	$time=600;
                    919:     }
1.599     albertel  920:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.600     albertel  921:     $memcache->set($id,$setvalue,$time);
                    922:     # need to make a copy of $value
                    923:     #&make_room($id,$value,$debug);
1.599     albertel  924:     return $value;
                    925: }
                    926: 
                    927: sub make_room {
                    928:     my ($id,$value,$debug)=@_;
                    929:     $remembered{$id}=$value;
                    930:     if ($to_remember<0) { return; }
                    931:     $accessed{$id}=[&gettimeofday()];
                    932:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                    933:     my $to_kick;
                    934:     my $max_time=0;
                    935:     foreach my $other (keys(%accessed)) {
                    936: 	if (&tv_interval($accessed{$other}) > $max_time) {
                    937: 	    $to_kick=$other;
                    938: 	    $max_time=&tv_interval($accessed{$other});
                    939: 	}
                    940:     }
                    941:     delete($remembered{$to_kick});
                    942:     delete($accessed{$to_kick});
                    943:     $kicks++;
                    944:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel  945:     return;
                    946: }
                    947: 
1.599     albertel  948: sub purge_remembered {
1.604     albertel  949:     #&logthis("Tossing ".scalar(keys(%remembered)));
                    950:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel  951:     undef(%remembered);
                    952:     undef(%accessed);
1.428     albertel  953: }
1.70      www       954: # ------------------------------------- Read an entry from a user's environment
                    955: 
                    956: sub userenvironment {
                    957:     my ($udom,$unam,@what)=@_;
                    958:     my %returnhash=();
                    959:     my @answer=split(/\&/,
                    960:                 &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
                    961:                       &homeserver($unam,$udom)));
                    962:     my $i;
                    963:     for ($i=0;$i<=$#what;$i++) {
                    964: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
                    965:     }
                    966:     return %returnhash;
1.1       albertel  967: }
                    968: 
1.617     albertel  969: # ---------------------------------------------------------- Get a studentphoto
                    970: sub studentphoto {
                    971:     my ($udom,$unam,$ext) = @_;
                    972:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn   973:     if (defined($env{'request.course.id'})) {
1.708     raeburn   974:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn   975:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                    976:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                    977:             } else {
                    978:                 my ($result,$perm_reqd)=
1.707     albertel  979: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn   980:                 if ($result eq 'ok') {
                    981:                     if (!($perm_reqd eq 'yes')) {
                    982:                         return(&retrievestudentphoto($udom,$unam,$ext));
                    983:                     }
                    984:                 }
                    985:             }
                    986:         }
                    987:     } else {
                    988:         my ($result,$perm_reqd) = 
1.707     albertel  989: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn   990:         if ($result eq 'ok') {
                    991:             if (!($perm_reqd eq 'yes')) {
                    992:                 return(&retrievestudentphoto($udom,$unam,$ext));
                    993:             }
                    994:         }
                    995:     }
                    996:     return '/adm/lonKaputt/lonlogo_broken.gif';
                    997: }
                    998: 
                    999: sub retrievestudentphoto {
                   1000:     my ($udom,$unam,$ext,$type) = @_;
                   1001:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   1002:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   1003:     if ($ret eq 'ok') {
                   1004:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   1005:         if ($type eq 'thumbnail') {
                   1006:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   1007:         }
                   1008:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   1009:         return $tokenurl;
                   1010:     } else {
                   1011:         if ($type eq 'thumbnail') {
                   1012:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   1013:         } else { 
                   1014:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   1015:         }
1.617     albertel 1016:     }
                   1017: }
                   1018: 
1.263     www      1019: # -------------------------------------------------------------------- New chat
                   1020: 
                   1021: sub chatsend {
1.724     raeburn  1022:     my ($newentry,$anon,$group)=@_;
1.620     albertel 1023:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1024:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1025:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      1026:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 1027: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  1028: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      1029: }
                   1030: 
                   1031: # ------------------------------------------ Find current version of a resource
                   1032: 
                   1033: sub getversion {
                   1034:     my $fname=&clutter(shift);
                   1035:     unless ($fname=~/^\/res\//) { return -1; }
                   1036:     return &currentversion(&filelocation('',$fname));
                   1037: }
                   1038: 
                   1039: sub currentversion {
                   1040:     my $fname=shift;
1.599     albertel 1041:     my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440     www      1042:     if (defined($cached)) { return $result; }
1.292     www      1043:     my $author=$fname;
                   1044:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1045:     my ($udom,$uname)=split(/\//,$author);
                   1046:     my $home=homeserver($uname,$udom);
                   1047:     if ($home eq 'no_host') { 
                   1048:         return -1; 
                   1049:     }
                   1050:     my $answer=reply("currentversion:$fname",$home);
                   1051:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1052: 	return -1;
                   1053:     }
1.599     albertel 1054:     return &do_cache_new('resversion',$fname,$answer,600);
1.263     www      1055: }
                   1056: 
1.1       albertel 1057: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      1058: 
1.1       albertel 1059: sub subscribe {
                   1060:     my $fname=shift;
1.761     raeburn  1061:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 1062:     $fname=~s/[\n\r]//g;
1.1       albertel 1063:     my $author=$fname;
                   1064:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1065:     my ($udom,$uname)=split(/\//,$author);
                   1066:     my $home=homeserver($uname,$udom);
1.335     albertel 1067:     if ($home eq 'no_host') {
                   1068:         return 'not_found';
1.1       albertel 1069:     }
                   1070:     my $answer=reply("sub:$fname",$home);
1.64      www      1071:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1072: 	$answer.=' by '.$home;
                   1073:     }
1.1       albertel 1074:     return $answer;
                   1075: }
                   1076:     
1.8       www      1077: # -------------------------------------------------------------- Replicate file
                   1078: 
                   1079: sub repcopy {
                   1080:     my $filename=shift;
1.23      www      1081:     $filename=~s/\/+/\//g;
1.607     raeburn  1082:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   1083:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 1084:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 1085: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 1086: 	return &repcopy_userfile($filename);
                   1087:     }
1.532     albertel 1088:     $filename=~s/[\n\r]//g;
1.8       www      1089:     my $transname="$filename.in.transfer";
1.607     raeburn  1090:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      1091:     my $remoteurl=subscribe($filename);
1.64      www      1092:     if ($remoteurl =~ /^con_lost by/) {
                   1093: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1094:            return 'unavailable';
1.8       www      1095:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 1096: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  1097: 	   return 'not_found';
1.64      www      1098:     } elsif ($remoteurl =~ /^rejected by/) {
                   1099: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1100:            return 'forbidden';
1.20      www      1101:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  1102:            return 'ok';
1.8       www      1103:     } else {
1.290     www      1104:         my $author=$filename;
                   1105:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1106:         my ($udom,$uname)=split(/\//,$author);
                   1107:         my $home=homeserver($uname,$udom);
                   1108:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      1109:            my @parts=split(/\//,$filename);
                   1110:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   1111:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   1112:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  1113: 	       return 'bad_request';
1.8       www      1114:            }
                   1115:            my $count;
                   1116:            for ($count=5;$count<$#parts;$count++) {
                   1117:                $path.="/$parts[$count]";
                   1118:                if ((-e $path)!=1) {
                   1119: 		   mkdir($path,0777);
                   1120:                }
                   1121:            }
                   1122:            my $ua=new LWP::UserAgent;
                   1123:            my $request=new HTTP::Request('GET',"$remoteurl");
                   1124:            my $response=$ua->request($request,$transname);
                   1125:            if ($response->is_error()) {
                   1126: 	       unlink($transname);
                   1127:                my $message=$response->status_line;
1.672     albertel 1128:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      1129:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  1130:                return 'unavailable';
1.8       www      1131:            } else {
1.16      www      1132: 	       if ($remoteurl!~/\.meta$/) {
                   1133:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   1134:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   1135:                   if ($mresponse->is_error()) {
                   1136: 		      unlink($filename.'.meta');
                   1137:                       &logthis(
1.672     albertel 1138:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      1139:                   }
                   1140: 	       }
1.8       www      1141:                rename($transname,$filename);
1.607     raeburn  1142:                return 'ok';
1.8       www      1143:            }
1.290     www      1144:        }
1.8       www      1145:     }
1.330     www      1146: }
                   1147: 
                   1148: # ------------------------------------------------ Get server side include body
                   1149: sub ssi_body {
1.381     albertel 1150:     my ($filelink,%form)=@_;
1.606     matthew  1151:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   1152:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   1153:     }
1.330     www      1154:     my $output=($filelink=~/^http\:/?&externalssi($filelink):
1.381     albertel 1155:                                      &ssi($filelink,%form));
1.778     albertel 1156:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 1157:     $output=~s/^.*?\<body[^\>]*\>//si;
                   1158:     $output=~s/(.*)\<\/body\s*\>.*?$/$1/si;
1.330     www      1159:     return $output;
1.8       www      1160: }
                   1161: 
1.15      www      1162: # --------------------------------------------------------- Server Side Include
                   1163: 
1.782     albertel 1164: sub absolute_url {
                   1165:     my ($host_name) = @_;
                   1166:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   1167:     if ($host_name eq '') {
                   1168: 	$host_name = $ENV{'SERVER_NAME'};
                   1169:     }
                   1170:     return $protocol.$host_name;
                   1171: }
                   1172: 
1.783     albertel 1173: sub absolute_url {
                   1174:     my ($host_name) = @_;
                   1175:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   1176:     if ($host_name eq '') {
                   1177: 	$host_name = $ENV{'SERVER_NAME'};
                   1178:     }
                   1179:     return $protocol.$host_name;
                   1180: }
                   1181: 
1.15      www      1182: sub ssi {
                   1183: 
1.23      www      1184:     my ($fn,%form)=@_;
1.15      www      1185: 
                   1186:     my $ua=new LWP::UserAgent;
1.23      www      1187:     
                   1188:     my $request;
1.711     albertel 1189: 
                   1190:     $form{'no_update_last_known'}=1;
                   1191: 
1.23      www      1192:     if (%form) {
1.782     albertel 1193:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.201     albertel 1194:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1.23      www      1195:     } else {
1.782     albertel 1196:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      1197:     }
                   1198: 
1.15      www      1199:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   1200:     my $response=$ua->request($request);
                   1201: 
1.324     www      1202:     return $response->content;
                   1203: }
                   1204: 
                   1205: sub externalssi {
                   1206:     my ($url)=@_;
                   1207:     my $ua=new LWP::UserAgent;
                   1208:     my $request=new HTTP::Request('GET',$url);
                   1209:     my $response=$ua->request($request);
1.15      www      1210:     return $response->content;
                   1211: }
1.254     www      1212: 
1.492     albertel 1213: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   1214: 
                   1215: sub allowuploaded {
                   1216:     my ($srcurl,$url)=@_;
                   1217:     $url=&clutter(&declutter($url));
                   1218:     my $dir=$url;
                   1219:     $dir=~s/\/[^\/]+$//;
                   1220:     my %httpref=();
                   1221:     my $httpurl=&hreflocation('',$url);
                   1222:     $httpref{'httpref.'.$httpurl}=$srcurl;
                   1223:     &Apache::lonnet::appenv(%httpref);
1.254     www      1224: }
1.477     raeburn  1225: 
1.478     albertel 1226: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 1227: # input: action, courseID, current domain, intended
1.637     raeburn  1228: #        path to file, source of file, instruction to parse file for objects,
                   1229: #        ref to hash for embedded objects,
                   1230: #        ref to hash for codebase of java objects.
                   1231: #
1.485     raeburn  1232: # output: url to file (if action was uploaddoc), 
                   1233: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  1234: #
1.478     albertel 1235: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   1236: # course.
1.477     raeburn  1237: #
1.478     albertel 1238: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1239: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   1240: #          course's home server.
1.477     raeburn  1241: #
1.478     albertel 1242: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   1243: #          be copied from $source (current location) to 
                   1244: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1245: #         and will then be copied to
                   1246: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   1247: #         course's home server.
1.485     raeburn  1248: #
1.481     raeburn  1249: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 1250: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  1251: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1252: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   1253: #         in course's home server.
1.637     raeburn  1254: #
1.477     raeburn  1255: 
                   1256: sub process_coursefile {
1.638     albertel 1257:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477     raeburn  1258:     my $fetchresult;
1.638     albertel 1259:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  1260:     if ($action eq 'propagate') {
1.638     albertel 1261:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   1262: 			     $home);
1.481     raeburn  1263:     } else {
1.477     raeburn  1264:         my $fpath = '';
                   1265:         my $fname = $file;
1.478     albertel 1266:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  1267:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  1268:         my $filepath = &build_filepath($fpath);
1.481     raeburn  1269:         if ($action eq 'copy') {
                   1270:             if ($source eq '') {
                   1271:                 $fetchresult = 'no source file';
                   1272:                 return $fetchresult;
                   1273:             } else {
                   1274:                 my $destination = $filepath.'/'.$fname;
                   1275:                 rename($source,$destination);
                   1276:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1277:                                  $home);
1.481     raeburn  1278:             }
                   1279:         } elsif ($action eq 'uploaddoc') {
                   1280:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 1281:             print $fh $env{'form.'.$source};
1.481     raeburn  1282:             close($fh);
1.637     raeburn  1283:             if ($parser eq 'parse') {
                   1284:                 my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
                   1285:                 unless ($parse_result eq 'ok') {
                   1286:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   1287:                 }
                   1288:             }
1.477     raeburn  1289:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1290:                                  $home);
1.481     raeburn  1291:             if ($fetchresult eq 'ok') {
                   1292:                 return '/uploaded/'.$fpath.'/'.$fname;
                   1293:             } else {
                   1294:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1295:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  1296:                 return '/adm/notfound.html';
                   1297:             }
1.477     raeburn  1298:         }
                   1299:     }
1.485     raeburn  1300:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  1301:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1302:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  1303:     }
                   1304:     return $fetchresult;
                   1305: }
                   1306: 
1.637     raeburn  1307: sub build_filepath {
                   1308:     my ($fpath) = @_;
                   1309:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   1310:     unless ($fpath eq '') {
                   1311:         my @parts=split('/',$fpath);
                   1312:         foreach my $part (@parts) {
                   1313:             $filepath.= '/'.$part;
                   1314:             if ((-e $filepath)!=1) {
                   1315:                 mkdir($filepath,0777);
                   1316:             }
                   1317:         }
                   1318:     }
                   1319:     return $filepath;
                   1320: }
                   1321: 
                   1322: sub store_edited_file {
1.638     albertel 1323:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  1324:     my $file = $primary_url;
                   1325:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   1326:     my $fpath = '';
                   1327:     my $fname = $file;
                   1328:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   1329:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   1330:     my $filepath = &build_filepath($fpath);
                   1331:     open(my $fh,'>'.$filepath.'/'.$fname);
                   1332:     print $fh $content;
                   1333:     close($fh);
1.638     albertel 1334:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  1335:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1336: 			  $home);
1.637     raeburn  1337:     if ($$fetchresult eq 'ok') {
                   1338:         return '/uploaded/'.$fpath.'/'.$fname;
                   1339:     } else {
1.638     albertel 1340:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   1341: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  1342:         return '/adm/notfound.html';
                   1343:     }
                   1344: }
                   1345: 
1.531     albertel 1346: sub clean_filename {
                   1347:     my ($fname)=@_;
1.315     www      1348: # Replace Windows backslashes by forward slashes
1.257     www      1349:     $fname=~s/\\/\//g;
1.315     www      1350: # Get rid of everything but the actual filename
1.257     www      1351:     $fname=~s/^.*\/([^\/]+)$/$1/;
1.315     www      1352: # Replace spaces by underscores
                   1353:     $fname=~s/\s+/\_/g;
                   1354: # Replace all other weird characters by nothing
1.317     www      1355:     $fname=~s/[^\w\.\-]//g;
1.540     albertel 1356: # Replace all .\d. sequences with _\d. so they no longer look like version
                   1357: # numbers
                   1358:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 1359:     return $fname;
                   1360: }
                   1361: 
1.608     albertel 1362: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 1363: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719     banghart 1364: #                    the desired filenam is in $env{"form.$formname.filename"}
1.686     albertel 1365: #        $coursedoc - if true up to the current course
                   1366: #                     if false
                   1367: #        $subdir - directory in userfile to store the file into
                   1368: #        $parser, $allfiles, $codebase - unknown
                   1369: #
                   1370: # output: url of file in userspace, or error: <message> 
                   1371: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 1372: 
                   1373: 
1.531     albertel 1374: sub userfileupload {
1.719     banghart 1375:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,$destudom)=@_;
1.531     albertel 1376:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 1377:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 1378:     $fname=&clean_filename($fname);
1.315     www      1379: # See if there is anything left
1.257     www      1380:     unless ($fname) { return 'error: no uploaded file'; }
1.620     albertel 1381:     chop($env{'form.'.$formname});
1.523     raeburn  1382:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
                   1383:         my $now = time;
                   1384:         my $filepath = 'tmp/helprequests/'.$now;
                   1385:         my @parts=split(/\//,$filepath);
                   1386:         my $fullpath = $perlvar{'lonDaemons'};
                   1387:         for (my $i=0;$i<@parts;$i++) {
                   1388:             $fullpath .= '/'.$parts[$i];
                   1389:             if ((-e $fullpath)!=1) {
                   1390:                 mkdir($fullpath,0777);
                   1391:             }
                   1392:         }
                   1393:         open(my $fh,'>'.$fullpath.'/'.$fname);
1.620     albertel 1394:         print $fh $env{'form.'.$formname};
1.523     raeburn  1395:         close($fh);
1.741     raeburn  1396:         return $fullpath.'/'.$fname;
                   1397:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
                   1398:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   1399:                        '_'.$env{'user.domain'}.'/pending';
                   1400:         my @parts=split(/\//,$filepath);
                   1401:         my $fullpath = $perlvar{'lonDaemons'};
                   1402:         for (my $i=0;$i<@parts;$i++) {
                   1403:             $fullpath .= '/'.$parts[$i];
                   1404:             if ((-e $fullpath)!=1) {
                   1405:                 mkdir($fullpath,0777);
                   1406:             }
                   1407:         }
                   1408:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   1409:         print $fh $env{'form.'.$formname};
                   1410:         close($fh);
                   1411:         return $fullpath.'/'.$fname;
1.523     raeburn  1412:     }
1.719     banghart 1413:     
1.258     www      1414: # Create the directory if not present
1.493     albertel 1415:     $fname="$subdir/$fname";
1.259     www      1416:     if ($coursedoc) {
1.638     albertel 1417: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1418: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  1419:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 1420:             return &finishuserfileupload($docuname,$docudom,
                   1421: 					 $formname,$fname,$parser,$allfiles,
                   1422: 					 $codebase);
1.481     raeburn  1423:         } else {
1.620     albertel 1424:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 1425:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   1426: 				       $fname,$formname,$parser,
                   1427: 				       $allfiles,$codebase);
1.481     raeburn  1428:         }
1.719     banghart 1429:     } elsif (defined($destuname)) {
                   1430:         my $docuname=$destuname;
                   1431:         my $docudom=$destudom;
                   1432: 	return &finishuserfileupload($docuname,$docudom,$formname,
                   1433: 				     $fname,$parser,$allfiles,$codebase);
                   1434:         
1.259     www      1435:     } else {
1.638     albertel 1436:         my $docuname=$env{'user.name'};
                   1437:         my $docudom=$env{'user.domain'};
1.714     raeburn  1438:         if (exists($env{'form.group'})) {
                   1439:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1440:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1441:         }
1.638     albertel 1442: 	return &finishuserfileupload($docuname,$docudom,$formname,
                   1443: 				     $fname,$parser,$allfiles,$codebase);
1.259     www      1444:     }
1.271     www      1445: }
                   1446: 
                   1447: sub finishuserfileupload {
1.638     albertel 1448:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase) = @_;
1.477     raeburn  1449:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      1450:     my $filepath=$perlvar{'lonDocRoot'};
1.494     albertel 1451:     my ($fnamepath,$file);
                   1452:     $file=$fname;
                   1453:     if ($fname=~m|/|) {
                   1454:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   1455: 	$path.=$fnamepath.'/';
                   1456:     }
1.259     www      1457:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      1458:     my $count;
                   1459:     for ($count=4;$count<=$#parts;$count++) {
                   1460:         $filepath.="/$parts[$count]";
                   1461:         if ((-e $filepath)!=1) {
                   1462: 	    mkdir($filepath,0777);
                   1463:         }
                   1464:     }
                   1465: # Save the file
                   1466:     {
1.701     albertel 1467: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   1468: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   1469: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   1470: 	    return '/adm/notfound.html';
                   1471: 	}
                   1472: 	if (!print FH ($env{'form.'.$formname})) {
                   1473: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   1474: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   1475: 	    return '/adm/notfound.html';
                   1476: 	}
1.570     albertel 1477: 	close(FH);
1.258     www      1478:     }
1.637     raeburn  1479:     if ($parser eq 'parse') {
1.638     albertel 1480:         my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
                   1481: 						   $codebase);
1.637     raeburn  1482:         unless ($parse_result eq 'ok') {
1.638     albertel 1483:             &logthis('Failed to parse '.$filepath.$file.
                   1484: 		     ' for embedded media: '.$parse_result); 
1.637     raeburn  1485:         }
                   1486:     }
1.259     www      1487: # Notify homeserver to grep it
                   1488: #
1.638     albertel 1489:     my $docuhome=&homeserver($docuname,$docudom);
1.494     albertel 1490:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      1491:     if ($fetchresult eq 'ok') {
1.259     www      1492: #
1.258     www      1493: # Return the URL to it
1.494     albertel 1494:         return '/uploaded/'.$path.$file;
1.263     www      1495:     } else {
1.494     albertel 1496:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   1497: 		 ': '.$fetchresult);
1.263     www      1498:         return '/adm/notfound.html';
                   1499:     }    
1.493     albertel 1500: }
                   1501: 
1.637     raeburn  1502: sub extract_embedded_items {
1.648     raeburn  1503:     my ($filepath,$file,$allfiles,$codebase,$content) = @_;
1.637     raeburn  1504:     my @state = ();
                   1505:     my %javafiles = (
                   1506:                       codebase => '',
                   1507:                       code => '',
                   1508:                       archive => ''
                   1509:                     );
                   1510:     my %mediafiles = (
                   1511:                       src => '',
                   1512:                       movie => '',
                   1513:                      );
1.648     raeburn  1514:     my $p;
                   1515:     if ($content) {
                   1516:         $p = HTML::LCParser->new($content);
                   1517:     } else {
                   1518:         $p = HTML::LCParser->new($filepath.'/'.$file);
                   1519:     }
1.641     albertel 1520:     while (my $t=$p->get_token()) {
1.640     albertel 1521: 	if ($t->[0] eq 'S') {
                   1522: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
                   1523: 	    push (@state, $tagname);
1.648     raeburn  1524:             if (lc($tagname) eq 'allow') {
                   1525:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   1526:             }
1.640     albertel 1527: 	    if (lc($tagname) eq 'img') {
                   1528: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   1529: 	    }
1.645     raeburn  1530:             if (lc($tagname) eq 'script') {
                   1531:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   1532:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   1533:                 } else {
                   1534:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   1535:                 }
                   1536:             }
                   1537:             if (lc($tagname) eq 'link') {
                   1538:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   1539:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   1540:                 }
                   1541:             }
1.640     albertel 1542: 	    if (lc($tagname) eq 'object' ||
                   1543: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   1544: 		foreach my $item (keys(%javafiles)) {
                   1545: 		    $javafiles{$item} = '';
                   1546: 		}
                   1547: 	    }
                   1548: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   1549: 		my $name = lc($attr->{'name'});
                   1550: 		foreach my $item (keys(%javafiles)) {
                   1551: 		    if ($name eq $item) {
                   1552: 			$javafiles{$item} = $attr->{'value'};
                   1553: 			last;
                   1554: 		    }
                   1555: 		}
                   1556: 		foreach my $item (keys(%mediafiles)) {
                   1557: 		    if ($name eq $item) {
                   1558: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   1559: 			last;
                   1560: 		    }
                   1561: 		}
                   1562: 	    }
                   1563: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   1564: 		foreach my $item (keys(%javafiles)) {
                   1565: 		    if ($attr->{$item}) {
                   1566: 			$javafiles{$item} = $attr->{$item};
                   1567: 			last;
                   1568: 		    }
                   1569: 		}
                   1570: 		foreach my $item (keys(%mediafiles)) {
                   1571: 		    if ($attr->{$item}) {
                   1572: 			&add_filetype($allfiles,$attr->{$item},$item);
                   1573: 			last;
                   1574: 		    }
                   1575: 		}
                   1576: 	    }
                   1577: 	} elsif ($t->[0] eq 'E') {
                   1578: 	    my ($tagname) = ($t->[1]);
                   1579: 	    if ($javafiles{'codebase'} ne '') {
                   1580: 		$javafiles{'codebase'} .= '/';
                   1581: 	    }  
                   1582: 	    if (lc($tagname) eq 'applet' ||
                   1583: 		lc($tagname) eq 'object' ||
                   1584: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   1585: 		) {
                   1586: 		foreach my $item (keys(%javafiles)) {
                   1587: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   1588: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   1589: 			&add_filetype($allfiles,$file,$item);
                   1590: 		    }
                   1591: 		}
                   1592: 	    } 
                   1593: 	    pop @state;
                   1594: 	}
                   1595:     }
1.637     raeburn  1596:     return 'ok';
                   1597: }
                   1598: 
1.639     albertel 1599: sub add_filetype {
                   1600:     my ($allfiles,$file,$type)=@_;
                   1601:     if (exists($allfiles->{$file})) {
                   1602: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   1603: 	    push(@{$allfiles->{$file}}, &escape($type));
                   1604: 	}
                   1605:     } else {
                   1606: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  1607:     }
                   1608: }
                   1609: 
1.493     albertel 1610: sub removeuploadedurl {
                   1611:     my ($url)=@_;
                   1612:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613     albertel 1613:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 1614: }
                   1615: 
                   1616: sub removeuserfile {
                   1617:     my ($docuname,$docudom,$fname)=@_;
                   1618:     my $home=&homeserver($docuname,$docudom);
                   1619:     return &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.257     www      1620: }
1.15      www      1621: 
1.530     albertel 1622: sub mkdiruserfile {
                   1623:     my ($docuname,$docudom,$dir)=@_;
                   1624:     my $home=&homeserver($docuname,$docudom);
                   1625:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   1626: }
                   1627: 
1.531     albertel 1628: sub renameuserfile {
                   1629:     my ($docuname,$docudom,$old,$new)=@_;
                   1630:     my $home=&homeserver($docuname,$docudom);
                   1631:     return &reply("renameuserfile:$docudom:$docuname:".&escape("$old").':'.
                   1632: 		  &escape("$new"),$home);
                   1633: }
                   1634: 
1.14      www      1635: # ------------------------------------------------------------------------- Log
                   1636: 
                   1637: sub log {
                   1638:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      1639:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      1640: }
                   1641: 
                   1642: # ------------------------------------------------------------------ Course Log
1.352     www      1643: #
                   1644: # This routine flushes several buffers of non-mission-critical nature
                   1645: #
1.157     www      1646: 
                   1647: sub flushcourselogs {
1.352     www      1648:     &logthis('Flushing log buffers');
                   1649: #
                   1650: # course logs
                   1651: # This is a log of all transactions in a course, which can be used
                   1652: # for data mining purposes
                   1653: #
                   1654: # It also collects the courseid database, which lists last transaction
                   1655: # times and course titles for all courseids
                   1656: #
                   1657:     my %courseidbuffer=();
1.191     harris41 1658:     foreach (keys %courselogs) {
1.157     www      1659:         my $crsid=$_;
1.352     www      1660:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      1661: 		          &escape($courselogs{$crsid}),
                   1662: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      1663: 	    delete $courselogs{$crsid};
                   1664:         } else {
                   1665:             &logthis('Failed to flush log buffer for '.$crsid);
                   1666:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 1667:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      1668:                         " exceeded maximum size, deleting.</font>");
                   1669:                delete $courselogs{$crsid};
                   1670:             }
1.352     www      1671:         }
                   1672:         if ($courseidbuffer{$coursehombuf{$crsid}}) {
                   1673:            $courseidbuffer{$coursehombuf{$crsid}}.='&'.
1.516     raeburn  1674: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.741     raeburn  1675:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1.352     www      1676:         } else {
                   1677:            $courseidbuffer{$coursehombuf{$crsid}}=
1.516     raeburn  1678: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.741     raeburn  1679:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1.571     raeburn  1680:         }
1.191     harris41 1681:     }
1.352     www      1682: #
                   1683: # Write course id database (reverse lookup) to homeserver of courses 
                   1684: # Is used in pickcourse
                   1685: #
                   1686:     foreach (keys %courseidbuffer) {
1.353     www      1687:         &courseidput($hostdom{$_},$courseidbuffer{$_},$_);
1.352     www      1688:     }
                   1689: #
                   1690: # File accesses
                   1691: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   1692: #
1.449     matthew  1693:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  1694:         if ($entry =~ /___count$/) {
                   1695:             my ($dom,$name);
                   1696:             ($dom,$name,undef)=($entry=~m:___(\w+)/(\w+)/(.*)___count$:);
                   1697:             if (! defined($dom) || $dom eq '' || 
                   1698:                 ! defined($name) || $name eq '') {
1.620     albertel 1699:                 my $cid = $env{'request.course.id'};
                   1700:                 $dom  = $env{'request.'.$cid.'.domain'};
                   1701:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  1702:             }
1.450     matthew  1703:             my $value = $accesshash{$entry};
                   1704:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   1705:             my %temphash=($url => $value);
1.449     matthew  1706:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   1707:             if ($result eq 'ok') {
                   1708:                 delete $accesshash{$entry};
                   1709:             } elsif ($result eq 'unknown_cmd') {
                   1710:                 # Target server has old code running on it.
1.450     matthew  1711:                 my %temphash=($entry => $value);
1.449     matthew  1712:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   1713:                     delete $accesshash{$entry};
                   1714:                 }
                   1715:             }
                   1716:         } else {
1.458     matthew  1717:             my ($dom,$name) = ($entry=~m:___(\w+)/(\w+)/(.*)___(\w+)$:);
1.450     matthew  1718:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  1719:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   1720:                 delete $accesshash{$entry};
                   1721:             }
1.185     www      1722:         }
1.191     harris41 1723:     }
1.352     www      1724: #
                   1725: # Roles
                   1726: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   1727: #
1.349     www      1728:     foreach (keys %userrolehash) {
                   1729:         my $entry=$_;
1.351     www      1730:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      1731: 	    split(/\:/,$entry);
                   1732:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      1733:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      1734:                 $rudom,$runame) eq 'ok') {
                   1735: 	    delete $userrolehash{$entry};
                   1736:         }
                   1737:     }
1.662     raeburn  1738: #
                   1739: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   1740: #
                   1741:     my %domrolebuffer = ();
                   1742:     foreach my $entry (keys %domainrolehash) {
                   1743:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split/:/,$entry;
                   1744:         if ($domrolebuffer{$rudom}) {
                   1745:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   1746:                       '='.&escape($domainrolehash{$entry});
                   1747:         } else {
                   1748:             $domrolebuffer{$rudom}.=&escape($entry).
                   1749:                       '='.&escape($domainrolehash{$entry});
                   1750:         }
                   1751:         delete $domainrolehash{$entry};
                   1752:     }
                   1753:     foreach my $dom (keys(%domrolebuffer)) {
                   1754:         foreach my $tryserver (keys %libserv) {
                   1755:             if ($hostdom{$tryserver} eq $dom) {
                   1756:                 unless (&reply('domroleput:'.$dom.':'.
                   1757:                   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   1758:                     &logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   1759:                 }
                   1760:             }
                   1761:         }
                   1762:     }
1.186     www      1763:     $dumpcount++;
1.157     www      1764: }
                   1765: 
                   1766: sub courselog {
                   1767:     my $what=shift;
1.158     www      1768:     $what=time.':'.$what;
1.620     albertel 1769:     unless ($env{'request.course.id'}) { return ''; }
                   1770:     $coursedombuf{$env{'request.course.id'}}=
                   1771:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   1772:     $coursenumbuf{$env{'request.course.id'}}=
                   1773:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   1774:     $coursehombuf{$env{'request.course.id'}}=
                   1775:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   1776:     $coursedescrbuf{$env{'request.course.id'}}=
                   1777:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   1778:     $courseinstcodebuf{$env{'request.course.id'}}=
                   1779:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   1780:     $courseownerbuf{$env{'request.course.id'}}=
                   1781:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  1782:     $coursetypebuf{$env{'request.course.id'}}=
                   1783:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 1784:     if (defined $courselogs{$env{'request.course.id'}}) {
                   1785: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      1786:     } else {
1.620     albertel 1787: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      1788:     }
1.620     albertel 1789:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      1790: 	&flushcourselogs();
                   1791:     }
1.158     www      1792: }
                   1793: 
                   1794: sub courseacclog {
                   1795:     my $fnsymb=shift;
1.620     albertel 1796:     unless ($env{'request.course.id'}) { return ''; }
                   1797:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 1798:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      1799:         $what.=':POST';
1.583     matthew  1800:         # FIXME: Probably ought to escape things....
1.620     albertel 1801: 	foreach (keys %env) {
1.158     www      1802:             if ($_=~/^form\.(.*)/) {
1.620     albertel 1803: 		$what.=':'.$1.'='.$env{$_};
1.158     www      1804:             }
1.191     harris41 1805:         }
1.583     matthew  1806:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   1807:         # FIXME: We should not be depending on a form parameter that someone
                   1808:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 1809:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  1810:             $what.= ':POST';
                   1811:             # FIXME: Probably ought to escape things....
                   1812:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   1813:                                  'crsdiscuss') {
1.620     albertel 1814:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  1815:             }
                   1816:         }
1.158     www      1817:     }
                   1818:     &courselog($what);
1.149     www      1819: }
                   1820: 
1.185     www      1821: sub countacc {
                   1822:     my $url=&declutter(shift);
1.458     matthew  1823:     return if (! defined($url) || $url eq '');
1.620     albertel 1824:     unless ($env{'request.course.id'}) { return ''; }
                   1825:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      1826:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  1827:     $accesshash{$key}++;
1.185     www      1828: }
1.349     www      1829: 
1.361     www      1830: sub linklog {
                   1831:     my ($from,$to)=@_;
                   1832:     $from=&declutter($from);
                   1833:     $to=&declutter($to);
                   1834:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   1835:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   1836: }
                   1837:   
1.349     www      1838: sub userrolelog {
                   1839:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  1840:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  1841:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  1842:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
                   1843:         ($trole=~/^ta/)) {
1.350     www      1844:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   1845:        $userrolehash
                   1846:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      1847:                     =$tend.':'.$tstart;
1.662     raeburn  1848:     }
                   1849:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   1850:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   1851:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   1852:         ($trole=~/^sc/)) {
                   1853:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   1854:        $domainrolehash
                   1855:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   1856:                     = $tend.':'.$tstart;
                   1857:     }
1.351     www      1858: }
                   1859: 
                   1860: sub get_course_adv_roles {
                   1861:     my $cid=shift;
1.620     albertel 1862:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      1863:     my %coursehash=&coursedescription($cid);
1.470     www      1864:     my %nothide=();
                   1865:     foreach (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   1866: 	$nothide{join(':',split(/[\@\:]/,$_))}=1;
                   1867:     }
1.351     www      1868:     my %returnhash=();
                   1869:     my %dumphash=
                   1870:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   1871:     my $now=time;
                   1872:     foreach (keys %dumphash) {
                   1873: 	my ($tend,$tstart)=split(/\:/,$dumphash{$_});
                   1874:         if (($tstart) && ($tstart<0)) { next; }
                   1875:         if (($tend) && ($tend<$now)) { next; }
                   1876:         if (($tstart) && ($now<$tstart)) { next; }
                   1877:         my ($role,$username,$domain,$section)=split(/\:/,$_);
1.576     albertel 1878: 	if ($username eq '' || $domain eq '') { next; }
1.470     www      1879: 	if ((&privileged($username,$domain)) && 
                   1880: 	    (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 1881: 	if ($role eq 'cr') { next; }
1.351     www      1882:         my $key=&plaintext($role);
                   1883:         if ($section) { $key.=' (Sec/Grp '.$section.')'; }
                   1884:         if ($returnhash{$key}) {
                   1885: 	    $returnhash{$key}.=','.$username.':'.$domain;
                   1886:         } else {
                   1887:             $returnhash{$key}=$username.':'.$domain;
                   1888:         }
1.400     www      1889:      }
                   1890:     return %returnhash;
                   1891: }
                   1892: 
                   1893: sub get_my_roles {
                   1894:     my ($uname,$udom)=@_;
1.620     albertel 1895:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   1896:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.400     www      1897:     my %dumphash=
                   1898:             &dump('nohist_userroles',$udom,$uname);
                   1899:     my %returnhash=();
                   1900:     my $now=time;
                   1901:     foreach (keys %dumphash) {
                   1902: 	my ($tend,$tstart)=split(/\:/,$dumphash{$_});
                   1903:         if (($tstart) && ($tstart<0)) { next; }
                   1904:         if (($tend) && ($tend<$now)) { next; }
                   1905:         if (($tstart) && ($now<$tstart)) { next; }
                   1906:         my ($role,$username,$domain,$section)=split(/\:/,$_);
                   1907: 	$returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
1.373     www      1908:      }
                   1909:     return %returnhash;
1.399     www      1910: }
                   1911: 
                   1912: # ----------------------------------------------------- Frontpage Announcements
                   1913: #
                   1914: #
                   1915: 
                   1916: sub postannounce {
                   1917:     my ($server,$text)=@_;
                   1918:     unless (&allowed('psa',$hostdom{$server})) { return 'refused'; }
                   1919:     unless ($text=~/\w/) { $text=''; }
                   1920:     return &reply('setannounce:'.&escape($text),$server);
                   1921: }
                   1922: 
                   1923: sub getannounce {
1.448     albertel 1924: 
                   1925:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      1926: 	my $announcement='';
                   1927: 	while (<$fh>) { $announcement .=$_; }
1.448     albertel 1928: 	close($fh);
1.399     www      1929: 	if ($announcement=~/\w/) { 
                   1930: 	    return 
                   1931:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 1932:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      1933: 	} else {
                   1934: 	    return '';
                   1935: 	}
                   1936:     } else {
                   1937: 	return '';
                   1938:     }
1.351     www      1939: }
1.353     www      1940: 
                   1941: # ---------------------------------------------------------- Course ID routines
                   1942: # Deal with domain's nohist_courseid.db files
                   1943: #
                   1944: 
                   1945: sub courseidput {
                   1946:     my ($domain,$what,$coursehome)=@_;
                   1947:     return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   1948: }
                   1949: 
                   1950: sub courseiddump {
1.741     raeburn  1951:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,$coursefilter,$hostidflag,$hostidref,$typefilter)=@_;
1.353     www      1952:     my %returnhash=();
1.355     www      1953:     unless ($domfilter) { $domfilter=''; }
1.353     www      1954:     foreach my $tryserver (keys %libserv) {
1.511     raeburn  1955:         if ( ($hostidflag == 1 && grep/^$tryserver$/,@{$hostidref}) || (!defined($hostidflag)) ) {
1.506     raeburn  1956: 	    if ((!$domfilter) || ($hostdom{$tryserver} eq $domfilter)) {
                   1957: 	        foreach (
                   1958:                  split(/\&/,&reply('courseiddump:'.$hostdom{$tryserver}.':'.
1.571     raeburn  1959: 			       $sincefilter.':'.&escape($descfilter).':'.
1.741     raeburn  1960:                                &escape($instcodefilter).':'.&escape($ownerfilter).':'.&escape($coursefilter).':'.&escape($typefilter),
1.354     www      1961:                                $tryserver))) {
1.506     raeburn  1962: 		    my ($key,$value)=split(/\=/,$_);
                   1963:                     if (($key) && ($value)) {
1.516     raeburn  1964: 		        $returnhash{&unescape($key)}=$value;
1.506     raeburn  1965:                     }
1.353     www      1966:                 }
                   1967:             }
                   1968:         }
                   1969:     }
                   1970:     return %returnhash;
                   1971: }
                   1972: 
1.658     raeburn  1973: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  1974: 
                   1975: sub dcmailput {
1.685     raeburn  1976:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  1977:     my $status = &Apache::lonnet::critical(
1.740     www      1978:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   1979:        &escape($message),$server);
1.662     raeburn  1980:     return $status;
                   1981: }
                   1982: 
1.658     raeburn  1983: sub dcmaildump {
                   1984:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  1985:     my %returnhash=();
                   1986:     if (exists($domain_primary{$dom})) {
                   1987:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   1988:                                                          &escape($enddate).':';
                   1989: 	my @esc_senders=map { &escape($_)} @$senders;
                   1990: 	$cmd.=&escape(join('&',@esc_senders));
                   1991: 	foreach (split(/\&/,&reply($cmd,$domain_primary{$dom}))) {
                   1992:             my ($key,$value) = split(/\=/,$_);
                   1993:             if (($key) && ($value)) {
                   1994:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  1995:             }
                   1996:         }
                   1997:     }
                   1998:     return %returnhash;
                   1999: }
1.662     raeburn  2000: # ---------------------------------------------------------- Domain roles
                   2001: 
                   2002: sub get_domain_roles {
                   2003:     my ($dom,$roles,$startdate,$enddate)=@_;
                   2004:     if (undef($startdate) || $startdate eq '') {
                   2005:         $startdate = '.';
                   2006:     }
                   2007:     if (undef($enddate) || $enddate eq '') {
                   2008:         $enddate = '.';
                   2009:     }
                   2010:     my $rolelist = join(':',@{$roles});
                   2011:     my %personnel = ();
                   2012:     foreach my $tryserver (keys(%libserv)) {
                   2013:         if ($hostdom{$tryserver} eq $dom) {
                   2014:             %{$personnel{$tryserver}}=();
                   2015:             foreach (
                   2016:                 split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   2017:                    &escape($startdate).':'.&escape($enddate).':'.
                   2018:                    &escape($rolelist), $tryserver))) {
                   2019:                 my($key,$value) = split(/\=/,$_);
                   2020:                 if (($key) && ($value)) {
                   2021:                     $personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   2022:                 }
                   2023:             }
                   2024:         }
                   2025:     }
                   2026:     return %personnel;
                   2027: }
1.658     raeburn  2028: 
1.149     www      2029: # ----------------------------------------------------------- Check out an item
                   2030: 
1.504     albertel 2031: sub get_first_access {
                   2032:     my ($type,$argsymb)=@_;
                   2033:     my ($symb,$courseid,$udom,$uname)=&Apache::lonxml::whichuser();
                   2034:     if ($argsymb) { $symb=$argsymb; }
                   2035:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 2036:     if ($type eq 'map') {
                   2037: 	$res=&symbread($map);
                   2038:     } else {
                   2039: 	$res=$symb;
                   2040:     }
                   2041:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   2042:     return $times{"$courseid\0$res"};
1.504     albertel 2043: }
                   2044: 
                   2045: sub set_first_access {
                   2046:     my ($type)=@_;
                   2047:     my ($symb,$courseid,$udom,$uname)=&Apache::lonxml::whichuser();
                   2048:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 2049:     if ($type eq 'map') {
                   2050: 	$res=&symbread($map);
                   2051:     } else {
                   2052: 	$res=$symb;
                   2053:     }
                   2054:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 2055:     if (!$firstaccess) {
1.588     albertel 2056: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 2057:     }
                   2058:     return 'already_set';
1.504     albertel 2059: }
                   2060: 
1.149     www      2061: sub checkout {
                   2062:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   2063:     my $now=time;
                   2064:     my $lonhost=$perlvar{'lonHostID'};
                   2065:     my $infostr=&escape(
1.234     www      2066:                  'CHECKOUTTOKEN&'.
1.149     www      2067:                  $tuname.'&'.
                   2068:                  $tudom.'&'.
                   2069:                  $tcrsid.'&'.
                   2070:                  $symb.'&'.
                   2071: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                   2072:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www      2073:     if ($token=~/^error\:/) { 
1.672     albertel 2074:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2075:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2076:                  "</font>");
                   2077:         return ''; 
                   2078:     }
                   2079: 
1.149     www      2080:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   2081:     $token=~tr/a-z/A-Z/;
                   2082: 
1.153     www      2083:     my %infohash=('resource.0.outtoken' => $token,
                   2084:                   'resource.0.checkouttime' => $now,
                   2085:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www      2086: 
                   2087:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2088:        return '';
1.151     www      2089:     } else {
1.672     albertel 2090:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2091:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2092:                  "</font>");
1.149     www      2093:     }    
                   2094: 
                   2095:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2096:                          &escape('Checkout '.$infostr.' - '.
                   2097:                                                  $token)) ne 'ok') {
                   2098: 	return '';
1.151     www      2099:     } else {
1.672     albertel 2100:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2101:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2102:                  "</font>");
1.149     www      2103:     }
1.151     www      2104:     return $token;
1.149     www      2105: }
                   2106: 
                   2107: # ------------------------------------------------------------ Check in an item
                   2108: 
                   2109: sub checkin {
                   2110:     my $token=shift;
1.150     www      2111:     my $now=time;
                   2112:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   2113:     $lonhost=~tr/A-Z/a-z/;
1.595     albertel 2114:     my $dtoken=$ta.'_'.$hostname{$lonhost}.'_'.$tb;
1.150     www      2115:     $dtoken=~s/\W/\_/g;
1.234     www      2116:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www      2117:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   2118: 
1.154     www      2119:     unless (($tuname) && ($tudom)) {
                   2120:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   2121:         return '';
                   2122:     }
                   2123:     
                   2124:     unless (&allowed('mgr',$tcrsid)) {
                   2125:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620     albertel 2126:                  $env{'user.name'}.' - '.$env{'user.domain'});
1.154     www      2127:         return '';
                   2128:     }
                   2129: 
1.153     www      2130:     my %infohash=('resource.0.intoken' => $token,
                   2131:                   'resource.0.checkintime' => $now,
                   2132:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      2133: 
                   2134:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2135:        return '';
                   2136:     }    
                   2137: 
                   2138:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2139:                          &escape('Checkin - '.$token)) ne 'ok') {
                   2140: 	return '';
                   2141:     }
                   2142: 
                   2143:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      2144: }
                   2145: 
                   2146: # --------------------------------------------- Set Expire Date for Spreadsheet
                   2147: 
                   2148: sub expirespread {
                   2149:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 2150:     my $cid=$env{'request.course.id'}; 
1.110     www      2151:     if ($cid) {
                   2152:        my $now=time;
                   2153:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 2154:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   2155:                             $env{'course.'.$cid.'.num'}.
1.110     www      2156: 	        	    ':nohist_expirationdates:'.
                   2157:                             &escape($key).'='.$now,
1.620     albertel 2158:                             $env{'course.'.$cid.'.home'})
1.110     www      2159:     }
                   2160:     return 'ok';
1.14      www      2161: }
                   2162: 
1.109     www      2163: # ----------------------------------------------------- Devalidate Spreadsheets
                   2164: 
                   2165: sub devalidate {
1.325     www      2166:     my ($symb,$uname,$udom)=@_;
1.620     albertel 2167:     my $cid=$env{'request.course.id'}; 
1.109     www      2168:     if ($cid) {
1.391     matthew  2169:         # delete the stored spreadsheets for
                   2170:         # - the student level sheet of this user in course's homespace
                   2171:         # - the assessment level sheet for this resource 
                   2172:         #   for this user in user's homespace
1.553     albertel 2173: 	# - current conditional state info
1.325     www      2174: 	my $key=$uname.':'.$udom.':';
1.109     www      2175:         my $status=
1.299     matthew  2176: 	    &del('nohist_calculatedsheets',
1.391     matthew  2177: 		 [$key.'studentcalc:'],
1.620     albertel 2178: 		 $env{'course.'.$cid.'.domain'},
                   2179: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 2180: 		.' '.
                   2181: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  2182: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      2183:         unless ($status eq 'ok ok') {
                   2184:            &logthis('Could not devalidate spreadsheet '.
1.325     www      2185:                     $uname.' at '.$udom.' for '.
1.109     www      2186: 		    $symb.': '.$status);
1.133     albertel 2187:         }
1.553     albertel 2188: 	&delenv('user.state.'.$cid);
1.109     www      2189:     }
                   2190: }
                   2191: 
1.265     albertel 2192: sub get_scalar {
                   2193:     my ($string,$end) = @_;
                   2194:     my $value;
                   2195:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   2196: 	$value = $1;
                   2197:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   2198: 	$value = $1;
                   2199:     }
                   2200:     return &unescape($value);
                   2201: }
                   2202: 
                   2203: sub array2str {
                   2204:   my (@array) = @_;
                   2205:   my $result=&arrayref2str(\@array);
                   2206:   $result=~s/^__ARRAY_REF__//;
                   2207:   $result=~s/__END_ARRAY_REF__$//;
                   2208:   return $result;
                   2209: }
                   2210: 
1.204     albertel 2211: sub arrayref2str {
                   2212:   my ($arrayref) = @_;
1.265     albertel 2213:   my $result='__ARRAY_REF__';
1.204     albertel 2214:   foreach my $elem (@$arrayref) {
1.265     albertel 2215:     if(ref($elem) eq 'ARRAY') {
                   2216:       $result.=&arrayref2str($elem).'&';
                   2217:     } elsif(ref($elem) eq 'HASH') {
                   2218:       $result.=&hashref2str($elem).'&';
                   2219:     } elsif(ref($elem)) {
                   2220:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 2221:     } else {
                   2222:       $result.=&escape($elem).'&';
                   2223:     }
                   2224:   }
                   2225:   $result=~s/\&$//;
1.265     albertel 2226:   $result .= '__END_ARRAY_REF__';
1.204     albertel 2227:   return $result;
                   2228: }
                   2229: 
1.168     albertel 2230: sub hash2str {
1.204     albertel 2231:   my (%hash) = @_;
                   2232:   my $result=&hashref2str(\%hash);
1.265     albertel 2233:   $result=~s/^__HASH_REF__//;
                   2234:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 2235:   return $result;
                   2236: }
                   2237: 
                   2238: sub hashref2str {
                   2239:   my ($hashref)=@_;
1.265     albertel 2240:   my $result='__HASH_REF__';
1.495     albertel 2241:   foreach (sort(keys(%$hashref))) {
1.204     albertel 2242:     if (ref($_) eq 'ARRAY') {
1.265     albertel 2243:       $result.=&arrayref2str($_).'=';
1.204     albertel 2244:     } elsif (ref($_) eq 'HASH') {
1.265     albertel 2245:       $result.=&hashref2str($_).'=';
1.204     albertel 2246:     } elsif (ref($_)) {
1.265     albertel 2247:       $result.='=';
                   2248:       #print("Got a ref of ".(ref($_))." skipping.");
1.204     albertel 2249:     } else {
1.265     albertel 2250: 	if ($_) {$result.=&escape($_).'=';} else { last; }
1.204     albertel 2251:     }
                   2252: 
1.265     albertel 2253:     if(ref($hashref->{$_}) eq 'ARRAY') {
                   2254:       $result.=&arrayref2str($hashref->{$_}).'&';
                   2255:     } elsif(ref($hashref->{$_}) eq 'HASH') {
                   2256:       $result.=&hashref2str($hashref->{$_}).'&';
                   2257:     } elsif(ref($hashref->{$_})) {
                   2258:        $result.='&';
                   2259:       #print("Got a ref of ".(ref($hashref->{$_}))." skipping.");
1.204     albertel 2260:     } else {
1.265     albertel 2261:       $result.=&escape($hashref->{$_}).'&';
1.204     albertel 2262:     }
                   2263:   }
1.168     albertel 2264:   $result=~s/\&$//;
1.265     albertel 2265:   $result .= '__END_HASH_REF__';
1.168     albertel 2266:   return $result;
                   2267: }
                   2268: 
                   2269: sub str2hash {
1.265     albertel 2270:     my ($string)=@_;
                   2271:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   2272:     return %$hash;
                   2273: }
                   2274: 
                   2275: sub str2hashref {
1.168     albertel 2276:   my ($string) = @_;
1.265     albertel 2277: 
                   2278:   my %hash;
                   2279: 
                   2280:   if($string !~ /^__HASH_REF__/) {
                   2281:       if (! ($string eq '' || !defined($string))) {
                   2282: 	  $hash{'error'}='Not hash reference';
                   2283:       }
                   2284:       return (\%hash, $string);
                   2285:   }
                   2286: 
                   2287:   $string =~ s/^__HASH_REF__//;
                   2288: 
                   2289:   while($string !~ /^__END_HASH_REF__/) {
                   2290:       #key
                   2291:       my $key='';
                   2292:       if($string =~ /^__HASH_REF__/) {
                   2293:           ($key, $string)=&str2hashref($string);
                   2294:           if(defined($key->{'error'})) {
                   2295:               $hash{'error'}='Bad data';
                   2296:               return (\%hash, $string);
                   2297:           }
                   2298:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2299:           ($key, $string)=&str2arrayref($string);
                   2300:           if($key->[0] eq 'Array reference error') {
                   2301:               $hash{'error'}='Bad data';
                   2302:               return (\%hash, $string);
                   2303:           }
                   2304:       } else {
                   2305:           $string =~ s/^(.*?)=//;
1.267     albertel 2306: 	  $key=&unescape($1);
1.265     albertel 2307:       }
                   2308:       $string =~ s/^=//;
                   2309: 
                   2310:       #value
                   2311:       my $value='';
                   2312:       if($string =~ /^__HASH_REF__/) {
                   2313:           ($value, $string)=&str2hashref($string);
                   2314:           if(defined($value->{'error'})) {
                   2315:               $hash{'error'}='Bad data';
                   2316:               return (\%hash, $string);
                   2317:           }
                   2318:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2319:           ($value, $string)=&str2arrayref($string);
                   2320:           if($value->[0] eq 'Array reference error') {
                   2321:               $hash{'error'}='Bad data';
                   2322:               return (\%hash, $string);
                   2323:           }
                   2324:       } else {
                   2325: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   2326:       }
                   2327:       $string =~ s/^&//;
                   2328: 
                   2329:       $hash{$key}=$value;
1.204     albertel 2330:   }
1.265     albertel 2331: 
                   2332:   $string =~ s/^__END_HASH_REF__//;
                   2333: 
                   2334:   return (\%hash, $string);
1.204     albertel 2335: }
                   2336: 
                   2337: sub str2array {
1.265     albertel 2338:     my ($string)=@_;
                   2339:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   2340:     return @$array;
                   2341: }
                   2342: 
                   2343: sub str2arrayref {
1.204     albertel 2344:   my ($string) = @_;
1.265     albertel 2345:   my @array;
                   2346: 
                   2347:   if($string !~ /^__ARRAY_REF__/) {
                   2348:       if (! ($string eq '' || !defined($string))) {
                   2349: 	  $array[0]='Array reference error';
                   2350:       }
                   2351:       return (\@array, $string);
                   2352:   }
                   2353: 
                   2354:   $string =~ s/^__ARRAY_REF__//;
                   2355: 
                   2356:   while($string !~ /^__END_ARRAY_REF__/) {
                   2357:       my $value='';
                   2358:       if($string =~ /^__HASH_REF__/) {
                   2359:           ($value, $string)=&str2hashref($string);
                   2360:           if(defined($value->{'error'})) {
                   2361:               $array[0] ='Array reference error';
                   2362:               return (\@array, $string);
                   2363:           }
                   2364:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2365:           ($value, $string)=&str2arrayref($string);
                   2366:           if($value->[0] eq 'Array reference error') {
                   2367:               $array[0] ='Array reference error';
                   2368:               return (\@array, $string);
                   2369:           }
                   2370:       } else {
                   2371: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   2372:       }
                   2373:       $string =~ s/^&//;
                   2374: 
                   2375:       push(@array, $value);
1.191     harris41 2376:   }
1.265     albertel 2377: 
                   2378:   $string =~ s/^__END_ARRAY_REF__//;
                   2379: 
                   2380:   return (\@array, $string);
1.168     albertel 2381: }
                   2382: 
1.167     albertel 2383: # -------------------------------------------------------------------Temp Store
                   2384: 
1.168     albertel 2385: sub tmpreset {
                   2386:   my ($symb,$namespace,$domain,$stuname) = @_;
                   2387:   if (!$symb) {
                   2388:     $symb=&symbread();
1.620     albertel 2389:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2390:   }
                   2391:   $symb=escape($symb);
                   2392: 
1.620     albertel 2393:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 2394:   $namespace=~s/\//\_/g;
                   2395:   $namespace=~s/\W//g;
                   2396: 
1.620     albertel 2397:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2398:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2399:   if ($domain eq 'public' && $stuname eq 'public') {
                   2400:       $stuname=$ENV{'REMOTE_ADDR'};
                   2401:   }
1.168     albertel 2402:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2403:   my %hash;
                   2404:   if (tie(%hash,'GDBM_File',
                   2405: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2406: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2407:     foreach my $key (keys %hash) {
1.180     albertel 2408:       if ($key=~ /:$symb/) {
1.168     albertel 2409: 	delete($hash{$key});
                   2410:       }
                   2411:     }
                   2412:   }
                   2413: }
                   2414: 
1.167     albertel 2415: sub tmpstore {
1.168     albertel 2416:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2417: 
                   2418:   if (!$symb) {
                   2419:     $symb=&symbread();
1.620     albertel 2420:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2421:   }
                   2422:   $symb=escape($symb);
                   2423: 
                   2424:   if (!$namespace) {
                   2425:     # I don't think we would ever want to store this for a course.
                   2426:     # it seems this will only be used if we don't have a course.
1.620     albertel 2427:     #$namespace=$env{'request.course.id'};
1.168     albertel 2428:     #if (!$namespace) {
1.620     albertel 2429:       $namespace=$env{'request.state'};
1.168     albertel 2430:     #}
                   2431:   }
                   2432:   $namespace=~s/\//\_/g;
                   2433:   $namespace=~s/\W//g;
1.620     albertel 2434:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2435:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2436:   if ($domain eq 'public' && $stuname eq 'public') {
                   2437:       $stuname=$ENV{'REMOTE_ADDR'};
                   2438:   }
1.168     albertel 2439:   my $now=time;
                   2440:   my %hash;
                   2441:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2442:   if (tie(%hash,'GDBM_File',
                   2443: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2444: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2445:     $hash{"version:$symb"}++;
                   2446:     my $version=$hash{"version:$symb"};
                   2447:     my $allkeys=''; 
                   2448:     foreach my $key (keys(%$storehash)) {
                   2449:       $allkeys.=$key.':';
1.591     albertel 2450:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 2451:     }
                   2452:     $hash{"$version:$symb:timestamp"}=$now;
                   2453:     $allkeys.='timestamp';
                   2454:     $hash{"$version:keys:$symb"}=$allkeys;
                   2455:     if (untie(%hash)) {
                   2456:       return 'ok';
                   2457:     } else {
                   2458:       return "error:$!";
                   2459:     }
                   2460:   } else {
                   2461:     return "error:$!";
                   2462:   }
                   2463: }
1.167     albertel 2464: 
1.168     albertel 2465: # -----------------------------------------------------------------Temp Restore
1.167     albertel 2466: 
1.168     albertel 2467: sub tmprestore {
                   2468:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 2469: 
1.168     albertel 2470:   if (!$symb) {
                   2471:     $symb=&symbread();
1.620     albertel 2472:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2473:   }
                   2474:   $symb=escape($symb);
                   2475: 
1.620     albertel 2476:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 2477: 
1.620     albertel 2478:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2479:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2480:   if ($domain eq 'public' && $stuname eq 'public') {
                   2481:       $stuname=$ENV{'REMOTE_ADDR'};
                   2482:   }
1.168     albertel 2483:   my %returnhash;
                   2484:   $namespace=~s/\//\_/g;
                   2485:   $namespace=~s/\W//g;
                   2486:   my %hash;
                   2487:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2488:   if (tie(%hash,'GDBM_File',
                   2489: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2490: 	  &GDBM_READER(),0640)) {
1.168     albertel 2491:     my $version=$hash{"version:$symb"};
                   2492:     $returnhash{'version'}=$version;
                   2493:     my $scope;
                   2494:     for ($scope=1;$scope<=$version;$scope++) {
                   2495:       my $vkeys=$hash{"$scope:keys:$symb"};
                   2496:       my @keys=split(/:/,$vkeys);
                   2497:       my $key;
                   2498:       $returnhash{"$scope:keys"}=$vkeys;
                   2499:       foreach $key (@keys) {
1.591     albertel 2500: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   2501: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 2502:       }
                   2503:     }
1.168     albertel 2504:     if (!(untie(%hash))) {
                   2505:       return "error:$!";
                   2506:     }
                   2507:   } else {
                   2508:     return "error:$!";
                   2509:   }
                   2510:   return %returnhash;
1.167     albertel 2511: }
                   2512: 
1.9       www      2513: # ----------------------------------------------------------------------- Store
                   2514: 
                   2515: sub store {
1.124     www      2516:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2517:     my $home='';
                   2518: 
1.168     albertel 2519:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2520: 
1.213     www      2521:     $symb=&symbclean($symb);
1.122     albertel 2522:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      2523: 
1.620     albertel 2524:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2525:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      2526: 
                   2527:     &devalidate($symb,$stuname,$domain);
1.109     www      2528: 
                   2529:     $symb=escape($symb);
1.187     www      2530:     if (!$namespace) { 
1.620     albertel 2531:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      2532:           return ''; 
                   2533:        } 
                   2534:     }
1.620     albertel 2535:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      2536: 
                   2537:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   2538:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   2539: 
1.12      www      2540:     my $namevalue='';
1.191     harris41 2541:     foreach (keys %$storehash) {
1.591     albertel 2542:         $namevalue.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
1.191     harris41 2543:     }
1.12      www      2544:     $namevalue=~s/\&$//;
1.187     www      2545:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      2546:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      2547: }
                   2548: 
1.47      www      2549: # -------------------------------------------------------------- Critical Store
                   2550: 
                   2551: sub cstore {
1.124     www      2552:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2553:     my $home='';
                   2554: 
1.168     albertel 2555:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2556: 
1.213     www      2557:     $symb=&symbclean($symb);
1.122     albertel 2558:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      2559: 
1.620     albertel 2560:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2561:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      2562: 
                   2563:     &devalidate($symb,$stuname,$domain);
1.109     www      2564: 
                   2565:     $symb=escape($symb);
1.187     www      2566:     if (!$namespace) { 
1.620     albertel 2567:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      2568:           return ''; 
                   2569:        } 
                   2570:     }
1.620     albertel 2571:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      2572: 
                   2573:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   2574:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 2575: 
1.47      www      2576:     my $namevalue='';
1.191     harris41 2577:     foreach (keys %$storehash) {
1.591     albertel 2578:         $namevalue.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
1.191     harris41 2579:     }
1.47      www      2580:     $namevalue=~s/\&$//;
1.187     www      2581:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      2582:     return critical
                   2583:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      2584: }
                   2585: 
1.9       www      2586: # --------------------------------------------------------------------- Restore
                   2587: 
                   2588: sub restore {
1.124     www      2589:     my ($symb,$namespace,$domain,$stuname) = @_;
                   2590:     my $home='';
                   2591: 
1.168     albertel 2592:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2593: 
1.122     albertel 2594:     if (!$symb) {
                   2595:       unless ($symb=escape(&symbread())) { return ''; }
                   2596:     } else {
1.213     www      2597:       $symb=&escape(&symbclean($symb));
1.122     albertel 2598:     }
1.188     www      2599:     if (!$namespace) { 
1.620     albertel 2600:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      2601:           return ''; 
                   2602:        } 
                   2603:     }
1.620     albertel 2604:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2605:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   2606:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 2607:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   2608: 
1.12      www      2609:     my %returnhash=();
1.191     harris41 2610:     foreach (split(/\&/,$answer)) {
1.12      www      2611: 	my ($name,$value)=split(/\=/,$_);
1.591     albertel 2612:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 2613:     }
1.75      www      2614:     my $version;
                   2615:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.191     harris41 2616:        foreach (split(/\:/,$returnhash{$version.':keys'})) {
1.75      www      2617:           $returnhash{$_}=$returnhash{$version.':'.$_};
1.191     harris41 2618:        }
1.75      www      2619:     }
1.13      www      2620:     return %returnhash;
1.34      www      2621: }
                   2622: 
                   2623: # ---------------------------------------------------------- Course Description
                   2624: 
                   2625: sub coursedescription {
1.731     albertel 2626:     my ($courseid,$args)=@_;
1.34      www      2627:     $courseid=~s/^\///;
1.49      www      2628:     $courseid=~s/\_/\//g;
1.34      www      2629:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 2630:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 2631:     my $normalid=$cdomain.'_'.$cnum;
                   2632:     # need to always cache even if we get errors otherwise we keep 
                   2633:     # trying and trying and trying to get the course description.
                   2634:     my %envhash=();
                   2635:     my %returnhash=();
1.731     albertel 2636:     
                   2637:     my $expiretime=600;
                   2638:     if ($env{'request.course.id'} eq $normalid) {
                   2639: 	$expiretime=120;
                   2640:     }
                   2641: 
                   2642:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   2643:     if (!$args->{'freshen_cache'}
                   2644: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   2645: 	foreach my $key (keys(%env)) {
                   2646: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   2647: 	    my ($setting) = $1;
                   2648: 	    $returnhash{$setting} = $env{$key};
                   2649: 	}
                   2650: 	return %returnhash;
                   2651:     }
                   2652: 
                   2653:     # get the data agin
                   2654:     if (!$args->{'one_time'}) {
                   2655: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   2656:     }
1.34      www      2657:     if ($chome ne 'no_host') {
1.302     albertel 2658:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 2659:        if (!exists($returnhash{'con_lost'})) {
                   2660:            $returnhash{'home'}= $chome;
                   2661: 	   $returnhash{'domain'} = $cdomain;
                   2662: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  2663:            if (!defined($returnhash{'type'})) {
                   2664:                $returnhash{'type'} = 'Course';
                   2665:            }
1.130     albertel 2666:            while (my ($name,$value) = each %returnhash) {
1.53      www      2667:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 2668:            }
1.270     www      2669:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      2670:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 2671: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      2672:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   2673:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   2674:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      2675:        }
                   2676:     }
1.731     albertel 2677:     if (!$args->{'one_time'}) {
                   2678: 	&appenv(%envhash);
                   2679:     }
1.302     albertel 2680:     return %returnhash;
1.461     www      2681: }
                   2682: 
                   2683: # -------------------------------------------------See if a user is privileged
                   2684: 
                   2685: sub privileged {
                   2686:     my ($username,$domain)=@_;
                   2687:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   2688: 			&homeserver($username,$domain));
                   2689:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
                   2690:     my $now=time;
                   2691:     if ($rolesdump ne '') {
                   2692:         foreach (split(/&/,$rolesdump)) {
1.586     albertel 2693: 	    if ($_!~/^rolesdef_/) {
1.461     www      2694: 		my ($area,$role)=split(/=/,$_);
                   2695: 		$area=~s/\_\w\w$//;
                   2696: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   2697: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   2698: 		    my $active=1;
                   2699: 		    if ($tend) {
                   2700: 			if ($tend<$now) { $active=0; }
                   2701: 		    }
                   2702: 		    if ($tstart) {
                   2703: 			if ($tstart>$now) { $active=0; }
                   2704: 		    }
                   2705: 		    if ($active) { return 1; }
                   2706: 		}
                   2707: 	    }
                   2708: 	}
                   2709:     }
                   2710:     return 0;
1.9       www      2711: }
1.1       albertel 2712: 
1.103     harris41 2713: # -------------------------------------------------------- Get user privileges
1.11      www      2714: 
                   2715: sub rolesinit {
                   2716:     my ($domain,$username,$authhost)=@_;
                   2717:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.12      www      2718:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
1.11      www      2719:     my %allroles=();
1.678     raeburn  2720:     my %allgroups=();   
1.11      www      2721:     my $now=time;
1.743     albertel 2722:     my %userroles = ('user.login.time' => $now);
1.678     raeburn  2723:     my $group_privs;
1.11      www      2724: 
                   2725:     if ($rolesdump ne '') {
1.191     harris41 2726:         foreach (split(/&/,$rolesdump)) {
1.586     albertel 2727: 	  if ($_!~/^rolesdef_/) {
1.11      www      2728:             my ($area,$role)=split(/=/,$_);
1.587     albertel 2729: 	    $area=~s/\_\w\w$//;
1.678     raeburn  2730:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 2731: 	    if ($role=~/^cr/) { 
1.655     albertel 2732: 		if ($role=~m|^(cr/\w+/\w+/[a-zA-Z0-9]+)_(.*)$|) {
                   2733: 		    ($trole,my $trest)=($role=~m|^(cr/\w+/\w+/[a-zA-Z0-9]+)_(.*)$|);
                   2734: 		    ($tend,$tstart)=split('_',$trest);
                   2735: 		} else {
                   2736: 		    $trole=$role;
                   2737: 		}
1.678     raeburn  2738:             } elsif ($role =~ m|^gr/|) {
                   2739:                 ($trole,$tend,$tstart) = split(/_/,$role);
                   2740:                 ($trole,$group_privs) = split(/\//,$trole);
                   2741:                 $group_privs = &unescape($group_privs);
1.587     albertel 2742: 	    } else {
                   2743: 		($trole,$tend,$tstart)=split(/_/,$role);
                   2744: 	    }
1.743     albertel 2745: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   2746: 					 $username);
                   2747: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  2748:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   2749:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      2750:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 2751: 		my $spec=$trole.'.'.$area;
                   2752: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   2753: 		if ($trole =~ /^cr\//) {
1.567     raeburn  2754:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  2755:                 } elsif ($trole eq 'gr') {
                   2756:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 2757: 		} else {
1.567     raeburn  2758:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 2759: 		}
1.12      www      2760:             }
1.662     raeburn  2761:           }
1.191     harris41 2762:         }
1.743     albertel 2763:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   2764:         $userroles{'user.adv'}    = $adv;
                   2765: 	$userroles{'user.author'} = $author;
1.620     albertel 2766:         $env{'user.adv'}=$adv;
1.11      www      2767:     }
1.743     albertel 2768:     return \%userroles;  
1.11      www      2769: }
                   2770: 
1.567     raeburn  2771: sub set_arearole {
                   2772:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   2773: # log the associated role with the area
                   2774:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 2775:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  2776: }
                   2777: 
                   2778: sub custom_roleprivs {
                   2779:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   2780:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   2781:     my $homsvr=homeserver($rauthor,$rdomain);
                   2782:     if ($hostname{$homsvr} ne '') {
                   2783:         my ($rdummy,$roledef)=
                   2784:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   2785:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   2786:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   2787:             if (defined($syspriv)) {
                   2788:                 $$allroles{'cm./'}.=':'.$syspriv;
                   2789:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   2790:             }
                   2791:             if ($tdomain ne '') {
                   2792:                 if (defined($dompriv)) {
                   2793:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   2794:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   2795:                 }
                   2796:                 if (($trest ne '') && (defined($coursepriv))) {
                   2797:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   2798:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   2799:                 }
                   2800:             }
                   2801:         }
                   2802:     }
                   2803: }
                   2804: 
1.678     raeburn  2805: sub group_roleprivs {
                   2806:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   2807:     my $access = 1;
                   2808:     my $now = time;
                   2809:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   2810:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   2811:     if ($access) {
                   2812:         my ($course,$group) = ($area =~ m|(/\w+/\w+)/([^/]+)$|);
                   2813:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   2814:     }
                   2815: }
1.567     raeburn  2816: 
                   2817: sub standard_roleprivs {
                   2818:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   2819:     if (defined($pr{$trole.':s'})) {
                   2820:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   2821:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   2822:     }
                   2823:     if ($tdomain ne '') {
                   2824:         if (defined($pr{$trole.':d'})) {
                   2825:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   2826:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   2827:         }
                   2828:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   2829:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   2830:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   2831:         }
                   2832:     }
                   2833: }
                   2834: 
                   2835: sub set_userprivs {
1.678     raeburn  2836:     my ($userroles,$allroles,$allgroups) = @_; 
1.567     raeburn  2837:     my $author=0;
                   2838:     my $adv=0;
1.678     raeburn  2839:     my %grouproles = ();
                   2840:     if (keys(%{$allgroups}) > 0) {
                   2841:         foreach my $role (keys %{$allroles}) {
1.681     raeburn  2842:             my ($trole,$area,$sec,$extendedarea);
1.771     raeburn  2843:             if ($role =~ m-^(\w+|cr/\w+/\w+/\w+)\.(/\w+/\w+)(/?\w*)-) {
1.678     raeburn  2844:                 $trole = $1;
                   2845:                 $area = $2;
1.681     raeburn  2846:                 $sec = $3;
                   2847:                 $extendedarea = $area.$sec;
                   2848:                 if (exists($$allgroups{$area})) {
                   2849:                     foreach my $group (keys(%{$$allgroups{$area}})) {
                   2850:                         my $spec = $trole.'.'.$extendedarea;
                   2851:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
                   2852:                                                 $$allgroups{$area}{$group};
1.678     raeburn  2853:                     }
                   2854:                 }
                   2855:             }
                   2856:         }
                   2857:     }
                   2858:     foreach (keys(%grouproles)) {
                   2859:         $$allroles{$_} = $grouproles{$_};
                   2860:     }
1.567     raeburn  2861:     foreach (keys %{$allroles}) {
                   2862:         my %thesepriv=();
                   2863:         if (($_=~/^au/) || ($_=~/^ca/)) { $author=1; }
                   2864:         foreach (split(/:/,$$allroles{$_})) {
                   2865:             if ($_ ne '') {
                   2866:                 my ($privilege,$restrictions)=split(/&/,$_);
                   2867:                 if ($restrictions eq '') {
                   2868:                     $thesepriv{$privilege}='F';
                   2869:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   2870:                     $thesepriv{$privilege}.=$restrictions;
                   2871:                 }
                   2872:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   2873:             }
                   2874:         }
                   2875:         my $thesestr='';
                   2876:         foreach (keys %thesepriv) { $thesestr.=':'.$_.'&'.$thesepriv{$_}; }
1.743     albertel 2877:         $userroles->{'user.priv.'.$_} = $thesestr;
1.567     raeburn  2878:     }
                   2879:     return ($author,$adv);
                   2880: }
                   2881: 
1.12      www      2882: # --------------------------------------------------------------- get interface
                   2883: 
                   2884: sub get {
1.131     albertel 2885:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      2886:    my $items='';
1.191     harris41 2887:    foreach (@$storearr) {
1.12      www      2888:        $items.=escape($_).'&';
1.191     harris41 2889:    }
1.12      www      2890:    $items=~s/\&$//;
1.620     albertel 2891:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2892:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 2893:    my $uhome=&homeserver($uname,$udomain);
                   2894: 
1.133     albertel 2895:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      2896:    my @pairs=split(/\&/,$rep);
1.273     albertel 2897:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   2898:      return @pairs;
                   2899:    }
1.15      www      2900:    my %returnhash=();
1.42      www      2901:    my $i=0;
1.191     harris41 2902:    foreach (@$storearr) {
1.557     albertel 2903:       $returnhash{$_}=&thaw_unescape($pairs[$i]);
1.42      www      2904:       $i++;
1.191     harris41 2905:    }
1.15      www      2906:    return %returnhash;
1.27      www      2907: }
                   2908: 
                   2909: # --------------------------------------------------------------- del interface
                   2910: 
                   2911: sub del {
1.133     albertel 2912:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      2913:    my $items='';
1.191     harris41 2914:    foreach (@$storearr) {
1.27      www      2915:        $items.=escape($_).'&';
1.191     harris41 2916:    }
1.27      www      2917:    $items=~s/\&$//;
1.620     albertel 2918:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2919:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 2920:    my $uhome=&homeserver($uname,$udomain);
                   2921: 
                   2922:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      2923: }
                   2924: 
                   2925: # -------------------------------------------------------------- dump interface
                   2926: 
                   2927: sub dump {
1.755     albertel 2928:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   2929:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2930:     if (!$uname) { $uname=$env{'user.name'}; }
                   2931:     my $uhome=&homeserver($uname,$udomain);
                   2932:     if ($regexp) {
                   2933: 	$regexp=&escape($regexp);
                   2934:     } else {
                   2935: 	$regexp='.';
                   2936:     }
                   2937:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   2938:     my @pairs=split(/\&/,$rep);
                   2939:     my %returnhash=();
                   2940:     foreach my $item (@pairs) {
                   2941: 	my ($key,$value)=split(/=/,$item,2);
                   2942: 	$key = &unescape($key);
                   2943: 	next if ($key =~ /^error: 2 /);
                   2944: 	$returnhash{$key}=&thaw_unescape($value);
                   2945:     }
                   2946:     return %returnhash;
1.407     www      2947: }
                   2948: 
1.717     albertel 2949: # --------------------------------------------------------- dumpstore interface
                   2950: 
                   2951: sub dumpstore {
                   2952:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   2953:    return &dump($namespace,$udomain,$uname,$regexp,$range);
                   2954: }
                   2955: 
1.407     www      2956: # -------------------------------------------------------------- keys interface
                   2957: 
                   2958: sub getkeys {
                   2959:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 2960:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2961:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      2962:    my $uhome=&homeserver($uname,$udomain);
                   2963:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   2964:    my @keyarray=();
                   2965:    foreach (split(/\&/,$rep)) {
                   2966:       push (@keyarray,&unescape($_));
                   2967:    }
                   2968:    return @keyarray;
1.318     matthew  2969: }
                   2970: 
1.319     matthew  2971: # --------------------------------------------------------------- currentdump
                   2972: sub currentdump {
1.328     matthew  2973:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 2974:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   2975:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   2976:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  2977:    my $uhome = &homeserver($sname,$sdom);
                   2978:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  2979:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  2980:    #
1.318     matthew  2981:    my %returnhash=();
1.319     matthew  2982:    #
                   2983:    if ($rep eq "unknown_cmd") { 
                   2984:        # an old lond will not know currentdump
                   2985:        # Do a dump and make it look like a currentdump
1.326     matthew  2986:        my @tmp = &dump($courseid,$sdom,$sname,'.');
1.319     matthew  2987:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   2988:        my %hash = @tmp;
                   2989:        @tmp=();
1.424     matthew  2990:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  2991:    } else {
                   2992:        my @pairs=split(/\&/,$rep);
                   2993:        foreach (@pairs) {
                   2994:            my ($key,$value)=split(/=/,$_);
                   2995:            my ($symb,$param) = split(/:/,$key);
                   2996:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 2997:                                                         &thaw_unescape($value);
1.319     matthew  2998:        }
1.191     harris41 2999:    }
1.12      www      3000:    return %returnhash;
1.424     matthew  3001: }
                   3002: 
                   3003: sub convert_dump_to_currentdump{
                   3004:     my %hash = %{shift()};
                   3005:     my %returnhash;
                   3006:     # Code ripped from lond, essentially.  The only difference
                   3007:     # here is the unescaping done by lonnet::dump().  Conceivably
                   3008:     # we might run in to problems with parameter names =~ /^v\./
                   3009:     while (my ($key,$value) = each(%hash)) {
                   3010:         my ($v,$symb,$param) = split(/:/,$key);
                   3011:         next if ($v eq 'version' || $symb eq 'keys');
                   3012:         next if (exists($returnhash{$symb}) &&
                   3013:                  exists($returnhash{$symb}->{$param}) &&
                   3014:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   3015:         $returnhash{$symb}->{$param}=$value;
                   3016:         $returnhash{$symb}->{'v.'.$param}=$v;
                   3017:     }
                   3018:     #
                   3019:     # Remove all of the keys in the hashes which keep track of
                   3020:     # the version of the parameter.
                   3021:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   3022:         # use a foreach because we are going to delete from the hash.
                   3023:         foreach my $key (keys(%$param_hash)) {
                   3024:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   3025:         }
                   3026:     }
                   3027:     return \%returnhash;
1.12      www      3028: }
                   3029: 
1.627     albertel 3030: # ------------------------------------------------------ critical inc interface
                   3031: 
                   3032: sub cinc {
                   3033:     return &inc(@_,'critical');
                   3034: }
                   3035: 
1.449     matthew  3036: # --------------------------------------------------------------- inc interface
                   3037: 
                   3038: sub inc {
1.627     albertel 3039:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 3040:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3041:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  3042:     my $uhome=&homeserver($uname,$udomain);
                   3043:     my $items='';
                   3044:     if (! ref($store)) {
                   3045:         # got a single value, so use that instead
                   3046:         $items = &escape($store).'=&';
                   3047:     } elsif (ref($store) eq 'SCALAR') {
                   3048:         $items = &escape($$store).'=&';        
                   3049:     } elsif (ref($store) eq 'ARRAY') {
                   3050:         $items = join('=&',map {&escape($_);} @{$store});
                   3051:     } elsif (ref($store) eq 'HASH') {
                   3052:         while (my($key,$value) = each(%{$store})) {
                   3053:             $items.= &escape($key).'='.&escape($value).'&';
                   3054:         }
                   3055:     }
                   3056:     $items=~s/\&$//;
1.627     albertel 3057:     if ($critical) {
                   3058: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3059:     } else {
                   3060: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3061:     }
1.449     matthew  3062: }
                   3063: 
1.12      www      3064: # --------------------------------------------------------------- put interface
                   3065: 
                   3066: sub put {
1.134     albertel 3067:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3068:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3069:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3070:    my $uhome=&homeserver($uname,$udomain);
1.12      www      3071:    my $items='';
1.191     harris41 3072:    foreach (keys %$storehash) {
1.557     albertel 3073:        $items.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
1.191     harris41 3074:    }
1.12      www      3075:    $items=~s/\&$//;
1.134     albertel 3076:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      3077: }
                   3078: 
1.631     albertel 3079: # ------------------------------------------------------------ newput interface
                   3080: 
                   3081: sub newput {
                   3082:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   3083:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3084:    if (!$uname) { $uname=$env{'user.name'}; }
                   3085:    my $uhome=&homeserver($uname,$udomain);
                   3086:    my $items='';
                   3087:    foreach my $key (keys(%$storehash)) {
                   3088:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   3089:    }
                   3090:    $items=~s/\&$//;
                   3091:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   3092: }
                   3093: 
                   3094: # ---------------------------------------------------------  putstore interface
                   3095: 
1.524     raeburn  3096: sub putstore {
1.715     albertel 3097:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 3098:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3099:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  3100:    my $uhome=&homeserver($uname,$udomain);
                   3101:    my $items='';
1.715     albertel 3102:    foreach my $key (keys(%$storehash)) {
                   3103:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  3104:    }
1.715     albertel 3105:    $items=~s/\&$//;
1.716     albertel 3106:    my $esc_symb=&escape($symb);
                   3107:    my $esc_v=&escape($version);
1.715     albertel 3108:    my $reply =
1.716     albertel 3109:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 3110: 	      $uhome);
                   3111:    if ($reply eq 'unknown_cmd') {
1.716     albertel 3112:        # gfall back to way things use to be done
1.715     albertel 3113:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   3114: 			    $uname);
1.524     raeburn  3115:    }
1.715     albertel 3116:    return $reply;
                   3117: }
                   3118: 
                   3119: sub old_putstore {
1.716     albertel 3120:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   3121:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3122:     if (!$uname) { $uname=$env{'user.name'}; }
                   3123:     my $uhome=&homeserver($uname,$udomain);
                   3124:     my %newstorehash;
                   3125:     foreach (keys %$storehash) {
                   3126: 	my $key = $version.':'.&escape($symb).':'.$_;
                   3127: 	$newstorehash{$key} = $storehash->{$_};
                   3128:     }
                   3129:     my $items='';
                   3130:     my %allitems = ();
                   3131:     foreach (keys %newstorehash) {
                   3132: 	if ($_ =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
                   3133: 	    my $key = $1.':keys:'.$2;
                   3134: 	    $allitems{$key} .= $3.':';
                   3135: 	}
                   3136: 	$items.=$_.'='.&freeze_escape($newstorehash{$_}).'&';
                   3137:     }
                   3138:     foreach (keys %allitems) {
                   3139: 	$allitems{$_} =~ s/\:$//;
                   3140: 	$items.= $_.'='.$allitems{$_}.'&';
                   3141:     }
                   3142:     $items=~s/\&$//;
                   3143:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  3144: }
                   3145: 
1.47      www      3146: # ------------------------------------------------------ critical put interface
                   3147: 
                   3148: sub cput {
1.134     albertel 3149:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3150:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3151:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3152:    my $uhome=&homeserver($uname,$udomain);
1.47      www      3153:    my $items='';
1.191     harris41 3154:    foreach (keys %$storehash) {
1.715     albertel 3155:        $items.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
1.191     harris41 3156:    }
1.47      www      3157:    $items=~s/\&$//;
1.134     albertel 3158:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3159: }
                   3160: 
                   3161: # -------------------------------------------------------------- eget interface
                   3162: 
                   3163: sub eget {
1.133     albertel 3164:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3165:    my $items='';
1.191     harris41 3166:    foreach (@$storearr) {
1.12      www      3167:        $items.=escape($_).'&';
1.191     harris41 3168:    }
1.12      www      3169:    $items=~s/\&$//;
1.620     albertel 3170:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3171:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3172:    my $uhome=&homeserver($uname,$udomain);
                   3173:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3174:    my @pairs=split(/\&/,$rep);
                   3175:    my %returnhash=();
1.42      www      3176:    my $i=0;
1.191     harris41 3177:    foreach (@$storearr) {
1.557     albertel 3178:       $returnhash{$_}=&thaw_unescape($pairs[$i]);
1.42      www      3179:       $i++;
1.191     harris41 3180:    }
1.12      www      3181:    return %returnhash;
                   3182: }
                   3183: 
1.667     albertel 3184: # ------------------------------------------------------------ tmpput interface
                   3185: sub tmpput {
                   3186:     my ($storehash,$server)=@_;
                   3187:     my $items='';
                   3188:     foreach (keys(%$storehash)) {
                   3189: 	$items.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
                   3190:     }
                   3191:     $items=~s/\&$//;
                   3192:     return &reply("tmpput:$items",$server);
                   3193: }
                   3194: 
                   3195: # ------------------------------------------------------------ tmpget interface
                   3196: sub tmpget {
1.688     albertel 3197:     my ($token,$server)=@_;
                   3198:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3199:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 3200:     my %returnhash;
                   3201:     foreach my $item (split(/\&/,$rep)) {
                   3202: 	my ($key,$value)=split(/=/,$item);
                   3203: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   3204:     }
                   3205:     return %returnhash;
                   3206: }
                   3207: 
1.688     albertel 3208: # ------------------------------------------------------------ tmpget interface
                   3209: sub tmpdel {
                   3210:     my ($token,$server)=@_;
                   3211:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3212:     return &reply("tmpdel:$token",$server);
                   3213: }
                   3214: 
1.765     albertel 3215: # -------------------------------------------------- portfolio access checking
                   3216: 
                   3217: sub portfolio_access {
1.766     albertel 3218:     my ($requrl) = @_;
1.765     albertel 3219:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   3220:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
                   3221:     if ($result eq 'ok') {
1.766     albertel 3222:        return 'F';
1.765     albertel 3223:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 3224:        return 'A';
1.765     albertel 3225:     }
1.766     albertel 3226:     return '';
1.765     albertel 3227: }
                   3228: 
                   3229: sub get_portfolio_access {
1.767     albertel 3230:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   3231: 
                   3232:     if (!ref($access_hash)) {
                   3233: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   3234: 	my %access_controls = &get_access_controls($current_perms,$group,
                   3235: 						   $file_name);
                   3236: 	$access_hash = $access_controls{$file_name};
                   3237:     }
                   3238: 
1.765     albertel 3239:     my ($public,$guest,@domains,@users,@courses,@groups);
                   3240:     my $now = time;
                   3241:     if (ref($access_hash) eq 'HASH') {
                   3242:         foreach my $key (keys(%{$access_hash})) {
                   3243:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   3244:             if ($start > $now) {
                   3245:                 next;
                   3246:             }
                   3247:             if ($end && $end<$now) {
                   3248:                 next;
                   3249:             }
                   3250:             if ($scope eq 'public') {
                   3251:                 $public = $key;
                   3252:                 last;
                   3253:             } elsif ($scope eq 'guest') {
                   3254:                 $guest = $key;
                   3255:             } elsif ($scope eq 'domains') {
                   3256:                 push(@domains,$key);
                   3257:             } elsif ($scope eq 'users') {
                   3258:                 push(@users,$key);
                   3259:             } elsif ($scope eq 'course') {
                   3260:                 push(@courses,$key);
                   3261:             } elsif ($scope eq 'group') {
                   3262:                 push(@groups,$key);
                   3263:             }
                   3264:         }
                   3265:         if ($public) {
                   3266:             return 'ok';
                   3267:         }
                   3268:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   3269:             if ($guest) {
                   3270:                 return $guest;
                   3271:             }
                   3272:         } else {
                   3273:             if (@domains > 0) {
                   3274:                 foreach my $domkey (@domains) {
                   3275:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   3276:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   3277:                             return 'ok';
                   3278:                         }
                   3279:                     }
                   3280:                 }
                   3281:             }
                   3282:             if (@users > 0) {
                   3283:                 foreach my $userkey (@users) {
                   3284:                     if (exists($access_hash->{$userkey}{'users'}{$env{'user.name'}.':'.$env{'user.domain'}})) {
                   3285:                         return 'ok';
                   3286:                     }
                   3287:                 }
                   3288:             }
                   3289:             my %roleshash;
                   3290:             my @courses_and_groups = @courses;
                   3291:             push(@courses_and_groups,@groups); 
                   3292:             if (@courses_and_groups > 0) {
                   3293:                 my (%allgroups,%allroles); 
                   3294:                 my ($start,$end,$role,$sec,$group);
                   3295:                 foreach my $envkey (%env) {
                   3296:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./([^/]+)/([^/]+)/?([^/]*)$-) {
                   3297:                         my $cid = $2.'_'.$3; 
                   3298:                         if ($1 eq 'gr') {
                   3299:                             $group = $4;
                   3300:                             $allgroups{$cid}{$group} = $env{$envkey};
                   3301:                         } else {
                   3302:                             if ($4 eq '') {
                   3303:                                 $sec = 'none';
                   3304:                             } else {
                   3305:                                 $sec = $4;
                   3306:                             }
                   3307:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   3308:                         }
                   3309:                     } elsif ($envkey =~ m-^user\.role\./cr/(\w+/\w+/\w*)./([^/]+)/([^/]+)/?([^/]*)$-) {
                   3310:                         my $cid = $2.'_'.$3;
                   3311:                         if ($4 eq '') {
                   3312:                             $sec = 'none';
                   3313:                         } else {
                   3314:                             $sec = $4;
                   3315:                         }
                   3316:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   3317:                     }
                   3318:                 }
                   3319:                 if (keys(%allroles) == 0) {
                   3320:                     return;
                   3321:                 }
                   3322:                 foreach my $key (@courses_and_groups) {
                   3323:                     my %content = %{$$access_hash{$key}};
                   3324:                     my $cnum = $content{'number'};
                   3325:                     my $cdom = $content{'domain'};
                   3326:                     my $cid = $cdom.'_'.$cnum;
                   3327:                     if (!exists($allroles{$cid})) {
                   3328:                         next;
                   3329:                     }    
                   3330:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   3331:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   3332:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   3333:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   3334:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   3335:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   3336:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   3337:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   3338:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   3339:                                         if (grep/^all$/,@sections) {
                   3340:                                             return 'ok';
                   3341:                                         } else {
                   3342:                                             if (grep/^$sec$/,@sections) {
                   3343:                                                 return 'ok';
                   3344:                                             }
                   3345:                                         }
                   3346:                                     }
                   3347:                                 }
                   3348:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   3349:                                     if (grep/^none$/,@groups) {
                   3350:                                         return 'ok';
                   3351:                                     }
                   3352:                                 } else {
                   3353:                                     if (grep/^all$/,@groups) {
                   3354:                                         return 'ok';
                   3355:                                     } 
                   3356:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   3357:                                         if (grep/^$group$/,@groups) {
                   3358:                                             return 'ok';
                   3359:                                         }
                   3360:                                     }
                   3361:                                 } 
                   3362:                             }
                   3363:                         }
                   3364:                     }
                   3365:                 }
                   3366:             }
                   3367:             if ($guest) {
                   3368:                 return $guest;
                   3369:             }
                   3370:         }
                   3371:     }
                   3372:     return;
                   3373: }
                   3374: 
                   3375: sub course_group_datechecker {
                   3376:     my ($dates,$now,$status) = @_;
                   3377:     my ($start,$end) = split(/\./,$dates);
                   3378:     if (!$start && !$end) {
                   3379:         return 'ok';
                   3380:     }
                   3381:     if (grep/^active$/,@{$status}) {
                   3382:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   3383:             return 'ok';
                   3384:         }
                   3385:     }
                   3386:     if (grep/^previous$/,@{$status}) {
                   3387:         if ($end > $now ) {
                   3388:             return 'ok';
                   3389:         }
                   3390:     }
                   3391:     if (grep/^future$/,@{$status}) {
                   3392:         if ($start > $now) {
                   3393:             return 'ok';
                   3394:         }
                   3395:     }
                   3396:     return; 
                   3397: }
                   3398: 
                   3399: sub parse_portfolio_url {
                   3400:     my ($url) = @_;
                   3401: 
                   3402:     my ($type,$udom,$unum,$group,$file_name);
                   3403:     
                   3404:     if ($url =~  m-^/*uploaded/([^/]+)/([^/]+)/portfolio(/.+)$-) {
                   3405: 	$type = 1;
                   3406:         $udom = $1;
                   3407:         $unum = $2;
                   3408:         $file_name = $3;
                   3409:     } elsif ($url =~ m-^/*uploaded/([^/]+)/([^/]+)/groups/([^/]+)/portfolio/(.+)$-) {
                   3410: 	$type = 2;
                   3411:         $udom = $1;
                   3412:         $unum = $2;
                   3413:         $group = $3;
                   3414:         $file_name = $3.'/'.$4;
                   3415:     }
                   3416:     if (wantarray) {
                   3417: 	return ($type,$udom,$unum,$file_name,$group);
                   3418:     }
                   3419:     return $type;
                   3420: }
                   3421: 
                   3422: sub is_portfolio_url {
                   3423:     my ($url) = @_;
                   3424:     return scalar(&parse_portfolio_url($url));
                   3425: }
                   3426: 
1.341     www      3427: # ---------------------------------------------- Custom access rule evaluation
                   3428: 
                   3429: sub customaccess {
                   3430:     my ($priv,$uri)=@_;
1.620     albertel 3431:     my ($urole,$urealm)=split(/\./,$env{'request.role'});
1.343     www      3432:     $urealm=~s/^\W//;
                   3433:     my ($udom,$ucrs,$usec)=split(/\//,$urealm);
1.341     www      3434:     my $access=0;
                   3435:     foreach (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.342     www      3436: 	my ($effect,$realm,$role)=split(/\:/,$_);
1.343     www      3437:         if ($role) {
                   3438: 	   if ($role ne $urole) { next; }
                   3439:         }
                   3440:         foreach (split(/\s*\,\s*/,$realm)) {
                   3441:             my ($tdom,$tcrs,$tsec)=split(/\_/,$_);
                   3442:             if ($tdom) {
                   3443: 		if ($tdom ne $udom) { next; }
                   3444:             }
                   3445:             if ($tcrs) {
                   3446: 		if ($tcrs ne $ucrs) { next; }
                   3447:             }
                   3448:             if ($tsec) {
                   3449: 		if ($tsec ne $usec) { next; }
                   3450:             }
                   3451:             $access=($effect eq 'allow');
                   3452:             last;
1.342     www      3453:         }
1.402     bowersj2 3454: 	if ($realm eq '' && $role eq '') {
                   3455:             $access=($effect eq 'allow');
                   3456: 	}
1.341     www      3457:     }
                   3458:     return $access;
                   3459: }
                   3460: 
1.103     harris41 3461: # ------------------------------------------------- Check for a user privilege
1.12      www      3462: 
                   3463: sub allowed {
1.579     albertel 3464:     my ($priv,$uri,$symb)=@_;
1.705     albertel 3465:     my $ver_orguri=$uri;
1.439     www      3466:     $uri=&deversion($uri);
1.152     www      3467:     my $orguri=$uri;
1.52      www      3468:     $uri=&declutter($uri);
1.545     banghart 3469:     
1.620     albertel 3470:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      3471: # Free bre access to adm and meta resources
1.775     albertel 3472:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 3473: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   3474: 	&& ($priv eq 'bre')) {
1.14      www      3475: 	return 'F';
1.159     www      3476:     }
                   3477: 
1.545     banghart 3478: # Free bre access to user's own portfolio contents
1.714     raeburn  3479:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  3480:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  3481: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.545     banghart 3482:         return 'F';
                   3483:     }
                   3484: 
1.762     raeburn  3485: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  3486:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   3487:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   3488:         if (exists($env{'request.course.id'})) {
                   3489:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3490:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3491:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   3492:                 my $courseprivid=$env{'request.course.id'};
                   3493:                 $courseprivid=~s/\_/\//;
                   3494:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   3495:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   3496:                     return $1; 
1.762     raeburn  3497:                 } else {
                   3498:                     if ($env{'request.course.sec'}) {
                   3499:                         $courseprivid.='/'.$env{'request.course.sec'};
                   3500:                     }
                   3501:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   3502:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   3503:                         return $2;
                   3504:                     }
1.714     raeburn  3505:                 }
                   3506:             }
                   3507:         }
                   3508:     }
                   3509: 
1.159     www      3510: # Free bre to public access
                   3511: 
                   3512:     if ($priv eq 'bre') {
1.238     www      3513:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 3514: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      3515:            return 'F'; 
                   3516:         }
1.238     www      3517:         if ($copyright eq 'priv') {
                   3518:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 3519: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      3520: 		return '';
                   3521:             }
                   3522:         }
                   3523:         if ($copyright eq 'domain') {
                   3524:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 3525: 	    unless (($env{'user.domain'} eq $1) ||
                   3526:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      3527: 		return '';
                   3528:             }
1.262     matthew  3529:         }
1.620     albertel 3530:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  3531:             # Library role, so allow browsing of resources in this domain.
                   3532:             return 'F';
1.238     www      3533:         }
1.341     www      3534:         if ($copyright eq 'custom') {
                   3535: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   3536:         }
1.14      www      3537:     }
1.264     matthew  3538:     # Domain coordinator is trying to create a course
1.620     albertel 3539:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  3540:         # uri is the requested domain in this case.
                   3541:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  3542:         # a role of dc for the domain in question.
1.620     albertel 3543:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  3544:     }
1.29      www      3545: 
1.52      www      3546:     my $thisallowed='';
                   3547:     my $statecond=0;
                   3548:     my $courseprivid='';
                   3549: 
                   3550: # Course
                   3551: 
1.620     albertel 3552:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3553:        $thisallowed.=$1;
                   3554:     }
1.29      www      3555: 
1.52      www      3556: # Domain
                   3557: 
1.620     albertel 3558:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 3559:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      3560:        $thisallowed.=$1;
                   3561:     }
1.52      www      3562: 
                   3563: # Course: uri itself is a course
1.66      www      3564:     my $courseuri=$uri;
                   3565:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      3566:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      3567: 
1.620     albertel 3568:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 3569:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      3570:        $thisallowed.=$1;
                   3571:     }
1.29      www      3572: 
1.665     albertel 3573: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 3574: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 3575:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 3576: 	$thisallowed='';
1.671     raeburn  3577:         my ($match)=&is_on_map($uri);
                   3578:         if ($match) {
                   3579:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   3580:                   =~/\Q$priv\E\&([^\:]*)/) {
                   3581:                 $thisallowed.=$1;
                   3582:             }
                   3583:         } else {
1.705     albertel 3584:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  3585:             if ($refuri) {
                   3586:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  3587:                     $thisallowed='F';
1.671     raeburn  3588:                 } else {
                   3589:                     $refuri=&declutter($refuri);
                   3590:                     my ($match) = &is_on_map($refuri);
                   3591:                     if ($match) {
                   3592:                         $thisallowed='F';
                   3593:                     }
1.669     raeburn  3594:                 }
1.671     raeburn  3595:             }
                   3596:         }
1.314     www      3597:     }
1.492     albertel 3598: 
1.766     albertel 3599:     if ($priv eq 'bre'
                   3600: 	&& $thisallowed ne 'F' 
                   3601: 	&& $thisallowed ne '2'
                   3602: 	&& &is_portfolio_url($uri)) {
                   3603: 	$thisallowed = &portfolio_access($uri);
                   3604:     }
                   3605:     
1.52      www      3606: # Full access at system, domain or course-wide level? Exit.
1.29      www      3607: 
                   3608:     if ($thisallowed=~/F/) {
                   3609: 	return 'F';
                   3610:     }
                   3611: 
1.52      www      3612: # If this is generating or modifying users, exit with special codes
1.29      www      3613: 
1.643     www      3614:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   3615: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 3616: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      3617: # no author name given, so this just checks on the general right to make a co-author in this domain
                   3618: 	    unless ($auname) { return $thisallowed; }
                   3619: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 3620: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   3621: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   3622: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   3623: 	}
1.52      www      3624: 	return $thisallowed;
                   3625:     }
                   3626: #
1.103     harris41 3627: # Gathered so far: system, domain and course wide privileges
1.52      www      3628: #
                   3629: # Course: See if uri or referer is an individual resource that is part of 
                   3630: # the course
                   3631: 
1.620     albertel 3632:     if ($env{'request.course.id'}) {
1.232     www      3633: 
1.620     albertel 3634:        $courseprivid=$env{'request.course.id'};
                   3635:        if ($env{'request.course.sec'}) {
                   3636:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      3637:        }
                   3638:        $courseprivid=~s/\_/\//;
                   3639:        my $checkreferer=1;
1.232     www      3640:        my ($match,$cond)=&is_on_map($uri);
                   3641:        if ($match) {
                   3642:            $statecond=$cond;
1.620     albertel 3643:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 3644:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3645:                $thisallowed.=$1;
                   3646:                $checkreferer=0;
                   3647:            }
1.29      www      3648:        }
1.83      www      3649:        
1.148     www      3650:        if ($checkreferer) {
1.620     albertel 3651: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      3652:             unless ($refuri) {
1.620     albertel 3653:                 foreach (keys %env) {
1.148     www      3654: 		    if ($_=~/^httpref\..*\*/) {
                   3655: 			my $pattern=$_;
1.156     www      3656:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      3657:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   3658:                         $pattern=~s/\//\\\//g;
1.152     www      3659:                         if ($orguri=~/$pattern/) {
1.620     albertel 3660: 			    $refuri=$env{$_};
1.148     www      3661:                         }
                   3662:                     }
1.191     harris41 3663:                 }
1.148     www      3664:             }
1.232     www      3665: 
1.148     www      3666:          if ($refuri) { 
1.152     www      3667: 	  $refuri=&declutter($refuri);
1.232     www      3668:           my ($match,$cond)=&is_on_map($refuri);
                   3669:             if ($match) {
                   3670:               my $refstatecond=$cond;
1.620     albertel 3671:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 3672:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3673:                   $thisallowed.=$1;
1.53      www      3674:                   $uri=$refuri;
                   3675:                   $statecond=$refstatecond;
1.52      www      3676:               }
                   3677:           }
1.148     www      3678:         }
1.29      www      3679:        }
1.52      www      3680:    }
1.29      www      3681: 
1.52      www      3682: #
1.103     harris41 3683: # Gathered now: all privileges that could apply, and condition number
1.52      www      3684: # 
                   3685: #
                   3686: # Full or no access?
                   3687: #
1.29      www      3688: 
1.52      www      3689:     if ($thisallowed=~/F/) {
                   3690: 	return 'F';
                   3691:     }
1.29      www      3692: 
1.52      www      3693:     unless ($thisallowed) {
                   3694:         return '';
                   3695:     }
1.29      www      3696: 
1.52      www      3697: # Restrictions exist, deal with them
                   3698: #
                   3699: #   C:according to course preferences
                   3700: #   R:according to resource settings
                   3701: #   L:unless locked
                   3702: #   X:according to user session state
                   3703: #
                   3704: 
                   3705: # Possibly locked functionality, check all courses
1.54      www      3706: # Locks might take effect only after 10 minutes cache expiration for other
                   3707: # courses, and 2 minutes for current course
1.52      www      3708: 
                   3709:     my $envkey;
                   3710:     if ($thisallowed=~/L/) {
1.620     albertel 3711:         foreach $envkey (keys %env) {
1.54      www      3712:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   3713:                my $courseid=$2;
                   3714:                my $roleid=$1.'.'.$2;
1.92      www      3715:                $courseid=~s/^\///;
1.54      www      3716:                my $expiretime=600;
1.620     albertel 3717:                if ($env{'request.role'} eq $roleid) {
1.54      www      3718: 		  $expiretime=120;
                   3719:                }
                   3720: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   3721:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 3722:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 3723: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      3724:                }
1.620     albertel 3725:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   3726:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   3727: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   3728:                        &log($env{'user.domain'},$env{'user.name'},
                   3729:                             $env{'user.home'},
1.57      www      3730:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      3731:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 3732:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      3733: 		       return '';
                   3734:                    }
                   3735:                }
1.620     albertel 3736:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   3737:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   3738: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   3739:                        &log($env{'user.domain'},$env{'user.name'},
                   3740:                             $env{'user.home'},
1.57      www      3741:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      3742:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 3743:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      3744: 		       return '';
                   3745:                    }
                   3746:                }
                   3747: 	   }
1.29      www      3748:        }
1.52      www      3749:     }
                   3750:    
                   3751: #
                   3752: # Rest of the restrictions depend on selected course
                   3753: #
                   3754: 
1.620     albertel 3755:     unless ($env{'request.course.id'}) {
1.766     albertel 3756: 	if ($thisallowed eq 'A') {
                   3757: 	    return 'A';
                   3758: 	} else {
                   3759: 	    return '1';
                   3760: 	}
1.52      www      3761:     }
1.29      www      3762: 
1.52      www      3763: #
                   3764: # Now user is definitely in a course
                   3765: #
1.53      www      3766: 
                   3767: 
                   3768: # Course preferences
                   3769: 
                   3770:    if ($thisallowed=~/C/) {
1.620     albertel 3771:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   3772:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   3773:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 3774: 	   =~/\Q$rolecode\E/) {
1.689     albertel 3775: 	   if ($priv ne 'pch') { 
                   3776: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   3777: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   3778: 			$env{'request.course.id'});
                   3779: 	   }
1.237     www      3780:            return '';
                   3781:        }
                   3782: 
1.620     albertel 3783:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 3784: 	   =~/\Q$unamedom\E/) {
1.689     albertel 3785: 	   if ($priv ne 'pch') { 
                   3786: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   3787: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   3788: 			$env{'request.course.id'});
                   3789: 	   }
1.54      www      3790:            return '';
                   3791:        }
1.53      www      3792:    }
                   3793: 
                   3794: # Resource preferences
                   3795: 
                   3796:    if ($thisallowed=~/R/) {
1.620     albertel 3797:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 3798:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689     albertel 3799: 	   if ($priv ne 'pch') { 
                   3800: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   3801: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   3802: 	   }
                   3803: 	   return '';
1.54      www      3804:        }
1.53      www      3805:    }
1.30      www      3806: 
1.246     www      3807: # Restricted by state or randomout?
1.30      www      3808: 
1.52      www      3809:    if ($thisallowed=~/X/) {
1.620     albertel 3810:       if ($env{'acc.randomout'}) {
1.579     albertel 3811: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 3812:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      3813:             return ''; 
                   3814:          }
1.247     www      3815:       }
                   3816:       if (&condval($statecond)) {
1.52      www      3817: 	 return '2';
                   3818:       } else {
                   3819:          return '';
                   3820:       }
                   3821:    }
1.30      www      3822: 
1.766     albertel 3823:     if ($thisallowed eq 'A') {
                   3824: 	return 'A';
                   3825:     }
1.52      www      3826:    return 'F';
1.232     www      3827: }
                   3828: 
1.710     albertel 3829: sub split_uri_for_cond {
                   3830:     my $uri=&deversion(&declutter(shift));
                   3831:     my @uriparts=split(/\//,$uri);
                   3832:     my $filename=pop(@uriparts);
                   3833:     my $pathname=join('/',@uriparts);
                   3834:     return ($pathname,$filename);
                   3835: }
1.232     www      3836: # --------------------------------------------------- Is a resource on the map?
                   3837: 
                   3838: sub is_on_map {
1.710     albertel 3839:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 3840:     #Trying to find the conditional for the file
1.620     albertel 3841:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 3842: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      3843:     if ($match) {
1.289     bowersj2 3844: 	return (1,$1);
                   3845:     } else {
1.434     www      3846: 	return (0,0);
1.289     bowersj2 3847:     }
1.12      www      3848: }
                   3849: 
1.427     www      3850: # --------------------------------------------------------- Get symb from alias
                   3851: 
                   3852: sub get_symb_from_alias {
                   3853:     my $symb=shift;
                   3854:     my ($map,$resid,$url)=&decode_symb($symb);
                   3855: # Already is a symb
                   3856:     if ($url) { return $symb; }
                   3857: # Must be an alias
                   3858:     my $aliassymb='';
                   3859:     my %bighash;
1.620     albertel 3860:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      3861:                             &GDBM_READER(),0640)) {
                   3862:         my $rid=$bighash{'mapalias_'.$symb};
                   3863: 	if ($rid) {
                   3864: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 3865: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   3866: 				    $resid,$bighash{'src_'.$rid});
1.427     www      3867: 	}
                   3868:         untie %bighash;
                   3869:     }
                   3870:     return $aliassymb;
                   3871: }
                   3872: 
1.12      www      3873: # ----------------------------------------------------------------- Define Role
                   3874: 
                   3875: sub definerole {
                   3876:   if (allowed('mcr','/')) {
                   3877:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.392     www      3878:     foreach (split(':',$sysrole)) {
1.21      www      3879: 	my ($crole,$cqual)=split(/\&/,$_);
1.479     albertel 3880:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   3881:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   3882: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      3883:                return "refused:s:$crole&$cqual"; 
                   3884:             }
                   3885:         }
1.191     harris41 3886:     }
1.392     www      3887:     foreach (split(':',$domrole)) {
1.21      www      3888: 	my ($crole,$cqual)=split(/\&/,$_);
1.479     albertel 3889:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   3890:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   3891: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      3892:                return "refused:d:$crole&$cqual"; 
                   3893:             }
                   3894:         }
1.191     harris41 3895:     }
1.392     www      3896:     foreach (split(':',$courole)) {
1.21      www      3897: 	my ($crole,$cqual)=split(/\&/,$_);
1.479     albertel 3898:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   3899:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   3900: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      3901:                return "refused:c:$crole&$cqual"; 
                   3902:             }
                   3903:         }
1.191     harris41 3904:     }
1.620     albertel 3905:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   3906:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      3907: 	        "rolesdef_$rolename=".
                   3908:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 3909:     return reply($command,$env{'user.home'});
1.12      www      3910:   } else {
                   3911:     return 'refused';
                   3912:   }
1.105     harris41 3913: }
                   3914: 
                   3915: # ---------------- Make a metadata query against the network of library servers
                   3916: 
                   3917: sub metadata_query {
1.244     matthew  3918:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 3919:     my %rhash;
1.244     matthew  3920:     my @server_list = (defined($server_array) ? @$server_array
                   3921:                                               : keys(%libserv) );
                   3922:     for my $server (@server_list) {
1.118     harris41 3923: 	unless ($custom or $customshow) {
                   3924: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   3925: 	    $rhash{$server}=$reply;
                   3926: 	}
                   3927: 	else {
                   3928: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   3929: 			     &escape($custom).':'.&escape($customshow),
                   3930: 			     $server);
                   3931: 	    $rhash{$server}=$reply;
                   3932: 	}
1.112     harris41 3933:     }
1.118     harris41 3934:     return \%rhash;
1.240     www      3935: }
                   3936: 
                   3937: # ----------------------------------------- Send log queries and wait for reply
                   3938: 
                   3939: sub log_query {
                   3940:     my ($uname,$udom,$query,%filters)=@_;
                   3941:     my $uhome=&homeserver($uname,$udom);
                   3942:     if ($uhome eq 'no_host') { return 'error: no_host'; }
                   3943:     my $uhost=$hostname{$uhome};
1.241     www      3944:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys %filters));
1.240     www      3945:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   3946:                        $uhome);
1.479     albertel 3947:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      3948:     return get_query_reply($queryid);
                   3949: }
                   3950: 
1.508     raeburn  3951: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  3952: 
                   3953: sub fetch_enrollment_query {
1.511     raeburn  3954:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  3955:     my $homeserver;
1.547     raeburn  3956:     my $maxtries = 1;
1.508     raeburn  3957:     if ($context eq 'automated') {
                   3958:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  3959:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  3960:     } else {
                   3961:         $homeserver = &homeserver($cnum,$dom);
                   3962:     }
1.506     raeburn  3963:     my $host=$hostname{$homeserver};
                   3964:     my $cmd = '';
                   3965:     foreach (keys %{$affiliatesref}) {
1.508     raeburn  3966:         $cmd .= $_.'='.join(",",@{$$affiliatesref{$_}}).'%%';
1.506     raeburn  3967:     }
                   3968:     $cmd =~ s/%%$//;
                   3969:     $cmd = &escape($cmd);
                   3970:     my $query = 'fetchenrollment';
1.620     albertel 3971:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  3972:     unless ($queryid=~/^\Q$host\E\_/) { 
                   3973:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   3974:         return 'error: '.$queryid;
                   3975:     }
1.506     raeburn  3976:     my $reply = &get_query_reply($queryid);
1.547     raeburn  3977:     my $tries = 1;
                   3978:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   3979:         $reply = &get_query_reply($queryid);
                   3980:         $tries ++;
                   3981:     }
1.526     raeburn  3982:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 3983:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  3984:     } else {
1.515     raeburn  3985:         my @responses = split/:/,$reply;
                   3986:         if ($homeserver eq $perlvar{'lonHostID'}) {
                   3987:             foreach (@responses) {
                   3988:                 my ($key,$value) = split/=/,$_;
                   3989:                 $$replyref{$key} = $value;
                   3990:             }
                   3991:         } else {
1.506     raeburn  3992:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
                   3993:             foreach (@responses) {
                   3994:                 my ($key,$value) = split/=/,$_;
                   3995:                 $$replyref{$key} = $value;
                   3996:                 if ($value > 0) {
                   3997:                     foreach (@{$$affiliatesref{$key}}) {
                   3998:                         my $filename = $dom.'_'.$key.'_'.$_.'_classlist.xml';
                   3999:                         my $destname = $pathname.'/'.$filename;
                   4000:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  4001:                         if ($xml_classlist =~ /^error/) {
                   4002:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   4003:                         } else {
1.506     raeburn  4004:                             if ( open(FILE,">$destname") ) {
                   4005:                                 print FILE &unescape($xml_classlist);
                   4006:                                 close(FILE);
1.526     raeburn  4007:                             } else {
                   4008:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  4009:                             }
                   4010:                         }
                   4011:                     }
                   4012:                 }
                   4013:             }
                   4014:         }
                   4015:         return 'ok';
                   4016:     }
                   4017:     return 'error';
                   4018: }
                   4019: 
1.242     www      4020: sub get_query_reply {
                   4021:     my $queryid=shift;
1.240     www      4022:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   4023:     my $reply='';
                   4024:     for (1..100) {
                   4025: 	sleep 2;
                   4026:         if (-e $replyfile.'.end') {
1.448     albertel 4027: 	    if (open(my $fh,$replyfile)) {
1.240     www      4028:                $reply.=<$fh>;
1.448     albertel 4029:                close($fh);
1.240     www      4030: 	   } else { return 'error: reply_file_error'; }
1.242     www      4031:            return &unescape($reply);
                   4032: 	}
1.240     www      4033:     }
1.242     www      4034:     return 'timeout:'.$queryid;
1.240     www      4035: }
                   4036: 
                   4037: sub courselog_query {
1.241     www      4038: #
                   4039: # possible filters:
                   4040: # url: url or symb
                   4041: # username
                   4042: # domain
                   4043: # action: view, submit, grade
                   4044: # start: timestamp
                   4045: # end: timestamp
                   4046: #
1.240     www      4047:     my (%filters)=@_;
1.620     albertel 4048:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      4049:     if ($filters{'url'}) {
                   4050: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   4051:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   4052:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   4053:     }
1.620     albertel 4054:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4055:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      4056:     return &log_query($cname,$cdom,'courselog',%filters);
                   4057: }
                   4058: 
                   4059: sub userlog_query {
                   4060:     my ($uname,$udom,%filters)=@_;
                   4061:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      4062: }
                   4063: 
1.506     raeburn  4064: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   4065: 
                   4066: sub auto_run {
1.508     raeburn  4067:     my ($cnum,$cdom) = @_;
                   4068:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  4069:     my $response = &reply('autorun:'.$cdom,$homeserver);
1.506     raeburn  4070:     return $response;
                   4071: }
1.776     albertel 4072: 
1.506     raeburn  4073: sub auto_get_sections {
1.508     raeburn  4074:     my ($cnum,$cdom,$inst_coursecode) = @_;
                   4075:     my $homeserver = &homeserver($cnum,$cdom);
1.506     raeburn  4076:     my @secs = ();
1.511     raeburn  4077:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506     raeburn  4078:     unless ($response eq 'refused') {
                   4079:         @secs = split/:/,$response;
                   4080:     }
                   4081:     return @secs;
                   4082: }
1.776     albertel 4083: 
1.506     raeburn  4084: sub auto_new_course {
1.508     raeburn  4085:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
                   4086:     my $homeserver = &homeserver($cnum,$cdom);
1.515     raeburn  4087:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506     raeburn  4088:     return $response;
                   4089: }
1.776     albertel 4090: 
1.506     raeburn  4091: sub auto_validate_courseID {
1.508     raeburn  4092:     my ($cnum,$cdom,$inst_course_id) = @_;
                   4093:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  4094:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  4095:     return $response;
                   4096: }
1.776     albertel 4097: 
1.506     raeburn  4098: sub auto_create_password {
1.508     raeburn  4099:     my ($cnum,$cdom,$authparam) = @_;
                   4100:     my $homeserver = &homeserver($cnum,$cdom); 
1.506     raeburn  4101:     my $create_passwd = 0;
                   4102:     my $authchk = '';
1.511     raeburn  4103:     my $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
1.506     raeburn  4104:     if ($response eq 'refused') {
                   4105:         $authchk = 'refused';
                   4106:     } else {
                   4107:         ($authparam,$create_passwd,$authchk) = split/:/,$response;
                   4108:     }
                   4109:     return ($authparam,$create_passwd,$authchk);
                   4110: }
                   4111: 
1.706     raeburn  4112: sub auto_photo_permission {
                   4113:     my ($cnum,$cdom,$students) = @_;
                   4114:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 4115:     my ($outcome,$perm_reqd,$conditions) = 
                   4116: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 4117:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4118: 	return (undef,undef);
                   4119:     }
1.706     raeburn  4120:     return ($outcome,$perm_reqd,$conditions);
                   4121: }
                   4122: 
                   4123: sub auto_checkphotos {
                   4124:     my ($uname,$udom,$pid) = @_;
                   4125:     my $homeserver = &homeserver($uname,$udom);
                   4126:     my ($result,$resulttype);
                   4127:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 4128: 				   &escape($uname).':'.&escape($pid),
                   4129: 				   $homeserver));
1.709     albertel 4130:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4131: 	return (undef,undef);
                   4132:     }
1.706     raeburn  4133:     if ($outcome) {
                   4134:         ($result,$resulttype) = split(/:/,$outcome);
                   4135:     } 
                   4136:     return ($result,$resulttype);
                   4137: }
                   4138: 
                   4139: sub auto_photochoice {
                   4140:     my ($cnum,$cdom) = @_;
                   4141:     my $homeserver = &homeserver($cnum,$cdom);
                   4142:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 4143: 						       &escape($cdom),
                   4144: 						       $homeserver)));
1.709     albertel 4145:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4146: 	return (undef,undef);
                   4147:     }
1.706     raeburn  4148:     return ($update,$comment);
                   4149: }
                   4150: 
                   4151: sub auto_photoupdate {
                   4152:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   4153:     my $homeserver = &homeserver($cnum,$dom);
                   4154:     my $host=$hostname{$homeserver};
                   4155:     my $cmd = '';
                   4156:     my $maxtries = 1;
                   4157:     foreach (keys %{$affiliatesref}) {
                   4158:         $cmd .= $_.'='.join(",",@{$$affiliatesref{$_}}).'%%';
                   4159:     }
                   4160:     $cmd =~ s/%%$//;
                   4161:     $cmd = &escape($cmd);
                   4162:     my $query = 'institutionalphotos';
                   4163:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   4164:     unless ($queryid=~/^\Q$host\E\_/) {
                   4165:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   4166:         return 'error: '.$queryid;
                   4167:     }
                   4168:     my $reply = &get_query_reply($queryid);
                   4169:     my $tries = 1;
                   4170:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   4171:         $reply = &get_query_reply($queryid);
                   4172:         $tries ++;
                   4173:     }
                   4174:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   4175:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   4176:     } else {
                   4177:         my @responses = split(/:/,$reply);
                   4178:         my $outcome = shift(@responses); 
                   4179:         foreach my $item (@responses) {
                   4180:             my ($key,$value) = split(/=/,$item);
                   4181:             $$photo{$key} = $value;
                   4182:         }
                   4183:         return $outcome;
                   4184:     }
                   4185:     return 'error';
                   4186: }
                   4187: 
1.521     raeburn  4188: sub auto_instcode_format {
                   4189:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,$cat_order) = @_;
                   4190:     my $courses = '';
1.772     raeburn  4191:     my @homeservers;
1.521     raeburn  4192:     if ($caller eq 'global') {
1.584     raeburn  4193:         foreach my $tryserver (keys %libserv) {
                   4194:             if ($hostdom{$tryserver} eq $codedom) {
1.772     raeburn  4195:                 if (!grep/^\Q$tryserver\E$/,@homeservers) {
                   4196:                     push(@homeservers,$tryserver);
                   4197:                 }
1.584     raeburn  4198:             }
                   4199:         }
1.521     raeburn  4200:     } else {
1.772     raeburn  4201:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  4202:     }
                   4203:     foreach (keys %{$instcodes}) {
                   4204:         $courses .= &escape($_).'='.&escape($$instcodes{$_}).'&';
                   4205:     }
                   4206:     chop($courses);
1.772     raeburn  4207:     my $ok_response = 0;
                   4208:     my $response;
                   4209:     while (@homeservers > 0 && $ok_response == 0) {
                   4210:         my $server = shift(@homeservers); 
                   4211:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   4212:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   4213:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
                   4214:                                                             split/:/,$response;
                   4215:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   4216:             push(@{$codetitles},&str2array($codetitles_str));
                   4217:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   4218:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   4219:             $ok_response = 1;
                   4220:         }
                   4221:     }
                   4222:     if ($ok_response) {
1.521     raeburn  4223:         return 'ok';
1.772     raeburn  4224:     } else {
                   4225:         return $response;
1.521     raeburn  4226:     }
                   4227: }
                   4228: 
1.777     albertel 4229: sub auto_validate_class_sec {
1.773     raeburn  4230:     my ($cdom,$cnum,$owner,$inst_class) = @_;
                   4231:     my $homeserver = &homeserver($cnum,$cdom);
                   4232:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.774     banghart 4233:                         &escape($owner).':'.$cdom,$homeserver);
1.773     raeburn  4234:     return $response;
                   4235: }
                   4236: 
1.679     raeburn  4237: # ------------------------------------------------------- Course Group routines
                   4238: 
                   4239: sub get_coursegroups {
1.683     raeburn  4240:     my ($cdom,$cnum,$group) = @_;
                   4241:     return(&dump('coursegroups',$cdom,$cnum,$group));
1.679     raeburn  4242: }
                   4243: 
                   4244: sub modify_coursegroup {
                   4245:     my ($cdom,$cnum,$groupsettings) = @_;
                   4246:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   4247: }
                   4248: 
                   4249: sub modify_group_roles {
                   4250:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
                   4251:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   4252:     my $role = 'gr/'.&escape($userprivs);
                   4253:     my ($uname,$udom) = split(/:/,$user);
                   4254:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
1.684     raeburn  4255:     if ($result eq 'ok') {
                   4256:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   4257:     }
1.679     raeburn  4258:     return $result;
                   4259: }
                   4260: 
                   4261: sub modify_coursegroup_membership {
                   4262:     my ($cdom,$cnum,$membership) = @_;
                   4263:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   4264:     return $result;
                   4265: }
                   4266: 
1.682     raeburn  4267: sub get_active_groups {
                   4268:     my ($udom,$uname,$cdom,$cnum) = @_;
                   4269:     my $now = time;
                   4270:     my %groups = ();
                   4271:     foreach my $key (keys(%env)) {
                   4272:         if ($key =~ m-user\.role\.gr\./([^/]+)/([^/]+)/(\w+)$-) {
                   4273:             my ($start,$end) = split(/\./,$env{$key});
                   4274:             if (($end!=0) && ($end<$now)) { next; }
                   4275:             if (($start!=0) && ($start>$now)) { next; }
                   4276:             if ($1 eq $cdom && $2 eq $cnum) {
                   4277:                 $groups{$3} = $env{$key} ;
                   4278:             }
                   4279:         }
                   4280:     }
                   4281:     return %groups;
                   4282: }
                   4283: 
1.683     raeburn  4284: sub get_group_membership {
                   4285:     my ($cdom,$cnum,$group) = @_;
                   4286:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   4287: }
                   4288: 
                   4289: sub get_users_groups {
                   4290:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  4291:     my @usersgroups;
1.683     raeburn  4292:     my $cachetime=1800;
                   4293:     $courseid=~s/\_/\//g;
                   4294:     $courseid=~s/^(\w)/\/$1/;
                   4295: 
                   4296:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  4297:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   4298:     if (defined($cached)) {
1.734     albertel 4299:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  4300:     } else {  
                   4301:         $grouplist = '';
                   4302:         my %roleshash = &dump('roles',$udom,$uname,$courseid);
                   4303:         my ($tmp) = keys(%roleshash);
                   4304:         if ($tmp=~/^error:/) {
                   4305:             &logthis('Error retrieving roles: '.$tmp.' for '.$uname.':'.$udom);
                   4306:         } else {
                   4307:             my $access_end = $env{'course.'.$courseid.
                   4308:                                   '.default_enrollment_end_date'};
                   4309:             my $now = time;
1.734     albertel 4310:             foreach my $key (keys(%roleshash)) {
1.733     raeburn  4311:                 if ($key =~ /^\Q$courseid\E\/(\w+)\_gr$/) {
                   4312:                     my $group = $1;
                   4313:                     if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   4314:                         my $start = $2;
                   4315:                         my $end = $1;
                   4316:                         if ($start == -1) { next; } # deleted from group
                   4317:                         if (($start!=0) && ($start>$now)) { next; }
                   4318:                         if (($end!=0) && ($end<$now)) {
                   4319:                             if ($access_end && $access_end < $now) {
                   4320:                                 if ($access_end - $end < 86400) {
                   4321:                                     push(@usersgroups,$group);
                   4322:                                 }
                   4323:                             }
                   4324:                             next;
                   4325:                         }
                   4326:                         push(@usersgroups,$group);
                   4327:                     }
1.683     raeburn  4328:                 }
                   4329:             }
1.733     raeburn  4330:             @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   4331:             $grouplist = join(':',@usersgroups);
                   4332:             &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  4333:         }
                   4334:     }
1.733     raeburn  4335:     return @usersgroups;
1.683     raeburn  4336: }
                   4337: 
                   4338: sub devalidate_getgroups_cache {
                   4339:     my ($udom,$uname,$cdom,$cnum)=@_;
                   4340:     my $courseid = $cdom.'_'.$cnum;
                   4341:     $courseid=~s/\_/\//g;
                   4342:     $courseid=~s/^(\w)/\/$1/;
                   4343:     my $hashid="$udom:$uname:$courseid";
                   4344:     &devalidate_cache_new('getgroups',$hashid);
                   4345: }
                   4346: 
1.12      www      4347: # ------------------------------------------------------------------ Plain Text
                   4348: 
                   4349: sub plaintext {
1.742     raeburn  4350:     my ($short,$type,$cid) = @_;
1.758     albertel 4351:     if ($short =~ /^cr/) {
                   4352: 	return (split('/',$short))[-1];
                   4353:     }
1.742     raeburn  4354:     if (!defined($cid)) {
                   4355:         $cid = $env{'request.course.id'};
                   4356:     }
                   4357:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
                   4358:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
                   4359:                                           '.plaintext'});
                   4360:     }
                   4361:     my %rolenames = (
                   4362:                       Course => 'std',
                   4363:                       Group => 'alt1',
                   4364:                     );
                   4365:     if (defined($type) && 
                   4366:          defined($rolenames{$type}) && 
                   4367:          defined($prp{$short}{$rolenames{$type}})) {
                   4368:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
                   4369:     } else {
                   4370:         return &Apache::lonlocal::mt($prp{$short}{'std'});
                   4371:     }
1.12      www      4372: }
                   4373: 
                   4374: # ----------------------------------------------------------------- Assign Role
                   4375: 
                   4376: sub assignrole {
1.357     www      4377:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
1.21      www      4378:     my $mrole;
                   4379:     if ($role =~ /^cr\//) {
1.393     www      4380:         my $cwosec=$url;
                   4381:         $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
                   4382: 	unless (&allowed('ccr',$cwosec)) {
1.104     www      4383:            &logthis('Refused custom assignrole: '.
                   4384:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 4385: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      4386:            return 'refused'; 
                   4387:         }
1.21      www      4388:         $mrole='cr';
1.678     raeburn  4389:     } elsif ($role =~ /^gr\//) {
                   4390:         my $cwogrp=$url;
                   4391:         $cwogrp=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
                   4392:         unless (&allowed('mdg',$cwogrp)) {
                   4393:             &logthis('Refused group assignrole: '.
                   4394:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   4395:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   4396:             return 'refused';
                   4397:         }
                   4398:         $mrole='gr';
1.21      www      4399:     } else {
1.82      www      4400:         my $cwosec=$url;
1.83      www      4401:         $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
1.373     www      4402:         unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) { 
1.104     www      4403:            &logthis('Refused assignrole: '.
                   4404:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 4405: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      4406:            return 'refused'; 
                   4407:         }
1.21      www      4408:         $mrole=$role;
                   4409:     }
1.620     albertel 4410:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      4411:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      4412:     if ($end) { $command.='_'.$end; }
1.21      www      4413:     if ($start) {
                   4414: 	if ($end) { 
1.81      www      4415:            $command.='_'.$start; 
1.21      www      4416:         } else {
1.81      www      4417:            $command.='_0_'.$start;
1.21      www      4418:         }
                   4419:     }
1.739     raeburn  4420:     my $origstart = $start;
                   4421:     my $origend = $end;
1.357     www      4422: # actually delete
                   4423:     if ($deleteflag) {
1.373     www      4424: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      4425: # modify command to delete the role
1.620     albertel 4426:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      4427:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 4428: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      4429: # set start and finish to negative values for userrolelog
                   4430:            $start=-1;
                   4431:            $end=-1;
                   4432:         }
                   4433:     }
                   4434: # send command
1.349     www      4435:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      4436: # log new user role if status is ok
1.349     www      4437:     if ($answer eq 'ok') {
1.663     raeburn  4438: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  4439: # for course roles, perform group memberships changes triggered by role change.
                   4440:         unless ($role =~ /^gr/) {
                   4441:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   4442:                                              $origstart);
                   4443:         }
1.349     www      4444:     }
                   4445:     return $answer;
1.169     harris41 4446: }
                   4447: 
                   4448: # -------------------------------------------------- Modify user authentication
1.197     www      4449: # Overrides without validation
                   4450: 
1.169     harris41 4451: sub modifyuserauth {
                   4452:     my ($udom,$uname,$umode,$upass)=@_;
                   4453:     my $uhome=&homeserver($uname,$udom);
1.197     www      4454:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   4455:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 4456:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   4457:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 4458:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   4459: 		     &escape($upass),$uhome);
1.620     albertel 4460:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      4461:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   4462:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   4463:     &log($udom,,$uname,$uhome,
1.620     albertel 4464:         'Authentication changed by '.$env{'user.domain'}.', '.
                   4465:                                      $env{'user.name'}.', '.$umode.
1.197     www      4466:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 4467:     unless ($reply eq 'ok') {
1.197     www      4468:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 4469: 	return 'error: '.$reply;
                   4470:     }   
1.170     harris41 4471:     return 'ok';
1.80      www      4472: }
                   4473: 
1.81      www      4474: # --------------------------------------------------------------- Modify a user
1.80      www      4475: 
1.81      www      4476: sub modifyuser {
1.206     matthew  4477:     my ($udom,    $uname, $uid,
                   4478:         $umode,   $upass, $first,
                   4479:         $middle,  $last,  $gene,
1.387     www      4480:         $forceid, $desiredhome, $email)=@_;
1.198     www      4481:     $udom=~s/\W//g;
                   4482:     $uname=~s/\W//g;
1.81      www      4483:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      4484:              $umode.', '.$first.', '.$middle.', '.
1.206     matthew  4485: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
                   4486:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   4487:                                      ' desiredhome not specified'). 
1.620     albertel 4488:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   4489:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 4490:     my $uhome=&homeserver($uname,$udom,'true');
1.80      www      4491: # ----------------------------------------------------------------- Create User
1.406     albertel 4492:     if (($uhome eq 'no_host') && 
                   4493: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      4494:         my $unhome='';
1.209     matthew  4495:         if (defined($desiredhome) && $hostdom{$desiredhome} eq $udom) { 
                   4496:             $unhome = $desiredhome;
1.620     albertel 4497: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   4498: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  4499:         } else { # load balancing routine for determining $unhome
1.80      www      4500:             my $tryserver;
1.81      www      4501:             my $loadm=10000000;
1.80      www      4502:             foreach $tryserver (keys %libserv) {
                   4503: 	       if ($hostdom{$tryserver} eq $udom) {
                   4504:                   my $answer=reply('load',$tryserver);
                   4505:                   if (($answer=~/\d+/) && ($answer<$loadm)) {
                   4506: 		      $loadm=$answer;
                   4507:                       $unhome=$tryserver;
                   4508:                   }
                   4509: 	       }
                   4510: 	    }
                   4511:         }
                   4512:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  4513: 	    return 'error: unable to find a home server for '.$uname.
                   4514:                    ' in domain '.$udom;
1.80      www      4515:         }
                   4516:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   4517:                          &escape($upass),$unhome);
                   4518: 	unless ($reply eq 'ok') {
                   4519:             return 'error: '.$reply;
                   4520:         }   
1.230     stredwic 4521:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      4522:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  4523: 	    return 'error: unable verify users home machine.';
1.80      www      4524:         }
1.209     matthew  4525:     }   # End of creation of new user
1.80      www      4526: # ---------------------------------------------------------------------- Add ID
                   4527:     if ($uid) {
                   4528:        $uid=~tr/A-Z/a-z/;
                   4529:        my %uidhash=&idrget($udom,$uname);
1.196     www      4530:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   4531:          && (!$forceid)) {
1.80      www      4532: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  4533: 	      return 'error: user id "'.$uid.'" does not match '.
                   4534:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      4535:           }
                   4536:        } else {
                   4537: 	  &idput($udom,($uname => $uid));
                   4538:        }
                   4539:     }
                   4540: # -------------------------------------------------------------- Add names, etc
1.313     matthew  4541:     my @tmp=&get('environment',
1.134     albertel 4542: 		   ['firstname','middlename','lastname','generation'],
                   4543: 		   $udom,$uname);
1.313     matthew  4544:     my %names;
                   4545:     if ($tmp[0] =~ m/^error:.*/) { 
                   4546:         %names=(); 
                   4547:     } else {
                   4548:         %names = @tmp;
                   4549:     }
1.388     www      4550: #
                   4551: # Make sure to not trash student environment if instructor does not bother
                   4552: # to supply name and email information
                   4553: #
                   4554:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  4555:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      4556:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  4557:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      4558:     if ($email) {
                   4559:        $email=~s/[^\w\@\.\-\,]//gs;
                   4560:        if ($email=~/\@/) { $names{'notification'} = $email;
                   4561: 			   $names{'critnotification'} = $email;
                   4562: 			   $names{'permanentemail'} = $email; }
                   4563:     }
1.134     albertel 4564:     my $reply = &put('environment', \%names, $udom,$uname);
                   4565:     if ($reply ne 'ok') { return 'error: '.$reply; }
1.680     www      4566:     &devalidate_cache_new('namescache',$uname.':'.$udom);
1.81      www      4567:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      4568:              $umode.', '.$first.', '.$middle.', '.
                   4569: 	     $last.', '.$gene.' by '.
1.620     albertel 4570:              $env{'user.name'}.' at '.$env{'user.domain'});
1.134     albertel 4571:     return 'ok';
1.80      www      4572: }
                   4573: 
1.81      www      4574: # -------------------------------------------------------------- Modify student
1.80      www      4575: 
1.81      www      4576: sub modifystudent {
                   4577:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.515     raeburn  4578:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
1.455     albertel 4579:     if (!$cid) {
1.620     albertel 4580: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 4581: 	    return 'not_in_class';
                   4582: 	}
1.80      www      4583:     }
                   4584: # --------------------------------------------------------------- Make the user
1.81      www      4585:     my $reply=&modifyuser
1.209     matthew  4586: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387     www      4587:          $desiredhome,$email);
1.80      www      4588:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  4589:     # This will cause &modify_student_enrollment to get the uid from the
                   4590:     # students environment
                   4591:     $uid = undef if (!$forceid);
1.455     albertel 4592:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.515     raeburn  4593: 					$gene,$usec,$end,$start,$type,$locktype,$cid);
1.297     matthew  4594:     return $reply;
                   4595: }
                   4596: 
                   4597: sub modify_student_enrollment {
1.515     raeburn  4598:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
1.455     albertel 4599:     my ($cdom,$cnum,$chome);
                   4600:     if (!$cid) {
1.620     albertel 4601: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 4602: 	    return 'not_in_class';
                   4603: 	}
1.620     albertel 4604: 	$cdom=$env{'course.'.$cid.'.domain'};
                   4605: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 4606:     } else {
                   4607: 	($cdom,$cnum)=split(/_/,$cid);
                   4608:     }
1.620     albertel 4609:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 4610:     if (!$chome) {
1.457     raeburn  4611: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  4612:     }
1.455     albertel 4613:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  4614:     # Make sure the user exists
1.81      www      4615:     my $uhome=&homeserver($uname,$udom);
                   4616:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   4617: 	return 'error: no such user';
                   4618:     }
1.297     matthew  4619:     # Get student data if we were not given enough information
                   4620:     if (!defined($first)  || $first  eq '' || 
                   4621:         !defined($last)   || $last   eq '' || 
                   4622:         !defined($uid)    || $uid    eq '' || 
                   4623:         !defined($middle) || $middle eq '' || 
                   4624:         !defined($gene)   || $gene   eq '') {
1.294     matthew  4625:         # They did not supply us with enough data to enroll the student, so
                   4626:         # we need to pick up more information.
1.297     matthew  4627:         my %tmp = &get('environment',
1.294     matthew  4628:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  4629:                        ,$udom,$uname);
                   4630: 
1.455     albertel 4631:         #foreach (keys(%tmp)) {
                   4632:         #    &logthis("key $_ = ".$tmp{$_});
                   4633:         #}
1.294     matthew  4634:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   4635:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   4636:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  4637:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  4638:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   4639:     }
1.556     albertel 4640:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 4641:     my $reply=cput('classlist',
                   4642: 		   {"$uname:$udom" => 
1.515     raeburn  4643: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 4644: 		   $cdom,$cnum);
1.81      www      4645:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   4646: 	return 'error: '.$reply;
1.652     albertel 4647:     } else {
                   4648: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      4649:     }
1.297     matthew  4650:     # Add student role to user
1.83      www      4651:     my $uurl='/'.$cid;
1.81      www      4652:     $uurl=~s/\_/\//g;
                   4653:     if ($usec) {
                   4654: 	$uurl.='/'.$usec;
                   4655:     }
                   4656:     return &assignrole($udom,$uname,$uurl,'st',$end,$start);
1.21      www      4657: }
                   4658: 
1.556     albertel 4659: sub format_name {
                   4660:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   4661:     my $name;
                   4662:     if ($first ne 'lastname') {
                   4663: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   4664:     } else {
                   4665: 	if ($lastname=~/\S/) {
                   4666: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   4667: 	    $name=~s/\s+,/,/;
                   4668: 	} else {
                   4669: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   4670: 	}
                   4671:     }
                   4672:     $name=~s/^\s+//;
                   4673:     $name=~s/\s+$//;
                   4674:     $name=~s/\s+/ /g;
                   4675:     return $name;
                   4676: }
                   4677: 
1.84      www      4678: # ------------------------------------------------- Write to course preferences
                   4679: 
                   4680: sub writecoursepref {
                   4681:     my ($courseid,%prefs)=@_;
                   4682:     $courseid=~s/^\///;
                   4683:     $courseid=~s/\_/\//g;
                   4684:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   4685:     my $chome=homeserver($cnum,$cdomain);
                   4686:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   4687: 	return 'error: no such course';
                   4688:     }
                   4689:     my $cstring='';
1.191     harris41 4690:     foreach (keys %prefs) {
1.84      www      4691: 	$cstring.=escape($_).'='.escape($prefs{$_}).'&';
1.191     harris41 4692:     }
1.84      www      4693:     $cstring=~s/\&$//;
                   4694:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   4695: }
                   4696: 
                   4697: # ---------------------------------------------------------- Make/modify course
                   4698: 
                   4699: sub createcourse {
1.741     raeburn  4700:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
                   4701:         $course_owner,$crstype)=@_;
1.84      www      4702:     $url=&declutter($url);
                   4703:     my $cid='';
1.264     matthew  4704:     unless (&allowed('ccc',$udom)) {
1.84      www      4705:         return 'refused';
                   4706:     }
                   4707: # ------------------------------------------------------------------- Create ID
1.674     www      4708:    my $uname=int(1+rand(9)).
                   4709:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   4710:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
1.84      www      4711:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   4712: # ----------------------------------------------- Make sure that does not exist
1.230     stredwic 4713:    my $uhome=&homeserver($uname,$udom,'true');
1.84      www      4714:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   4715:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   4716:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230     stredwic 4717:        $uhome=&homeserver($uname,$udom,'true');       
1.84      www      4718:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   4719:            return 'error: unable to generate unique course-ID';
                   4720:        } 
                   4721:    }
1.264     matthew  4722: # ------------------------------------------------ Check supplied server name
1.620     albertel 4723:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.264     matthew  4724:     if (! exists($libserv{$course_server})) {
                   4725:         return 'error:bad server name '.$course_server;
                   4726:     }
1.84      www      4727: # ------------------------------------------------------------- Make the course
                   4728:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  4729:                       $course_server);
1.84      www      4730:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230     stredwic 4731:     $uhome=&homeserver($uname,$udom,'true');
1.84      www      4732:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   4733: 	return 'error: no such course';
                   4734:     }
1.271     www      4735: # ----------------------------------------------------------------- Course made
1.516     raeburn  4736: # log existence
                   4737:     &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description).
1.741     raeburn  4738:                  ':'.&escape($inst_code).':'.&escape($course_owner).':'.
                   4739:                   &escape($crstype),$uhome);
1.358     www      4740:     &flushcourselogs();
                   4741: # set toplevel url
1.271     www      4742:     my $topurl=$url;
                   4743:     unless ($nonstandard) {
                   4744: # ------------------------------------------ For standard courses, make top url
                   4745:         my $mapurl=&clutter($url);
1.278     www      4746:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 4747:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      4748: <map>
                   4749: <resource id="1" type="start"></resource>
                   4750: <resource id="2" src="$mapurl"></resource>
                   4751: <resource id="3" type="finish"></resource>
                   4752: <link index="1" from="1" to="2"></link>
                   4753: <link index="2" from="2" to="3"></link>
                   4754: </map>
                   4755: ENDINITMAP
                   4756:         $topurl=&declutter(
1.638     albertel 4757:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      4758:                           );
                   4759:     }
                   4760: # ----------------------------------------------------------- Write preferences
1.84      www      4761:     &writecoursepref($udom.'_'.$uname,
                   4762:                      ('description' => $description,
1.271     www      4763:                       'url'         => $topurl));
1.84      www      4764:     return '/'.$udom.'/'.$uname;
                   4765: }
                   4766: 
1.21      www      4767: # ---------------------------------------------------------- Assign Custom Role
                   4768: 
                   4769: sub assigncustomrole {
1.357     www      4770:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
1.21      www      4771:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.357     www      4772:                        $end,$start,$deleteflag);
1.21      www      4773: }
                   4774: 
                   4775: # ----------------------------------------------------------------- Revoke Role
                   4776: 
                   4777: sub revokerole {
1.357     www      4778:     my ($udom,$uname,$url,$role,$deleteflag)=@_;
1.21      www      4779:     my $now=time;
1.357     www      4780:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
1.21      www      4781: }
                   4782: 
                   4783: # ---------------------------------------------------------- Revoke Custom Role
                   4784: 
                   4785: sub revokecustomrole {
1.357     www      4786:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
1.21      www      4787:     my $now=time;
1.357     www      4788:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
                   4789:            $deleteflag);
1.17      www      4790: }
                   4791: 
1.533     banghart 4792: # ------------------------------------------------------------ Disk usage
1.535     albertel 4793: sub diskusage {
1.533     banghart 4794:     my ($udom,$uname,$directoryRoot)=@_;
                   4795:     $directoryRoot =~ s/\/$//;
1.535     albertel 4796:     my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
1.514     albertel 4797:     return $listing;
1.512     banghart 4798: }
                   4799: 
1.566     banghart 4800: sub is_locked {
                   4801:     my ($file_name, $domain, $user) = @_;
                   4802:     my @check;
                   4803:     my $is_locked;
                   4804:     push @check, $file_name;
1.613     albertel 4805:     my %locked = &get('file_permissions',\@check,
1.620     albertel 4806: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 4807:     my ($tmp)=keys(%locked);
                   4808:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  4809:     
1.566     banghart 4810:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  4811:         $is_locked = 'false';
                   4812:         foreach my $entry (@{$locked{$file_name}}) {
                   4813:            if (ref($entry) eq 'ARRAY') { 
1.746     raeburn  4814:                $is_locked = 'true';
                   4815:                last;
1.745     raeburn  4816:            }
                   4817:        }
1.566     banghart 4818:     } else {
                   4819:         $is_locked = 'false';
                   4820:     }
                   4821: }
                   4822: 
1.759     albertel 4823: sub declutter_portfile {
                   4824:     my ($file) = @_;
                   4825:     &logthis("got $file");
                   4826:     $file =~ s-^(/portfolio/|portfolio/)-/-;
                   4827:     &logthis("ret $file");
                   4828:     return $file;
                   4829: }
                   4830: 
1.559     banghart 4831: # ------------------------------------------------------------- Mark as Read Only
                   4832: 
                   4833: sub mark_as_readonly {
                   4834:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 4835:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 4836:     my ($tmp)=keys(%current_permissions);
                   4837:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 4838:     foreach my $file (@{$files}) {
1.759     albertel 4839: 	$file = &declutter_portfile($file);
1.561     banghart 4840:         push(@{$current_permissions{$file}},$what);
1.559     banghart 4841:     }
1.613     albertel 4842:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 4843:     return;
                   4844: }
                   4845: 
1.572     banghart 4846: # ------------------------------------------------------------Save Selected Files
                   4847: 
                   4848: sub save_selected_files {
                   4849:     my ($user, $path, @files) = @_;
                   4850:     my $filename = $user."savedfiles";
1.573     banghart 4851:     my @other_files = &files_not_in_path($user, $path);
1.574     banghart 4852:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 4853:     foreach my $file (@files) {
1.620     albertel 4854:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 4855:     }
                   4856:     foreach my $file (@other_files) {
1.574     banghart 4857:         print (OUT $file."\n");
1.572     banghart 4858:     }
1.574     banghart 4859:     close (OUT);
1.572     banghart 4860:     return 'ok';
                   4861: }
                   4862: 
1.574     banghart 4863: sub clear_selected_files {
                   4864:     my ($user) = @_;
                   4865:     my $filename = $user."savedfiles";
                   4866:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   4867:     print (OUT undef);
                   4868:     close (OUT);
                   4869:     return ("ok");    
                   4870: }
                   4871: 
1.572     banghart 4872: sub files_in_path {
                   4873:     my ($user, $path) = @_;
                   4874:     my $filename = $user."savedfiles";
                   4875:     my %return_files;
1.574     banghart 4876:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 4877:     while (my $line_in = <IN>) {
1.574     banghart 4878:         chomp ($line_in);
                   4879:         my @paths_and_file = split (m!/!, $line_in);
                   4880:         my $file_part = pop (@paths_and_file);
                   4881:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 4882:         $path_part.='/';
                   4883:         my $path_and_file = $path_part.$file_part;
                   4884:         if ($path_part eq $path) {
                   4885:             $return_files{$file_part}= 'selected';
                   4886:         }
                   4887:     }
1.574     banghart 4888:     close (IN);
                   4889:     return (\%return_files);
1.572     banghart 4890: }
                   4891: 
                   4892: # called in portfolio select mode, to show files selected NOT in current directory
                   4893: sub files_not_in_path {
                   4894:     my ($user, $path) = @_;
                   4895:     my $filename = $user."savedfiles";
                   4896:     my @return_files;
                   4897:     my $path_part;
1.574     banghart 4898:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.572     banghart 4899:     while (<IN>) {
                   4900:         #ok, I know it's clunky, but I want it to work
                   4901:         my @paths_and_file = split m!/!, $_;
1.574     banghart 4902:         my $file_part = pop (@paths_and_file);
                   4903:         chomp ($file_part);
                   4904:         my $path_part = join ('/', @paths_and_file);
1.572     banghart 4905:         $path_part .= '/';
                   4906:         my $path_and_file = $path_part.$file_part;
                   4907:         if ($path_part ne $path) {
1.574     banghart 4908:             push (@return_files, ($path_and_file));
1.572     banghart 4909:         }
                   4910:     }
1.574     banghart 4911:     close (OUT);
                   4912:     return (@return_files);
1.572     banghart 4913: }
                   4914: 
1.745     raeburn  4915: #----------------------------------------------Get portfolio file permissions
1.629     banghart 4916: 
1.745     raeburn  4917: sub get_portfile_permissions {
                   4918:     my ($domain,$user) = @_;
1.613     albertel 4919:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 4920:     my ($tmp)=keys(%current_permissions);
                   4921:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  4922:     return \%current_permissions;
                   4923: }
                   4924: 
                   4925: #---------------------------------------------Get portfolio file access controls
                   4926: 
1.749     raeburn  4927: sub get_access_controls {
1.745     raeburn  4928:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 4929:     my %access;
                   4930:     my $real_file = $file;
                   4931:     $file =~ s/\.meta$//;
1.745     raeburn  4932:     if (defined($file)) {
1.749     raeburn  4933:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   4934:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 4935:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  4936:             }
                   4937:         }
1.745     raeburn  4938:     } else {
1.749     raeburn  4939:         foreach my $key (keys(%{$current_permissions})) {
                   4940:             if ($key =~ /\0accesscontrol$/) {
                   4941:                 if (defined($group)) {
                   4942:                     if ($key !~ m-^\Q$group\E/-) {
                   4943:                         next;
                   4944:                     }
                   4945:                 }
                   4946:                 my ($fullpath) = split(/\0/,$key);
                   4947:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   4948:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   4949:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   4950:                     }
                   4951:                 }
                   4952:             }
                   4953:         }
                   4954:     }
                   4955:     return %access;
                   4956: }
                   4957: 
                   4958: sub modify_access_controls {
                   4959:     my ($file_name,$changes,$domain,$user)=@_;
                   4960:     my ($outcome,$deloutcome);
                   4961:     my %store_permissions;
                   4962:     my %new_values;
                   4963:     my %new_control;
                   4964:     my %translation;
                   4965:     my @deletions = ();
                   4966:     my $now = time;
                   4967:     if (exists($$changes{'activate'})) {
                   4968:         if (ref($$changes{'activate'}) eq 'HASH') {
                   4969:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   4970:             my $numnew = scalar(@newitems);
                   4971:             for (my $i=0; $i<$numnew; $i++) {
                   4972:                 my $newkey = $newitems[$i];
                   4973:                 my $newid = &Apache::loncommon::get_cgi_id();
                   4974:                 $newkey =~ s/^(\d+)/$newid/;
                   4975:                 $translation{$1} = $newid;
                   4976:                 $new_values{$file_name."\0".$newkey} = 
                   4977:                                           $$changes{'activate'}{$newitems[$i]};
                   4978:                 $new_control{$newkey} = $now;
                   4979:             }
                   4980:         }
                   4981:     }
                   4982:     my %todelete;
                   4983:     my %changed_items;
                   4984:     foreach my $action ('delete','update') {
                   4985:         if (exists($$changes{$action})) {
                   4986:             if (ref($$changes{$action}) eq 'HASH') {
                   4987:                 foreach my $key (keys(%{$$changes{$action}})) {
                   4988:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   4989:                     if ($action eq 'delete') { 
                   4990:                         $todelete{$itemnum} = 1;
                   4991:                     } else {
                   4992:                         $changed_items{$itemnum} = $key;
                   4993:                     }
                   4994:                 }
1.745     raeburn  4995:             }
                   4996:         }
1.749     raeburn  4997:     }
                   4998:     # get lock on access controls for file.
                   4999:     my $lockhash = {
                   5000:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   5001:                                                        ':'.$env{'user.domain'},
                   5002:                    }; 
                   5003:     my $tries = 0;
                   5004:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   5005:    
                   5006:     while (($gotlock ne 'ok') && $tries <3) {
                   5007:         $tries ++;
                   5008:         sleep 1;
                   5009:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   5010:     }
                   5011:     if ($gotlock eq 'ok') {
                   5012:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   5013:         my ($tmp)=keys(%curr_permissions);
                   5014:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   5015:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   5016:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   5017:             if (ref($curr_controls) eq 'HASH') {
                   5018:                 foreach my $control_item (keys(%{$curr_controls})) {
                   5019:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   5020:                     if (defined($todelete{$itemnum})) {
                   5021:                         push(@deletions,$file_name."\0".$control_item);
                   5022:                     } else {
                   5023:                         if (defined($changed_items{$itemnum})) {
                   5024:                             $new_control{$changed_items{$itemnum}} = $now;
                   5025:                             push(@deletions,$file_name."\0".$control_item);
                   5026:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   5027:                         } else {
                   5028:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   5029:                         }
                   5030:                     }
1.745     raeburn  5031:                 }
                   5032:             }
                   5033:         }
1.749     raeburn  5034:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   5035:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   5036:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   5037:         #  remove lock
                   5038:         my @del_lock = ($file_name."\0".'locked_access_records');
                   5039:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
                   5040:     } else {
                   5041:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  5042:     }
1.749     raeburn  5043:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  5044: }
                   5045: 
                   5046: #------------------------------------------------------Get Marked as Read Only
                   5047: 
                   5048: sub get_marked_as_readonly {
                   5049:     my ($domain,$user,$what,$group) = @_;
                   5050:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 5051:     my @readonly_files;
1.629     banghart 5052:     my $cmp1=$what;
                   5053:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  5054:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   5055:         if (defined($group)) {
                   5056:             if ($file_name !~ m-^\Q$group\E/-) {
                   5057:                 next;
                   5058:             }
                   5059:         }
1.561     banghart 5060:         if (ref($value) eq "ARRAY"){
                   5061:             foreach my $stored_what (@{$value}) {
1.629     banghart 5062:                 my $cmp2=$stored_what;
1.759     albertel 5063:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  5064:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  5065:                 }
1.629     banghart 5066:                 if ($cmp1 eq $cmp2) {
1.561     banghart 5067:                     push(@readonly_files, $file_name);
1.745     raeburn  5068:                     last;
1.563     banghart 5069:                 } elsif (!defined($what)) {
                   5070:                     push(@readonly_files, $file_name);
1.745     raeburn  5071:                     last;
1.561     banghart 5072:                 }
                   5073:             }
1.745     raeburn  5074:         }
1.561     banghart 5075:     }
                   5076:     return @readonly_files;
                   5077: }
1.577     banghart 5078: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 5079: 
1.577     banghart 5080: sub get_marked_as_readonly_hash {
1.745     raeburn  5081:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 5082:     my %readonly_files;
1.745     raeburn  5083:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   5084:         if (defined($group)) {
                   5085:             if ($file_name !~ m-^\Q$group\E/-) {
                   5086:                 next;
                   5087:             }
                   5088:         }
1.577     banghart 5089:         if (ref($value) eq "ARRAY"){
                   5090:             foreach my $stored_what (@{$value}) {
1.745     raeburn  5091:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 5092:                     foreach my $lock_descriptor(@{$stored_what}) {
                   5093:                         if ($lock_descriptor eq 'graded') {
                   5094:                             $readonly_files{$file_name} = 'graded';
                   5095:                         } elsif ($lock_descriptor eq 'handback') {
                   5096:                             $readonly_files{$file_name} = 'handback';
                   5097:                         } else {
                   5098:                             if (!exists($readonly_files{$file_name})) {
                   5099:                                 $readonly_files{$file_name} = 'locked';
                   5100:                             }
                   5101:                         }
1.745     raeburn  5102:                     }
1.750     banghart 5103:                 } 
1.577     banghart 5104:             }
                   5105:         } 
                   5106:     }
                   5107:     return %readonly_files;
                   5108: }
1.559     banghart 5109: # ------------------------------------------------------------ Unmark as Read Only
                   5110: 
                   5111: sub unmark_as_readonly {
1.629     banghart 5112:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   5113:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  5114:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 5115:     $file_name = &declutter_portfile($file_name);
1.634     albertel 5116:     my $symb_crs = $what;
                   5117:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  5118:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 5119:     my ($tmp)=keys(%current_permissions);
                   5120:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  5121:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 5122:     foreach my $file (@readonly_files) {
1.759     albertel 5123: 	my $clean_file = &declutter_portfile($file);
                   5124: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 5125: 	my $current_locks = $current_permissions{$file};
1.563     banghart 5126:         my @new_locks;
                   5127:         my @del_keys;
                   5128:         if (ref($current_locks) eq "ARRAY"){
                   5129:             foreach my $locker (@{$current_locks}) {
1.632     albertel 5130:                 my $compare=$locker;
1.749     raeburn  5131:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  5132:                     $compare=join('',@{$locker});
1.746     raeburn  5133:                     if ($compare ne $symb_crs) {
                   5134:                         push(@new_locks, $locker);
                   5135:                     }
1.563     banghart 5136:                 }
                   5137:             }
1.650     albertel 5138:             if (scalar(@new_locks) > 0) {
1.563     banghart 5139:                 $current_permissions{$file} = \@new_locks;
                   5140:             } else {
                   5141:                 push(@del_keys, $file);
1.613     albertel 5142:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 5143:                 delete($current_permissions{$file});
1.563     banghart 5144:             }
                   5145:         }
1.561     banghart 5146:     }
1.613     albertel 5147:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 5148:     return;
                   5149: }
1.512     banghart 5150: 
1.17      www      5151: # ------------------------------------------------------------ Directory lister
                   5152: 
                   5153: sub dirlist {
1.253     stredwic 5154:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
                   5155: 
1.18      www      5156:     $uri=~s/^\///;
                   5157:     $uri=~s/\/$//;
1.253     stredwic 5158:     my ($udom, $uname);
                   5159:     (undef,$udom,$uname)=split(/\//,$uri);
                   5160:     if(defined($userdomain)) {
                   5161:         $udom = $userdomain;
                   5162:     }
                   5163:     if(defined($username)) {
                   5164:         $uname = $username;
                   5165:     }
                   5166: 
                   5167:     my $dirRoot = $perlvar{'lonDocRoot'};
                   5168:     if(defined($alternateDirectoryRoot)) {
                   5169:         $dirRoot = $alternateDirectoryRoot;
                   5170:         $dirRoot =~ s/\/$//;
1.751     banghart 5171:     }
1.253     stredwic 5172: 
                   5173:     if($udom) {
                   5174:         if($uname) {
1.605     matthew  5175:             my $listing=reply('ls2:'.$dirRoot.'/'.$uri,
1.253     stredwic 5176:                               homeserver($uname,$udom));
1.605     matthew  5177:             my @listing_results;
                   5178:             if ($listing eq 'unknown_cmd') {
                   5179:                 $listing=reply('ls:'.$dirRoot.'/'.$uri,
                   5180:                                homeserver($uname,$udom));
                   5181:                 @listing_results = split(/:/,$listing);
                   5182:             } else {
                   5183:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   5184:             }
                   5185:             return @listing_results;
1.253     stredwic 5186:         } elsif(!defined($alternateDirectoryRoot)) {
                   5187:             my $tryserver;
                   5188:             my %allusers=();
                   5189:             foreach $tryserver (keys %libserv) {
                   5190:                 if($hostdom{$tryserver} eq $udom) {
1.605     matthew  5191:                     my $listing=reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
1.253     stredwic 5192:                                       $udom, $tryserver);
1.605     matthew  5193:                     my @listing_results;
                   5194:                     if ($listing eq 'unknown_cmd') {
                   5195:                         $listing=reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   5196:                                        $udom, $tryserver);
                   5197:                         @listing_results = split(/:/,$listing);
                   5198:                     } else {
                   5199:                         @listing_results =
                   5200:                             map { &unescape($_); } split(/:/,$listing);
                   5201:                     }
                   5202:                     if ($listing_results[0] ne 'no_such_dir' && 
                   5203:                         $listing_results[0] ne 'empty'       &&
                   5204:                         $listing_results[0] ne 'con_lost') {
                   5205:                         foreach (@listing_results) {
1.253     stredwic 5206:                             my ($entry,@stat)=split(/&/,$_);
                   5207:                             $allusers{$entry}=1;
                   5208:                         }
                   5209:                     }
1.191     harris41 5210:                 }
1.253     stredwic 5211:             }
                   5212:             my $alluserstr='';
                   5213:             foreach (sort keys %allusers) {
                   5214:                 $alluserstr.=$_.'&user:';
                   5215:             }
                   5216:             $alluserstr=~s/:$//;
                   5217:             return split(/:/,$alluserstr);
                   5218:         } else {
                   5219:             my @emptyResults = ();
                   5220:             push(@emptyResults, 'missing user name');
                   5221:             return split(':',@emptyResults);
                   5222:         }
                   5223:     } elsif(!defined($alternateDirectoryRoot)) {
                   5224:         my $tryserver;
                   5225:         my %alldom=();
                   5226:         foreach $tryserver (keys %libserv) {
                   5227:             $alldom{$hostdom{$tryserver}}=1;
                   5228:         }
                   5229:         my $alldomstr='';
                   5230:         foreach (sort keys %alldom) {
1.397     albertel 5231:             $alldomstr.=$perlvar{'lonDocRoot'}.'/res/'.$_.'/&domain:';
1.253     stredwic 5232:         }
                   5233:         $alldomstr=~s/:$//;
                   5234:         return split(/:/,$alldomstr);       
                   5235:     } else {
                   5236:         my @emptyResults = ();
                   5237:         push(@emptyResults, 'missing domain');
                   5238:         return split(':',@emptyResults);
1.275     stredwic 5239:     }
                   5240: }
                   5241: 
                   5242: # --------------------------------------------- GetFileTimestamp
                   5243: # This function utilizes dirlist and returns the date stamp for
                   5244: # when it was last modified.  It will also return an error of -1
                   5245: # if an error occurs
                   5246: 
1.410     matthew  5247: ##
                   5248: ## FIXME: This subroutine assumes its caller knows something about the
                   5249: ## directory structure of the home server for the student ($root).
                   5250: ## Not a good assumption to make.  Since this is for looking up files
                   5251: ## in user directories, the full path should be constructed by lond, not
                   5252: ## whatever machine we request data from.
                   5253: ##
1.275     stredwic 5254: sub GetFileTimestamp {
                   5255:     my ($studentDomain,$studentName,$filename,$root)=@_;
                   5256:     $studentDomain=~s/\W//g;
                   5257:     $studentName=~s/\W//g;
                   5258:     my $subdir=$studentName.'__';
                   5259:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   5260:     my $proname="$studentDomain/$subdir/$studentName";
                   5261:     $proname .= '/'.$filename;
1.375     matthew  5262:     my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain, 
                   5263:                                               $studentName, $root);
1.275     stredwic 5264:     my @stats = split('&', $fileStat);
                   5265:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  5266:         # @stats contains first the filename, then the stat output
                   5267:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 5268:     } else {
                   5269:         return -1;
1.253     stredwic 5270:     }
1.26      www      5271: }
                   5272: 
1.712     albertel 5273: sub stat_file {
                   5274:     my ($uri) = @_;
1.722     albertel 5275:     $uri = &clutter($uri);
                   5276: 
                   5277:     # we want just the url part without the unneeded accessor url bits
1.723     banghart 5278:     if ($uri =~ m-^/adm/-) {
                   5279: 	$uri=~s-^/adm/wrapper/-/-;
                   5280: 	$uri=~s-^/adm/coursedocs/showdoc/-/-;
1.722     albertel 5281:     }
1.712     albertel 5282:     my ($udom,$uname,$file,$dir);
                   5283:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   5284: 	($udom,$uname,$file) =
                   5285: 	    ($uri =~ m-/(?:uploaded|editupload)/?([^/]*)/?([^/]*)/?(.*)-);
                   5286: 	$file = 'userfiles/'.$file;
1.740     www      5287: 	$dir = &propath($udom,$uname);
1.712     albertel 5288:     }
                   5289:     if ($uri =~ m-^/res/-) {
                   5290: 	($udom,$uname) = 
                   5291: 	    ($uri =~ m-/(?:res)/?([^/]*)/?([^/]*)/-);
                   5292: 	$file = $uri;
                   5293:     }
                   5294: 
                   5295:     if (!$udom || !$uname || !$file) {
                   5296: 	# unable to handle the uri
                   5297: 	return ();
                   5298:     }
                   5299: 
                   5300:     my ($result) = &dirlist($file,$udom,$uname,$dir);
                   5301:     my @stats = split('&', $result);
1.721     banghart 5302:     
1.712     albertel 5303:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   5304: 	shift(@stats); #filename is first
                   5305: 	return @stats;
                   5306:     }
                   5307:     return ();
                   5308: }
                   5309: 
1.26      www      5310: # -------------------------------------------------------- Value of a Condition
                   5311: 
1.713     albertel 5312: # gets the value of a specific preevaluated condition
                   5313: #    stored in the string  $env{user.state.<cid>}
                   5314: # or looks up a condition reference in the bighash and if if hasn't
                   5315: # already been evaluated recurses into docondval to get the value of
                   5316: # the condition, then memoizing it to 
                   5317: #   $env{user.state.<cid>.<condition>}
1.40      www      5318: sub directcondval {
                   5319:     my $number=shift;
1.620     albertel 5320:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 5321: 	&Apache::lonuserstate::evalstate();
                   5322:     }
1.713     albertel 5323:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   5324: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   5325:     } elsif ($number =~ /^_/) {
                   5326: 	my $sub_condition;
                   5327: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   5328: 		&GDBM_READER(),0640)) {
                   5329: 	    $sub_condition=$bighash{'conditions'.$number};
                   5330: 	    untie(%bighash);
                   5331: 	}
                   5332: 	my $value = &docondval($sub_condition);
                   5333: 	&appenv('user.state.'.$env{'request.course.id'}.".$number" => $value);
                   5334: 	return $value;
                   5335:     }
1.620     albertel 5336:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   5337:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      5338:     } else {
                   5339:        return 2;
                   5340:     }
                   5341: }
                   5342: 
1.713     albertel 5343: # get the collection of conditions for this resource
1.26      www      5344: sub condval {
                   5345:     my $condidx=shift;
1.54      www      5346:     my $allpathcond='';
1.713     albertel 5347:     foreach my $cond (split(/\|/,$condidx)) {
                   5348: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   5349: 	    $allpathcond.=
                   5350: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   5351: 	}
1.191     harris41 5352:     }
1.54      www      5353:     $allpathcond=~s/\|$//;
1.713     albertel 5354:     return &docondval($allpathcond);
                   5355: }
                   5356: 
                   5357: #evaluates an expression of conditions
                   5358: sub docondval {
                   5359:     my ($allpathcond) = @_;
                   5360:     my $result=0;
                   5361:     if ($env{'request.course.id'}
                   5362: 	&& defined($allpathcond)) {
                   5363: 	my $operand='|';
                   5364: 	my @stack;
                   5365: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   5366: 	    if ($chunk eq '(') {
                   5367: 		push @stack,($operand,$result);
                   5368: 	    } elsif ($chunk eq ')') {
                   5369: 		my $before=pop @stack;
                   5370: 		if (pop @stack eq '&') {
                   5371: 		    $result=$result>$before?$before:$result;
                   5372: 		} else {
                   5373: 		    $result=$result>$before?$result:$before;
                   5374: 		}
                   5375: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   5376: 		$operand=$chunk;
                   5377: 	    } else {
                   5378: 		my $new=directcondval($chunk);
                   5379: 		if ($operand eq '&') {
                   5380: 		    $result=$result>$new?$new:$result;
                   5381: 		} else {
                   5382: 		    $result=$result>$new?$result:$new;
                   5383: 		}
                   5384: 	    }
                   5385: 	}
1.26      www      5386:     }
                   5387:     return $result;
1.421     albertel 5388: }
                   5389: 
                   5390: # ---------------------------------------------------- Devalidate courseresdata
                   5391: 
                   5392: sub devalidatecourseresdata {
                   5393:     my ($coursenum,$coursedomain)=@_;
                   5394:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 5395:     &devalidate_cache_new('courseres',$hashid);
1.28      www      5396: }
                   5397: 
1.763     www      5398: 
1.200     www      5399: # --------------------------------------------------- Course Resourcedata Query
                   5400: 
1.624     albertel 5401: sub get_courseresdata {
                   5402:     my ($coursenum,$coursedomain)=@_;
1.200     www      5403:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   5404:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 5405:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 5406:     my %dumpreply;
1.417     albertel 5407:     unless (defined($cached)) {
1.624     albertel 5408: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 5409: 	$result=\%dumpreply;
1.251     albertel 5410: 	my ($tmp) = keys(%dumpreply);
                   5411: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 5412: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 5413: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   5414: 	    return $tmp;
1.416     albertel 5415: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 5416: 	    $result=undef;
1.599     albertel 5417: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 5418: 	}
                   5419:     }
1.624     albertel 5420:     return $result;
                   5421: }
                   5422: 
1.633     albertel 5423: sub devalidateuserresdata {
                   5424:     my ($uname,$udom)=@_;
                   5425:     my $hashid="$udom:$uname";
                   5426:     &devalidate_cache_new('userres',$hashid);
                   5427: }
                   5428: 
1.624     albertel 5429: sub get_userresdata {
                   5430:     my ($uname,$udom)=@_;
                   5431:     #most student don\'t have any data set, check if there is some data
                   5432:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   5433: 
                   5434:     my $hashid="$udom:$uname";
                   5435:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   5436:     if (!defined($cached)) {
                   5437: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   5438: 	$result=\%resourcedata;
                   5439: 	&do_cache_new('userres',$hashid,$result,600);
                   5440:     }
                   5441:     my ($tmp)=keys(%$result);
                   5442:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   5443: 	return $result;
                   5444:     }
                   5445:     #error 2 occurs when the .db doesn't exist
                   5446:     if ($tmp!~/error: 2 /) {
1.672     albertel 5447: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 5448: 		 " Trying to get resource data for ".
                   5449: 		 $uname." at ".$udom.": ".
                   5450: 		 $tmp."</font>");
                   5451:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 5452: 	#&EXT_cache_set($udom,$uname);
                   5453: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 5454: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 5455:     }
                   5456:     return $tmp;
                   5457: }
                   5458: 
                   5459: sub resdata {
                   5460:     my ($name,$domain,$type,@which)=@_;
                   5461:     my $result;
                   5462:     if ($type eq 'course') {
                   5463: 	$result=&get_courseresdata($name,$domain);
                   5464:     } elsif ($type eq 'user') {
                   5465: 	$result=&get_userresdata($name,$domain);
                   5466:     }
                   5467:     if (!ref($result)) { return $result; }    
1.251     albertel 5468:     foreach my $item (@which) {
1.417     albertel 5469: 	if (defined($result->{$item})) {
                   5470: 	    return $result->{$item};
1.251     albertel 5471: 	}
1.250     albertel 5472:     }
1.291     albertel 5473:     return undef;
1.200     www      5474: }
                   5475: 
1.379     matthew  5476: #
                   5477: # EXT resource caching routines
                   5478: #
                   5479: 
                   5480: sub clear_EXT_cache_status {
1.383     albertel 5481:     &delenv('cache.EXT.');
1.379     matthew  5482: }
                   5483: 
                   5484: sub EXT_cache_status {
                   5485:     my ($target_domain,$target_user) = @_;
1.383     albertel 5486:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 5487:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  5488:         # We know already the user has no data
                   5489:         return 1;
                   5490:     } else {
                   5491:         return 0;
                   5492:     }
                   5493: }
                   5494: 
                   5495: sub EXT_cache_set {
                   5496:     my ($target_domain,$target_user) = @_;
1.383     albertel 5497:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.633     albertel 5498:     #&appenv($cachename => time);
1.379     matthew  5499: }
                   5500: 
1.28      www      5501: # --------------------------------------------------------- Value of a Variable
1.58      www      5502: sub EXT {
1.715     albertel 5503: 
1.395     albertel 5504:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      5505:     unless ($varname) { return ''; }
1.218     albertel 5506:     #get real user name/domain, courseid and symb
                   5507:     my $courseid;
1.359     albertel 5508:     my $publicuser;
1.427     www      5509:     if ($symbparm) {
                   5510: 	$symbparm=&get_symb_from_alias($symbparm);
                   5511:     }
1.218     albertel 5512:     if (!($uname && $udom)) {
1.360     albertel 5513:       (my $cursymb,$courseid,$udom,$uname,$publicuser)=
1.378     matthew  5514: 	  &Apache::lonxml::whichuser($symbparm);
1.218     albertel 5515:       if (!$symbparm) {	$symbparm=$cursymb; }
                   5516:     } else {
1.620     albertel 5517: 	$courseid=$env{'request.course.id'};
1.218     albertel 5518:     }
1.48      www      5519:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   5520:     my $rest;
1.320     albertel 5521:     if (defined($therest[0])) {
1.48      www      5522:        $rest=join('.',@therest);
                   5523:     } else {
                   5524:        $rest='';
                   5525:     }
1.320     albertel 5526: 
1.57      www      5527:     my $qualifierrest=$qualifier;
                   5528:     if ($rest) { $qualifierrest.='.'.$rest; }
                   5529:     my $spacequalifierrest=$space;
                   5530:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      5531:     if ($realm eq 'user') {
1.48      www      5532: # --------------------------------------------------------------- user.resource
                   5533: 	if ($space eq 'resource') {
1.651     albertel 5534: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   5535: 		  || defined($Apache::lonhomework::parsing_a_task))
                   5536: 		 &&
1.744     albertel 5537: 		 ($symbparm eq &symbread()) ) {	
                   5538: 		# if we are in the middle of processing the resource the
                   5539: 		# get the value we are planning on committing
                   5540:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   5541:                     return $Apache::lonhomework::results{$qualifierrest};
                   5542:                 } else {
                   5543:                     return $Apache::lonhomework::history{$qualifierrest};
                   5544:                 }
1.335     albertel 5545: 	    } else {
1.359     albertel 5546: 		my %restored;
1.620     albertel 5547: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 5548: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   5549: 		} else {
                   5550: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   5551: 		}
1.335     albertel 5552: 		return $restored{$qualifierrest};
                   5553: 	    }
1.48      www      5554: # ----------------------------------------------------------------- user.access
                   5555:         } elsif ($space eq 'access') {
1.218     albertel 5556: 	    # FIXME - not supporting calls for a specific user
1.48      www      5557:             return &allowed($qualifier,$rest);
                   5558: # ------------------------------------------ user.preferences, user.environment
                   5559:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 5560: 	    if (($uname eq $env{'user.name'}) &&
                   5561: 		($udom eq $env{'user.domain'})) {
                   5562: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 5563: 	    } else {
1.359     albertel 5564: 		my %returnhash;
                   5565: 		if (!$publicuser) {
                   5566: 		    %returnhash=&userenvironment($udom,$uname,
                   5567: 						 $qualifierrest);
                   5568: 		}
1.218     albertel 5569: 		return $returnhash{$qualifierrest};
                   5570: 	    }
1.48      www      5571: # ----------------------------------------------------------------- user.course
                   5572:         } elsif ($space eq 'course') {
1.218     albertel 5573: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 5574:             return $env{join('.',('request.course',$qualifier))};
1.48      www      5575: # ------------------------------------------------------------------- user.role
                   5576:         } elsif ($space eq 'role') {
1.218     albertel 5577: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 5578:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      5579:             if ($qualifier eq 'value') {
                   5580: 		return $role;
                   5581:             } elsif ($qualifier eq 'extent') {
                   5582:                 return $where;
                   5583:             }
                   5584: # ----------------------------------------------------------------- user.domain
                   5585:         } elsif ($space eq 'domain') {
1.218     albertel 5586:             return $udom;
1.48      www      5587: # ------------------------------------------------------------------- user.name
                   5588:         } elsif ($space eq 'name') {
1.218     albertel 5589:             return $uname;
1.48      www      5590: # ---------------------------------------------------- Any other user namespace
1.29      www      5591:         } else {
1.359     albertel 5592: 	    my %reply;
                   5593: 	    if (!$publicuser) {
                   5594: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   5595: 	    }
                   5596: 	    return $reply{$qualifierrest};
1.48      www      5597:         }
1.236     www      5598:     } elsif ($realm eq 'query') {
                   5599: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 5600:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   5601: 						[$spacequalifierrest]);
1.620     albertel 5602: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      5603:    } elsif ($realm eq 'request') {
1.48      www      5604: # ------------------------------------------------------------- request.browser
                   5605:         if ($space eq 'browser') {
1.430     www      5606: 	    if ($qualifier eq 'textremote') {
1.676     albertel 5607: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      5608: 		    return 1;
                   5609: 		} else {
                   5610: 		    return 0;
                   5611: 		}
                   5612: 	    } else {
1.620     albertel 5613: 		return $env{'browser.'.$qualifier};
1.430     www      5614: 	    }
1.57      www      5615: # ------------------------------------------------------------ request.filename
                   5616:         } else {
1.620     albertel 5617:             return $env{'request.'.$spacequalifierrest};
1.29      www      5618:         }
1.28      www      5619:     } elsif ($realm eq 'course') {
1.48      www      5620: # ---------------------------------------------------------- course.description
1.620     albertel 5621:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      5622:     } elsif ($realm eq 'resource') {
1.165     www      5623: 
1.620     albertel 5624: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 5625: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   5626: 	}
1.693     albertel 5627: 
                   5628: 	if ($space eq 'title') {
                   5629: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   5630: 	    return &gettitle($symbparm);
                   5631: 	}
                   5632: 	
                   5633: 	if ($space eq 'map') {
                   5634: 	    my ($map) = &decode_symb($symbparm);
                   5635: 	    return &symbread($map);
                   5636: 	}
                   5637: 
                   5638: 	my ($section, $group, @groups);
1.593     albertel 5639: 	my ($courselevelm,$courselevel);
1.539     albertel 5640: 	if ($symbparm && defined($courseid) && 
1.620     albertel 5641: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      5642: 
1.218     albertel 5643: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      5644: 
1.60      www      5645: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 5646: 	    my $symbp=$symbparm;
1.735     albertel 5647: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 5648: 
                   5649: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   5650: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   5651: 
1.620     albertel 5652: 	    if (($env{'user.name'} eq $uname) &&
                   5653: 		($env{'user.domain'} eq $udom)) {
                   5654: 		$section=$env{'request.course.sec'};
1.733     raeburn  5655:                 @groups = split(/:/,$env{'request.course.groups'});  
                   5656:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 5657: 	    } else {
1.539     albertel 5658: 		if (! defined($usection)) {
1.551     albertel 5659: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 5660: 		} else {
                   5661: 		    $section = $usection;
                   5662: 		}
1.733     raeburn  5663:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 5664: 	    }
                   5665: 
                   5666: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   5667: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   5668: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   5669: 
1.593     albertel 5670: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 5671: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 5672: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      5673: 
1.60      www      5674: # ----------------------------------------------------------- first, check user
1.624     albertel 5675: 
                   5676: 	    my $userreply=&resdata($uname,$udom,'user',
                   5677: 				       ($courselevelr,$courselevelm,
                   5678: 					$courselevel));
                   5679: 	    if (defined($userreply)) { return $userreply; }
1.95      www      5680: 
1.594     albertel 5681: # ------------------------------------------------ second, check some of course
1.684     raeburn  5682:             my $coursereply;
1.691     raeburn  5683:             if (@groups > 0) {
                   5684:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   5685:                                        $mapparm,$spacequalifierrest);
1.684     raeburn  5686:                 if (defined($coursereply)) { return $coursereply; }
                   5687:             }
1.96      www      5688: 
1.684     raeburn  5689: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.624     albertel 5690: 				     $env{'course.'.$courseid.'.domain'},
                   5691: 				     'course',
                   5692: 				     ($seclevelr,$seclevelm,$seclevel,
                   5693: 				      $courselevelr));
1.287     albertel 5694: 	    if (defined($coursereply)) { return $coursereply; }
1.200     www      5695: 
1.60      www      5696: # ------------------------------------------------------ third, check map parms
1.218     albertel 5697: 	    my %parmhash=();
                   5698: 	    my $thisparm='';
                   5699: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 5700: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 5701: 		    &GDBM_READER(),0640)) {
1.218     albertel 5702: 		$thisparm=$parmhash{$symbparm};
                   5703: 		untie(%parmhash);
                   5704: 	    }
                   5705: 	    if ($thisparm) { return $thisparm; }
                   5706: 	}
1.594     albertel 5707: # ------------------------------------------ fourth, look in resource metadata
1.71      www      5708: 
1.218     albertel 5709: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 5710: 	my $filename;
                   5711: 	if (!$symbparm) { $symbparm=&symbread(); }
                   5712: 	if ($symbparm) {
1.409     www      5713: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 5714: 	} else {
1.620     albertel 5715: 	    $filename=$env{'request.filename'};
1.282     albertel 5716: 	}
                   5717: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.288     albertel 5718: 	if (defined($metadata)) { return $metadata; }
1.282     albertel 5719: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.288     albertel 5720: 	if (defined($metadata)) { return $metadata; }
1.142     www      5721: 
1.594     albertel 5722: # ---------------------------------------------- fourth, look in rest pf course
1.593     albertel 5723: 	if ($symbparm && defined($courseid) && 
1.620     albertel 5724: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 5725: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   5726: 				     $env{'course.'.$courseid.'.domain'},
                   5727: 				     'course',
                   5728: 				     ($courselevelm,$courselevel));
1.593     albertel 5729: 	    if (defined($coursereply)) { return $coursereply; }
                   5730: 	}
1.145     www      5731: # ------------------------------------------------------------------ Cascade up
1.218     albertel 5732: 	unless ($space eq '0') {
1.336     albertel 5733: 	    my @parts=split(/_/,$space);
                   5734: 	    my $id=pop(@parts);
                   5735: 	    my $part=join('_',@parts);
                   5736: 	    if ($part eq '') { $part='0'; }
                   5737: 	    my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 5738: 				 $symbparm,$udom,$uname,$section,1);
1.337     albertel 5739: 	    if (defined($partgeneral)) { return $partgeneral; }
1.218     albertel 5740: 	}
1.395     albertel 5741: 	if ($recurse) { return undef; }
                   5742: 	my $pack_def=&packages_tab_default($filename,$varname);
                   5743: 	if (defined($pack_def)) { return $pack_def; }
1.71      www      5744: 
1.48      www      5745: # ---------------------------------------------------- Any other user namespace
                   5746:     } elsif ($realm eq 'environment') {
                   5747: # ----------------------------------------------------------------- environment
1.620     albertel 5748: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   5749: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 5750: 	} else {
1.770     albertel 5751: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   5752: 		return '';
                   5753: 	    }
1.219     albertel 5754: 	    my %returnhash=&userenvironment($udom,$uname,
                   5755: 					    $spacequalifierrest);
                   5756: 	    return $returnhash{$spacequalifierrest};
                   5757: 	}
1.28      www      5758:     } elsif ($realm eq 'system') {
1.48      www      5759: # ----------------------------------------------------------------- system.time
                   5760: 	if ($space eq 'time') {
                   5761: 	    return time;
                   5762:         }
1.696     albertel 5763:     } elsif ($realm eq 'server') {
                   5764: # ----------------------------------------------------------------- system.time
                   5765: 	if ($space eq 'name') {
                   5766: 	    return $ENV{'SERVER_NAME'};
                   5767:         }
1.28      www      5768:     }
1.48      www      5769:     return '';
1.61      www      5770: }
                   5771: 
1.691     raeburn  5772: sub check_group_parms {
                   5773:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   5774:     my @groupitems = ();
                   5775:     my $resultitem;
                   5776:     my @levels = ($symbparm,$mapparm,$what);
                   5777:     foreach my $group (@{$groups}) {
                   5778:         foreach my $level (@levels) {
                   5779:              my $item = $courseid.'.['.$group.'].'.$level;
                   5780:              push(@groupitems,$item);
                   5781:         }
                   5782:     }
                   5783:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   5784:                             $env{'course.'.$courseid.'.domain'},
                   5785:                                      'course',@groupitems);
                   5786:     return $coursereply;
                   5787: }
                   5788: 
                   5789: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  5790:     my ($courseid,@groups) = @_;
                   5791:     @groups = sort(@groups);
1.691     raeburn  5792:     return @groups;
                   5793: }
                   5794: 
1.395     albertel 5795: sub packages_tab_default {
                   5796:     my ($uri,$varname)=@_;
                   5797:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 5798: 
                   5799:     my (@extension,@specifics,$do_default);
                   5800:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 5801: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 5802: 	if ($pack_type eq 'default') {
                   5803: 	    $do_default=1;
                   5804: 	} elsif ($pack_type eq 'extension') {
                   5805: 	    push(@extension,[$package,$pack_type,$pack_part]);
                   5806: 	} else {
                   5807: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   5808: 	}
                   5809:     }
                   5810:     # first look for a package that matches the requested part id
                   5811:     foreach my $package (@specifics) {
                   5812: 	my (undef,$pack_type,$pack_part)=@{$package};
                   5813: 	next if ($pack_part ne $part);
                   5814: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   5815: 	    return $packagetab{"$pack_type&$name&default"};
                   5816: 	}
                   5817:     }
                   5818:     # look for any possible matching non extension_ package
                   5819:     foreach my $package (@specifics) {
                   5820: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 5821: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   5822: 	    return $packagetab{"$pack_type&$name&default"};
                   5823: 	}
1.585     albertel 5824: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 5825: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   5826: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 5827: 	}
                   5828:     }
1.738     albertel 5829:     # look for any posible extension_ match
                   5830:     foreach my $package (@extension) {
                   5831: 	my ($package,$pack_type)=@{$package};
                   5832: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   5833: 	    return $packagetab{"$pack_type&$name&default"};
                   5834: 	}
                   5835: 	if (defined($packagetab{$package."&$name&default"})) {
                   5836: 	    return $packagetab{$package."&$name&default"};
                   5837: 	}
                   5838:     }
                   5839:     # look for a global default setting
                   5840:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   5841: 	return $packagetab{"default&$name&default"};
                   5842:     }
1.395     albertel 5843:     return undef;
                   5844: }
                   5845: 
1.334     albertel 5846: sub add_prefix_and_part {
                   5847:     my ($prefix,$part)=@_;
                   5848:     my $keyroot;
                   5849:     if (defined($prefix) && $prefix !~ /^__/) {
                   5850: 	# prefix that has a part already
                   5851: 	$keyroot=$prefix;
                   5852:     } elsif (defined($prefix)) {
                   5853: 	# prefix that is missing a part
                   5854: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   5855:     } else {
                   5856: 	# no prefix at all
                   5857: 	if (defined($part)) { $keyroot='_'.$part; }
                   5858:     }
                   5859:     return $keyroot;
                   5860: }
                   5861: 
1.71      www      5862: # ---------------------------------------------------------------- Get metadata
                   5863: 
1.599     albertel 5864: my %metaentry;
1.71      www      5865: sub metadata {
1.176     www      5866:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      5867:     $uri=&declutter($uri);
1.288     albertel 5868:     # if it is a non metadata possible uri return quickly
1.529     albertel 5869:     if (($uri eq '') || 
                   5870: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 5871: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.423     albertel 5872:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) ||
1.489     albertel 5873: 	($uri =~ m|home/[^/]+/public_html/|)) {
1.468     albertel 5874: 	return undef;
1.288     albertel 5875:     }
1.73      www      5876:     my $filename=$uri;
                   5877:     $uri=~s/\.meta$//;
1.172     www      5878: #
                   5879: # Is the metadata already cached?
1.177     www      5880: # Look at timestamp of caching
1.172     www      5881: # Everything is cached by the main uri, libraries are never directly cached
                   5882: #
1.428     albertel 5883:     if (!defined($liburi)) {
1.599     albertel 5884: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 5885: 	if (defined($cached)) { return $result->{':'.$what}; }
                   5886:     }
                   5887:     {
1.172     www      5888: #
                   5889: # Is this a recursive call for a library?
                   5890: #
1.599     albertel 5891: #	if (! exists($metacache{$uri})) {
                   5892: #	    $metacache{$uri}={};
                   5893: #	}
1.171     www      5894:         if ($liburi) {
                   5895: 	    $liburi=&declutter($liburi);
                   5896:             $filename=$liburi;
1.401     bowersj2 5897:         } else {
1.599     albertel 5898: 	    &devalidate_cache_new('meta',$uri);
                   5899: 	    undef(%metaentry);
1.401     bowersj2 5900: 	}
1.140     www      5901:         my %metathesekeys=();
1.73      www      5902:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 5903: 	my $metastring;
1.768     albertel 5904: 	if ($uri !~ m -^(editupload)/-) {
1.543     albertel 5905: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 5906: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 5907: 	    $metastring=&getfile($file);
1.489     albertel 5908: 	}
1.208     albertel 5909:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      5910:         my $token;
1.140     www      5911:         undef %metathesekeys;
1.71      www      5912:         while ($token=$parser->get_token) {
1.339     albertel 5913: 	    if ($token->[0] eq 'S') {
                   5914: 		if (defined($token->[2]->{'package'})) {
1.172     www      5915: #
                   5916: # This is a package - get package info
                   5917: #
1.339     albertel 5918: 		    my $package=$token->[2]->{'package'};
                   5919: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   5920: 		    if (defined($token->[2]->{'id'})) { 
                   5921: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   5922: 		    }
1.599     albertel 5923: 		    if ($metaentry{':packages'}) {
                   5924: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 5925: 		    } else {
1.599     albertel 5926: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 5927: 		    }
1.736     albertel 5928: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 5929: 			my $part=$keyroot;
                   5930: 			$part=~s/^\_//;
1.736     albertel 5931: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   5932: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   5933: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 5934: 			    # ignore package.tab specified default values
                   5935:                             # here &package_tab_default() will fetch those
                   5936: 			    if ($subp eq 'default') { next; }
1.736     albertel 5937: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 5938: 			    my $unikey;
                   5939: 			    if ($pack =~ /_0$/) {
                   5940: 				$unikey='parameter_0_'.$name;
                   5941: 				$part=0;
                   5942: 			    } else {
                   5943: 				$unikey='parameter'.$keyroot.'_'.$name;
                   5944: 			    }
1.339     albertel 5945: 			    if ($subp eq 'display') {
                   5946: 				$value.=' [Part: '.$part.']';
                   5947: 			    }
1.599     albertel 5948: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 5949: 			    $metathesekeys{$unikey}=1;
1.599     albertel 5950: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   5951: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 5952: 			    }
1.599     albertel 5953: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   5954: 				$metaentry{':'.$unikey}=
                   5955: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 5956: 			    }
1.339     albertel 5957: 			}
                   5958: 		    }
                   5959: 		} else {
1.172     www      5960: #
                   5961: # This is not a package - some other kind of start tag
1.339     albertel 5962: #
                   5963: 		    my $entry=$token->[1];
                   5964: 		    my $unikey;
                   5965: 		    if ($entry eq 'import') {
                   5966: 			$unikey='';
                   5967: 		    } else {
                   5968: 			$unikey=$entry;
                   5969: 		    }
                   5970: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   5971: 
                   5972: 		    if (defined($token->[2]->{'id'})) { 
                   5973: 			$unikey.='_'.$token->[2]->{'id'}; 
                   5974: 		    }
1.175     www      5975: 
1.339     albertel 5976: 		    if ($entry eq 'import') {
1.175     www      5977: #
                   5978: # Importing a library here
1.339     albertel 5979: #
                   5980: 			if ($depthcount<20) {
                   5981: 			    my $location=$parser->get_text('/import');
                   5982: 			    my $dir=$filename;
                   5983: 			    $dir=~s|[^/]*$||;
                   5984: 			    $location=&filelocation($dir,$location);
1.736     albertel 5985: 			    my $metadata = 
                   5986: 				&metadata($uri,'keys', $location,$unikey,
                   5987: 					  $depthcount+1);
                   5988: 			    foreach my $meta (split(',',$metadata)) {
                   5989: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   5990: 				$metathesekeys{$meta}=1;
1.339     albertel 5991: 			    }
                   5992: 			}
                   5993: 		    } else { 
                   5994: 			
                   5995: 			if (defined($token->[2]->{'name'})) { 
                   5996: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   5997: 			}
                   5998: 			$metathesekeys{$unikey}=1;
1.736     albertel 5999: 			foreach my $param (@{$token->[3]}) {
                   6000: 			    $metaentry{':'.$unikey.'.'.$param} =
                   6001: 				$token->[2]->{$param};
1.339     albertel 6002: 			}
                   6003: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 6004: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 6005: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   6006: 		 # only ws inside the tag, and not in default, so use default
                   6007: 		 # as value
1.599     albertel 6008: 			    $metaentry{':'.$unikey}=$default;
1.339     albertel 6009: 			} else {
1.321     albertel 6010: 		  # either something interesting inside the tag or default
                   6011:                   # uninteresting
1.599     albertel 6012: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 6013: 			}
1.172     www      6014: # end of not-a-package not-a-library import
1.339     albertel 6015: 		    }
1.172     www      6016: # end of not-a-package start tag
1.339     albertel 6017: 		}
1.172     www      6018: # the next is the end of "start tag"
1.339     albertel 6019: 	    }
                   6020: 	}
1.483     albertel 6021: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.737     albertel 6022: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 6023: 	    #no specific packages #how's our extension
                   6024: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 6025: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 6026: 					 \%metathesekeys);
                   6027: 	}
1.599     albertel 6028: 	if (!exists($metaentry{':packages'})) {
1.737     albertel 6029: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 6030: 		#no specific packages well let's get default then
                   6031: 		if ($key!~/^default&/) { next; }
1.488     albertel 6032: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 6033: 					     \%metathesekeys);
                   6034: 	    }
                   6035: 	}
1.338     www      6036: # are there custom rights to evaluate
1.599     albertel 6037: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 6038: 
1.338     www      6039:     #
                   6040:     # Importing a rights file here
1.339     albertel 6041:     #
                   6042: 	    unless ($depthcount) {
1.599     albertel 6043: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 6044: 		my $dir=$filename;
                   6045: 		$dir=~s|[^/]*$||;
                   6046: 		$location=&filelocation($dir,$location);
1.736     albertel 6047: 		my $rights_metadata =
                   6048: 		    &metadata($uri,'keys',$location,'_rights',
                   6049: 			      $depthcount+1);
                   6050: 		foreach my $rights (split(',',$rights_metadata)) {
                   6051: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   6052: 		    $metathesekeys{$rights}=1;
1.339     albertel 6053: 		}
                   6054: 	    }
                   6055: 	}
1.737     albertel 6056: 	# uniqifiy package listing
                   6057: 	my %seen;
                   6058: 	my @uniq_packages =
                   6059: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   6060: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   6061: 
                   6062: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 6063: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   6064: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.699     albertel 6065: 	&do_cache_new('meta',$uri,\%metaentry,60*60);
1.177     www      6066: # this is the end of "was not already recently cached
1.71      www      6067:     }
1.599     albertel 6068:     return $metaentry{':'.$what};
1.261     albertel 6069: }
                   6070: 
1.488     albertel 6071: sub metadata_create_package_def {
1.483     albertel 6072:     my ($uri,$key,$package,$metathesekeys)=@_;
                   6073:     my ($pack,$name,$subp)=split(/\&/,$key);
                   6074:     if ($subp eq 'default') { next; }
                   6075:     
1.599     albertel 6076:     if (defined($metaentry{':packages'})) {
                   6077: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 6078:     } else {
1.599     albertel 6079: 	$metaentry{':packages'}=$package;
1.483     albertel 6080:     }
                   6081:     my $value=$packagetab{$key};
                   6082:     my $unikey;
                   6083:     $unikey='parameter_0_'.$name;
1.599     albertel 6084:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 6085:     $$metathesekeys{$unikey}=1;
1.599     albertel 6086:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   6087: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 6088:     }
1.599     albertel 6089:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   6090: 	$metaentry{':'.$unikey}=
                   6091: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 6092:     }
                   6093: }
                   6094: 
1.261     albertel 6095: sub metadata_generate_part0 {
                   6096:     my ($metadata,$metacache,$uri) = @_;
                   6097:     my %allnames;
1.737     albertel 6098:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 6099: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 6100: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   6101: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 6102: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 6103: 	    $allnames{$name}=$part;
                   6104: 	  }
                   6105: 	}
                   6106:     }
                   6107:     foreach my $name (keys(%allnames)) {
                   6108:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 6109:       my $key=":parameter_0_$name";
1.261     albertel 6110:       $$metacache{"$key.part"}='0';
                   6111:       $$metacache{"$key.name"}=$name;
1.428     albertel 6112:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 6113: 					   $allnames{$name}.'_'.$name.
                   6114: 					   '.type'};
1.428     albertel 6115:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 6116: 			     '.display'};
1.644     www      6117:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 6118:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 6119:       $$metacache{"$key.display"}=$olddis;
                   6120:     }
1.71      www      6121: }
                   6122: 
1.764     albertel 6123: # ------------------------------------------------------ Devalidate title cache
                   6124: 
                   6125: sub devalidate_title_cache {
                   6126:     my ($url)=@_;
                   6127:     if (!$env{'request.course.id'}) { return; }
                   6128:     my $symb=&symbread($url);
                   6129:     if (!$symb) { return; }
                   6130:     my $key=$env{'request.course.id'}."\0".$symb;
                   6131:     &devalidate_cache_new('title',$key);
                   6132: }
                   6133: 
1.301     www      6134: # ------------------------------------------------- Get the title of a resource
                   6135: 
                   6136: sub gettitle {
                   6137:     my $urlsymb=shift;
                   6138:     my $symb=&symbread($urlsymb);
1.534     albertel 6139:     if ($symb) {
1.620     albertel 6140: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 6141: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 6142: 	if (defined($cached)) { 
                   6143: 	    return $result;
                   6144: 	}
1.534     albertel 6145: 	my ($map,$resid,$url)=&decode_symb($symb);
                   6146: 	my $title='';
                   6147: 	my %bighash;
1.620     albertel 6148: 	if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.534     albertel 6149: 		&GDBM_READER(),0640)) {
                   6150: 	    my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   6151: 	    $title=$bighash{'title_'.$mapid.'.'.$resid};
                   6152: 	    untie %bighash;
                   6153: 	}
                   6154: 	$title=~s/\&colon\;/\:/gs;
                   6155: 	if ($title) {
1.599     albertel 6156: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 6157: 	}
                   6158: 	$urlsymb=$url;
                   6159:     }
                   6160:     my $title=&metadata($urlsymb,'title');
                   6161:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   6162:     return $title;
1.301     www      6163: }
1.613     albertel 6164: 
1.614     albertel 6165: sub get_slot {
                   6166:     my ($which,$cnum,$cdom)=@_;
                   6167:     if (!$cnum || !$cdom) {
                   6168: 	(undef,my $courseid)=&Apache::lonxml::whichuser();
1.620     albertel 6169: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   6170: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 6171:     }
1.703     albertel 6172:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   6173:     my %slotinfo;
                   6174:     if (exists($remembered{$key})) {
                   6175: 	$slotinfo{$which} = $remembered{$key};
                   6176:     } else {
                   6177: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   6178: 	&Apache::lonhomework::showhash(%slotinfo);
                   6179: 	my ($tmp)=keys(%slotinfo);
                   6180: 	if ($tmp=~/^error:/) { return (); }
                   6181: 	$remembered{$key} = $slotinfo{$which};
                   6182:     }
1.616     albertel 6183:     if (ref($slotinfo{$which}) eq 'HASH') {
                   6184: 	return %{$slotinfo{$which}};
                   6185:     }
                   6186:     return $slotinfo{$which};
1.614     albertel 6187: }
1.31      www      6188: # ------------------------------------------------- Update symbolic store links
                   6189: 
                   6190: sub symblist {
                   6191:     my ($mapname,%newhash)=@_;
1.438     www      6192:     $mapname=&deversion(&declutter($mapname));
1.31      www      6193:     my %hash;
1.620     albertel 6194:     if (($env{'request.course.fn'}) && (%newhash)) {
                   6195:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 6196:                       &GDBM_WRCREAT(),0640)) {
1.711     albertel 6197: 	    foreach my $url (keys %newhash) {
                   6198: 		next if ($url eq 'last_known'
                   6199: 			 && $env{'form.no_update_last_known'});
                   6200: 		$hash{declutter($url)}=&encode_symb($mapname,
                   6201: 						    $newhash{$url}->[1],
                   6202: 						    $newhash{$url}->[0]);
1.191     harris41 6203:             }
1.31      www      6204:             if (untie(%hash)) {
                   6205: 		return 'ok';
                   6206:             }
                   6207:         }
                   6208:     }
                   6209:     return 'error';
1.212     www      6210: }
                   6211: 
                   6212: # --------------------------------------------------------------- Verify a symb
                   6213: 
                   6214: sub symbverify {
1.510     www      6215:     my ($symb,$thisurl)=@_;
                   6216:     my $thisfn=$thisurl;
                   6217: # wrapper not part of symbs
                   6218:     $thisfn=~s/^\/adm\/wrapper//;
1.694     albertel 6219:     $thisfn=~s/^\/adm\/coursedocs\/showdoc\///;
1.439     www      6220:     $thisfn=&declutter($thisfn);
1.215     www      6221: # direct jump to resource in page or to a sequence - will construct own symbs
                   6222:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   6223: # check URL part
1.409     www      6224:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      6225: 
1.431     www      6226:     unless ($url eq $thisfn) { return 0; }
1.213     www      6227: 
1.216     www      6228:     $symb=&symbclean($symb);
1.510     www      6229:     $thisurl=&deversion($thisurl);
1.439     www      6230:     $thisfn=&deversion($thisfn);
1.213     www      6231: 
                   6232:     my %bighash;
                   6233:     my $okay=0;
1.431     www      6234: 
1.620     albertel 6235:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 6236:                             &GDBM_READER(),0640)) {
1.510     www      6237:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      6238:         unless ($ids) { 
1.510     www      6239:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      6240:         }
                   6241:         if ($ids) {
                   6242: # ------------------------------------------------------------------- Has ID(s)
                   6243: 	    foreach (split(/\,/,$ids)) {
1.644     www      6244: 	       my ($mapid,$resid)=split(/\./,$_);
1.216     www      6245:                if (
                   6246:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   6247:    eq $symb) { 
1.620     albertel 6248: 		   if (($env{'request.role.adv'}) ||
                   6249: 		       $bighash{'encrypted_'.$_} eq $env{'request.enc'}) {
1.582     albertel 6250: 		       $okay=1; 
                   6251: 		   }
                   6252: 	       }
1.216     www      6253: 	   }
                   6254:         }
1.213     www      6255: 	untie(%bighash);
                   6256:     }
                   6257:     return $okay;
1.31      www      6258: }
                   6259: 
1.210     www      6260: # --------------------------------------------------------------- Clean-up symb
                   6261: 
                   6262: sub symbclean {
                   6263:     my $symb=shift;
1.568     albertel 6264:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      6265: # remove version from map
                   6266:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      6267: 
1.210     www      6268: # remove version from URL
                   6269:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      6270: 
1.507     www      6271: # remove wrapper
                   6272: 
1.510     www      6273:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 6274:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      6275:     return $symb;
1.409     www      6276: }
                   6277: 
                   6278: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 6279: 
                   6280: sub encode_symb {
                   6281:     my ($map,$resid,$url)=@_;
                   6282:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   6283: }
1.409     www      6284: 
                   6285: sub decode_symb {
1.568     albertel 6286:     my $symb=shift;
                   6287:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   6288:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      6289:     return (&fixversion($map),$resid,&fixversion($url));
                   6290: }
                   6291: 
                   6292: sub fixversion {
                   6293:     my $fn=shift;
1.609     banghart 6294:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      6295:     my %bighash;
                   6296:     my $uri=&clutter($fn);
1.620     albertel 6297:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      6298: # is this cached?
1.599     albertel 6299:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      6300:     if (defined($cached)) { return $result; }
                   6301: # unfortunately not cached, or expired
1.620     albertel 6302:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      6303: 	    &GDBM_READER(),0640)) {
                   6304:  	if ($bighash{'version_'.$uri}) {
                   6305:  	    my $version=$bighash{'version_'.$uri};
1.444     www      6306:  	    unless (($version eq 'mostrecent') || 
                   6307: 		    ($version==&getversion($uri))) {
1.440     www      6308:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   6309:  	    }
                   6310:  	}
                   6311:  	untie %bighash;
1.413     www      6312:     }
1.599     albertel 6313:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      6314: }
                   6315: 
                   6316: sub deversion {
                   6317:     my $url=shift;
                   6318:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   6319:     return $url;
1.210     www      6320: }
                   6321: 
1.31      www      6322: # ------------------------------------------------------ Return symb list entry
                   6323: 
                   6324: sub symbread {
1.249     www      6325:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 6326:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 6327:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      6328: # no filename provided? try from environment
1.44      www      6329:     unless ($thisfn) {
1.620     albertel 6330:         if ($env{'request.symb'}) {
                   6331: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 6332: 	}
1.620     albertel 6333: 	$thisfn=$env{'request.filename'};
1.44      www      6334:     }
1.569     albertel 6335:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      6336: # is that filename actually a symb? Verify, clean, and return
                   6337:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 6338: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 6339: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 6340: 	}
1.242     www      6341:     }
1.44      www      6342:     $thisfn=declutter($thisfn);
1.31      www      6343:     my %hash;
1.37      www      6344:     my %bighash;
                   6345:     my $syval='';
1.620     albertel 6346:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  6347:         my $targetfn = $thisfn;
1.609     banghart 6348:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  6349:             $targetfn = 'adm/wrapper/'.$thisfn;
                   6350:         }
1.687     albertel 6351: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   6352: 	    $targetfn=$1;
                   6353: 	}
1.620     albertel 6354:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 6355:                       &GDBM_READER(),0640)) {
1.481     raeburn  6356: 	    $syval=$hash{$targetfn};
1.37      www      6357:             untie(%hash);
                   6358:         }
                   6359: # ---------------------------------------------------------- There was an entry
                   6360:         if ($syval) {
1.601     albertel 6361: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 6362: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.601     albertel 6363: 		    #&appenv('request.ambiguous' => $thisfn);
1.620     albertel 6364: 		    #return $env{$cache_str}='';
1.601     albertel 6365: 		#}    
                   6366: 		#$syval.=$1;
                   6367: 	    #}
1.37      www      6368:         } else {
                   6369: # ------------------------------------------------------- Was not in symb table
1.620     albertel 6370:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 6371:                             &GDBM_READER(),0640)) {
1.37      www      6372: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      6373:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      6374:               unless ($ids) { 
                   6375:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      6376:               }
                   6377:               unless ($ids) {
                   6378: # alias?
                   6379: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      6380:               }
1.37      www      6381:               if ($ids) {
                   6382: # ------------------------------------------------------------------- Has ID(s)
                   6383:                  my @possibilities=split(/\,/,$ids);
1.39      www      6384:                  if ($#possibilities==0) {
                   6385: # ----------------------------------------------- There is only one possibility
1.37      www      6386: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 6387: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   6388: 						    $resid,$thisfn);
1.249     www      6389:                  } elsif (!$donotrecurse) {
1.39      www      6390: # ------------------------------------------ There is more than one possibility
                   6391:                      my $realpossible=0;
1.191     harris41 6392:                      foreach (@possibilities) {
1.39      www      6393: 			 my $file=$bighash{'src_'.$_};
                   6394:                          if (&allowed('bre',$file)) {
                   6395:          		    my ($mapid,$resid)=split(/\./,$_);
                   6396:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   6397: 				$realpossible++;
1.626     albertel 6398:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   6399: 						    $resid,$thisfn);
1.39      www      6400:                             }
                   6401: 			 }
1.191     harris41 6402:                      }
1.39      www      6403: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      6404:                  } else {
                   6405:                      $syval='';
1.37      www      6406:                  }
                   6407: 	      }
                   6408:               untie(%bighash)
1.481     raeburn  6409:            }
1.31      www      6410:         }
1.62      www      6411:         if ($syval) {
1.620     albertel 6412: 	    return $env{$cache_str}=$syval;
1.62      www      6413:         }
1.31      www      6414:     }
1.44      www      6415:     &appenv('request.ambiguous' => $thisfn);
1.620     albertel 6416:     return $env{$cache_str}='';
1.31      www      6417: }
                   6418: 
                   6419: # ---------------------------------------------------------- Return random seed
                   6420: 
1.32      www      6421: sub numval {
                   6422:     my $txt=shift;
                   6423:     $txt=~tr/A-J/0-9/;
                   6424:     $txt=~tr/a-j/0-9/;
                   6425:     $txt=~tr/K-T/0-9/;
                   6426:     $txt=~tr/k-t/0-9/;
                   6427:     $txt=~tr/U-Z/0-5/;
                   6428:     $txt=~tr/u-z/0-5/;
                   6429:     $txt=~s/\D//g;
1.564     albertel 6430:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      6431:     return int($txt);
1.368     albertel 6432: }
                   6433: 
1.484     albertel 6434: sub numval2 {
                   6435:     my $txt=shift;
                   6436:     $txt=~tr/A-J/0-9/;
                   6437:     $txt=~tr/a-j/0-9/;
                   6438:     $txt=~tr/K-T/0-9/;
                   6439:     $txt=~tr/k-t/0-9/;
                   6440:     $txt=~tr/U-Z/0-5/;
                   6441:     $txt=~tr/u-z/0-5/;
                   6442:     $txt=~s/\D//g;
                   6443:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   6444:     my $total;
                   6445:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 6446:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 6447:     return int($total);
                   6448: }
                   6449: 
1.575     albertel 6450: sub numval3 {
                   6451:     use integer;
                   6452:     my $txt=shift;
                   6453:     $txt=~tr/A-J/0-9/;
                   6454:     $txt=~tr/a-j/0-9/;
                   6455:     $txt=~tr/K-T/0-9/;
                   6456:     $txt=~tr/k-t/0-9/;
                   6457:     $txt=~tr/U-Z/0-5/;
                   6458:     $txt=~tr/u-z/0-5/;
                   6459:     $txt=~s/\D//g;
                   6460:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   6461:     my $total;
                   6462:     foreach my $val (@txts) { $total+=$val; }
                   6463:     if ($_64bit) { $total=(($total<<32)>>32); }
                   6464:     return $total;
                   6465: }
                   6466: 
1.675     albertel 6467: sub digest {
                   6468:     my ($data)=@_;
                   6469:     my $digest=&Digest::MD5::md5($data);
                   6470:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   6471:     my ($e,$f);
                   6472:     {
                   6473:         use integer;
                   6474:         $e=($a+$b);
                   6475:         $f=($c+$d);
                   6476:         if ($_64bit) {
                   6477:             $e=(($e<<32)>>32);
                   6478:             $f=(($f<<32)>>32);
                   6479:         }
                   6480:     }
                   6481:     if (wantarray) {
                   6482: 	return ($e,$f);
                   6483:     } else {
                   6484: 	my $g;
                   6485: 	{
                   6486: 	    use integer;
                   6487: 	    $g=($e+$f);
                   6488: 	    if ($_64bit) {
                   6489: 		$g=(($g<<32)>>32);
                   6490: 	    }
                   6491: 	}
                   6492: 	return $g;
                   6493:     }
                   6494: }
                   6495: 
1.368     albertel 6496: sub latest_rnd_algorithm_id {
1.675     albertel 6497:     return '64bit5';
1.366     albertel 6498: }
1.32      www      6499: 
1.503     albertel 6500: sub get_rand_alg {
                   6501:     my ($courseid)=@_;
                   6502:     if (!$courseid) { $courseid=(&Apache::lonxml::whichuser())[1]; }
                   6503:     if ($courseid) {
1.620     albertel 6504: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 6505:     }
                   6506:     return &latest_rnd_algorithm_id();
                   6507: }
                   6508: 
1.562     albertel 6509: sub validCODE {
                   6510:     my ($CODE)=@_;
                   6511:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   6512:     return 0;
                   6513: }
                   6514: 
1.491     albertel 6515: sub getCODE {
1.620     albertel 6516:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 6517:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   6518: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   6519: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 6520: 	return $Apache::lonhomework::history{'resource.CODE'};
                   6521:     }
                   6522:     return undef;
                   6523: }
                   6524: 
1.31      www      6525: sub rndseed {
1.155     albertel 6526:     my ($symb,$courseid,$domain,$username)=@_;
1.366     albertel 6527: 
                   6528:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&Apache::lonxml::whichuser();
1.155     albertel 6529:     if (!$symb) {
1.366     albertel 6530: 	unless ($symb=$wsymb) { return time; }
                   6531:     }
                   6532:     if (!$courseid) { $courseid=$wcourseid; }
                   6533:     if (!$domain) { $domain=$wdomain; }
                   6534:     if (!$username) { $username=$wusername }
1.503     albertel 6535:     my $which=&get_rand_alg();
1.491     albertel 6536:     if (defined(&getCODE())) {
1.675     albertel 6537: 	if ($which eq '64bit5') {
                   6538: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   6539: 	} elsif ($which eq '64bit4') {
1.575     albertel 6540: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   6541: 	} else {
                   6542: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   6543: 	}
1.675     albertel 6544:     } elsif ($which eq '64bit5') {
                   6545: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 6546:     } elsif ($which eq '64bit4') {
                   6547: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 6548:     } elsif ($which eq '64bit3') {
                   6549: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 6550:     } elsif ($which eq '64bit2') {
                   6551: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 6552:     } elsif ($which eq '64bit') {
                   6553: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   6554:     }
                   6555:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   6556: }
                   6557: 
                   6558: sub rndseed_32bit {
                   6559:     my ($symb,$courseid,$domain,$username)=@_;
                   6560:     {
                   6561: 	use integer;
                   6562: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   6563: 	my $symbseed=numval($symb) << 22;
                   6564: 	my $namechck=unpack("%32C*",$username) << 17;
                   6565: 	my $nameseed=numval($username) << 12;
                   6566: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   6567: 	my $courseseed=unpack("%32C*",$courseid);
                   6568: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
                   6569: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6570: 	#&Apache::lonxml::debug("rndseed :$num:$symb");
1.564     albertel 6571: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 6572: 	return $num;
                   6573:     }
                   6574: }
                   6575: 
                   6576: sub rndseed_64bit {
                   6577:     my ($symb,$courseid,$domain,$username)=@_;
                   6578:     {
                   6579: 	use integer;
                   6580: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   6581: 	my $symbseed=numval($symb) << 10;
                   6582: 	my $namechck=unpack("%32S*",$username);
                   6583: 	
                   6584: 	my $nameseed=numval($username) << 21;
                   6585: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   6586: 	my $courseseed=unpack("%32S*",$courseid);
                   6587: 	
                   6588: 	my $num1=$symbchck+$symbseed+$namechck;
                   6589: 	my $num2=$nameseed+$domainseed+$courseseed;
                   6590: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6591: 	#&Apache::lonxml::debug("rndseed :$num:$symb");
1.564     albertel 6592: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   6593: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 6594: 	return "$num1,$num2";
1.155     albertel 6595:     }
1.366     albertel 6596: }
                   6597: 
1.443     albertel 6598: sub rndseed_64bit2 {
                   6599:     my ($symb,$courseid,$domain,$username)=@_;
                   6600:     {
                   6601: 	use integer;
                   6602: 	# strings need to be an even # of cahracters long, it it is odd the
                   6603:         # last characters gets thrown away
                   6604: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6605: 	my $symbseed=numval($symb) << 10;
                   6606: 	my $namechck=unpack("%32S*",$username.' ');
                   6607: 	
                   6608: 	my $nameseed=numval($username) << 21;
1.501     albertel 6609: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   6610: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6611: 	
                   6612: 	my $num1=$symbchck+$symbseed+$namechck;
                   6613: 	my $num2=$nameseed+$domainseed+$courseseed;
                   6614: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6615: 	#&Apache::lonxml::debug("rndseed :$num:$symb");
                   6616: 	return "$num1,$num2";
                   6617:     }
                   6618: }
                   6619: 
                   6620: sub rndseed_64bit3 {
                   6621:     my ($symb,$courseid,$domain,$username)=@_;
                   6622:     {
                   6623: 	use integer;
                   6624: 	# strings need to be an even # of cahracters long, it it is odd the
                   6625:         # last characters gets thrown away
                   6626: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6627: 	my $symbseed=numval2($symb) << 10;
                   6628: 	my $namechck=unpack("%32S*",$username.' ');
                   6629: 	
                   6630: 	my $nameseed=numval2($username) << 21;
1.443     albertel 6631: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   6632: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6633: 	
                   6634: 	my $num1=$symbchck+$symbseed+$namechck;
                   6635: 	my $num2=$nameseed+$domainseed+$courseseed;
                   6636: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
1.564     albertel 6637: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$_64bit");
                   6638: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   6639: 	
1.503     albertel 6640: 	return "$num1:$num2";
1.443     albertel 6641:     }
                   6642: }
                   6643: 
1.575     albertel 6644: sub rndseed_64bit4 {
                   6645:     my ($symb,$courseid,$domain,$username)=@_;
                   6646:     {
                   6647: 	use integer;
                   6648: 	# strings need to be an even # of cahracters long, it it is odd the
                   6649:         # last characters gets thrown away
                   6650: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6651: 	my $symbseed=numval3($symb) << 10;
                   6652: 	my $namechck=unpack("%32S*",$username.' ');
                   6653: 	
                   6654: 	my $nameseed=numval3($username) << 21;
                   6655: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   6656: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6657: 	
                   6658: 	my $num1=$symbchck+$symbseed+$namechck;
                   6659: 	my $num2=$nameseed+$domainseed+$courseseed;
                   6660: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6661: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$_64bit");
                   6662: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   6663: 	
                   6664: 	return "$num1:$num2";
                   6665:     }
                   6666: }
                   6667: 
1.675     albertel 6668: sub rndseed_64bit5 {
                   6669:     my ($symb,$courseid,$domain,$username)=@_;
                   6670:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   6671:     return "$num1:$num2";
                   6672: }
                   6673: 
1.366     albertel 6674: sub rndseed_CODE_64bit {
                   6675:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 6676:     {
1.366     albertel 6677: 	use integer;
1.443     albertel 6678: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 6679: 	my $symbseed=numval2($symb);
1.491     albertel 6680: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   6681: 	my $CODEseed=numval(&getCODE());
1.443     albertel 6682: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 6683: 	my $num1=$symbseed+$CODEchck;
                   6684: 	my $num2=$CODEseed+$courseseed+$symbchck;
                   6685: 	#&Apache::lonxml::debug("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
1.366     albertel 6686: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$symb");
1.564     albertel 6687: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   6688: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 6689: 	return "$num1:$num2";
1.366     albertel 6690:     }
                   6691: }
                   6692: 
1.575     albertel 6693: sub rndseed_CODE_64bit4 {
                   6694:     my ($symb,$courseid,$domain,$username)=@_;
                   6695:     {
                   6696: 	use integer;
                   6697: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   6698: 	my $symbseed=numval3($symb);
                   6699: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   6700: 	my $CODEseed=numval3(&getCODE());
                   6701: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6702: 	my $num1=$symbseed+$CODEchck;
                   6703: 	my $num2=$CODEseed+$courseseed+$symbchck;
                   6704: 	#&Apache::lonxml::debug("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   6705: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$symb");
                   6706: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   6707: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   6708: 	return "$num1:$num2";
                   6709:     }
                   6710: }
                   6711: 
1.675     albertel 6712: sub rndseed_CODE_64bit5 {
                   6713:     my ($symb,$courseid,$domain,$username)=@_;
                   6714:     my $code = &getCODE();
                   6715:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   6716:     return "$num1:$num2";
                   6717: }
                   6718: 
1.366     albertel 6719: sub setup_random_from_rndseed {
                   6720:     my ($rndseed)=@_;
1.503     albertel 6721:     if ($rndseed =~/([,:])/) {
                   6722: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 6723: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   6724:     } else {
                   6725: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 6726:     }
1.36      albertel 6727: }
                   6728: 
1.474     albertel 6729: sub latest_receipt_algorithm_id {
                   6730:     return 'receipt2';
                   6731: }
                   6732: 
1.480     www      6733: sub recunique {
                   6734:     my $fucourseid=shift;
                   6735:     my $unique;
1.620     albertel 6736:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   6737: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      6738:     } else {
                   6739: 	$unique=$perlvar{'lonReceipt'};
                   6740:     }
                   6741:     return unpack("%32C*",$unique);
                   6742: }
                   6743: 
                   6744: sub recprefix {
                   6745:     my $fucourseid=shift;
                   6746:     my $prefix;
1.620     albertel 6747:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   6748: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      6749:     } else {
                   6750: 	$prefix=$perlvar{'lonHostID'};
                   6751:     }
                   6752:     return unpack("%32C*",$prefix);
                   6753: }
                   6754: 
1.76      www      6755: sub ireceipt {
1.474     albertel 6756:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.76      www      6757:     my $cuname=unpack("%32C*",$funame);
                   6758:     my $cudom=unpack("%32C*",$fudom);
                   6759:     my $cucourseid=unpack("%32C*",$fucourseid);
                   6760:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      6761:     my $cunique=&recunique($fucourseid);
1.474     albertel 6762:     my $cpart=unpack("%32S*",$part);
1.480     www      6763:     my $return =&recprefix($fucourseid).'-';
1.620     albertel 6764:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   6765: 	$env{'request.state'} eq 'construct') {
1.474     albertel 6766: 	&Apache::lonxml::debug("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname).
                   6767: 			       " and ".($cpart%$cudom));
                   6768: 			       
                   6769: 	$return.= ($cunique%$cuname+
                   6770: 		   $cunique%$cudom+
                   6771: 		   $cusymb%$cuname+
                   6772: 		   $cusymb%$cudom+
                   6773: 		   $cucourseid%$cuname+
                   6774: 		   $cucourseid%$cudom+
                   6775: 		   $cpart%$cuname+
                   6776: 		   $cpart%$cudom);
                   6777:     } else {
                   6778: 	$return.= ($cunique%$cuname+
                   6779: 		   $cunique%$cudom+
                   6780: 		   $cusymb%$cuname+
                   6781: 		   $cusymb%$cudom+
                   6782: 		   $cucourseid%$cuname+
                   6783: 		   $cucourseid%$cudom);
                   6784:     }
                   6785:     return $return;
1.76      www      6786: }
                   6787: 
                   6788: sub receipt {
1.474     albertel 6789:     my ($part)=@_;
                   6790:     my ($symb,$courseid,$domain,$name) = &Apache::lonxml::whichuser();
                   6791:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      6792: }
1.260     ng       6793: 
1.36      albertel 6794: # ------------------------------------------------------------ Serves up a file
1.472     albertel 6795: # returns either the contents of the file or 
                   6796: # -1 if the file doesn't exist
1.481     raeburn  6797: #
                   6798: # if the target is a file that was uploaded via DOCS, 
                   6799: # a check will be made to see if a current copy exists on the local server,
                   6800: # if it does this will be served, otherwise a copy will be retrieved from
                   6801: # the home server for the course and stored in /home/httpd/html/userfiles on
                   6802: # the local server.   
1.472     albertel 6803: 
1.36      albertel 6804: sub getfile {
1.538     albertel 6805:     my ($file) = @_;
1.609     banghart 6806:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 6807:     &repcopy($file);
                   6808:     return &readfile($file);
                   6809: }
                   6810: 
                   6811: sub repcopy_userfile {
                   6812:     my ($file)=@_;
1.609     banghart 6813:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 6814:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 6815:     my ($cdom,$cnum,$filename) = 
                   6816: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+([^/]+)/+([^/]+)/+(.*)|);
                   6817:     my ($info,$rtncode);
                   6818:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   6819:     if (-e "$file") {
                   6820: 	my @fileinfo = stat($file);
                   6821: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 6822: 	if ($lwpresp ne 'ok') {
                   6823: 	    if ($rtncode eq '404') {
1.538     albertel 6824: 		unlink($file);
1.482     albertel 6825: 	    }
1.517     albertel 6826: 	    #my $ua=new LWP::UserAgent;
1.538     albertel 6827: 	    #my $request=new HTTP::Request('GET',&tokenwrapper($uri));
1.517     albertel 6828: 	    #my $response=$ua->request($request);
                   6829: 	    #if ($response->is_success()) {
                   6830: 	#	return $response->content;
                   6831: 	#    } else {
                   6832: 	#	return -1;
                   6833: 	#    }
1.482     albertel 6834: 	    return -1;
                   6835: 	}
                   6836: 	if ($info < $fileinfo[9]) {
1.607     raeburn  6837: 	    return 'ok';
1.482     albertel 6838: 	}
                   6839: 	$info = '';
1.538     albertel 6840: 	$lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 6841: 	if ($lwpresp ne 'ok') {
                   6842: 	    return -1;
                   6843: 	}
                   6844:     } else {
1.538     albertel 6845: 	my $lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 6846: 	if ($lwpresp ne 'ok') {
1.517     albertel 6847: 	    my $ua=new LWP::UserAgent;
1.538     albertel 6848: 	    my $request=new HTTP::Request('GET',&tokenwrapper($uri));
1.517     albertel 6849: 	    my $response=$ua->request($request);
                   6850: 	    if ($response->is_success()) {
1.538     albertel 6851: 		$info=$response->content;
1.517     albertel 6852: 	    } else {
                   6853: 		return -1;
                   6854: 	    }
1.482     albertel 6855: 	}
                   6856: 	my @parts = ($cdom,$cnum); 
                   6857: 	if ($filename =~ m|^(.+)/[^/]+$|) {
                   6858: 	    push @parts, split(/\//,$1);
1.518     albertel 6859: 	}
1.538     albertel 6860: 	my $path = $perlvar{'lonDocRoot'}.'/userfiles';
1.482     albertel 6861: 	foreach my $part (@parts) {
                   6862: 	    $path .= '/'.$part;
                   6863: 	    if (!-e $path) {
                   6864: 		mkdir($path,0770);
                   6865: 	    }
                   6866: 	}
                   6867:     }
1.538     albertel 6868:     open(FILE,">$file");
1.482     albertel 6869:     print FILE $info;
                   6870:     close(FILE);
1.607     raeburn  6871:     return 'ok';
1.481     raeburn  6872: }
                   6873: 
1.517     albertel 6874: sub tokenwrapper {
                   6875:     my $uri=shift;
1.552     albertel 6876:     $uri=~s|^http\://([^/]+)||;
                   6877:     $uri=~s|^/||;
1.620     albertel 6878:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 6879:     my $token=$1;
1.552     albertel 6880:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   6881:     if ($udom && $uname && $file) {
                   6882: 	$file=~s|(\?\.*)*$||;
1.620     albertel 6883:         &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
1.552     albertel 6884:         return 'http://'.$hostname{ &homeserver($uname,$udom)}.'/'.$uri.
1.517     albertel 6885:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   6886:                                '&tokenissued='.$perlvar{'lonHostID'};
                   6887:     } else {
                   6888:         return '/adm/notfound.html';
                   6889:     }
                   6890: }
                   6891: 
1.481     raeburn  6892: sub getuploaded {
                   6893:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   6894:     $uri=~s/^\///;
                   6895:     $uri = 'http://'.$hostname{ &homeserver($cnum,$cdom)}.'/raw/'.$uri;
                   6896:     my $ua=new LWP::UserAgent;
                   6897:     my $request=new HTTP::Request($reqtype,$uri);
                   6898:     my $response=$ua->request($request);
                   6899:     $$rtncode = $response->code;
1.482     albertel 6900:     if (! $response->is_success()) {
                   6901: 	return 'failed';
                   6902:     }      
                   6903:     if ($reqtype eq 'HEAD') {
1.486     www      6904: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 6905:     } elsif ($reqtype eq 'GET') {
                   6906: 	$$info = $response->content;
1.472     albertel 6907:     }
1.482     albertel 6908:     return 'ok';
1.36      albertel 6909: }
                   6910: 
1.481     raeburn  6911: sub readfile {
                   6912:     my $file = shift;
                   6913:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   6914:     my $fh;
                   6915:     open($fh,"<$file");
                   6916:     my $a='';
                   6917:     while (<$fh>) { $a .=$_; }
                   6918:     return $a;
                   6919: }
                   6920: 
1.36      albertel 6921: sub filelocation {
1.590     banghart 6922:     my ($dir,$file) = @_;
                   6923:     my $location;
                   6924:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 6925: 
                   6926:     if ($file =~ m-^/adm/-) {
                   6927: 	$file=~s-^/adm/wrapper/-/-;
                   6928: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   6929:     }
1.590     banghart 6930:     if ($file=~m:^/~:) { # is a contruction space reference
                   6931:         $location = $file;
                   6932:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.649     albertel 6933:     } elsif ($file=~m:^/home/[^/]*/public_html/:) {
                   6934: 	# is a correct contruction space reference
                   6935:         $location = $file;
1.609     banghart 6936:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 6937:         my ($udom,$uname,$filename)=
1.609     banghart 6938:   	    ($file=~m -^/+(?:uploaded|editupload)/+([^/]+)/+([^/]+)/+(.*)$-);
1.590     banghart 6939:         my $home=&homeserver($uname,$udom);
                   6940:         my $is_me=0;
                   6941:         my @ids=&current_machine_ids();
                   6942:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   6943:         if ($is_me) {
1.740     www      6944:   	    $location=&propath($udom,$uname).
1.590     banghart 6945:   	      '/userfiles/'.$filename;
                   6946:         } else {
                   6947:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   6948:   	      $udom.'/'.$uname.'/'.$filename;
                   6949:         }
                   6950:     } else {
                   6951:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   6952:         $file=~s:^/res/:/:;
                   6953:         if ( !( $file =~ m:^/:) ) {
                   6954:             $location = $dir. '/'.$file;
                   6955:         } else {
                   6956:             $location = '/home/httpd/html/res'.$file;
                   6957:         }
1.59      albertel 6958:     }
1.590     banghart 6959:     $location=~s://+:/:g; # remove duplicate /
                   6960:     while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
                   6961:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   6962:     return $location;
1.46      www      6963: }
1.36      albertel 6964: 
1.46      www      6965: sub hreflocation {
                   6966:     my ($dir,$file)=@_;
1.460     albertel 6967:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
1.666     albertel 6968: 	$file=filelocation($dir,$file);
1.700     albertel 6969:     } elsif ($file=~m-^/adm/-) {
                   6970: 	$file=~s-^/adm/wrapper/-/-;
                   6971: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 6972:     }
                   6973:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   6974: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   6975:     } elsif ($file=~m-/home/(\w+)/public_html/-) {
1.462     albertel 6976: 	$file=~s-^/home/(\w+)/public_html/-/~$1/-;
1.666     albertel 6977:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
                   6978: 	$file=~s-^/home/httpd/lonUsers/([^/]*)/./././([^/]*)/userfiles/
                   6979: 	    -/uploaded/$1/$2/-x;
1.46      www      6980:     }
1.462     albertel 6981:     return $file;
1.465     albertel 6982: }
                   6983: 
                   6984: sub current_machine_domains {
                   6985:     my $hostname=$hostname{$perlvar{'lonHostID'}};
                   6986:     my @domains;
                   6987:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  6988: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 6989: 	if ($hostname eq $name) {
                   6990: 	    push(@domains,$hostdom{$id});
                   6991: 	}
                   6992:     }
                   6993:     return @domains;
                   6994: }
                   6995: 
                   6996: sub current_machine_ids {
                   6997:     my $hostname=$hostname{$perlvar{'lonHostID'}};
                   6998:     my @ids;
                   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(@ids,$id);
                   7003: 	}
                   7004:     }
                   7005:     return @ids;
1.31      www      7006: }
                   7007: 
                   7008: # ------------------------------------------------------------- Declutters URLs
                   7009: 
                   7010: sub declutter {
                   7011:     my $thisfn=shift;
1.569     albertel 7012:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 7013:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      7014:     $thisfn=~s/^\///;
1.697     albertel 7015:     $thisfn=~s|^adm/wrapper/||;
                   7016:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      7017:     $thisfn=~s/^res\///;
1.235     www      7018:     $thisfn=~s/\?.+$//;
1.268     www      7019:     return $thisfn;
                   7020: }
                   7021: 
                   7022: # ------------------------------------------------------------- Clutter up URLs
                   7023: 
                   7024: sub clutter {
                   7025:     my $thisfn='/'.&declutter(shift);
1.609     banghart 7026:     unless ($thisfn=~/^\/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)\//) { 
1.270     www      7027:        $thisfn='/res'.$thisfn; 
                   7028:     }
1.694     albertel 7029:     if ($thisfn !~m|/adm|) {
1.695     albertel 7030: 	if ($thisfn =~ m|/ext/|) {
1.694     albertel 7031: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 7032: 	} else {
                   7033: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   7034: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 7035: 	    if ($embstyle eq 'ssi'
                   7036: 		|| ($embstyle eq 'hdn')
                   7037: 		|| ($embstyle eq 'rat')
                   7038: 		|| ($embstyle eq 'prv')
                   7039: 		|| ($embstyle eq 'ign')) {
                   7040: 		#do nothing with these
                   7041: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 7042: 		|| ($embstyle eq 'emb')
                   7043: 		|| ($embstyle eq 'wrp')) {
                   7044: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 7045: 	    } elsif ($embstyle eq 'unk'
                   7046: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 7047: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 7048: 	    } else {
1.718     www      7049: #		&logthis("Got a blank emb style");
1.695     albertel 7050: 	    }
1.694     albertel 7051: 	}
                   7052:     }
1.31      www      7053:     return $thisfn;
1.12      www      7054: }
                   7055: 
1.557     albertel 7056: sub freeze_escape {
                   7057:     my ($value)=@_;
                   7058:     if (ref($value)) {
                   7059: 	$value=&nfreeze($value);
                   7060: 	return '__FROZEN__'.&escape($value);
                   7061:     }
                   7062:     return &escape($value);
                   7063: }
                   7064: 
1.11      www      7065: 
1.557     albertel 7066: sub thaw_unescape {
                   7067:     my ($value)=@_;
                   7068:     if ($value =~ /^__FROZEN__/) {
                   7069: 	substr($value,0,10,undef);
                   7070: 	$value=&unescape($value);
                   7071: 	return &thaw($value);
                   7072:     }
                   7073:     return &unescape($value);
                   7074: }
                   7075: 
1.436     albertel 7076: sub correct_line_ends {
                   7077:     my ($result)=@_;
                   7078:     $$result =~s/\r\n/\n/mg;
                   7079:     $$result =~s/\r/\n/mg;
1.415     albertel 7080: }
1.1       albertel 7081: # ================================================================ Main Program
                   7082: 
1.184     www      7083: sub goodbye {
1.204     albertel 7084:    &logthis("Starting Shut down");
1.443     albertel 7085: #not converted to using infrastruture and probably shouldn't be
1.599     albertel 7086:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&freeze(\%badServerCache))));
1.443     albertel 7087: #converted
1.599     albertel 7088: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
                   7089:    &logthis(sprintf("%-20s is %s",'%homecache',length(&freeze(\%homecache))));
                   7090: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&freeze(\%titlecache))));
                   7091: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&freeze(\%courseresdatacache))));
1.425     albertel 7092: #1.1 only
1.599     albertel 7093: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&freeze(\%userresdatacache))));
                   7094: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&freeze(\%getsectioncache))));
                   7095: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&freeze(\%courseresversioncache))));
                   7096: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&freeze(\%resversioncache))));
                   7097:    &logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
                   7098:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   7099:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      7100:    &flushcourselogs();
                   7101:    &logthis("Shutting down");
                   7102: }
                   7103: 
1.179     www      7104: BEGIN {
1.228     harris41 7105: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
1.195     www      7106:     unless ($readit) {
1.217     harris41 7107: {
1.781     raeburn  7108:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   7109:     %perlvar = (%perlvar,%{$configvars});
1.227     harris41 7110: }
1.1       albertel 7111: 
1.327     albertel 7112: # ------------------------------------------------------------ Read domain file
                   7113: {
                   7114:     %domaindescription = ();
                   7115:     %domain_auth_def = ();
                   7116:     %domain_auth_arg_def = ();
1.448     albertel 7117:     my $fh;
                   7118:     if (open($fh,"<".$Apache::lonnet::perlvar{'lonTabDir'}.'/domain.tab')) {
1.327     albertel 7119:        while (<$fh>) {
1.390     matthew  7120:            next if (/^(\#|\s*$)/);
                   7121: #           next if /^\#/;
1.327     albertel 7122:            chomp;
1.403     www      7123:            my ($domain, $domain_description, $def_auth, $def_auth_arg,
1.685     raeburn  7124: 	       $def_lang, $city, $longi, $lati, $primary) = split(/:/,$_);
1.403     www      7125: 	   $domain_auth_def{$domain}=$def_auth;
1.327     albertel 7126:            $domain_auth_arg_def{$domain}=$def_auth_arg;
1.403     www      7127: 	   $domaindescription{$domain}=$domain_description;
                   7128: 	   $domain_lang_def{$domain}=$def_lang;
                   7129: 	   $domain_city{$domain}=$city;
                   7130: 	   $domain_longi{$domain}=$longi;
                   7131: 	   $domain_lati{$domain}=$lati;
1.685     raeburn  7132:            $domain_primary{$domain}=$primary;
1.403     www      7133: 
1.448     albertel 7134:  #         &logthis("Domain.tab: $domain, $domain_auth_def{$domain}, $domain_auth_arg_def{$domain},$domaindescription{$domain}");
1.327     albertel 7135: #          &logthis("Domain.tab: $domain ".$domaindescription{$domain} );
1.448     albertel 7136: 	}
1.327     albertel 7137:     }
1.448     albertel 7138:     close ($fh);
1.327     albertel 7139: }
                   7140: 
                   7141: 
1.1       albertel 7142: # ------------------------------------------------------------- Read hosts file
                   7143: {
1.448     albertel 7144:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
1.1       albertel 7145: 
                   7146:     while (my $configline=<$config>) {
1.303     matthew  7147:        next if ($configline =~ /^(\#|\s*$)/);
1.154     www      7148:        chomp($configline);
1.595     albertel 7149:        my ($id,$domain,$role,$name)=split(/:/,$configline);
1.597     albertel 7150:        $name=~s/\s//g;
1.595     albertel 7151:        if ($id && $domain && $role && $name) {
1.252     albertel 7152: 	 $hostname{$id}=$name;
                   7153: 	 $hostdom{$id}=$domain;
                   7154: 	 if ($role eq 'library') { $libserv{$id}=$name; }
1.245     www      7155:        }
1.1       albertel 7156:     }
1.448     albertel 7157:     close($config);
1.619     albertel 7158:     # FIXME: dev server don't want this, production servers _do_ want this
1.654     albertel 7159:     #&get_iphost();
1.1       albertel 7160: }
                   7161: 
1.598     albertel 7162: sub get_iphost {
                   7163:     if (%iphost) { return %iphost; }
1.653     albertel 7164:     my %name_to_ip;
1.598     albertel 7165:     foreach my $id (keys(%hostname)) {
                   7166: 	my $name=$hostname{$id};
1.653     albertel 7167: 	my $ip;
                   7168: 	if (!exists($name_to_ip{$name})) {
                   7169: 	    $ip = gethostbyname($name);
                   7170: 	    if (!$ip || length($ip) ne 4) {
                   7171: 		&logthis("Skipping host $id name $name no IP found\n");
                   7172: 		next;
                   7173: 	    }
                   7174: 	    $ip=inet_ntoa($ip);
                   7175: 	    $name_to_ip{$name} = $ip;
                   7176: 	} else {
                   7177: 	    $ip = $name_to_ip{$name};
1.598     albertel 7178: 	}
                   7179: 	push(@{$iphost{$ip}},$id);
                   7180:     }
                   7181:     return %iphost;
                   7182: }
                   7183: 
1.1       albertel 7184: # ------------------------------------------------------ Read spare server file
                   7185: {
1.448     albertel 7186:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 7187: 
                   7188:     while (my $configline=<$config>) {
                   7189:        chomp($configline);
1.284     matthew  7190:        if ($configline) {
1.784     albertel 7191: 	   my ($host,$type) = split(':',$configline,2);
1.785   ! albertel 7192: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 7193: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 7194:        }
                   7195:     }
1.448     albertel 7196:     close($config);
1.1       albertel 7197: }
1.11      www      7198: # ------------------------------------------------------------ Read permissions
                   7199: {
1.448     albertel 7200:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      7201: 
                   7202:     while (my $configline=<$config>) {
1.448     albertel 7203: 	chomp($configline);
                   7204: 	if ($configline) {
                   7205: 	    my ($role,$perm)=split(/ /,$configline);
                   7206: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   7207: 	}
1.11      www      7208:     }
1.448     albertel 7209:     close($config);
1.11      www      7210: }
                   7211: 
                   7212: # -------------------------------------------- Read plain texts for permissions
                   7213: {
1.448     albertel 7214:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      7215: 
                   7216:     while (my $configline=<$config>) {
1.448     albertel 7217: 	chomp($configline);
                   7218: 	if ($configline) {
1.742     raeburn  7219: 	    my ($short,@plain)=split(/:/,$configline);
                   7220:             %{$prp{$short}} = ();
                   7221: 	    if (@plain > 0) {
                   7222:                 $prp{$short}{'std'} = $plain[0];
                   7223:                 for (my $i=1; $i<@plain; $i++) {
                   7224:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   7225:                 }
                   7226:             }
1.448     albertel 7227: 	}
1.135     www      7228:     }
1.448     albertel 7229:     close($config);
1.135     www      7230: }
                   7231: 
                   7232: # ---------------------------------------------------------- Read package table
                   7233: {
1.448     albertel 7234:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      7235: 
                   7236:     while (my $configline=<$config>) {
1.483     albertel 7237: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 7238: 	chomp($configline);
                   7239: 	my ($short,$plain)=split(/:/,$configline);
                   7240: 	my ($pack,$name)=split(/\&/,$short);
                   7241: 	if ($plain ne '') {
                   7242: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   7243: 	    $packagetab{$short}=$plain; 
                   7244: 	}
1.11      www      7245:     }
1.448     albertel 7246:     close($config);
1.329     matthew  7247: }
                   7248: 
                   7249: # ------------- set up temporary directory
                   7250: {
                   7251:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   7252: 
1.11      www      7253: }
                   7254: 
1.599     albertel 7255: $memcache=new Cache::Memcached({'servers'=>['127.0.0.1:11211']});
1.185     www      7256: 
1.281     www      7257: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      7258: $dumpcount=0;
1.22      www      7259: 
1.163     harris41 7260: &logtouch();
1.672     albertel 7261: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      7262: $readit=1;
1.564     albertel 7263:     {
                   7264: 	use integer;
                   7265: 	my $test=(2**32)+1;
1.568     albertel 7266: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 7267: 	&logthis(" Detected 64bit platform ($_64bit)");
                   7268:     }
1.195     www      7269: }
1.1       albertel 7270: }
1.179     www      7271: 
1.1       albertel 7272: 1;
1.191     harris41 7273: __END__
                   7274: 
1.243     albertel 7275: =pod
                   7276: 
1.191     harris41 7277: =head1 NAME
                   7278: 
1.243     albertel 7279: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 7280: 
                   7281: =head1 SYNOPSIS
                   7282: 
1.243     albertel 7283: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 7284: 
                   7285:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   7286: 
1.243     albertel 7287: Common parameters:
                   7288: 
                   7289: =over 4
                   7290: 
                   7291: =item *
                   7292: 
                   7293: $uname : an internal username (if $cname expecting a course Id specifically)
                   7294: 
                   7295: =item *
                   7296: 
                   7297: $udom : a domain (if $cdom expecting a course's domain specifically)
                   7298: 
                   7299: =item *
                   7300: 
                   7301: $symb : a resource instance identifier
                   7302: 
                   7303: =item *
                   7304: 
                   7305: $namespace : the name of a .db file that contains the data needed or
                   7306: being set.
                   7307: 
                   7308: =back
                   7309: 
1.394     bowersj2 7310: =head1 OVERVIEW
1.191     harris41 7311: 
1.394     bowersj2 7312: lonnet provides subroutines which interact with the
                   7313: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   7314: about classes, users, and resources.
1.243     albertel 7315: 
                   7316: For many of these objects you can also use this to store data about
                   7317: them or modify them in various ways.
1.191     harris41 7318: 
1.394     bowersj2 7319: =head2 Symbs
1.191     harris41 7320: 
1.394     bowersj2 7321: To identify a specific instance of a resource, LON-CAPA uses symbols
                   7322: or "symbs"X<symb>. These identifiers are built from the URL of the
                   7323: map, the resource number of the resource in the map, and the URL of
                   7324: the resource itself. The latter is somewhat redundant, but might help
                   7325: if maps change.
                   7326: 
                   7327: An example is
                   7328: 
                   7329:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   7330: 
                   7331: The respective map entry is
                   7332: 
                   7333:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   7334:   title="Problem 2">
                   7335:  </resource>
                   7336: 
                   7337: Symbs are used by the random number generator, as well as to store and
                   7338: restore data specific to a certain instance of for example a problem.
                   7339: 
                   7340: =head2 Storing And Retrieving Data
                   7341: 
                   7342: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   7343: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   7344: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   7345: is is the non-critical message twin of cstore. These functions are for
                   7346: handlers to store a perl hash to a user's permanent data space in an
                   7347: easy manner, and to retrieve it again on another call. It is expected
                   7348: that a handler would use this once at the beginning to retrieve data,
                   7349: and then again once at the end to send only the new data back.
                   7350: 
                   7351: The data is stored in the user's data directory on the user's
                   7352: homeserver under the ID of the course.
                   7353: 
                   7354: The hash that is returned by restore will have all of the previous
                   7355: value for all of the elements of the hash.
                   7356: 
                   7357: Example:
                   7358: 
                   7359:  #creating a hash
                   7360:  my %hash;
                   7361:  $hash{'foo'}='bar';
                   7362: 
                   7363:  #storing it
                   7364:  &Apache::lonnet::cstore(\%hash);
                   7365: 
                   7366:  #changing a value
                   7367:  $hash{'foo'}='notbar';
                   7368: 
                   7369:  #adding a new value
                   7370:  $hash{'bar'}='foo';
                   7371:  &Apache::lonnet::cstore(\%hash);
                   7372: 
                   7373:  #retrieving the hash
                   7374:  my %history=&Apache::lonnet::restore();
                   7375: 
                   7376:  #print the hash
                   7377:  foreach my $key (sort(keys(%history))) {
                   7378:    print("\%history{$key} = $history{$key}");
                   7379:  }
                   7380: 
                   7381: Will print out:
1.191     harris41 7382: 
1.394     bowersj2 7383:  %history{1:foo} = bar
                   7384:  %history{1:keys} = foo:timestamp
                   7385:  %history{1:timestamp} = 990455579
                   7386:  %history{2:bar} = foo
                   7387:  %history{2:foo} = notbar
                   7388:  %history{2:keys} = foo:bar:timestamp
                   7389:  %history{2:timestamp} = 990455580
                   7390:  %history{bar} = foo
                   7391:  %history{foo} = notbar
                   7392:  %history{timestamp} = 990455580
                   7393:  %history{version} = 2
                   7394: 
                   7395: Note that the special hash entries C<keys>, C<version> and
                   7396: C<timestamp> were added to the hash. C<version> will be equal to the
                   7397: total number of versions of the data that have been stored. The
                   7398: C<timestamp> attribute will be the UNIX time the hash was
                   7399: stored. C<keys> is available in every historical section to list which
                   7400: keys were added or changed at a specific historical revision of a
                   7401: hash.
                   7402: 
                   7403: B<Warning>: do not store the hash that restore returns directly. This
                   7404: will cause a mess since it will restore the historical keys as if the
                   7405: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 7406: 
1.394     bowersj2 7407: Calling convention:
1.191     harris41 7408: 
1.394     bowersj2 7409:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   7410:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 7411: 
1.394     bowersj2 7412: For more detailed information, see lonnet specific documentation.
1.191     harris41 7413: 
1.394     bowersj2 7414: =head1 RETURN MESSAGES
1.191     harris41 7415: 
1.394     bowersj2 7416: =over 4
1.191     harris41 7417: 
1.394     bowersj2 7418: =item * B<con_lost>: unable to contact remote host
1.191     harris41 7419: 
1.394     bowersj2 7420: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   7421: when the connection is brought back up
1.191     harris41 7422: 
1.394     bowersj2 7423: =item * B<con_failed>: unable to contact remote host and unable to save message
                   7424: for later delivery
1.191     harris41 7425: 
1.394     bowersj2 7426: =item * B<error:>: an error a occured, a description of the error follows the :
1.191     harris41 7427: 
1.394     bowersj2 7428: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 7429: that was requested
1.191     harris41 7430: 
1.243     albertel 7431: =back
1.191     harris41 7432: 
1.243     albertel 7433: =head1 PUBLIC SUBROUTINES
1.191     harris41 7434: 
1.243     albertel 7435: =head2 Session Environment Functions
1.191     harris41 7436: 
1.243     albertel 7437: =over 4
1.191     harris41 7438: 
1.394     bowersj2 7439: =item * 
                   7440: X<appenv()>
                   7441: B<appenv(%hash)>: the value of %hash is written to
                   7442: the user envirnoment file, and will be restored for each access this
1.620     albertel 7443: user makes during this session, also modifies the %env for the current
1.394     bowersj2 7444: process
1.191     harris41 7445: 
                   7446: =item *
1.394     bowersj2 7447: X<delenv()>
                   7448: B<delenv($regexp)>: removes all items from the session
                   7449: environment file that matches the regular expression in $regexp. The
1.620     albertel 7450: values are also delted from the current processes %env.
1.191     harris41 7451: 
1.243     albertel 7452: =back
                   7453: 
                   7454: =head2 User Information
1.191     harris41 7455: 
1.243     albertel 7456: =over 4
1.191     harris41 7457: 
                   7458: =item *
1.394     bowersj2 7459: X<queryauthenticate()>
                   7460: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 7461: authentication scheme
                   7462: 
                   7463: =item *
1.394     bowersj2 7464: X<authenticate()>
                   7465: B<authenticate($uname,$upass,$udom)>: try to
                   7466: authenticate user from domain's lib servers (first use the current
                   7467: one). C<$upass> should be the users password.
1.191     harris41 7468: 
                   7469: =item *
1.394     bowersj2 7470: X<homeserver()>
                   7471: B<homeserver($uname,$udom)>: find the server which has
                   7472: the user's directory and files (there must be only one), this caches
                   7473: the answer, and also caches if there is a borken connection.
1.191     harris41 7474: 
                   7475: =item *
1.394     bowersj2 7476: X<idget()>
                   7477: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   7478: (IDs are a unique resource in a domain, there must be only 1 ID per
                   7479: username, and only 1 username per ID in a specific domain) (returns
                   7480: hash: id=>name,id=>name)
1.191     harris41 7481: 
                   7482: =item *
1.394     bowersj2 7483: X<idrget()>
                   7484: B<idrget($udom,@unames)>: find the IDs behind a list of
                   7485: usernames (returns hash: name=>id,name=>id)
1.191     harris41 7486: 
                   7487: =item *
1.394     bowersj2 7488: X<idput()>
                   7489: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 7490: 
                   7491: =item *
1.394     bowersj2 7492: X<rolesinit()>
                   7493: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 7494: 
                   7495: =item *
1.551     albertel 7496: X<getsection()>
                   7497: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 7498: course $cname, return section name/number or '' for "not in course"
                   7499: and '-1' for "no section"
                   7500: 
                   7501: =item *
1.394     bowersj2 7502: X<userenvironment()>
                   7503: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 7504: passed in @what from the requested user's environment, returns a hash
                   7505: 
                   7506: =back
                   7507: 
                   7508: =head2 User Roles
                   7509: 
                   7510: =over 4
                   7511: 
                   7512: =item *
                   7513: 
                   7514: allowed($priv,$uri) : check for a user privilege; returns codes for allowed
                   7515: actions
                   7516:  F: full access
                   7517:  U,I,K: authentication modes (cxx only)
                   7518:  '': forbidden
                   7519:  1: user needs to choose course
                   7520:  2: browse allowed
1.766     albertel 7521:  A: passphrase authentication needed
1.243     albertel 7522: 
                   7523: =item *
                   7524: 
                   7525: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   7526: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   7527: and course level
                   7528: 
                   7529: =item *
                   7530: 
                   7531: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
                   7532: explanation of a user role term
                   7533: 
                   7534: =back
                   7535: 
                   7536: =head2 User Modification
                   7537: 
                   7538: =over 4
                   7539: 
                   7540: =item *
                   7541: 
                   7542: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
                   7543: user for the level given by URL.  Optional start and end dates (leave empty
                   7544: string or zero for "no date")
1.191     harris41 7545: 
                   7546: =item *
                   7547: 
1.243     albertel 7548: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   7549: change a users, password, possible return values are: ok,
                   7550: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   7551: refused
1.191     harris41 7552: 
                   7553: =item *
                   7554: 
1.243     albertel 7555: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 7556: 
                   7557: =item *
                   7558: 
1.243     albertel 7559: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
                   7560: modify user
1.191     harris41 7561: 
                   7562: =item *
                   7563: 
1.286     matthew  7564: modifystudent
                   7565: 
                   7566: modify a students enrollment and identification information.
                   7567: The course id is resolved based on the current users environment.  
                   7568: This means the envoking user must be a course coordinator or otherwise
                   7569: associated with a course.
                   7570: 
1.297     matthew  7571: This call is essentially a wrapper for lonnet::modifyuser and
                   7572: lonnet::modify_student_enrollment
1.286     matthew  7573: 
                   7574: Inputs: 
                   7575: 
                   7576: =over 4
                   7577: 
                   7578: =item B<$udom> Students loncapa domain
                   7579: 
                   7580: =item B<$uname> Students loncapa login name
                   7581: 
                   7582: =item B<$uid> Students id/student number
                   7583: 
                   7584: =item B<$umode> Students authentication mode
                   7585: 
                   7586: =item B<$upass> Students password
                   7587: 
                   7588: =item B<$first> Students first name
                   7589: 
                   7590: =item B<$middle> Students middle name
                   7591: 
                   7592: =item B<$last> Students last name
                   7593: 
                   7594: =item B<$gene> Students generation
                   7595: 
                   7596: =item B<$usec> Students section in course
                   7597: 
                   7598: =item B<$end> Unix time of the roles expiration
                   7599: 
                   7600: =item B<$start> Unix time of the roles start date
                   7601: 
                   7602: =item B<$forceid> If defined, allow $uid to be changed
                   7603: 
                   7604: =item B<$desiredhome> server to use as home server for student
                   7605: 
                   7606: =back
1.297     matthew  7607: 
                   7608: =item *
                   7609: 
                   7610: modify_student_enrollment
                   7611: 
                   7612: Change a students enrollment status in a class.  The environment variable
                   7613: 'role.request.course' must be defined for this function to proceed.
                   7614: 
                   7615: Inputs:
                   7616: 
                   7617: =over 4
                   7618: 
                   7619: =item $udom, students domain
                   7620: 
                   7621: =item $uname, students name
                   7622: 
                   7623: =item $uid, students user id
                   7624: 
                   7625: =item $first, students first name
                   7626: 
                   7627: =item $middle
                   7628: 
                   7629: =item $last
                   7630: 
                   7631: =item $gene
                   7632: 
                   7633: =item $usec
                   7634: 
                   7635: =item $end
                   7636: 
                   7637: =item $start
                   7638: 
                   7639: =back
                   7640: 
1.191     harris41 7641: 
                   7642: =item *
                   7643: 
1.243     albertel 7644: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   7645: custom role; give a custom role to a user for the level given by URL.  Specify
                   7646: name and domain of role author, and role name
1.191     harris41 7647: 
                   7648: =item *
                   7649: 
1.243     albertel 7650: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 7651: 
                   7652: =item *
                   7653: 
1.243     albertel 7654: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   7655: 
                   7656: =back
                   7657: 
                   7658: =head2 Course Infomation
                   7659: 
                   7660: =over 4
1.191     harris41 7661: 
                   7662: =item *
                   7663: 
1.631     albertel 7664: coursedescription($courseid) : returns a hash of information about the
                   7665: specified course id, including all environment settings for the
                   7666: course, the description of the course will be in the hash under the
                   7667: key 'description'
1.191     harris41 7668: 
                   7669: =item *
                   7670: 
1.624     albertel 7671: resdata($name,$domain,$type,@which) : request for current parameter
                   7672: setting for a specific $type, where $type is either 'course' or 'user',
                   7673: @what should be a list of parameters to ask about. This routine caches
                   7674: answers for 5 minutes.
1.243     albertel 7675: 
                   7676: =back
                   7677: 
                   7678: =head2 Course Modification
                   7679: 
                   7680: =over 4
1.191     harris41 7681: 
                   7682: =item *
                   7683: 
1.243     albertel 7684: writecoursepref($courseid,%prefs) : write preferences (environment
                   7685: database) for a course
1.191     harris41 7686: 
                   7687: =item *
                   7688: 
1.243     albertel 7689: createcourse($udom,$description,$url) : make/modify course
                   7690: 
                   7691: =back
                   7692: 
                   7693: =head2 Resource Subroutines
                   7694: 
                   7695: =over 4
1.191     harris41 7696: 
                   7697: =item *
                   7698: 
1.243     albertel 7699: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 7700: 
                   7701: =item *
                   7702: 
1.243     albertel 7703: repcopy($filename) : subscribes to the requested file, and attempts to
                   7704: replicate from the owning library server, Might return
1.607     raeburn  7705: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   7706: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 7707: resource. Expects the local filesystem pathname
                   7708: (/home/httpd/html/res/....)
                   7709: 
                   7710: =back
                   7711: 
                   7712: =head2 Resource Information
                   7713: 
                   7714: =over 4
1.191     harris41 7715: 
                   7716: =item *
                   7717: 
1.243     albertel 7718: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   7719: a vairety of different possible values, $varname should be a request
                   7720: string, and the other parameters can be used to specify who and what
                   7721: one is asking about.
                   7722: 
                   7723: Possible values for $varname are environment.lastname (or other item
                   7724: from the envirnment hash), user.name (or someother aspect about the
                   7725: user), resource.0.maxtries (or some other part and parameter of a
                   7726: resource)
1.204     albertel 7727: 
                   7728: =item *
                   7729: 
1.243     albertel 7730: directcondval($number) : get current value of a condition; reads from a state
                   7731: string
1.204     albertel 7732: 
                   7733: =item *
                   7734: 
1.243     albertel 7735: condval($condidx) : value of condition index based on state
1.204     albertel 7736: 
                   7737: =item *
                   7738: 
1.243     albertel 7739: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   7740: resource's metadata, $what should be either a specific key, or either
                   7741: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   7742: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   7743: 
                   7744: this function automatically caches all requests
1.191     harris41 7745: 
                   7746: =item *
                   7747: 
1.243     albertel 7748: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   7749: network of library servers; returns file handle of where SQL and regex results
                   7750: will be stored for query
1.191     harris41 7751: 
                   7752: =item *
                   7753: 
1.243     albertel 7754: symbread($filename) : return symbolic list entry (filename argument optional);
                   7755: returns the data handle
1.191     harris41 7756: 
                   7757: =item *
                   7758: 
1.243     albertel 7759: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 7760: a possible symb for the URL in $thisfn, and if is an encryypted
                   7761: resource that the user accessed using /enc/ returns a 1 on success, 0
                   7762: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 7763: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 7764: 
1.191     harris41 7765: 
                   7766: =item *
                   7767: 
1.243     albertel 7768: symbclean($symb) : removes versions numbers from a symb, returns the
                   7769: cleaned symb
1.191     harris41 7770: 
                   7771: =item *
                   7772: 
1.243     albertel 7773: is_on_map($uri) : checks if the $uri is somewhere on the current
                   7774: course map, user must be in a course for it to work.
1.191     harris41 7775: 
                   7776: =item *
                   7777: 
1.243     albertel 7778: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 7779: 
                   7780: =item *
                   7781: 
1.243     albertel 7782: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   7783: a random seed, all arguments are optional, if they aren't sent it uses the
                   7784: environment to derive them. Note: if symb isn't sent and it can't get one
                   7785: from &symbread it will use the current time as its return value
1.191     harris41 7786: 
                   7787: =item *
                   7788: 
1.243     albertel 7789: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   7790: unfakeable, receipt
1.191     harris41 7791: 
                   7792: =item *
                   7793: 
1.620     albertel 7794: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 7795: 
                   7796: =item *
                   7797: 
1.243     albertel 7798: countacc($url) : count the number of accesses to a given URL
1.191     harris41 7799: 
                   7800: =item *
                   7801: 
1.243     albertel 7802: 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 7803: 
                   7804: =item *
                   7805: 
1.243     albertel 7806: 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 7807: 
                   7808: =item *
                   7809: 
1.243     albertel 7810: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 7811: 
                   7812: =item *
                   7813: 
1.243     albertel 7814: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   7815: forcing spreadsheet to reevaluate the resource scores next time.
                   7816: 
                   7817: =back
                   7818: 
                   7819: =head2 Storing/Retreiving Data
                   7820: 
                   7821: =over 4
1.191     harris41 7822: 
                   7823: =item *
                   7824: 
1.243     albertel 7825: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   7826: for this url; hashref needs to be given and should be a \%hashname; the
                   7827: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 7828: be derived from the env
1.191     harris41 7829: 
                   7830: =item *
                   7831: 
1.243     albertel 7832: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   7833: uses critical subroutine
1.191     harris41 7834: 
                   7835: =item *
                   7836: 
1.243     albertel 7837: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   7838: all args are optional
1.191     harris41 7839: 
                   7840: =item *
                   7841: 
1.717     albertel 7842: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   7843: dumps the complete (or key matching regexp) namespace into a hash
                   7844: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   7845: normally &store()ed into
                   7846: 
                   7847: $range should be either an integer '100' (give me the first 100
                   7848:                                            matching records)
                   7849:               or be  two integers sperated by a - with no spaces
                   7850:                  '30-50' (give me the 30th through the 50th matching
                   7851:                           records)
                   7852: 
                   7853: 
                   7854: =item *
                   7855: 
                   7856: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   7857: replaces a &store() version of data with a replacement set of data
                   7858: for a particular resource in a namespace passed in the $storehash hash 
                   7859: reference
                   7860: 
                   7861: =item *
                   7862: 
1.243     albertel 7863: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   7864: works very similar to store/cstore, but all data is stored in a
                   7865: temporary location and can be reset using tmpreset, $storehash should
                   7866: be a hash reference, returns nothing on success
1.191     harris41 7867: 
                   7868: =item *
                   7869: 
1.243     albertel 7870: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   7871: similar to restore, but all data is stored in a temporary location and
                   7872: can be reset using tmpreset. Returns a hash of values on success,
                   7873: error string otherwise.
1.191     harris41 7874: 
                   7875: =item *
                   7876: 
1.243     albertel 7877: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   7878: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 7879: 
                   7880: =item *
                   7881: 
1.243     albertel 7882: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   7883: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 7884: 
                   7885: =item *
                   7886: 
1.243     albertel 7887: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   7888: namesp ($udom and $uname are optional)
1.191     harris41 7889: 
                   7890: =item *
                   7891: 
1.702     albertel 7892: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 7893: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 7894: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  7895: 
1.702     albertel 7896: $range should be either an integer '100' (give me the first 100
                   7897:                                            matching records)
                   7898:               or be  two integers sperated by a - with no spaces
                   7899:                  '30-50' (give me the 30th through the 50th matching
                   7900:                           records)
1.449     matthew  7901: =item *
                   7902: 
                   7903: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   7904: $store can be a scalar, an array reference, or if the amount to be 
                   7905: incremented is > 1, a hash reference.
                   7906: 
                   7907: ($udom and $uname are optional)
1.191     harris41 7908: 
                   7909: =item *
                   7910: 
1.243     albertel 7911: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   7912: ($udom and $uname are optional)
1.191     harris41 7913: 
                   7914: =item *
                   7915: 
1.243     albertel 7916: cput($namespace,$storehash,$udom,$uname) : critical put
                   7917: ($udom and $uname are optional)
1.191     harris41 7918: 
                   7919: =item *
                   7920: 
1.748     albertel 7921: newput($namespace,$storehash,$udom,$uname) :
                   7922: 
                   7923: Attempts to store the items in the $storehash, but only if they don't
                   7924: currently exist, if this succeeds you can be certain that you have 
                   7925: successfully created a new key value pair in the $namespace db.
                   7926: 
                   7927: 
                   7928: Args:
                   7929:  $namespace: name of database to store values to
                   7930:  $storehash: hashref to store to the db
                   7931:  $udom: (optional) domain of user containing the db
                   7932:  $uname: (optional) name of user caontaining the db
                   7933: 
                   7934: Returns:
                   7935:  'ok' -> succeeded in storing all keys of $storehash
                   7936:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   7937:                         least <key> already existed in the db (other
                   7938:                         requested keys may also already exist)
                   7939:  'error: <msg>' -> unable to tie the DB or other erorr occured
                   7940:  'con_lost' -> unable to contact request server
                   7941:  'refused' -> action was not allowed by remote machine
                   7942: 
                   7943: 
                   7944: =item *
                   7945: 
1.243     albertel 7946: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   7947: reference filled in from namesp (encrypts the return communication)
                   7948: ($udom and $uname are optional)
1.191     harris41 7949: 
                   7950: =item *
                   7951: 
1.243     albertel 7952: log($udom,$name,$home,$message) : write to permanent log for user; use
                   7953: critical subroutine
                   7954: 
                   7955: =back
                   7956: 
                   7957: =head2 Network Status Functions
                   7958: 
                   7959: =over 4
1.191     harris41 7960: 
                   7961: =item *
                   7962: 
                   7963: dirlist($uri) : return directory list based on URI
                   7964: 
                   7965: =item *
                   7966: 
1.243     albertel 7967: spareserver() : find server with least workload from spare.tab
                   7968: 
                   7969: =back
                   7970: 
                   7971: =head2 Apache Request
                   7972: 
                   7973: =over 4
1.191     harris41 7974: 
                   7975: =item *
                   7976: 
1.243     albertel 7977: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   7978: localhost, posts hash
                   7979: 
                   7980: =back
                   7981: 
                   7982: =head2 Data to String to Data
                   7983: 
                   7984: =over 4
1.191     harris41 7985: 
                   7986: =item *
                   7987: 
1.243     albertel 7988: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   7989: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 7990: 
                   7991: =item *
                   7992: 
1.243     albertel 7993: hashref2str($hashref) : convert a hashref into a string complete with
                   7994: escaping and '=' and '&' separators, supports elements that are
                   7995: arrayrefs and hashrefs
1.191     harris41 7996: 
                   7997: =item *
                   7998: 
1.243     albertel 7999: arrayref2str($arrayref) : convert an arrayref into a string complete
                   8000: with escaping and '&' separators, supports elements that are arrayrefs
                   8001: and hashrefs
1.191     harris41 8002: 
                   8003: =item *
                   8004: 
1.243     albertel 8005: str2hash($string) : convert string to hash using unescaping and
                   8006: splitting on '=' and '&', supports elements that are arrayrefs and
                   8007: hashrefs
1.191     harris41 8008: 
                   8009: =item *
                   8010: 
1.243     albertel 8011: str2array($string) : convert string to hash using unescaping and
                   8012: splitting on '&', supports elements that are arrayrefs and hashrefs
                   8013: 
                   8014: =back
                   8015: 
                   8016: =head2 Logging Routines
                   8017: 
                   8018: =over 4
                   8019: 
                   8020: These routines allow one to make log messages in the lonnet.log and
                   8021: lonnet.perm logfiles.
1.191     harris41 8022: 
                   8023: =item *
                   8024: 
1.243     albertel 8025: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 8026: 
                   8027: =item *
                   8028: 
1.243     albertel 8029: logthis() : append message to the normal lonnet.log file, it gets
                   8030: preiodically rolled over and deleted.
1.191     harris41 8031: 
                   8032: =item *
                   8033: 
1.243     albertel 8034: logperm() : append a permanent message to lonnet.perm.log, this log
                   8035: file never gets deleted by any automated portion of the system, only
                   8036: messages of critical importance should go in here.
                   8037: 
                   8038: =back
                   8039: 
                   8040: =head2 General File Helper Routines
                   8041: 
                   8042: =over 4
1.191     harris41 8043: 
                   8044: =item *
                   8045: 
1.481     raeburn  8046: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   8047: (a) files in /uploaded
                   8048:   (i) If a local copy of the file exists - 
                   8049:       compares modification date of local copy with last-modified date for 
                   8050:       definitive version stored on home server for course. If local copy is 
                   8051:       stale, requests a new version from the home server and stores it. 
                   8052:       If the original has been removed from the home server, then local copy 
                   8053:       is unlinked.
                   8054:   (ii) If local copy does not exist -
                   8055:       requests the file from the home server and stores it. 
                   8056:   
                   8057:   If $caller is 'uploadrep':  
                   8058:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   8059:     for request for files originally uploaded via DOCS. 
                   8060:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   8061:   
                   8062:   Otherwise:
                   8063:      This indicates a call from the content generation phase of the request.
                   8064:      -  returns the entire contents of the file or -1.
                   8065:      
                   8066: (b) files in /res
                   8067:    - returns the entire contents of a file or -1; 
                   8068:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 8069: 
1.712     albertel 8070: 
                   8071: =item *
                   8072: 
                   8073: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   8074:                   reference
                   8075: 
                   8076: returns either a stat() list of data about the file or an empty list
                   8077: if the file doesn't exist or couldn't find out about it (connection
                   8078: problems or user unknown)
                   8079: 
1.191     harris41 8080: =item *
                   8081: 
1.243     albertel 8082: filelocation($dir,$file) : returns file system location of a file
                   8083: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   8084: directory that relative $file lookups are to looked in ($dir of /a/dir
                   8085: and a file of ../bob will become /a/bob)
1.191     harris41 8086: 
                   8087: =item *
                   8088: 
                   8089: hreflocation($dir,$file) : returns file system location or a URL; same as
                   8090: filelocation except for hrefs
                   8091: 
                   8092: =item *
                   8093: 
                   8094: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   8095: 
1.243     albertel 8096: =back
                   8097: 
1.608     albertel 8098: =head2 Usererfile file routines (/uploaded*)
                   8099: 
                   8100: =over 4
                   8101: 
                   8102: =item *
                   8103: 
                   8104: userfileupload(): main rotine for putting a file in a user or course's
                   8105:                   filespace, arguments are,
                   8106: 
1.620     albertel 8107:  formname - required - this is the name of the element in $env where the
1.608     albertel 8108:            filename, and the contents of the file to create/modifed exist
1.620     albertel 8109:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   8110:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 8111:  coursedoc - if true, store the file in the course of the active role
                   8112:              of the current user
                   8113:  subdir - required - subdirectory to put the file in under ../userfiles/
                   8114:          if undefined, it will be placed in "unknown"
                   8115: 
                   8116:  (This routine calls clean_filename() to remove any dangerous
                   8117:  characters from the filename, and then calls finuserfileupload() to
                   8118:  complete the transaction)
                   8119: 
                   8120:  returns either the url of the uploaded file (/uploaded/....) if successful
                   8121:  and /adm/notfound.html if unsuccessful
                   8122: 
                   8123: =item *
                   8124: 
                   8125: clean_filename(): routine for cleaing a filename up for storage in
                   8126:                  userfile space, argument is:
                   8127: 
                   8128:  filename - proposed filename
                   8129: 
                   8130: returns: the new clean filename
                   8131: 
                   8132: =item *
                   8133: 
                   8134: finishuserfileupload(): routine that creaes and sends the file to
                   8135: userspace, probably shouldn't be called directly
                   8136: 
                   8137:   docuname: username or courseid of destination for the file
                   8138:   docudom: domain of user/course of destination for the file
                   8139:   formname: same as for userfileupload()
                   8140:   fname: filename (inculding subdirectories) for the file
                   8141: 
                   8142:  returns either the url of the uploaded file (/uploaded/....) if successful
                   8143:  and /adm/notfound.html if unsuccessful
                   8144: 
                   8145: =item *
                   8146: 
                   8147: renameuserfile(): renames an existing userfile to a new name
                   8148: 
                   8149:   Args:
                   8150:    docuname: username or courseid of destination for the file
                   8151:    docudom: domain of user/course of destination for the file
                   8152:    old: current file name (including any subdirs under userfiles)
                   8153:    new: desired file name (including any subdirs under userfiles)
                   8154: 
                   8155: =item *
                   8156: 
                   8157: mkdiruserfile(): creates a directory is a userfiles dir
                   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:    dir: dir to create (including any subdirs under userfiles)
                   8163: 
                   8164: =item *
                   8165: 
                   8166: removeuserfile(): removes a file that exists in userfiles
                   8167: 
                   8168:   Args:
                   8169:    docuname: username or courseid of destination for the file
                   8170:    docudom: domain of user/course of destination for the file
                   8171:    fname: filname to delete (including any subdirs under userfiles)
                   8172: 
                   8173: =item *
                   8174: 
                   8175: removeuploadedurl(): convience function for removeuserfile()
                   8176: 
                   8177:   Args:
                   8178:    url:  a full /uploaded/... url to delete
                   8179: 
1.747     albertel 8180: =item * 
                   8181: 
                   8182: get_portfile_permissions():
                   8183:   Args:
                   8184:     domain: domain of user or course contain the portfolio files
                   8185:     user: name of user or num of course contain the portfolio files
                   8186:   Returns:
                   8187:     hashref of a dump of the proper file_permissions.db
                   8188:    
                   8189: 
                   8190: =item * 
                   8191: 
                   8192: get_access_controls():
                   8193: 
                   8194: Args:
                   8195:   current_permissions: the hash ref returned from get_portfile_permissions()
                   8196:   group: (optional) the group you want the files associated with
                   8197:   file: (optional) the file you want access info on
                   8198: 
                   8199: Returns:
1.749     raeburn  8200:     a hash (keys are file names) of hashes containing
                   8201:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   8202:         values are XML containing access control settings (see below) 
1.747     albertel 8203: 
                   8204: Internal notes:
                   8205: 
1.749     raeburn  8206:  access controls are stored in file_permissions.db as key=value pairs.
                   8207:     key -> path to file/file_name\0uniqueID:scope_end_start
                   8208:         where scope -> public,guest,course,group,domains or users.
                   8209:               end -> UNIX time for end of access (0 -> no end date)
                   8210:               start -> UNIX time for start of access
                   8211: 
                   8212:     value -> XML description of access control
                   8213:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   8214:             <start></start>
                   8215:             <end></end>
                   8216: 
                   8217:             <password></password>  for scope type = guest
                   8218: 
                   8219:             <domain></domain>     for scope type = course or group
                   8220:             <number></number>
                   8221:             <roles id="">
                   8222:              <role></role>
                   8223:              <access></access>
                   8224:              <section></section>
                   8225:              <group></group>
                   8226:             </roles>
                   8227: 
                   8228:             <dom></dom>         for scope type = domains
                   8229: 
                   8230:             <users>             for scope type = users
                   8231:              <user>
                   8232:               <uname></uname>
                   8233:               <udom></udom>
                   8234:              </user>
                   8235:             </users>
                   8236:            </scope> 
                   8237:               
                   8238:  Access data is also aggregated for each file in an additional key=value pair:
                   8239:  key -> path to file/file_name\0accesscontrol 
                   8240:  value -> reference to hash
                   8241:           hash contains key = value pairs
                   8242:           where key = uniqueID:scope_end_start
                   8243:                 value = UNIX time record was last updated
                   8244: 
                   8245:           Used to improve speed of look-ups of access controls for each file.  
                   8246:  
                   8247:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   8248: 
                   8249: modify_access_controls():
                   8250: 
                   8251: Modifies access controls for a portfolio file
                   8252: Args
                   8253: 1. file name
                   8254: 2. reference to hash of required changes,
                   8255: 3. domain
                   8256: 4. username
                   8257:   where domain,username are the domain of the portfolio owner 
                   8258:   (either a user or a course) 
                   8259: 
                   8260: Returns:
                   8261: 1. result of additions or updates ('ok' or 'error', with error message). 
                   8262: 2. result of deletions ('ok' or 'error', with error message).
                   8263: 3. reference to hash of any new or updated access controls.
                   8264: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   8265:    key = integer (inbound ID)
                   8266:    value = uniqueID  
1.747     albertel 8267: 
1.608     albertel 8268: =back
                   8269: 
1.243     albertel 8270: =head2 HTTP Helper Routines
                   8271: 
                   8272: =over 4
                   8273: 
1.191     harris41 8274: =item *
                   8275: 
                   8276: escape() : unpack non-word characters into CGI-compatible hex codes
                   8277: 
                   8278: =item *
                   8279: 
                   8280: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   8281: 
1.243     albertel 8282: =back
                   8283: 
                   8284: =head1 PRIVATE SUBROUTINES
                   8285: 
                   8286: =head2 Underlying communication routines (Shouldn't call)
                   8287: 
                   8288: =over 4
                   8289: 
                   8290: =item *
                   8291: 
                   8292: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   8293: 
                   8294: =item *
                   8295: 
                   8296: reply() : uses subreply to send a message to remote machine, logs all failures
                   8297: 
                   8298: =item *
                   8299: 
                   8300: critical() : passes a critical message to another server; if cannot
                   8301: get through then place message in connection buffer directory and
                   8302: returns con_delayed, if incapable of saving message, returns
                   8303: con_failed
                   8304: 
                   8305: =item *
                   8306: 
                   8307: reconlonc() : tries to reconnect lonc client processes.
                   8308: 
                   8309: =back
                   8310: 
                   8311: =head2 Resource Access Logging
                   8312: 
                   8313: =over 4
                   8314: 
                   8315: =item *
                   8316: 
                   8317: flushcourselogs() : flush (save) buffer logs and access logs
                   8318: 
                   8319: =item *
                   8320: 
                   8321: courselog($what) : save message for course in hash
                   8322: 
                   8323: =item *
                   8324: 
                   8325: courseacclog($what) : save message for course using &courselog().  Perform
                   8326: special processing for specific resource types (problems, exams, quizzes, etc).
                   8327: 
1.191     harris41 8328: =item *
                   8329: 
                   8330: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   8331: as a PerlChildExitHandler
1.243     albertel 8332: 
                   8333: =back
                   8334: 
                   8335: =head2 Other
                   8336: 
                   8337: =over 4
                   8338: 
                   8339: =item *
                   8340: 
                   8341: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 8342: 
                   8343: =back
                   8344: 
                   8345: =cut

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