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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.890   ! albertel    4: # $Id: lonnet.pm,v 1.889 2007/06/13 02:21:54 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.486     www        34: use HTTP::Date;
                     35: # use Date::Parse;
1.871     albertel   36: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
                     37:             $_64bit %env);
                     38: 
                     39: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
                     40:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
                     41:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
                     42:     %courseownerbuf, %coursetypebuf);
1.403     www        43: 
1.1       albertel   44: use IO::Socket;
1.31      www        45: use GDBM_File;
1.208     albertel   46: use HTML::LCParser;
1.88      www        47: use Fcntl qw(:flock);
1.870     albertel   48: use Storable qw(thaw nfreeze);
1.539     albertel   49: use Time::HiRes qw( gettimeofday tv_interval );
1.599     albertel   50: use Cache::Memcached;
1.676     albertel   51: use Digest::MD5;
1.790     albertel   52: use Math::Random;
1.807     albertel   53: use LONCAPA qw(:DEFAULT :match);
1.740     www        54: use LONCAPA::Configuration;
1.676     albertel   55: 
1.195     www        56: my $readit;
1.550     foxr       57: my $max_connection_retries = 10;     # Or some such value.
1.1       albertel   58: 
1.619     albertel   59: require Exporter;
                     60: 
                     61: our @ISA = qw (Exporter);
                     62: our @EXPORT = qw(%env);
                     63: 
1.449     matthew    64: =pod
                     65: 
                     66: =head1 Package Variables
                     67: 
                     68: These are largely undocumented, so if you decipher one please note it here.
                     69: 
                     70: =over 4
                     71: 
                     72: =item $processmarker
                     73: 
                     74: Contains the time this process was started and this servers host id.
                     75: 
                     76: =item $dumpcount
                     77: 
                     78: Counts the number of times a message log flush has been attempted (regardless
                     79: of success) by this process.  Used as part of the filename when messages are
                     80: delayed.
                     81: 
                     82: =back
                     83: 
                     84: =cut
                     85: 
                     86: 
1.1       albertel   87: # --------------------------------------------------------------------- Logging
1.729     www        88: {
                     89:     my $logid;
                     90:     sub instructor_log {
                     91: 	my ($hash_name,$storehash,$delflag,$uname,$udom)=@_;
                     92: 	$logid++;
                     93: 	my $id=time().'00000'.$$.'00000'.$logid;
                     94: 	return &Apache::lonnet::put('nohist_'.$hash_name,
1.730     www        95: 				    { $id => {
                     96: 					'exe_uname' => $env{'user.name'},
                     97: 					'exe_udom'  => $env{'user.domain'},
                     98: 					'exe_time'  => time(),
                     99: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    100: 					'delflag'   => $delflag,
                    101: 					'logentry'  => $storehash,
                    102: 					'uname'     => $uname,
                    103: 					'udom'      => $udom,
                    104: 				    }
                    105: 				  },
1.729     www       106: 				    $env{'course.'.$env{'request.course.id'}.'.domain'},
                    107: 				    $env{'course.'.$env{'request.course.id'}.'.num'}
                    108: 				    );
                    109:     }
                    110: }
1.1       albertel  111: 
1.163     harris41  112: sub logtouch {
                    113:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  114:     unless (-e "$execdir/logs/lonnet.log") {	
                    115: 	open(my $fh,">>$execdir/logs/lonnet.log");
1.163     harris41  116: 	close $fh;
                    117:     }
                    118:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    119:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    120: }
                    121: 
1.1       albertel  122: sub logthis {
                    123:     my $message=shift;
                    124:     my $execdir=$perlvar{'lonDaemons'};
                    125:     my $now=time;
                    126:     my $local=localtime($now);
1.448     albertel  127:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
                    128: 	print $fh "$local ($$): $message\n";
                    129: 	close($fh);
                    130:     }
1.1       albertel  131:     return 1;
                    132: }
                    133: 
                    134: sub logperm {
                    135:     my $message=shift;
                    136:     my $execdir=$perlvar{'lonDaemons'};
                    137:     my $now=time;
                    138:     my $local=localtime($now);
1.448     albertel  139:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
                    140: 	print $fh "$now:$message:$local\n";
                    141: 	close($fh);
                    142:     }
1.1       albertel  143:     return 1;
                    144: }
                    145: 
1.850     albertel  146: sub create_connection {
1.853     albertel  147:     my ($hostname,$lonid) = @_;
1.851     albertel  148:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
1.850     albertel  149: 				     Type    => SOCK_STREAM,
                    150: 				     Timeout => 10);
                    151:     return 0 if (!$client);
1.890   ! albertel  152:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850     albertel  153:     my $result = <$client>;
                    154:     chomp($result);
                    155:     return 1 if ($result eq 'done');
                    156:     return 0;
                    157: }
                    158: 
                    159: 
1.1       albertel  160: # -------------------------------------------------- Non-critical communication
                    161: sub subreply {
                    162:     my ($cmd,$server)=@_;
1.838     albertel  163:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      164:     #
                    165:     #  With loncnew process trimming, there's a timing hole between lonc server
                    166:     #  process exit and the master server picking up the listen on the AF_UNIX
                    167:     #  socket.  In that time interval, a lock file will exist:
                    168: 
                    169:     my $lockfile=$peerfile.".lock";
                    170:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
                    171: 	sleep(1);
                    172:     }
                    173:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      174:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      175:     #
1.550     foxr      176:     #   We'll give the connection a few tries before abandoning it.  If
                    177:     #   connection is not possible, we'll con_lost back to the client.
                    178:     #   
                    179:     my $client;
                    180:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    181: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    182: 				      Type    => SOCK_STREAM,
                    183: 				      Timeout => 10);
1.869     albertel  184: 	if ($client) {
1.550     foxr      185: 	    last;		# Connected!
1.850     albertel  186: 	} else {
1.853     albertel  187: 	    &create_connection(&hostname($server),$server);
1.550     foxr      188: 	}
1.850     albertel  189:         sleep(1);		# Try again later if failed connection.
1.550     foxr      190:     }
                    191:     my $answer;
                    192:     if ($client) {
1.704     albertel  193: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      194: 	$answer=<$client>;
                    195: 	if (!$answer) { $answer="con_lost"; }
                    196: 	chomp($answer);
                    197:     } else {
                    198: 	$answer = 'con_lost';	# Failed connection.
                    199:     }
1.1       albertel  200:     return $answer;
                    201: }
                    202: 
                    203: sub reply {
                    204:     my ($cmd,$server)=@_;
1.838     albertel  205:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  206:     my $answer=subreply($cmd,$server);
1.65      www       207:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  208:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       209:                 " $cmd to $server returned $answer</font>");
                    210:     }
1.1       albertel  211:     return $answer;
                    212: }
                    213: 
                    214: # ----------------------------------------------------------- Send USR1 to lonc
                    215: 
                    216: sub reconlonc {
1.836     www       217:     &logthis("Trying to reconnect lonc");
1.1       albertel  218:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  219:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  220: 	my $loncpid=<$fh>;
                    221:         chomp($loncpid);
                    222:         if (kill 0 => $loncpid) {
                    223: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    224:             kill USR1 => $loncpid;
                    225:             sleep 1;
1.836     www       226:          } else {
1.12      www       227: 	    &logthis(
1.672     albertel  228:                "<font color=\"blue\">WARNING:".
1.12      www       229:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  230:         }
                    231:     } else {
1.836     www       232: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  233:     }
                    234: }
                    235: 
                    236: # ------------------------------------------------------ Critical communication
1.12      www       237: 
1.1       albertel  238: sub critical {
                    239:     my ($cmd,$server)=@_;
1.838     albertel  240:     unless (&hostname($server)) {
1.672     albertel  241:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       242:                " Critical message to unknown server ($server)</font>");
                    243:         return 'no_such_host';
                    244:     }
1.1       albertel  245:     my $answer=reply($cmd,$server);
                    246:     if ($answer eq 'con_lost') {
                    247: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
1.589     albertel  248: 	my $answer=reply($cmd,$server);
1.1       albertel  249:         if ($answer eq 'con_lost') {
                    250:             my $now=time;
                    251:             my $middlename=$cmd;
1.5       www       252:             $middlename=substr($middlename,0,16);
1.1       albertel  253:             $middlename=~s/\W//g;
                    254:             my $dfilename=
1.305     www       255:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    256:             $dumpcount++;
1.1       albertel  257:             {
1.448     albertel  258: 		my $dfh;
                    259: 		if (open($dfh,">$dfilename")) {
                    260: 		    print $dfh "$cmd\n"; 
                    261: 		    close($dfh);
                    262: 		}
1.1       albertel  263:             }
                    264:             sleep 2;
                    265:             my $wcmd='';
                    266:             {
1.448     albertel  267: 		my $dfh;
                    268: 		if (open($dfh,"<$dfilename")) {
                    269: 		    $wcmd=<$dfh>; 
                    270: 		    close($dfh);
                    271: 		}
1.1       albertel  272:             }
                    273:             chomp($wcmd);
1.7       www       274:             if ($wcmd eq $cmd) {
1.672     albertel  275: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       276:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  277:                 &logperm("D:$server:$cmd");
                    278: 	        return 'con_delayed';
                    279:             } else {
1.672     albertel  280:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       281:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  282:                 &logperm("F:$server:$cmd");
                    283:                 return 'con_failed';
                    284:             }
                    285:         }
                    286:     }
                    287:     return $answer;
1.405     albertel  288: }
                    289: 
1.755     albertel  290: # ------------------------------------------- check if return value is an error
                    291: 
                    292: sub error {
                    293:     my ($result) = @_;
1.756     albertel  294:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  295: 	if ($2 == 2) { return undef; }
                    296: 	return $1;
                    297:     }
                    298:     return undef;
                    299: }
                    300: 
1.783     albertel  301: sub convert_and_load_session_env {
                    302:     my ($lonidsdir,$handle)=@_;
                    303:     my @profile;
                    304:     {
                    305: 	open(my $idf,"$lonidsdir/$handle.id");
                    306: 	flock($idf,LOCK_SH);
                    307: 	@profile=<$idf>;
                    308: 	close($idf);
                    309:     }
                    310:     my %temp_env;
                    311:     foreach my $line (@profile) {
1.786     albertel  312: 	if ($line !~ m/=/) {
                    313: 	    return 0;
                    314: 	}
1.783     albertel  315: 	chomp($line);
                    316: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    317: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    318:     }
                    319:     unlink("$lonidsdir/$handle.id");
                    320:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    321: 	    0640)) {
                    322: 	%disk_env = %temp_env;
                    323: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    324: 	untie(%disk_env);
                    325:     }
1.786     albertel  326:     return 1;
1.783     albertel  327: }
                    328: 
1.374     www       329: # ------------------------------------------- Transfer profile into environment
1.780     albertel  330: my $env_loaded;
                    331: sub transfer_profile_to_env {
1.788     albertel  332:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    333:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       334: 
1.720     albertel  335:     if (!defined($lonidsdir)) {
                    336: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    337:     }
                    338:     if (!defined($handle)) {
                    339:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    340:     }
                    341: 
1.786     albertel  342:     my $convert;
                    343:     {
                    344:     	open(my $idf,"$lonidsdir/$handle.id");
                    345: 	flock($idf,LOCK_SH);
                    346: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    347: 		&GDBM_READER(),0640)) {
                    348: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    349: 	    untie(%disk_env);
                    350: 	} else {
                    351: 	    $convert = 1;
                    352: 	}
                    353:     }
                    354:     if ($convert) {
                    355: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    356: 	    &logthis("Failed to load session, or convert session.");
                    357: 	}
1.374     www       358:     }
1.783     albertel  359: 
1.786     albertel  360:     my %remove;
1.783     albertel  361:     while ( my $envname = each(%env) ) {
1.433     matthew   362:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    363:             if ($time < time-300) {
1.783     albertel  364:                 $remove{$key}++;
1.433     matthew   365:             }
                    366:         }
                    367:     }
1.783     albertel  368: 
1.619     albertel  369:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  370:     $env_loaded=1;
1.783     albertel  371:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   372:         &delenv($expired_key);
1.374     www       373:     }
1.1       albertel  374: }
                    375: 
1.830     albertel  376: sub timed_flock {
                    377:     my ($file,$lock_type) = @_;
                    378:     my $failed=0;
                    379:     eval {
                    380: 	local $SIG{__DIE__}='DEFAULT';
                    381: 	local $SIG{ALRM}=sub {
                    382: 	    $failed=1;
                    383: 	    die("failed lock");
                    384: 	};
                    385: 	alarm(13);
                    386: 	flock($file,$lock_type);
                    387: 	alarm(0);
                    388:     };
                    389:     if ($failed) {
                    390: 	return undef;
                    391:     } else {
                    392: 	return 1;
                    393:     }
                    394: }
                    395: 
1.5       www       396: # ---------------------------------------------------------- Append Environment
                    397: 
                    398: sub appenv {
1.6       www       399:     my %newenv=@_;
1.692     albertel  400:     foreach my $key (keys(%newenv)) {
                    401: 	if (($newenv{$key}=~/^user\.role/) || ($newenv{$key}=~/^user\.priv/)) {
1.672     albertel  402:             &logthis("<font color=\"blue\">WARNING: ".
1.692     albertel  403:                 "Attempt to modify environment ".$key." to ".$newenv{$key}
1.151     www       404:                 .'</font>');
1.692     albertel  405: 	    delete($newenv{$key});
1.35      www       406:         } else {
1.692     albertel  407:             $env{$key}=$newenv{$key};
1.35      www       408:         }
1.191     harris41  409:     }
1.830     albertel  410:     open(my $env_file,$env{'user.environment'});
                    411:     if (&timed_flock($env_file,LOCK_EX)
                    412: 	&&
                    413: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    414: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  415: 	while (my ($key,$value) = each(%newenv)) {
                    416: 	    $disk_env{$key} = $value;
1.448     albertel  417: 	}
1.783     albertel  418: 	untie(%disk_env);
1.56      www       419:     }
                    420:     return 'ok';
                    421: }
                    422: # ----------------------------------------------------- Delete from Environment
                    423: 
                    424: sub delenv {
                    425:     my $delthis=shift;
                    426:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
1.672     albertel  427:         &logthis("<font color=\"blue\">WARNING: ".
1.56      www       428:                 "Attempt to delete from environment ".$delthis);
                    429:         return 'error';
                    430:     }
1.830     albertel  431:     open(my $env_file,$env{'user.environment'});
                    432:     if (&timed_flock($env_file,LOCK_EX)
                    433: 	&&
                    434: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    435: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  436: 	foreach my $key (keys(%disk_env)) {
                    437: 	    if ($key=~/^$delthis/) { 
1.619     albertel  438:                 delete($env{$key});
1.783     albertel  439:                 delete($disk_env{$key});
1.473     matthew   440:             }
1.448     albertel  441: 	}
1.783     albertel  442: 	untie(%disk_env);
1.5       www       443:     }
                    444:     return 'ok';
1.369     albertel  445: }
                    446: 
1.790     albertel  447: sub get_env_multiple {
                    448:     my ($name) = @_;
                    449:     my @values;
                    450:     if (defined($env{$name})) {
                    451:         # exists is it an array
                    452:         if (ref($env{$name})) {
                    453:             @values=@{ $env{$name} };
                    454:         } else {
                    455:             $values[0]=$env{$name};
                    456:         }
                    457:     }
                    458:     return(@values);
                    459: }
                    460: 
1.369     albertel  461: # ------------------------------------------ Find out current server userload
                    462: # there is a copy in lond
                    463: sub userload {
                    464:     my $numusers=0;
                    465:     {
                    466: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    467: 	my $filename;
                    468: 	my $curtime=time;
                    469: 	while ($filename=readdir(LONIDS)) {
                    470: 	    if ($filename eq '.' || $filename eq '..') {next;}
1.404     albertel  471: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  472: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  473: 	}
                    474: 	closedir(LONIDS);
                    475:     }
                    476:     my $userloadpercent=0;
                    477:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    478:     if ($maxuserload) {
1.371     albertel  479: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  480:     }
1.372     albertel  481:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  482:     return $userloadpercent;
1.283     www       483: }
                    484: 
                    485: # ------------------------------------------ Fight off request when overloaded
                    486: 
                    487: sub overloaderror {
                    488:     my ($r,$checkserver)=@_;
                    489:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
                    490:     my $loadavg;
                    491:     if ($checkserver eq $perlvar{'lonHostID'}) {
1.448     albertel  492:        open(my $loadfile,'/proc/loadavg');
1.283     www       493:        $loadavg=<$loadfile>;
                    494:        $loadavg =~ s/\s.*//g;
1.285     matthew   495:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
1.448     albertel  496:        close($loadfile);
1.283     www       497:     } else {
                    498:        $loadavg=&reply('load',$checkserver);
                    499:     }
1.285     matthew   500:     my $overload=$loadavg-100;
1.283     www       501:     if ($overload>0) {
1.285     matthew   502: 	$r->err_headers_out->{'Retry-After'}=$overload;
1.283     www       503:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
1.554     www       504:         return 413;
1.283     www       505:     }    
                    506:     return '';
1.5       www       507: }
1.1       albertel  508: 
                    509: # ------------------------------ Find server with least workload from spare.tab
1.11      www       510: 
1.1       albertel  511: sub spareserver {
1.670     albertel  512:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
1.784     albertel  513:     my $spare_server;
1.370     albertel  514:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  515:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    516:                                                      :  $userloadpercent;
                    517:     
                    518:     foreach my $try_server (@{ $spareid{'primary'} }) {
                    519: 	($spare_server, $lowest_load) =
                    520: 	    &compare_server_load($try_server, $spare_server, $lowest_load);
                    521:     }
                    522: 
                    523:     my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    524: 
                    525:     if (!$found_server) {
                    526: 	foreach my $try_server (@{ $spareid{'default'} }) {
                    527: 	    ($spare_server, $lowest_load) =
                    528: 		&compare_server_load($try_server, $spare_server, $lowest_load);
                    529: 	}
                    530:     }
                    531: 
                    532:     if (!$want_server_name) {
1.838     albertel  533: 	$spare_server="http://".&hostname($spare_server);
1.784     albertel  534:     }
                    535:     return $spare_server;
                    536: }
                    537: 
                    538: sub compare_server_load {
                    539:     my ($try_server, $spare_server, $lowest_load) = @_;
                    540: 
                    541:     my $loadans     = &reply('load',    $try_server);
                    542:     my $userloadans = &reply('userload',$try_server);
                    543: 
                    544:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
                    545: 	next; #didn't get a number from the server
                    546:     }
                    547: 
                    548:     my $load;
                    549:     if ($loadans =~ /\d/) {
                    550: 	if ($userloadans =~ /\d/) {
                    551: 	    #both are numbers, pick the bigger one
                    552: 	    $load = ($loadans > $userloadans) ? $loadans 
                    553: 		                              : $userloadans;
1.411     albertel  554: 	} else {
1.784     albertel  555: 	    $load = $loadans;
1.411     albertel  556: 	}
1.784     albertel  557:     } else {
                    558: 	$load = $userloadans;
                    559:     }
                    560: 
                    561:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    562: 	$spare_server = $try_server;
                    563: 	$lowest_load  = $load;
1.370     albertel  564:     }
1.784     albertel  565:     return ($spare_server,$lowest_load);
1.202     matthew   566: }
                    567: # --------------------------------------------- Try to change a user's password
                    568: 
                    569: sub changepass {
1.799     raeburn   570:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew   571:     $currentpass = &escape($currentpass);
                    572:     $newpass     = &escape($newpass);
1.799     raeburn   573:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context",
1.202     matthew   574: 		       $server);
                    575:     if (! $answer) {
                    576: 	&logthis("No reply on password change request to $server ".
                    577: 		 "by $uname in domain $udom.");
                    578:     } elsif ($answer =~ "^ok") {
                    579:         &logthis("$uname in $udom successfully changed their password ".
                    580: 		 "on $server.");
                    581:     } elsif ($answer =~ "^pwchange_failure") {
                    582: 	&logthis("$uname in $udom was unable to change their password ".
                    583: 		 "on $server.  The action was blocked by either lcpasswd ".
                    584: 		 "or pwchange");
                    585:     } elsif ($answer =~ "^non_authorized") {
                    586:         &logthis("$uname in $udom did not get their password correct when ".
                    587: 		 "attempting to change it on $server.");
                    588:     } elsif ($answer =~ "^auth_mode_error") {
                    589:         &logthis("$uname in $udom attempted to change their password despite ".
                    590: 		 "not being locally or internally authenticated on $server.");
                    591:     } elsif ($answer =~ "^unknown_user") {
                    592:         &logthis("$uname in $udom attempted to change their password ".
                    593: 		 "on $server but were unable to because $server is not ".
                    594: 		 "their home server.");
                    595:     } elsif ($answer =~ "^refused") {
                    596: 	&logthis("$server refused to change $uname in $udom password because ".
                    597: 		 "it was sent an unencrypted request to change the password.");
                    598:     }
                    599:     return $answer;
1.1       albertel  600: }
                    601: 
1.169     harris41  602: # ----------------------- Try to determine user's current authentication scheme
                    603: 
                    604: sub queryauthenticate {
                    605:     my ($uname,$udom)=@_;
1.456     albertel  606:     my $uhome=&homeserver($uname,$udom);
                    607:     if (!$uhome) {
                    608: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                    609: 	return 'no_host';
                    610:     }
                    611:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                    612:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                    613: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41  614:     }
1.456     albertel  615:     return $answer;
1.169     harris41  616: }
                    617: 
1.1       albertel  618: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www       619: 
1.1       albertel  620: sub authenticate {
                    621:     my ($uname,$upass,$udom)=@_;
1.807     albertel  622:     $upass=&escape($upass);
                    623:     $uname= &LONCAPA::clean_username($uname);
1.836     www       624:     my $uhome=&homeserver($uname,$udom,1);
                    625:     if ((!$uhome) || ($uhome eq 'no_host')) {
                    626: # Maybe the machine was offline and only re-appeared again recently?
                    627:         &reconlonc();
                    628: # One more
                    629: 	my $uhome=&homeserver($uname,$udom,1);
                    630: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                    631: 	    &logthis("User $uname at $udom is unknown in authenticate");
                    632: 	}
1.471     albertel  633: 	return 'no_host';
1.1       albertel  634:     }
1.471     albertel  635:     my $answer=reply("encrypt:auth:$udom:$uname:$upass",$uhome);
                    636:     if ($answer eq 'authorized') {
                    637: 	&logthis("User $uname at $udom authorized by $uhome"); 
                    638: 	return $uhome; 
                    639:     }
                    640:     if ($answer eq 'non_authorized') {
                    641: 	&logthis("User $uname at $udom rejected by $uhome");
                    642: 	return 'no_host'; 
1.9       www       643:     }
1.471     albertel  644:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel  645:     return 'no_host';
                    646: }
                    647: 
                    648: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www       649: 
1.599     albertel  650: my %homecache;
1.1       albertel  651: sub homeserver {
1.230     stredwic  652:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel  653:     my $index="$uname:$udom";
1.426     albertel  654: 
1.599     albertel  655:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel  656: 
                    657:     my %servers = &get_servers($udom,'library');
                    658:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic  659:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic  660: 		 exists($badServerCache{$tryserver}));
1.841     albertel  661: 
                    662: 	my $answer=reply("home:$udom:$uname",$tryserver);
                    663: 	if ($answer eq 'found') {
                    664: 	    delete($badServerCache{$tryserver}); 
                    665: 	    return $homecache{$index}=$tryserver;
                    666: 	} elsif ($answer eq 'no_host') {
                    667: 	    $badServerCache{$tryserver}=1;
                    668: 	}
1.1       albertel  669:     }    
                    670:     return 'no_host';
1.70      www       671: }
                    672: 
                    673: # ------------------------------------- Find the usernames behind a list of IDs
                    674: 
                    675: sub idget {
                    676:     my ($udom,@ids)=@_;
                    677:     my %returnhash=();
                    678:     
1.841     albertel  679:     my %servers = &get_servers($udom,'library');
                    680:     foreach my $tryserver (keys(%servers)) {
                    681: 	my $idlist=join('&',@ids);
                    682: 	$idlist=~tr/A-Z/a-z/; 
                    683: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                    684: 	my @answer=();
                    685: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                    686: 	    @answer=split(/\&/,$reply);
                    687: 	}                    ;
                    688: 	my $i;
                    689: 	for ($i=0;$i<=$#ids;$i++) {
                    690: 	    if ($answer[$i]) {
                    691: 		$returnhash{$ids[$i]}=$answer[$i];
                    692: 	    } 
                    693: 	}
                    694:     } 
1.70      www       695:     return %returnhash;
                    696: }
                    697: 
                    698: # ------------------------------------- Find the IDs behind a list of usernames
                    699: 
                    700: sub idrget {
                    701:     my ($udom,@unames)=@_;
                    702:     my %returnhash=();
1.800     albertel  703:     foreach my $uname (@unames) {
                    704:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41  705:     }
1.70      www       706:     return %returnhash;
                    707: }
                    708: 
                    709: # ------------------------------- Store away a list of names and associated IDs
                    710: 
                    711: sub idput {
                    712:     my ($udom,%ids)=@_;
                    713:     my %servers=();
1.800     albertel  714:     foreach my $uname (keys(%ids)) {
                    715: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                    716:         my $uhom=&homeserver($uname,$udom);
1.70      www       717:         if ($uhom ne 'no_host') {
1.800     albertel  718:             my $id=&escape($ids{$uname});
1.70      www       719:             $id=~tr/A-Z/a-z/;
1.800     albertel  720:             my $esc_unam=&escape($uname);
1.70      www       721: 	    if ($servers{$uhom}) {
1.800     albertel  722: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www       723:             } else {
1.800     albertel  724:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www       725:             }
                    726:         }
1.191     harris41  727:     }
1.800     albertel  728:     foreach my $server (keys(%servers)) {
                    729:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41  730:     }
1.344     www       731: }
                    732: 
1.806     raeburn   733: # ------------------------------------------- get items from domain db files   
                    734: 
                    735: sub get_dom {
1.860     raeburn   736:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.806     raeburn   737:     my $items='';
                    738:     foreach my $item (@$storearr) {
                    739:         $items.=&escape($item).'&';
                    740:     }
                    741:     $items=~s/\&$//;
1.860     raeburn   742:     if (!$udom) {
                    743:         $udom=$env{'user.domain'};
                    744:         if (defined(&domain($udom,'primary'))) {
                    745:             $uhome=&domain($udom,'primary');
                    746:         } else {
1.874     albertel  747:             undef($uhome);
1.860     raeburn   748:         }
                    749:     } else {
                    750:         if (!$uhome) {
                    751:             if (defined(&domain($udom,'primary'))) {
                    752:                 $uhome=&domain($udom,'primary');
                    753:             }
                    754:         }
                    755:     }
                    756:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn   757:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn   758:         my %returnhash;
1.875     albertel  759:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn   760:             return %returnhash;
                    761:         }
1.806     raeburn   762:         my @pairs=split(/\&/,$rep);
                    763:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                    764:             return @pairs;
                    765:         }
                    766:         my $i=0;
                    767:         foreach my $item (@$storearr) {
                    768:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                    769:             $i++;
                    770:         }
                    771:         return %returnhash;
                    772:     } else {
1.880     banghart  773:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn   774:     }
                    775: }
                    776: 
                    777: # -------------------------------------------- put items in domain db files 
                    778: 
                    779: sub put_dom {
1.860     raeburn   780:     my ($namespace,$storehash,$udom,$uhome)=@_;
                    781:     if (!$udom) {
                    782:         $udom=$env{'user.domain'};
                    783:         if (defined(&domain($udom,'primary'))) {
                    784:             $uhome=&domain($udom,'primary');
                    785:         } else {
1.874     albertel  786:             undef($uhome);
1.860     raeburn   787:         }
                    788:     } else {
                    789:         if (!$uhome) {
                    790:             if (defined(&domain($udom,'primary'))) {
                    791:                 $uhome=&domain($udom,'primary');
                    792:             }
                    793:         }
                    794:     } 
                    795:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn   796:         my $items='';
                    797:         foreach my $item (keys(%$storehash)) {
                    798:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                    799:         }
                    800:         $items=~s/\&$//;
                    801:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                    802:     } else {
1.860     raeburn   803:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn   804:     }
                    805: }
                    806: 
1.837     raeburn   807: sub retrieve_inst_usertypes {
                    808:     my ($udom) = @_;
                    809:     my (%returnhash,@order);
1.846     albertel  810:     if (defined(&domain($udom,'primary'))) {
                    811:         my $uhome=&domain($udom,'primary');
1.837     raeburn   812:         my $rep=&reply("inst_usertypes:$udom",$uhome);
                    813:         my ($hashitems,$orderitems) = split(/:/,$rep); 
                    814:         my @pairs=split(/\&/,$hashitems);
                    815:         foreach my $item (@pairs) {
                    816:             my ($key,$value)=split(/=/,$item,2);
                    817:             $key = &unescape($key);
                    818:             next if ($key =~ /^error: 2 /);
                    819:             $returnhash{$key}=&thaw_unescape($value);
                    820:         }
                    821:         my @esc_order = split(/\&/,$orderitems);
                    822:         foreach my $item (@esc_order) {
                    823:             push(@order,&unescape($item));
                    824:         }
                    825:     } else {
                    826:         &logthis("get_dom failed - no primary domain server for $udom");
                    827:     }
                    828:     return (\%returnhash,\@order);
                    829: }
                    830: 
1.868     raeburn   831: sub is_domainimage {
                    832:     my ($url) = @_;
                    833:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
                    834:         if (&domain($1) ne '') {
                    835:             return '1';
                    836:         }
                    837:     }
                    838:     return;
                    839: }
                    840: 
1.344     www       841: # --------------------------------------------------- Assign a key to a student
                    842: 
                    843: sub assign_access_key {
1.364     www       844: #
                    845: # a valid key looks like uname:udom#comments
                    846: # comments are being appended
                    847: #
1.498     www       848:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                    849:     $kdom=
1.620     albertel  850:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www       851:     $knum=
1.620     albertel  852:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www       853:     $cdom=
1.620     albertel  854:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       855:     $cnum=
1.620     albertel  856:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                    857:     $udom=$env{'user.name'} unless (defined($udom));
                    858:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www       859:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www       860:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel  861:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www       862:                                                   # assigned to this person
                    863:                                                   # - this should not happen,
1.345     www       864:                                                   # unless something went wrong
                    865:                                                   # the first time around
                    866: # ready to assign
1.364     www       867:         $logentry=$1.'; '.$logentry;
1.496     www       868:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www       869:                                                  $kdom,$knum) eq 'ok') {
1.345     www       870: # key now belongs to user
1.346     www       871: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www       872:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
                    873:                 &appenv('environment.'.$envkey => $ckey);
                    874:                 return 'ok';
                    875:             } else {
                    876:                 return 
                    877:   'error: Count not permanently assign key, will need to be re-entered later.';
                    878: 	    }
                    879:         } else {
                    880:             return 'error: Could not assign key, try again later.';
                    881:         }
1.364     www       882:     } elsif (!$existing{$ckey}) {
1.345     www       883: # the key does not exist
                    884: 	return 'error: The key does not exist';
                    885:     } else {
                    886: # the key is somebody else's
                    887: 	return 'error: The key is already in use';
                    888:     }
1.344     www       889: }
                    890: 
1.364     www       891: # ------------------------------------------ put an additional comment on a key
                    892: 
                    893: sub comment_access_key {
                    894: #
                    895: # a valid key looks like uname:udom#comments
                    896: # comments are being appended
                    897: #
                    898:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                    899:     $cdom=
1.620     albertel  900:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www       901:     $cnum=
1.620     albertel  902:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www       903:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                    904:     if ($existing{$ckey}) {
                    905:         $existing{$ckey}.='; '.$logentry;
                    906: # ready to assign
1.367     www       907:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www       908:                                                  $cdom,$cnum) eq 'ok') {
                    909: 	    return 'ok';
                    910:         } else {
                    911: 	    return 'error: Count not store comment.';
                    912:         }
                    913:     } else {
                    914: # the key does not exist
                    915: 	return 'error: The key does not exist';
                    916:     }
                    917: }
                    918: 
1.344     www       919: # ------------------------------------------------------ Generate a set of keys
                    920: 
                    921: sub generate_access_keys {
1.364     www       922:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www       923:     $cdom=
1.620     albertel  924:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       925:     $cnum=
1.620     albertel  926:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www       927:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www       928:     unless (($cdom) && ($cnum)) { return 0; }
                    929:     if ($number>10000) { return 0; }
                    930:     sleep(2); # make sure don't get same seed twice
                    931:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                    932:     my $total=0;
                    933:     for (my $i=1;$i<=$number;$i++) {
                    934:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                    935:                   sprintf("%lx",int(100000*rand)).'-'.
                    936:                   sprintf("%lx",int(100000*rand));
                    937:        $newkey=~s/1/g/g; # folks mix up 1 and l
                    938:        $newkey=~s/0/h/g; # and also 0 and O
                    939:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                    940:        if ($existing{$newkey}) {
                    941:            $i--;
                    942:        } else {
1.364     www       943: 	  if (&put('accesskeys',
                    944:               { $newkey => '# generated '.localtime().
1.620     albertel  945:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www       946:                            '; '.$logentry },
                    947: 		   $cdom,$cnum) eq 'ok') {
1.344     www       948:               $total++;
                    949: 	  }
                    950:        }
                    951:     }
1.620     albertel  952:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www       953:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                    954:     return $total;
                    955: }
                    956: 
                    957: # ------------------------------------------------------- Validate an accesskey
                    958: 
                    959: sub validate_access_key {
                    960:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                    961:     $cdom=
1.620     albertel  962:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       963:     $cnum=
1.620     albertel  964:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                    965:     $udom=$env{'user.domain'} unless (defined($udom));
                    966:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www       967:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel  968:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www       969: }
                    970: 
                    971: # ------------------------------------- Find the section of student in a course
1.652     albertel  972: sub devalidate_getsection_cache {
                    973:     my ($udom,$unam,$courseid)=@_;
                    974:     my $hashid="$udom:$unam:$courseid";
                    975:     &devalidate_cache_new('getsection',$hashid);
                    976: }
1.298     matthew   977: 
1.815     albertel  978: sub courseid_to_courseurl {
                    979:     my ($courseid) = @_;
                    980:     #already url style courseid
                    981:     return $courseid if ($courseid =~ m{^/});
                    982: 
                    983:     if (exists($env{'course.'.$courseid.'.num'})) {
                    984: 	my $cnum = $env{'course.'.$courseid.'.num'};
                    985: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                    986: 	return "/$cdom/$cnum";
                    987:     }
                    988: 
                    989:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                    990:     if (exists($courseinfo{'num'})) {
                    991: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                    992:     }
                    993: 
                    994:     return undef;
                    995: }
                    996: 
1.298     matthew   997: sub getsection {
                    998:     my ($udom,$unam,$courseid)=@_;
1.599     albertel  999:     my $cachetime=1800;
1.551     albertel 1000: 
                   1001:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 1002:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 1003:     if (defined($cached)) { return $result; }
                   1004: 
1.298     matthew  1005:     my %Pending; 
                   1006:     my %Expired;
                   1007:     #
                   1008:     # Each role can either have not started yet (pending), be active, 
                   1009:     #    or have expired.
                   1010:     #
                   1011:     # If there is an active role, we are done.
                   1012:     #
                   1013:     # If there is more than one role which has not started yet, 
                   1014:     #     choose the one which will start sooner
                   1015:     # If there is one role which has not started yet, return it.
                   1016:     #
                   1017:     # If there is more than one expired role, choose the one which ended last.
                   1018:     # If there is a role which has expired, return it.
                   1019:     #
1.815     albertel 1020:     $courseid = &courseid_to_courseurl($courseid);
1.817     raeburn  1021:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
                   1022:     foreach my $key (keys(%roleshash)) {
1.479     albertel 1023:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  1024:         my $section=$1;
                   1025:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  1026:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  1027:         my $now=time;
1.548     albertel 1028:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  1029:             $Expired{$end}=$section;
                   1030:             next;
                   1031:         }
1.548     albertel 1032:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  1033:             $Pending{$start}=$section;
                   1034:             next;
                   1035:         }
1.599     albertel 1036:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  1037:     }
                   1038:     #
                   1039:     # Presumedly there will be few matching roles from the above
                   1040:     # loop and the sorting time will be negligible.
                   1041:     if (scalar(keys(%Pending))) {
                   1042:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 1043:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  1044:     } 
                   1045:     if (scalar(keys(%Expired))) {
                   1046:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   1047:         my $time = pop(@sorted);
1.599     albertel 1048:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  1049:     }
1.599     albertel 1050:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  1051: }
1.70      www      1052: 
1.599     albertel 1053: sub save_cache {
                   1054:     &purge_remembered();
1.722     albertel 1055:     #&Apache::loncommon::validate_page();
1.620     albertel 1056:     undef(%env);
1.780     albertel 1057:     undef($env_loaded);
1.599     albertel 1058: }
1.452     albertel 1059: 
1.599     albertel 1060: my $to_remember=-1;
                   1061: my %remembered;
                   1062: my %accessed;
                   1063: my $kicks=0;
                   1064: my $hits=0;
1.849     albertel 1065: sub make_key {
                   1066:     my ($name,$id) = @_;
1.872     albertel 1067:     if (length($id) > 65 
                   1068: 	&& length(&escape($id)) > 200) {
                   1069: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   1070:     }
1.849     albertel 1071:     return &escape($name.':'.$id);
                   1072: }
                   1073: 
1.599     albertel 1074: sub devalidate_cache_new {
                   1075:     my ($name,$id,$debug) = @_;
                   1076:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 1077:     $id=&make_key($name,$id);
1.599     albertel 1078:     $memcache->delete($id);
                   1079:     delete($remembered{$id});
                   1080:     delete($accessed{$id});
                   1081: }
                   1082: 
                   1083: sub is_cached_new {
                   1084:     my ($name,$id,$debug) = @_;
1.849     albertel 1085:     $id=&make_key($name,$id);
1.599     albertel 1086:     if (exists($remembered{$id})) {
                   1087: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                   1088: 	$accessed{$id}=[&gettimeofday()];
                   1089: 	$hits++;
                   1090: 	return ($remembered{$id},1);
                   1091:     }
                   1092:     my $value = $memcache->get($id);
                   1093:     if (!(defined($value))) {
                   1094: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 1095: 	return (undef,undef);
1.416     albertel 1096:     }
1.599     albertel 1097:     if ($value eq '__undef__') {
                   1098: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   1099: 	$value=undef;
                   1100:     }
                   1101:     &make_room($id,$value,$debug);
                   1102:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   1103:     return ($value,1);
                   1104: }
                   1105: 
                   1106: sub do_cache_new {
                   1107:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 1108:     $id=&make_key($name,$id);
1.599     albertel 1109:     my $setvalue=$value;
                   1110:     if (!defined($setvalue)) {
                   1111: 	$setvalue='__undef__';
                   1112:     }
1.623     albertel 1113:     if (!defined($time) ) {
                   1114: 	$time=600;
                   1115:     }
1.599     albertel 1116:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.872     albertel 1117:     if (!($memcache->set($id,$setvalue,$time))) {
                   1118: 	&logthis("caching of id -> $id  failed");
                   1119:     }
1.600     albertel 1120:     # need to make a copy of $value
                   1121:     #&make_room($id,$value,$debug);
1.599     albertel 1122:     return $value;
                   1123: }
                   1124: 
                   1125: sub make_room {
                   1126:     my ($id,$value,$debug)=@_;
                   1127:     $remembered{$id}=$value;
                   1128:     if ($to_remember<0) { return; }
                   1129:     $accessed{$id}=[&gettimeofday()];
                   1130:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   1131:     my $to_kick;
                   1132:     my $max_time=0;
                   1133:     foreach my $other (keys(%accessed)) {
                   1134: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   1135: 	    $to_kick=$other;
                   1136: 	    $max_time=&tv_interval($accessed{$other});
                   1137: 	}
                   1138:     }
                   1139:     delete($remembered{$to_kick});
                   1140:     delete($accessed{$to_kick});
                   1141:     $kicks++;
                   1142:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 1143:     return;
                   1144: }
                   1145: 
1.599     albertel 1146: sub purge_remembered {
1.604     albertel 1147:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   1148:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 1149:     undef(%remembered);
                   1150:     undef(%accessed);
1.428     albertel 1151: }
1.70      www      1152: # ------------------------------------- Read an entry from a user's environment
                   1153: 
                   1154: sub userenvironment {
                   1155:     my ($udom,$unam,@what)=@_;
                   1156:     my %returnhash=();
                   1157:     my @answer=split(/\&/,
                   1158:                 &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
                   1159:                       &homeserver($unam,$udom)));
                   1160:     my $i;
                   1161:     for ($i=0;$i<=$#what;$i++) {
                   1162: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
                   1163:     }
                   1164:     return %returnhash;
1.1       albertel 1165: }
                   1166: 
1.617     albertel 1167: # ---------------------------------------------------------- Get a studentphoto
                   1168: sub studentphoto {
                   1169:     my ($udom,$unam,$ext) = @_;
                   1170:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  1171:     if (defined($env{'request.course.id'})) {
1.708     raeburn  1172:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  1173:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   1174:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   1175:             } else {
                   1176:                 my ($result,$perm_reqd)=
1.707     albertel 1177: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1178:                 if ($result eq 'ok') {
                   1179:                     if (!($perm_reqd eq 'yes')) {
                   1180:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   1181:                     }
                   1182:                 }
                   1183:             }
                   1184:         }
                   1185:     } else {
                   1186:         my ($result,$perm_reqd) = 
1.707     albertel 1187: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1188:         if ($result eq 'ok') {
                   1189:             if (!($perm_reqd eq 'yes')) {
                   1190:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   1191:             }
                   1192:         }
                   1193:     }
                   1194:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   1195: }
                   1196: 
                   1197: sub retrievestudentphoto {
                   1198:     my ($udom,$unam,$ext,$type) = @_;
                   1199:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   1200:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   1201:     if ($ret eq 'ok') {
                   1202:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   1203:         if ($type eq 'thumbnail') {
                   1204:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   1205:         }
                   1206:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   1207:         return $tokenurl;
                   1208:     } else {
                   1209:         if ($type eq 'thumbnail') {
                   1210:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   1211:         } else { 
                   1212:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   1213:         }
1.617     albertel 1214:     }
                   1215: }
                   1216: 
1.263     www      1217: # -------------------------------------------------------------------- New chat
                   1218: 
                   1219: sub chatsend {
1.724     raeburn  1220:     my ($newentry,$anon,$group)=@_;
1.620     albertel 1221:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1222:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1223:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      1224:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 1225: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  1226: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      1227: }
                   1228: 
                   1229: # ------------------------------------------ Find current version of a resource
                   1230: 
                   1231: sub getversion {
                   1232:     my $fname=&clutter(shift);
                   1233:     unless ($fname=~/^\/res\//) { return -1; }
                   1234:     return &currentversion(&filelocation('',$fname));
                   1235: }
                   1236: 
                   1237: sub currentversion {
                   1238:     my $fname=shift;
1.599     albertel 1239:     my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440     www      1240:     if (defined($cached)) { return $result; }
1.292     www      1241:     my $author=$fname;
                   1242:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1243:     my ($udom,$uname)=split(/\//,$author);
                   1244:     my $home=homeserver($uname,$udom);
                   1245:     if ($home eq 'no_host') { 
                   1246:         return -1; 
                   1247:     }
                   1248:     my $answer=reply("currentversion:$fname",$home);
                   1249:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1250: 	return -1;
                   1251:     }
1.599     albertel 1252:     return &do_cache_new('resversion',$fname,$answer,600);
1.263     www      1253: }
                   1254: 
1.1       albertel 1255: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      1256: 
1.1       albertel 1257: sub subscribe {
                   1258:     my $fname=shift;
1.761     raeburn  1259:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 1260:     $fname=~s/[\n\r]//g;
1.1       albertel 1261:     my $author=$fname;
                   1262:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1263:     my ($udom,$uname)=split(/\//,$author);
                   1264:     my $home=homeserver($uname,$udom);
1.335     albertel 1265:     if ($home eq 'no_host') {
                   1266:         return 'not_found';
1.1       albertel 1267:     }
                   1268:     my $answer=reply("sub:$fname",$home);
1.64      www      1269:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1270: 	$answer.=' by '.$home;
                   1271:     }
1.1       albertel 1272:     return $answer;
                   1273: }
                   1274:     
1.8       www      1275: # -------------------------------------------------------------- Replicate file
                   1276: 
                   1277: sub repcopy {
                   1278:     my $filename=shift;
1.23      www      1279:     $filename=~s/\/+/\//g;
1.607     raeburn  1280:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   1281:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 1282:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 1283: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 1284: 	return &repcopy_userfile($filename);
                   1285:     }
1.532     albertel 1286:     $filename=~s/[\n\r]//g;
1.8       www      1287:     my $transname="$filename.in.transfer";
1.828     www      1288: # FIXME: this should flock
1.607     raeburn  1289:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      1290:     my $remoteurl=subscribe($filename);
1.64      www      1291:     if ($remoteurl =~ /^con_lost by/) {
                   1292: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1293:            return 'unavailable';
1.8       www      1294:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 1295: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  1296: 	   return 'not_found';
1.64      www      1297:     } elsif ($remoteurl =~ /^rejected by/) {
                   1298: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1299:            return 'forbidden';
1.20      www      1300:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  1301:            return 'ok';
1.8       www      1302:     } else {
1.290     www      1303:         my $author=$filename;
                   1304:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1305:         my ($udom,$uname)=split(/\//,$author);
                   1306:         my $home=homeserver($uname,$udom);
                   1307:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      1308:            my @parts=split(/\//,$filename);
                   1309:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   1310:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   1311:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  1312: 	       return 'bad_request';
1.8       www      1313:            }
                   1314:            my $count;
                   1315:            for ($count=5;$count<$#parts;$count++) {
                   1316:                $path.="/$parts[$count]";
                   1317:                if ((-e $path)!=1) {
                   1318: 		   mkdir($path,0777);
                   1319:                }
                   1320:            }
                   1321:            my $ua=new LWP::UserAgent;
                   1322:            my $request=new HTTP::Request('GET',"$remoteurl");
                   1323:            my $response=$ua->request($request,$transname);
                   1324:            if ($response->is_error()) {
                   1325: 	       unlink($transname);
                   1326:                my $message=$response->status_line;
1.672     albertel 1327:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      1328:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  1329:                return 'unavailable';
1.8       www      1330:            } else {
1.16      www      1331: 	       if ($remoteurl!~/\.meta$/) {
                   1332:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   1333:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   1334:                   if ($mresponse->is_error()) {
                   1335: 		      unlink($filename.'.meta');
                   1336:                       &logthis(
1.672     albertel 1337:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      1338:                   }
                   1339: 	       }
1.8       www      1340:                rename($transname,$filename);
1.607     raeburn  1341:                return 'ok';
1.8       www      1342:            }
1.290     www      1343:        }
1.8       www      1344:     }
1.330     www      1345: }
                   1346: 
                   1347: # ------------------------------------------------ Get server side include body
                   1348: sub ssi_body {
1.381     albertel 1349:     my ($filelink,%form)=@_;
1.606     matthew  1350:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   1351:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   1352:     }
1.330     www      1353:     my $output=($filelink=~/^http\:/?&externalssi($filelink):
1.381     albertel 1354:                                      &ssi($filelink,%form));
1.778     albertel 1355:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 1356:     $output=~s/^.*?\<body[^\>]*\>//si;
                   1357:     $output=~s/(.*)\<\/body\s*\>.*?$/$1/si;
1.330     www      1358:     return $output;
1.8       www      1359: }
                   1360: 
1.15      www      1361: # --------------------------------------------------------- Server Side Include
                   1362: 
1.782     albertel 1363: sub absolute_url {
                   1364:     my ($host_name) = @_;
                   1365:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   1366:     if ($host_name eq '') {
                   1367: 	$host_name = $ENV{'SERVER_NAME'};
                   1368:     }
                   1369:     return $protocol.$host_name;
                   1370: }
                   1371: 
1.15      www      1372: sub ssi {
                   1373: 
1.23      www      1374:     my ($fn,%form)=@_;
1.15      www      1375: 
                   1376:     my $ua=new LWP::UserAgent;
1.23      www      1377:     
                   1378:     my $request;
1.711     albertel 1379: 
                   1380:     $form{'no_update_last_known'}=1;
                   1381: 
1.23      www      1382:     if (%form) {
1.782     albertel 1383:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.201     albertel 1384:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1.23      www      1385:     } else {
1.782     albertel 1386:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      1387:     }
                   1388: 
1.15      www      1389:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   1390:     my $response=$ua->request($request);
                   1391: 
1.324     www      1392:     return $response->content;
                   1393: }
                   1394: 
                   1395: sub externalssi {
                   1396:     my ($url)=@_;
                   1397:     my $ua=new LWP::UserAgent;
                   1398:     my $request=new HTTP::Request('GET',$url);
                   1399:     my $response=$ua->request($request);
1.15      www      1400:     return $response->content;
                   1401: }
1.254     www      1402: 
1.492     albertel 1403: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   1404: 
                   1405: sub allowuploaded {
                   1406:     my ($srcurl,$url)=@_;
                   1407:     $url=&clutter(&declutter($url));
                   1408:     my $dir=$url;
                   1409:     $dir=~s/\/[^\/]+$//;
                   1410:     my %httpref=();
                   1411:     my $httpurl=&hreflocation('',$url);
                   1412:     $httpref{'httpref.'.$httpurl}=$srcurl;
                   1413:     &Apache::lonnet::appenv(%httpref);
1.254     www      1414: }
1.477     raeburn  1415: 
1.478     albertel 1416: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 1417: # input: action, courseID, current domain, intended
1.637     raeburn  1418: #        path to file, source of file, instruction to parse file for objects,
                   1419: #        ref to hash for embedded objects,
                   1420: #        ref to hash for codebase of java objects.
                   1421: #
1.485     raeburn  1422: # output: url to file (if action was uploaddoc), 
                   1423: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  1424: #
1.478     albertel 1425: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   1426: # course.
1.477     raeburn  1427: #
1.478     albertel 1428: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1429: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   1430: #          course's home server.
1.477     raeburn  1431: #
1.478     albertel 1432: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   1433: #          be copied from $source (current location) to 
                   1434: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1435: #         and will then be copied to
                   1436: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   1437: #         course's home server.
1.485     raeburn  1438: #
1.481     raeburn  1439: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 1440: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  1441: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1442: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   1443: #         in course's home server.
1.637     raeburn  1444: #
1.477     raeburn  1445: 
                   1446: sub process_coursefile {
1.638     albertel 1447:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477     raeburn  1448:     my $fetchresult;
1.638     albertel 1449:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  1450:     if ($action eq 'propagate') {
1.638     albertel 1451:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   1452: 			     $home);
1.481     raeburn  1453:     } else {
1.477     raeburn  1454:         my $fpath = '';
                   1455:         my $fname = $file;
1.478     albertel 1456:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  1457:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  1458:         my $filepath = &build_filepath($fpath);
1.481     raeburn  1459:         if ($action eq 'copy') {
                   1460:             if ($source eq '') {
                   1461:                 $fetchresult = 'no source file';
                   1462:                 return $fetchresult;
                   1463:             } else {
                   1464:                 my $destination = $filepath.'/'.$fname;
                   1465:                 rename($source,$destination);
                   1466:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1467:                                  $home);
1.481     raeburn  1468:             }
                   1469:         } elsif ($action eq 'uploaddoc') {
                   1470:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 1471:             print $fh $env{'form.'.$source};
1.481     raeburn  1472:             close($fh);
1.637     raeburn  1473:             if ($parser eq 'parse') {
                   1474:                 my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
                   1475:                 unless ($parse_result eq 'ok') {
                   1476:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   1477:                 }
                   1478:             }
1.477     raeburn  1479:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1480:                                  $home);
1.481     raeburn  1481:             if ($fetchresult eq 'ok') {
                   1482:                 return '/uploaded/'.$fpath.'/'.$fname;
                   1483:             } else {
                   1484:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1485:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  1486:                 return '/adm/notfound.html';
                   1487:             }
1.477     raeburn  1488:         }
                   1489:     }
1.485     raeburn  1490:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  1491:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1492:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  1493:     }
                   1494:     return $fetchresult;
                   1495: }
                   1496: 
1.637     raeburn  1497: sub build_filepath {
                   1498:     my ($fpath) = @_;
                   1499:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   1500:     unless ($fpath eq '') {
                   1501:         my @parts=split('/',$fpath);
                   1502:         foreach my $part (@parts) {
                   1503:             $filepath.= '/'.$part;
                   1504:             if ((-e $filepath)!=1) {
                   1505:                 mkdir($filepath,0777);
                   1506:             }
                   1507:         }
                   1508:     }
                   1509:     return $filepath;
                   1510: }
                   1511: 
                   1512: sub store_edited_file {
1.638     albertel 1513:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  1514:     my $file = $primary_url;
                   1515:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   1516:     my $fpath = '';
                   1517:     my $fname = $file;
                   1518:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   1519:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   1520:     my $filepath = &build_filepath($fpath);
                   1521:     open(my $fh,'>'.$filepath.'/'.$fname);
                   1522:     print $fh $content;
                   1523:     close($fh);
1.638     albertel 1524:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  1525:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1526: 			  $home);
1.637     raeburn  1527:     if ($$fetchresult eq 'ok') {
                   1528:         return '/uploaded/'.$fpath.'/'.$fname;
                   1529:     } else {
1.638     albertel 1530:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   1531: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  1532:         return '/adm/notfound.html';
                   1533:     }
                   1534: }
                   1535: 
1.531     albertel 1536: sub clean_filename {
1.831     albertel 1537:     my ($fname,$args)=@_;
1.315     www      1538: # Replace Windows backslashes by forward slashes
1.257     www      1539:     $fname=~s/\\/\//g;
1.831     albertel 1540:     if (!$args->{'keep_path'}) {
                   1541:         # Get rid of everything but the actual filename
                   1542: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   1543:     }
1.315     www      1544: # Replace spaces by underscores
                   1545:     $fname=~s/\s+/\_/g;
                   1546: # Replace all other weird characters by nothing
1.831     albertel 1547:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 1548: # Replace all .\d. sequences with _\d. so they no longer look like version
                   1549: # numbers
                   1550:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 1551:     return $fname;
                   1552: }
                   1553: 
1.608     albertel 1554: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 1555: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719     banghart 1556: #                    the desired filenam is in $env{"form.$formname.filename"}
1.686     albertel 1557: #        $coursedoc - if true up to the current course
                   1558: #                     if false
                   1559: #        $subdir - directory in userfile to store the file into
1.858     raeburn  1560: #        $parser - instruction to parse file for objects ($parser = parse)    
                   1561: #        $allfiles - reference to hash for embedded objects
                   1562: #        $codebase - reference to hash for codebase of java objects
                   1563: #        $desuname - username for permanent storage of uploaded file
                   1564: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  1565: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   1566: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.858     raeburn  1567: # 
1.686     albertel 1568: # output: url of file in userspace, or error: <message> 
                   1569: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 1570: 
                   1571: 
1.531     albertel 1572: sub userfileupload {
1.860     raeburn  1573:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
                   1574:         $destudom,$thumbwidth,$thumbheight)=@_;
1.531     albertel 1575:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 1576:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 1577:     $fname=&clean_filename($fname);
1.315     www      1578: # See if there is anything left
1.257     www      1579:     unless ($fname) { return 'error: no uploaded file'; }
1.620     albertel 1580:     chop($env{'form.'.$formname});
1.523     raeburn  1581:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
                   1582:         my $now = time;
                   1583:         my $filepath = 'tmp/helprequests/'.$now;
                   1584:         my @parts=split(/\//,$filepath);
                   1585:         my $fullpath = $perlvar{'lonDaemons'};
                   1586:         for (my $i=0;$i<@parts;$i++) {
                   1587:             $fullpath .= '/'.$parts[$i];
                   1588:             if ((-e $fullpath)!=1) {
                   1589:                 mkdir($fullpath,0777);
                   1590:             }
                   1591:         }
                   1592:         open(my $fh,'>'.$fullpath.'/'.$fname);
1.620     albertel 1593:         print $fh $env{'form.'.$formname};
1.523     raeburn  1594:         close($fh);
1.741     raeburn  1595:         return $fullpath.'/'.$fname;
                   1596:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
                   1597:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   1598:                        '_'.$env{'user.domain'}.'/pending';
                   1599:         my @parts=split(/\//,$filepath);
                   1600:         my $fullpath = $perlvar{'lonDaemons'};
                   1601:         for (my $i=0;$i<@parts;$i++) {
                   1602:             $fullpath .= '/'.$parts[$i];
                   1603:             if ((-e $fullpath)!=1) {
                   1604:                 mkdir($fullpath,0777);
                   1605:             }
                   1606:         }
                   1607:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   1608:         print $fh $env{'form.'.$formname};
                   1609:         close($fh);
                   1610:         return $fullpath.'/'.$fname;
1.523     raeburn  1611:     }
1.719     banghart 1612:     
1.258     www      1613: # Create the directory if not present
1.493     albertel 1614:     $fname="$subdir/$fname";
1.259     www      1615:     if ($coursedoc) {
1.638     albertel 1616: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1617: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  1618:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 1619:             return &finishuserfileupload($docuname,$docudom,
                   1620: 					 $formname,$fname,$parser,$allfiles,
1.860     raeburn  1621: 					 $codebase,$thumbwidth,$thumbheight);
1.481     raeburn  1622:         } else {
1.620     albertel 1623:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 1624:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   1625: 				       $fname,$formname,$parser,
                   1626: 				       $allfiles,$codebase);
1.481     raeburn  1627:         }
1.719     banghart 1628:     } elsif (defined($destuname)) {
                   1629:         my $docuname=$destuname;
                   1630:         my $docudom=$destudom;
1.860     raeburn  1631: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   1632: 				     $parser,$allfiles,$codebase,
                   1633:                                      $thumbwidth,$thumbheight);
1.719     banghart 1634:         
1.259     www      1635:     } else {
1.638     albertel 1636:         my $docuname=$env{'user.name'};
                   1637:         my $docudom=$env{'user.domain'};
1.714     raeburn  1638:         if (exists($env{'form.group'})) {
                   1639:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1640:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1641:         }
1.860     raeburn  1642: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   1643: 				     $parser,$allfiles,$codebase,
                   1644:                                      $thumbwidth,$thumbheight);
1.259     www      1645:     }
1.271     www      1646: }
                   1647: 
                   1648: sub finishuserfileupload {
1.860     raeburn  1649:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
                   1650:         $thumbwidth,$thumbheight) = @_;
1.477     raeburn  1651:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      1652:     my $filepath=$perlvar{'lonDocRoot'};
1.860     raeburn  1653:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 1654:     $file=$fname;
                   1655:     if ($fname=~m|/|) {
                   1656:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   1657: 	$path.=$fnamepath.'/';
                   1658:     }
1.259     www      1659:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      1660:     my $count;
                   1661:     for ($count=4;$count<=$#parts;$count++) {
                   1662:         $filepath.="/$parts[$count]";
                   1663:         if ((-e $filepath)!=1) {
                   1664: 	    mkdir($filepath,0777);
                   1665:         }
                   1666:     }
                   1667: # Save the file
                   1668:     {
1.701     albertel 1669: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   1670: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   1671: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   1672: 	    return '/adm/notfound.html';
                   1673: 	}
                   1674: 	if (!print FH ($env{'form.'.$formname})) {
                   1675: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   1676: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   1677: 	    return '/adm/notfound.html';
                   1678: 	}
1.570     albertel 1679: 	close(FH);
1.258     www      1680:     }
1.637     raeburn  1681:     if ($parser eq 'parse') {
1.638     albertel 1682:         my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
                   1683: 						   $codebase);
1.637     raeburn  1684:         unless ($parse_result eq 'ok') {
1.638     albertel 1685:             &logthis('Failed to parse '.$filepath.$file.
                   1686: 		     ' for embedded media: '.$parse_result); 
1.637     raeburn  1687:         }
                   1688:     }
1.860     raeburn  1689:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   1690:         my $input = $filepath.'/'.$file;
                   1691:         my $output = $filepath.'/'.'tn-'.$file;
                   1692:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   1693:         system("convert -sample $thumbsize $input $output");
                   1694:         if (-e $filepath.'/'.'tn-'.$file) {
                   1695:             $fetchthumb  = 1; 
                   1696:         }
                   1697:     }
1.858     raeburn  1698:  
1.259     www      1699: # Notify homeserver to grep it
                   1700: #
1.638     albertel 1701:     my $docuhome=&homeserver($docuname,$docudom);
1.494     albertel 1702:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      1703:     if ($fetchresult eq 'ok') {
1.860     raeburn  1704:         if ($fetchthumb) {
                   1705:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   1706:             if ($thumbresult ne 'ok') {
                   1707:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   1708:                          $docuhome.': '.$thumbresult);
                   1709:             }
                   1710:         }
1.259     www      1711: #
1.258     www      1712: # Return the URL to it
1.494     albertel 1713:         return '/uploaded/'.$path.$file;
1.263     www      1714:     } else {
1.494     albertel 1715:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   1716: 		 ': '.$fetchresult);
1.263     www      1717:         return '/adm/notfound.html';
1.858     raeburn  1718:     }
1.493     albertel 1719: }
                   1720: 
1.637     raeburn  1721: sub extract_embedded_items {
1.648     raeburn  1722:     my ($filepath,$file,$allfiles,$codebase,$content) = @_;
1.637     raeburn  1723:     my @state = ();
                   1724:     my %javafiles = (
                   1725:                       codebase => '',
                   1726:                       code => '',
                   1727:                       archive => ''
                   1728:                     );
                   1729:     my %mediafiles = (
                   1730:                       src => '',
                   1731:                       movie => '',
                   1732:                      );
1.648     raeburn  1733:     my $p;
                   1734:     if ($content) {
                   1735:         $p = HTML::LCParser->new($content);
                   1736:     } else {
                   1737:         $p = HTML::LCParser->new($filepath.'/'.$file);
                   1738:     }
1.641     albertel 1739:     while (my $t=$p->get_token()) {
1.640     albertel 1740: 	if ($t->[0] eq 'S') {
                   1741: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 1742: 	    push(@state, $tagname);
1.648     raeburn  1743:             if (lc($tagname) eq 'allow') {
                   1744:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   1745:             }
1.640     albertel 1746: 	    if (lc($tagname) eq 'img') {
                   1747: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   1748: 	    }
1.886     albertel 1749: 	    if (lc($tagname) eq 'a') {
                   1750: 		&add_filetype($allfiles,$attr->{'href'},'href');
                   1751: 	    }
1.645     raeburn  1752:             if (lc($tagname) eq 'script') {
                   1753:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   1754:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   1755:                 } else {
                   1756:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   1757:                 }
                   1758:             }
                   1759:             if (lc($tagname) eq 'link') {
                   1760:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   1761:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   1762:                 }
                   1763:             }
1.640     albertel 1764: 	    if (lc($tagname) eq 'object' ||
                   1765: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   1766: 		foreach my $item (keys(%javafiles)) {
                   1767: 		    $javafiles{$item} = '';
                   1768: 		}
                   1769: 	    }
                   1770: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   1771: 		my $name = lc($attr->{'name'});
                   1772: 		foreach my $item (keys(%javafiles)) {
                   1773: 		    if ($name eq $item) {
                   1774: 			$javafiles{$item} = $attr->{'value'};
                   1775: 			last;
                   1776: 		    }
                   1777: 		}
                   1778: 		foreach my $item (keys(%mediafiles)) {
                   1779: 		    if ($name eq $item) {
                   1780: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   1781: 			last;
                   1782: 		    }
                   1783: 		}
                   1784: 	    }
                   1785: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   1786: 		foreach my $item (keys(%javafiles)) {
                   1787: 		    if ($attr->{$item}) {
                   1788: 			$javafiles{$item} = $attr->{$item};
                   1789: 			last;
                   1790: 		    }
                   1791: 		}
                   1792: 		foreach my $item (keys(%mediafiles)) {
                   1793: 		    if ($attr->{$item}) {
                   1794: 			&add_filetype($allfiles,$attr->{$item},$item);
                   1795: 			last;
                   1796: 		    }
                   1797: 		}
                   1798: 	    }
                   1799: 	} elsif ($t->[0] eq 'E') {
                   1800: 	    my ($tagname) = ($t->[1]);
                   1801: 	    if ($javafiles{'codebase'} ne '') {
                   1802: 		$javafiles{'codebase'} .= '/';
                   1803: 	    }  
                   1804: 	    if (lc($tagname) eq 'applet' ||
                   1805: 		lc($tagname) eq 'object' ||
                   1806: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   1807: 		) {
                   1808: 		foreach my $item (keys(%javafiles)) {
                   1809: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   1810: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   1811: 			&add_filetype($allfiles,$file,$item);
                   1812: 		    }
                   1813: 		}
                   1814: 	    } 
                   1815: 	    pop @state;
                   1816: 	}
                   1817:     }
1.637     raeburn  1818:     return 'ok';
                   1819: }
                   1820: 
1.639     albertel 1821: sub add_filetype {
                   1822:     my ($allfiles,$file,$type)=@_;
                   1823:     if (exists($allfiles->{$file})) {
                   1824: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   1825: 	    push(@{$allfiles->{$file}}, &escape($type));
                   1826: 	}
                   1827:     } else {
                   1828: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  1829:     }
                   1830: }
                   1831: 
1.493     albertel 1832: sub removeuploadedurl {
                   1833:     my ($url)=@_;
                   1834:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613     albertel 1835:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 1836: }
                   1837: 
                   1838: sub removeuserfile {
                   1839:     my ($docuname,$docudom,$fname)=@_;
                   1840:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  1841:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
                   1842:     if ($result eq 'ok') {
                   1843:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   1844:             my $metafile = $fname.'.meta';
                   1845:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 1846: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
                   1847:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  1848:             my $sqlresult = 
1.823     albertel 1849:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  1850:                                         'portfolio_metadata',$group,
                   1851:                                         'delete');
1.798     raeburn  1852:         }
                   1853:     }
                   1854:     return $result;
1.257     www      1855: }
1.15      www      1856: 
1.530     albertel 1857: sub mkdiruserfile {
                   1858:     my ($docuname,$docudom,$dir)=@_;
                   1859:     my $home=&homeserver($docuname,$docudom);
                   1860:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   1861: }
                   1862: 
1.531     albertel 1863: sub renameuserfile {
                   1864:     my ($docuname,$docudom,$old,$new)=@_;
                   1865:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  1866:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   1867:                         &escape("$old").':'.&escape("$new"),$home);
                   1868:     if ($result eq 'ok') {
                   1869:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   1870:             my $oldmeta = $old.'.meta';
                   1871:             my $newmeta = $new.'.meta';
                   1872:             my $metaresult = 
                   1873:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 1874: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   1875:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  1876:             my $sqlresult = 
1.823     albertel 1877:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  1878:                                         'portfolio_metadata',$group,
                   1879:                                         'delete');
1.798     raeburn  1880:         }
                   1881:     }
                   1882:     return $result;
1.531     albertel 1883: }
                   1884: 
1.14      www      1885: # ------------------------------------------------------------------------- Log
                   1886: 
                   1887: sub log {
                   1888:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      1889:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      1890: }
                   1891: 
                   1892: # ------------------------------------------------------------------ Course Log
1.352     www      1893: #
                   1894: # This routine flushes several buffers of non-mission-critical nature
                   1895: #
1.157     www      1896: 
                   1897: sub flushcourselogs {
1.352     www      1898:     &logthis('Flushing log buffers');
                   1899: #
                   1900: # course logs
                   1901: # This is a log of all transactions in a course, which can be used
                   1902: # for data mining purposes
                   1903: #
                   1904: # It also collects the courseid database, which lists last transaction
                   1905: # times and course titles for all courseids
                   1906: #
                   1907:     my %courseidbuffer=();
1.800     albertel 1908:     foreach my $crsid (keys %courselogs) {
1.352     www      1909:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      1910: 		          &escape($courselogs{$crsid}),
                   1911: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      1912: 	    delete $courselogs{$crsid};
                   1913:         } else {
                   1914:             &logthis('Failed to flush log buffer for '.$crsid);
                   1915:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 1916:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      1917:                         " exceeded maximum size, deleting.</font>");
                   1918:                delete $courselogs{$crsid};
                   1919:             }
1.352     www      1920:         }
                   1921:         if ($courseidbuffer{$coursehombuf{$crsid}}) {
                   1922:            $courseidbuffer{$coursehombuf{$crsid}}.='&'.
1.516     raeburn  1923: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.741     raeburn  1924:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1.352     www      1925:         } else {
                   1926:            $courseidbuffer{$coursehombuf{$crsid}}=
1.516     raeburn  1927: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.741     raeburn  1928:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1.571     raeburn  1929:         }
1.191     harris41 1930:     }
1.352     www      1931: #
                   1932: # Write course id database (reverse lookup) to homeserver of courses 
                   1933: # Is used in pickcourse
                   1934: #
1.840     albertel 1935:     foreach my $crs_home (keys(%courseidbuffer)) {
1.844     albertel 1936:         &courseidput(&host_domain($crs_home),$courseidbuffer{$crs_home},
1.840     albertel 1937: 		     $crs_home);
1.352     www      1938:     }
                   1939: #
                   1940: # File accesses
                   1941: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   1942: #
1.449     matthew  1943:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  1944:         if ($entry =~ /___count$/) {
                   1945:             my ($dom,$name);
1.807     albertel 1946:             ($dom,$name,undef)=
1.811     albertel 1947: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  1948:             if (! defined($dom) || $dom eq '' || 
                   1949:                 ! defined($name) || $name eq '') {
1.620     albertel 1950:                 my $cid = $env{'request.course.id'};
                   1951:                 $dom  = $env{'request.'.$cid.'.domain'};
                   1952:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  1953:             }
1.450     matthew  1954:             my $value = $accesshash{$entry};
                   1955:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   1956:             my %temphash=($url => $value);
1.449     matthew  1957:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   1958:             if ($result eq 'ok') {
                   1959:                 delete $accesshash{$entry};
                   1960:             } elsif ($result eq 'unknown_cmd') {
                   1961:                 # Target server has old code running on it.
1.450     matthew  1962:                 my %temphash=($entry => $value);
1.449     matthew  1963:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   1964:                     delete $accesshash{$entry};
                   1965:                 }
                   1966:             }
                   1967:         } else {
1.811     albertel 1968:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450     matthew  1969:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  1970:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   1971:                 delete $accesshash{$entry};
                   1972:             }
1.185     www      1973:         }
1.191     harris41 1974:     }
1.352     www      1975: #
                   1976: # Roles
                   1977: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   1978: #
1.800     albertel 1979:     foreach my $entry (keys(%userrolehash)) {
1.351     www      1980:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      1981: 	    split(/\:/,$entry);
                   1982:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      1983:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      1984:                 $rudom,$runame) eq 'ok') {
                   1985: 	    delete $userrolehash{$entry};
                   1986:         }
                   1987:     }
1.662     raeburn  1988: #
                   1989: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   1990: #
                   1991:     my %domrolebuffer = ();
                   1992:     foreach my $entry (keys %domainrolehash) {
                   1993:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split/:/,$entry;
                   1994:         if ($domrolebuffer{$rudom}) {
                   1995:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   1996:                       '='.&escape($domainrolehash{$entry});
                   1997:         } else {
                   1998:             $domrolebuffer{$rudom}.=&escape($entry).
                   1999:                       '='.&escape($domainrolehash{$entry});
                   2000:         }
                   2001:         delete $domainrolehash{$entry};
                   2002:     }
                   2003:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 2004: 	my %servers = &get_servers($dom,'library');
                   2005: 	foreach my $tryserver (keys(%servers)) {
                   2006: 	    unless (&reply('domroleput:'.$dom.':'.
                   2007: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   2008: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   2009: 	    }
1.662     raeburn  2010:         }
                   2011:     }
1.186     www      2012:     $dumpcount++;
1.157     www      2013: }
                   2014: 
                   2015: sub courselog {
                   2016:     my $what=shift;
1.158     www      2017:     $what=time.':'.$what;
1.620     albertel 2018:     unless ($env{'request.course.id'}) { return ''; }
                   2019:     $coursedombuf{$env{'request.course.id'}}=
                   2020:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2021:     $coursenumbuf{$env{'request.course.id'}}=
                   2022:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   2023:     $coursehombuf{$env{'request.course.id'}}=
                   2024:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   2025:     $coursedescrbuf{$env{'request.course.id'}}=
                   2026:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   2027:     $courseinstcodebuf{$env{'request.course.id'}}=
                   2028:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   2029:     $courseownerbuf{$env{'request.course.id'}}=
                   2030:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  2031:     $coursetypebuf{$env{'request.course.id'}}=
                   2032:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 2033:     if (defined $courselogs{$env{'request.course.id'}}) {
                   2034: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      2035:     } else {
1.620     albertel 2036: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      2037:     }
1.620     albertel 2038:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      2039: 	&flushcourselogs();
                   2040:     }
1.158     www      2041: }
                   2042: 
                   2043: sub courseacclog {
                   2044:     my $fnsymb=shift;
1.620     albertel 2045:     unless ($env{'request.course.id'}) { return ''; }
                   2046:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 2047:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      2048:         $what.=':POST';
1.583     matthew  2049:         # FIXME: Probably ought to escape things....
1.800     albertel 2050: 	foreach my $key (keys(%env)) {
                   2051:             if ($key=~/^form\.(.*)/) {
                   2052: 		$what.=':'.$1.'='.$env{$key};
1.158     www      2053:             }
1.191     harris41 2054:         }
1.583     matthew  2055:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   2056:         # FIXME: We should not be depending on a form parameter that someone
                   2057:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 2058:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  2059:             $what.= ':POST';
                   2060:             # FIXME: Probably ought to escape things....
                   2061:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   2062:                                  'crsdiscuss') {
1.620     albertel 2063:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  2064:             }
                   2065:         }
1.158     www      2066:     }
                   2067:     &courselog($what);
1.149     www      2068: }
                   2069: 
1.185     www      2070: sub countacc {
                   2071:     my $url=&declutter(shift);
1.458     matthew  2072:     return if (! defined($url) || $url eq '');
1.620     albertel 2073:     unless ($env{'request.course.id'}) { return ''; }
                   2074:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      2075:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  2076:     $accesshash{$key}++;
1.185     www      2077: }
1.349     www      2078: 
1.361     www      2079: sub linklog {
                   2080:     my ($from,$to)=@_;
                   2081:     $from=&declutter($from);
                   2082:     $to=&declutter($to);
                   2083:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   2084:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   2085: }
                   2086:   
1.349     www      2087: sub userrolelog {
                   2088:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  2089:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  2090:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  2091:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
                   2092:         ($trole=~/^ta/)) {
1.350     www      2093:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2094:        $userrolehash
                   2095:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      2096:                     =$tend.':'.$tstart;
1.662     raeburn  2097:     }
                   2098:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   2099:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   2100:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   2101:         ($trole=~/^sc/)) {
                   2102:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2103:        $domainrolehash
                   2104:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   2105:                     = $tend.':'.$tstart;
                   2106:     }
1.351     www      2107: }
                   2108: 
                   2109: sub get_course_adv_roles {
                   2110:     my $cid=shift;
1.620     albertel 2111:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      2112:     my %coursehash=&coursedescription($cid);
1.470     www      2113:     my %nothide=();
1.800     albertel 2114:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   2115: 	$nothide{join(':',split(/[\@\:]/,$user))}=1;
1.470     www      2116:     }
1.351     www      2117:     my %returnhash=();
                   2118:     my %dumphash=
                   2119:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   2120:     my $now=time;
1.800     albertel 2121:     foreach my $entry (keys %dumphash) {
                   2122: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      2123:         if (($tstart) && ($tstart<0)) { next; }
                   2124:         if (($tend) && ($tend<$now)) { next; }
                   2125:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 2126:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 2127: 	if ($username eq '' || $domain eq '') { next; }
1.470     www      2128: 	if ((&privileged($username,$domain)) && 
                   2129: 	    (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 2130: 	if ($role eq 'cr') { next; }
1.351     www      2131:         my $key=&plaintext($role);
                   2132:         if ($section) { $key.=' (Sec/Grp '.$section.')'; }
                   2133:         if ($returnhash{$key}) {
                   2134: 	    $returnhash{$key}.=','.$username.':'.$domain;
                   2135:         } else {
                   2136:             $returnhash{$key}=$username.':'.$domain;
                   2137:         }
1.400     www      2138:      }
                   2139:     return %returnhash;
                   2140: }
                   2141: 
                   2142: sub get_my_roles {
1.858     raeburn  2143:     my ($uname,$udom,$context,$types,$roles,$roledoms)=@_;
1.620     albertel 2144:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   2145:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.858     raeburn  2146:     my %dumphash;
                   2147:     if ($context eq 'userroles') { 
                   2148:         %dumphash = &dump('roles',$udom,$uname);
                   2149:     } else {
                   2150:         %dumphash=
1.400     www      2151:             &dump('nohist_userroles',$udom,$uname);
1.858     raeburn  2152:     }
1.400     www      2153:     my %returnhash=();
                   2154:     my $now=time;
1.800     albertel 2155:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  2156:         my ($role,$tend,$tstart);
                   2157:         if ($context eq 'userroles') {
                   2158: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   2159:         } else {
                   2160:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   2161:         }
1.400     www      2162:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  2163:         my $status = 'active';
                   2164:         if (($tend) && ($tend<$now)) {
                   2165:             $status = 'previous';
                   2166:         } 
                   2167:         if (($tstart) && ($now<$tstart)) {
                   2168:             $status = 'future';
                   2169:         }
                   2170:         if (ref($types) eq 'ARRAY') {
                   2171:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   2172:                 next;
                   2173:             } 
                   2174:         } else {
                   2175:             if ($status ne 'active') {
                   2176:                 next;
                   2177:             }
                   2178:         }
1.867     raeburn  2179:         my ($rolecode,$username,$domain,$section,$area);
                   2180:         if ($context eq 'userroles') {
                   2181:             ($area,$rolecode) = split(/_/,$entry);
                   2182:             (undef,$domain,$username,$section) = split(/\//,$area);
                   2183:         } else {
                   2184:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   2185:         }
1.832     raeburn  2186:         if (ref($roledoms) eq 'ARRAY') {
                   2187:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   2188:                 next;
                   2189:             }
                   2190:         }
                   2191:         if (ref($roles) eq 'ARRAY') {
                   2192:             if (!grep(/^\Q$role\E$/,@{$roles})) {
                   2193:                 next;
                   2194:             }
1.867     raeburn  2195:         }
1.400     www      2196: 	$returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
1.832     raeburn  2197:     }
1.373     www      2198:     return %returnhash;
1.399     www      2199: }
                   2200: 
                   2201: # ----------------------------------------------------- Frontpage Announcements
                   2202: #
                   2203: #
                   2204: 
                   2205: sub postannounce {
                   2206:     my ($server,$text)=@_;
1.844     albertel 2207:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      2208:     unless ($text=~/\w/) { $text=''; }
                   2209:     return &reply('setannounce:'.&escape($text),$server);
                   2210: }
                   2211: 
                   2212: sub getannounce {
1.448     albertel 2213: 
                   2214:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      2215: 	my $announcement='';
1.800     albertel 2216: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 2217: 	close($fh);
1.399     www      2218: 	if ($announcement=~/\w/) { 
                   2219: 	    return 
                   2220:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 2221:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      2222: 	} else {
                   2223: 	    return '';
                   2224: 	}
                   2225:     } else {
                   2226: 	return '';
                   2227:     }
1.351     www      2228: }
1.353     www      2229: 
                   2230: # ---------------------------------------------------------- Course ID routines
                   2231: # Deal with domain's nohist_courseid.db files
                   2232: #
                   2233: 
                   2234: sub courseidput {
                   2235:     my ($domain,$what,$coursehome)=@_;
                   2236:     return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   2237: }
                   2238: 
                   2239: sub courseiddump {
1.791     raeburn  2240:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,$coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok)=@_;
1.353     www      2241:     my %returnhash=();
1.355     www      2242:     unless ($domfilter) { $domfilter=''; }
1.845     albertel 2243:     my %libserv = &all_library();
                   2244:     foreach my $tryserver (keys(%libserv)) {
                   2245:         if ( (  $hostidflag == 1 
                   2246: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   2247: 	     || (!defined($hostidflag)) ) {
                   2248: 
                   2249: 	    if ($domfilter eq ''
                   2250: 		|| (&host_domain($tryserver) eq $domfilter)) {
1.800     albertel 2251: 	        foreach my $line (
1.844     albertel 2252:                  split(/\&/,&reply('courseiddump:'.&host_domain($tryserver).':'.
1.571     raeburn  2253: 			       $sincefilter.':'.&escape($descfilter).':'.
1.791     raeburn  2254:                                &escape($instcodefilter).':'.&escape($ownerfilter).':'.&escape($coursefilter).':'.&escape($typefilter).':'.&escape($regexp_ok),
1.354     www      2255:                                $tryserver))) {
1.800     albertel 2256: 		    my ($key,$value)=split(/\=/,$line,2);
1.506     raeburn  2257:                     if (($key) && ($value)) {
1.516     raeburn  2258: 		        $returnhash{&unescape($key)}=$value;
1.506     raeburn  2259:                     }
1.353     www      2260:                 }
                   2261:             }
                   2262:         }
                   2263:     }
                   2264:     return %returnhash;
                   2265: }
                   2266: 
1.658     raeburn  2267: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  2268: 
                   2269: sub dcmailput {
1.685     raeburn  2270:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  2271:     my $status = &Apache::lonnet::critical(
1.740     www      2272:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   2273:        &escape($message),$server);
1.662     raeburn  2274:     return $status;
                   2275: }
                   2276: 
1.658     raeburn  2277: sub dcmaildump {
                   2278:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  2279:     my %returnhash=();
1.846     albertel 2280: 
                   2281:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  2282:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   2283:                                                          &escape($enddate).':';
                   2284: 	my @esc_senders=map { &escape($_)} @$senders;
                   2285: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 2286: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 2287:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  2288:             if (($key) && ($value)) {
                   2289:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  2290:             }
                   2291:         }
                   2292:     }
                   2293:     return %returnhash;
                   2294: }
1.662     raeburn  2295: # ---------------------------------------------------------- Domain roles
                   2296: 
                   2297: sub get_domain_roles {
                   2298:     my ($dom,$roles,$startdate,$enddate)=@_;
                   2299:     if (undef($startdate) || $startdate eq '') {
                   2300:         $startdate = '.';
                   2301:     }
                   2302:     if (undef($enddate) || $enddate eq '') {
                   2303:         $enddate = '.';
                   2304:     }
                   2305:     my $rolelist = join(':',@{$roles});
                   2306:     my %personnel = ();
1.841     albertel 2307: 
                   2308:     my %servers = &get_servers($dom,'library');
                   2309:     foreach my $tryserver (keys(%servers)) {
                   2310: 	%{$personnel{$tryserver}}=();
                   2311: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   2312: 					    &escape($startdate).':'.
                   2313: 					    &escape($enddate).':'.
                   2314: 					    &escape($rolelist), $tryserver))) {
                   2315: 	    my ($key,$value) = split(/\=/,$line,2);
                   2316: 	    if (($key) && ($value)) {
                   2317: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   2318: 	    }
                   2319: 	}
1.662     raeburn  2320:     }
                   2321:     return %personnel;
                   2322: }
1.658     raeburn  2323: 
1.149     www      2324: # ----------------------------------------------------------- Check out an item
                   2325: 
1.504     albertel 2326: sub get_first_access {
                   2327:     my ($type,$argsymb)=@_;
1.790     albertel 2328:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2329:     if ($argsymb) { $symb=$argsymb; }
                   2330:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 2331:     if ($type eq 'map') {
                   2332: 	$res=&symbread($map);
                   2333:     } else {
                   2334: 	$res=$symb;
                   2335:     }
                   2336:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   2337:     return $times{"$courseid\0$res"};
1.504     albertel 2338: }
                   2339: 
                   2340: sub set_first_access {
                   2341:     my ($type)=@_;
1.790     albertel 2342:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2343:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 2344:     if ($type eq 'map') {
                   2345: 	$res=&symbread($map);
                   2346:     } else {
                   2347: 	$res=$symb;
                   2348:     }
                   2349:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 2350:     if (!$firstaccess) {
1.588     albertel 2351: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 2352:     }
                   2353:     return 'already_set';
1.504     albertel 2354: }
                   2355: 
1.149     www      2356: sub checkout {
                   2357:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   2358:     my $now=time;
                   2359:     my $lonhost=$perlvar{'lonHostID'};
                   2360:     my $infostr=&escape(
1.234     www      2361:                  'CHECKOUTTOKEN&'.
1.149     www      2362:                  $tuname.'&'.
                   2363:                  $tudom.'&'.
                   2364:                  $tcrsid.'&'.
                   2365:                  $symb.'&'.
                   2366: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                   2367:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www      2368:     if ($token=~/^error\:/) { 
1.672     albertel 2369:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2370:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2371:                  "</font>");
                   2372:         return ''; 
                   2373:     }
                   2374: 
1.149     www      2375:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   2376:     $token=~tr/a-z/A-Z/;
                   2377: 
1.153     www      2378:     my %infohash=('resource.0.outtoken' => $token,
                   2379:                   'resource.0.checkouttime' => $now,
                   2380:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www      2381: 
                   2382:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2383:        return '';
1.151     www      2384:     } else {
1.672     albertel 2385:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2386:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2387:                  "</font>");
1.149     www      2388:     }    
                   2389: 
                   2390:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2391:                          &escape('Checkout '.$infostr.' - '.
                   2392:                                                  $token)) ne 'ok') {
                   2393: 	return '';
1.151     www      2394:     } else {
1.672     albertel 2395:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2396:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2397:                  "</font>");
1.149     www      2398:     }
1.151     www      2399:     return $token;
1.149     www      2400: }
                   2401: 
                   2402: # ------------------------------------------------------------ Check in an item
                   2403: 
                   2404: sub checkin {
                   2405:     my $token=shift;
1.150     www      2406:     my $now=time;
                   2407:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   2408:     $lonhost=~tr/A-Z/a-z/;
1.838     albertel 2409:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
1.150     www      2410:     $dtoken=~s/\W/\_/g;
1.234     www      2411:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www      2412:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   2413: 
1.154     www      2414:     unless (($tuname) && ($tudom)) {
                   2415:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   2416:         return '';
                   2417:     }
                   2418:     
                   2419:     unless (&allowed('mgr',$tcrsid)) {
                   2420:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620     albertel 2421:                  $env{'user.name'}.' - '.$env{'user.domain'});
1.154     www      2422:         return '';
                   2423:     }
                   2424: 
1.153     www      2425:     my %infohash=('resource.0.intoken' => $token,
                   2426:                   'resource.0.checkintime' => $now,
                   2427:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      2428: 
                   2429:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2430:        return '';
                   2431:     }    
                   2432: 
                   2433:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2434:                          &escape('Checkin - '.$token)) ne 'ok') {
                   2435: 	return '';
                   2436:     }
                   2437: 
                   2438:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      2439: }
                   2440: 
                   2441: # --------------------------------------------- Set Expire Date for Spreadsheet
                   2442: 
                   2443: sub expirespread {
                   2444:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 2445:     my $cid=$env{'request.course.id'}; 
1.110     www      2446:     if ($cid) {
                   2447:        my $now=time;
                   2448:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 2449:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   2450:                             $env{'course.'.$cid.'.num'}.
1.110     www      2451: 	        	    ':nohist_expirationdates:'.
                   2452:                             &escape($key).'='.$now,
1.620     albertel 2453:                             $env{'course.'.$cid.'.home'})
1.110     www      2454:     }
                   2455:     return 'ok';
1.14      www      2456: }
                   2457: 
1.109     www      2458: # ----------------------------------------------------- Devalidate Spreadsheets
                   2459: 
                   2460: sub devalidate {
1.325     www      2461:     my ($symb,$uname,$udom)=@_;
1.620     albertel 2462:     my $cid=$env{'request.course.id'}; 
1.109     www      2463:     if ($cid) {
1.391     matthew  2464:         # delete the stored spreadsheets for
                   2465:         # - the student level sheet of this user in course's homespace
                   2466:         # - the assessment level sheet for this resource 
                   2467:         #   for this user in user's homespace
1.553     albertel 2468: 	# - current conditional state info
1.325     www      2469: 	my $key=$uname.':'.$udom.':';
1.109     www      2470:         my $status=
1.299     matthew  2471: 	    &del('nohist_calculatedsheets',
1.391     matthew  2472: 		 [$key.'studentcalc:'],
1.620     albertel 2473: 		 $env{'course.'.$cid.'.domain'},
                   2474: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 2475: 		.' '.
                   2476: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  2477: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      2478:         unless ($status eq 'ok ok') {
                   2479:            &logthis('Could not devalidate spreadsheet '.
1.325     www      2480:                     $uname.' at '.$udom.' for '.
1.109     www      2481: 		    $symb.': '.$status);
1.133     albertel 2482:         }
1.553     albertel 2483: 	&delenv('user.state.'.$cid);
1.109     www      2484:     }
                   2485: }
                   2486: 
1.265     albertel 2487: sub get_scalar {
                   2488:     my ($string,$end) = @_;
                   2489:     my $value;
                   2490:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   2491: 	$value = $1;
                   2492:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   2493: 	$value = $1;
                   2494:     }
                   2495:     return &unescape($value);
                   2496: }
                   2497: 
                   2498: sub array2str {
                   2499:   my (@array) = @_;
                   2500:   my $result=&arrayref2str(\@array);
                   2501:   $result=~s/^__ARRAY_REF__//;
                   2502:   $result=~s/__END_ARRAY_REF__$//;
                   2503:   return $result;
                   2504: }
                   2505: 
1.204     albertel 2506: sub arrayref2str {
                   2507:   my ($arrayref) = @_;
1.265     albertel 2508:   my $result='__ARRAY_REF__';
1.204     albertel 2509:   foreach my $elem (@$arrayref) {
1.265     albertel 2510:     if(ref($elem) eq 'ARRAY') {
                   2511:       $result.=&arrayref2str($elem).'&';
                   2512:     } elsif(ref($elem) eq 'HASH') {
                   2513:       $result.=&hashref2str($elem).'&';
                   2514:     } elsif(ref($elem)) {
                   2515:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 2516:     } else {
                   2517:       $result.=&escape($elem).'&';
                   2518:     }
                   2519:   }
                   2520:   $result=~s/\&$//;
1.265     albertel 2521:   $result .= '__END_ARRAY_REF__';
1.204     albertel 2522:   return $result;
                   2523: }
                   2524: 
1.168     albertel 2525: sub hash2str {
1.204     albertel 2526:   my (%hash) = @_;
                   2527:   my $result=&hashref2str(\%hash);
1.265     albertel 2528:   $result=~s/^__HASH_REF__//;
                   2529:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 2530:   return $result;
                   2531: }
                   2532: 
                   2533: sub hashref2str {
                   2534:   my ($hashref)=@_;
1.265     albertel 2535:   my $result='__HASH_REF__';
1.800     albertel 2536:   foreach my $key (sort(keys(%$hashref))) {
                   2537:     if (ref($key) eq 'ARRAY') {
                   2538:       $result.=&arrayref2str($key).'=';
                   2539:     } elsif (ref($key) eq 'HASH') {
                   2540:       $result.=&hashref2str($key).'=';
                   2541:     } elsif (ref($key)) {
1.265     albertel 2542:       $result.='=';
1.800     albertel 2543:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 2544:     } else {
1.800     albertel 2545: 	if ($key) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 2546:     }
                   2547: 
1.800     albertel 2548:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   2549:       $result.=&arrayref2str($hashref->{$key}).'&';
                   2550:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   2551:       $result.=&hashref2str($hashref->{$key}).'&';
                   2552:     } elsif(ref($hashref->{$key})) {
1.265     albertel 2553:        $result.='&';
1.800     albertel 2554:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 2555:     } else {
1.800     albertel 2556:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 2557:     }
                   2558:   }
1.168     albertel 2559:   $result=~s/\&$//;
1.265     albertel 2560:   $result .= '__END_HASH_REF__';
1.168     albertel 2561:   return $result;
                   2562: }
                   2563: 
                   2564: sub str2hash {
1.265     albertel 2565:     my ($string)=@_;
                   2566:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   2567:     return %$hash;
                   2568: }
                   2569: 
                   2570: sub str2hashref {
1.168     albertel 2571:   my ($string) = @_;
1.265     albertel 2572: 
                   2573:   my %hash;
                   2574: 
                   2575:   if($string !~ /^__HASH_REF__/) {
                   2576:       if (! ($string eq '' || !defined($string))) {
                   2577: 	  $hash{'error'}='Not hash reference';
                   2578:       }
                   2579:       return (\%hash, $string);
                   2580:   }
                   2581: 
                   2582:   $string =~ s/^__HASH_REF__//;
                   2583: 
                   2584:   while($string !~ /^__END_HASH_REF__/) {
                   2585:       #key
                   2586:       my $key='';
                   2587:       if($string =~ /^__HASH_REF__/) {
                   2588:           ($key, $string)=&str2hashref($string);
                   2589:           if(defined($key->{'error'})) {
                   2590:               $hash{'error'}='Bad data';
                   2591:               return (\%hash, $string);
                   2592:           }
                   2593:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2594:           ($key, $string)=&str2arrayref($string);
                   2595:           if($key->[0] eq 'Array reference error') {
                   2596:               $hash{'error'}='Bad data';
                   2597:               return (\%hash, $string);
                   2598:           }
                   2599:       } else {
                   2600:           $string =~ s/^(.*?)=//;
1.267     albertel 2601: 	  $key=&unescape($1);
1.265     albertel 2602:       }
                   2603:       $string =~ s/^=//;
                   2604: 
                   2605:       #value
                   2606:       my $value='';
                   2607:       if($string =~ /^__HASH_REF__/) {
                   2608:           ($value, $string)=&str2hashref($string);
                   2609:           if(defined($value->{'error'})) {
                   2610:               $hash{'error'}='Bad data';
                   2611:               return (\%hash, $string);
                   2612:           }
                   2613:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2614:           ($value, $string)=&str2arrayref($string);
                   2615:           if($value->[0] eq 'Array reference error') {
                   2616:               $hash{'error'}='Bad data';
                   2617:               return (\%hash, $string);
                   2618:           }
                   2619:       } else {
                   2620: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   2621:       }
                   2622:       $string =~ s/^&//;
                   2623: 
                   2624:       $hash{$key}=$value;
1.204     albertel 2625:   }
1.265     albertel 2626: 
                   2627:   $string =~ s/^__END_HASH_REF__//;
                   2628: 
                   2629:   return (\%hash, $string);
1.204     albertel 2630: }
                   2631: 
                   2632: sub str2array {
1.265     albertel 2633:     my ($string)=@_;
                   2634:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   2635:     return @$array;
                   2636: }
                   2637: 
                   2638: sub str2arrayref {
1.204     albertel 2639:   my ($string) = @_;
1.265     albertel 2640:   my @array;
                   2641: 
                   2642:   if($string !~ /^__ARRAY_REF__/) {
                   2643:       if (! ($string eq '' || !defined($string))) {
                   2644: 	  $array[0]='Array reference error';
                   2645:       }
                   2646:       return (\@array, $string);
                   2647:   }
                   2648: 
                   2649:   $string =~ s/^__ARRAY_REF__//;
                   2650: 
                   2651:   while($string !~ /^__END_ARRAY_REF__/) {
                   2652:       my $value='';
                   2653:       if($string =~ /^__HASH_REF__/) {
                   2654:           ($value, $string)=&str2hashref($string);
                   2655:           if(defined($value->{'error'})) {
                   2656:               $array[0] ='Array reference error';
                   2657:               return (\@array, $string);
                   2658:           }
                   2659:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2660:           ($value, $string)=&str2arrayref($string);
                   2661:           if($value->[0] eq 'Array reference error') {
                   2662:               $array[0] ='Array reference error';
                   2663:               return (\@array, $string);
                   2664:           }
                   2665:       } else {
                   2666: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   2667:       }
                   2668:       $string =~ s/^&//;
                   2669: 
                   2670:       push(@array, $value);
1.191     harris41 2671:   }
1.265     albertel 2672: 
                   2673:   $string =~ s/^__END_ARRAY_REF__//;
                   2674: 
                   2675:   return (\@array, $string);
1.168     albertel 2676: }
                   2677: 
1.167     albertel 2678: # -------------------------------------------------------------------Temp Store
                   2679: 
1.168     albertel 2680: sub tmpreset {
                   2681:   my ($symb,$namespace,$domain,$stuname) = @_;
                   2682:   if (!$symb) {
                   2683:     $symb=&symbread();
1.620     albertel 2684:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2685:   }
                   2686:   $symb=escape($symb);
                   2687: 
1.620     albertel 2688:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 2689:   $namespace=~s/\//\_/g;
                   2690:   $namespace=~s/\W//g;
                   2691: 
1.620     albertel 2692:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2693:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2694:   if ($domain eq 'public' && $stuname eq 'public') {
                   2695:       $stuname=$ENV{'REMOTE_ADDR'};
                   2696:   }
1.168     albertel 2697:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2698:   my %hash;
                   2699:   if (tie(%hash,'GDBM_File',
                   2700: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2701: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2702:     foreach my $key (keys %hash) {
1.180     albertel 2703:       if ($key=~ /:$symb/) {
1.168     albertel 2704: 	delete($hash{$key});
                   2705:       }
                   2706:     }
                   2707:   }
                   2708: }
                   2709: 
1.167     albertel 2710: sub tmpstore {
1.168     albertel 2711:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2712: 
                   2713:   if (!$symb) {
                   2714:     $symb=&symbread();
1.620     albertel 2715:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2716:   }
                   2717:   $symb=escape($symb);
                   2718: 
                   2719:   if (!$namespace) {
                   2720:     # I don't think we would ever want to store this for a course.
                   2721:     # it seems this will only be used if we don't have a course.
1.620     albertel 2722:     #$namespace=$env{'request.course.id'};
1.168     albertel 2723:     #if (!$namespace) {
1.620     albertel 2724:       $namespace=$env{'request.state'};
1.168     albertel 2725:     #}
                   2726:   }
                   2727:   $namespace=~s/\//\_/g;
                   2728:   $namespace=~s/\W//g;
1.620     albertel 2729:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2730:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2731:   if ($domain eq 'public' && $stuname eq 'public') {
                   2732:       $stuname=$ENV{'REMOTE_ADDR'};
                   2733:   }
1.168     albertel 2734:   my $now=time;
                   2735:   my %hash;
                   2736:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2737:   if (tie(%hash,'GDBM_File',
                   2738: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2739: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2740:     $hash{"version:$symb"}++;
                   2741:     my $version=$hash{"version:$symb"};
                   2742:     my $allkeys=''; 
                   2743:     foreach my $key (keys(%$storehash)) {
                   2744:       $allkeys.=$key.':';
1.591     albertel 2745:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 2746:     }
                   2747:     $hash{"$version:$symb:timestamp"}=$now;
                   2748:     $allkeys.='timestamp';
                   2749:     $hash{"$version:keys:$symb"}=$allkeys;
                   2750:     if (untie(%hash)) {
                   2751:       return 'ok';
                   2752:     } else {
                   2753:       return "error:$!";
                   2754:     }
                   2755:   } else {
                   2756:     return "error:$!";
                   2757:   }
                   2758: }
1.167     albertel 2759: 
1.168     albertel 2760: # -----------------------------------------------------------------Temp Restore
1.167     albertel 2761: 
1.168     albertel 2762: sub tmprestore {
                   2763:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 2764: 
1.168     albertel 2765:   if (!$symb) {
                   2766:     $symb=&symbread();
1.620     albertel 2767:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2768:   }
                   2769:   $symb=escape($symb);
                   2770: 
1.620     albertel 2771:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 2772: 
1.620     albertel 2773:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2774:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2775:   if ($domain eq 'public' && $stuname eq 'public') {
                   2776:       $stuname=$ENV{'REMOTE_ADDR'};
                   2777:   }
1.168     albertel 2778:   my %returnhash;
                   2779:   $namespace=~s/\//\_/g;
                   2780:   $namespace=~s/\W//g;
                   2781:   my %hash;
                   2782:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2783:   if (tie(%hash,'GDBM_File',
                   2784: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2785: 	  &GDBM_READER(),0640)) {
1.168     albertel 2786:     my $version=$hash{"version:$symb"};
                   2787:     $returnhash{'version'}=$version;
                   2788:     my $scope;
                   2789:     for ($scope=1;$scope<=$version;$scope++) {
                   2790:       my $vkeys=$hash{"$scope:keys:$symb"};
                   2791:       my @keys=split(/:/,$vkeys);
                   2792:       my $key;
                   2793:       $returnhash{"$scope:keys"}=$vkeys;
                   2794:       foreach $key (@keys) {
1.591     albertel 2795: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   2796: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 2797:       }
                   2798:     }
1.168     albertel 2799:     if (!(untie(%hash))) {
                   2800:       return "error:$!";
                   2801:     }
                   2802:   } else {
                   2803:     return "error:$!";
                   2804:   }
                   2805:   return %returnhash;
1.167     albertel 2806: }
                   2807: 
1.9       www      2808: # ----------------------------------------------------------------------- Store
                   2809: 
                   2810: sub store {
1.124     www      2811:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2812:     my $home='';
                   2813: 
1.168     albertel 2814:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2815: 
1.213     www      2816:     $symb=&symbclean($symb);
1.122     albertel 2817:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      2818: 
1.620     albertel 2819:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2820:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      2821: 
                   2822:     &devalidate($symb,$stuname,$domain);
1.109     www      2823: 
                   2824:     $symb=escape($symb);
1.187     www      2825:     if (!$namespace) { 
1.620     albertel 2826:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      2827:           return ''; 
                   2828:        } 
                   2829:     }
1.620     albertel 2830:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      2831: 
                   2832:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   2833:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   2834: 
1.12      www      2835:     my $namevalue='';
1.800     albertel 2836:     foreach my $key (keys(%$storehash)) {
                   2837:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 2838:     }
1.12      www      2839:     $namevalue=~s/\&$//;
1.187     www      2840:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      2841:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      2842: }
                   2843: 
1.47      www      2844: # -------------------------------------------------------------- Critical Store
                   2845: 
                   2846: sub cstore {
1.124     www      2847:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2848:     my $home='';
                   2849: 
1.168     albertel 2850:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2851: 
1.213     www      2852:     $symb=&symbclean($symb);
1.122     albertel 2853:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      2854: 
1.620     albertel 2855:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2856:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      2857: 
                   2858:     &devalidate($symb,$stuname,$domain);
1.109     www      2859: 
                   2860:     $symb=escape($symb);
1.187     www      2861:     if (!$namespace) { 
1.620     albertel 2862:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      2863:           return ''; 
                   2864:        } 
                   2865:     }
1.620     albertel 2866:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      2867: 
                   2868:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   2869:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 2870: 
1.47      www      2871:     my $namevalue='';
1.800     albertel 2872:     foreach my $key (keys(%$storehash)) {
                   2873:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 2874:     }
1.47      www      2875:     $namevalue=~s/\&$//;
1.187     www      2876:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      2877:     return critical
                   2878:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      2879: }
                   2880: 
1.9       www      2881: # --------------------------------------------------------------------- Restore
                   2882: 
                   2883: sub restore {
1.124     www      2884:     my ($symb,$namespace,$domain,$stuname) = @_;
                   2885:     my $home='';
                   2886: 
1.168     albertel 2887:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2888: 
1.122     albertel 2889:     if (!$symb) {
                   2890:       unless ($symb=escape(&symbread())) { return ''; }
                   2891:     } else {
1.213     www      2892:       $symb=&escape(&symbclean($symb));
1.122     albertel 2893:     }
1.188     www      2894:     if (!$namespace) { 
1.620     albertel 2895:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      2896:           return ''; 
                   2897:        } 
                   2898:     }
1.620     albertel 2899:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2900:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   2901:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 2902:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   2903: 
1.12      www      2904:     my %returnhash=();
1.800     albertel 2905:     foreach my $line (split(/\&/,$answer)) {
                   2906: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 2907:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 2908:     }
1.75      www      2909:     my $version;
                   2910:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 2911:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   2912:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 2913:        }
1.75      www      2914:     }
1.13      www      2915:     return %returnhash;
1.34      www      2916: }
                   2917: 
                   2918: # ---------------------------------------------------------- Course Description
                   2919: 
                   2920: sub coursedescription {
1.731     albertel 2921:     my ($courseid,$args)=@_;
1.34      www      2922:     $courseid=~s/^\///;
1.49      www      2923:     $courseid=~s/\_/\//g;
1.34      www      2924:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 2925:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 2926:     my $normalid=$cdomain.'_'.$cnum;
                   2927:     # need to always cache even if we get errors otherwise we keep 
                   2928:     # trying and trying and trying to get the course description.
                   2929:     my %envhash=();
                   2930:     my %returnhash=();
1.731     albertel 2931:     
                   2932:     my $expiretime=600;
                   2933:     if ($env{'request.course.id'} eq $normalid) {
                   2934: 	$expiretime=120;
                   2935:     }
                   2936: 
                   2937:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   2938:     if (!$args->{'freshen_cache'}
                   2939: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   2940: 	foreach my $key (keys(%env)) {
                   2941: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   2942: 	    my ($setting) = $1;
                   2943: 	    $returnhash{$setting} = $env{$key};
                   2944: 	}
                   2945: 	return %returnhash;
                   2946:     }
                   2947: 
                   2948:     # get the data agin
                   2949:     if (!$args->{'one_time'}) {
                   2950: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   2951:     }
1.811     albertel 2952: 
1.34      www      2953:     if ($chome ne 'no_host') {
1.302     albertel 2954:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 2955:        if (!exists($returnhash{'con_lost'})) {
                   2956:            $returnhash{'home'}= $chome;
                   2957: 	   $returnhash{'domain'} = $cdomain;
                   2958: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  2959:            if (!defined($returnhash{'type'})) {
                   2960:                $returnhash{'type'} = 'Course';
                   2961:            }
1.130     albertel 2962:            while (my ($name,$value) = each %returnhash) {
1.53      www      2963:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 2964:            }
1.270     www      2965:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      2966:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 2967: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      2968:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   2969:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   2970:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      2971:        }
                   2972:     }
1.731     albertel 2973:     if (!$args->{'one_time'}) {
                   2974: 	&appenv(%envhash);
                   2975:     }
1.302     albertel 2976:     return %returnhash;
1.461     www      2977: }
                   2978: 
                   2979: # -------------------------------------------------See if a user is privileged
                   2980: 
                   2981: sub privileged {
                   2982:     my ($username,$domain)=@_;
                   2983:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   2984: 			&homeserver($username,$domain));
                   2985:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
                   2986:     my $now=time;
                   2987:     if ($rolesdump ne '') {
1.800     albertel 2988:         foreach my $entry (split(/&/,$rolesdump)) {
                   2989: 	    if ($entry!~/^rolesdef_/) {
                   2990: 		my ($area,$role)=split(/=/,$entry);
1.461     www      2991: 		$area=~s/\_\w\w$//;
                   2992: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   2993: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   2994: 		    my $active=1;
                   2995: 		    if ($tend) {
                   2996: 			if ($tend<$now) { $active=0; }
                   2997: 		    }
                   2998: 		    if ($tstart) {
                   2999: 			if ($tstart>$now) { $active=0; }
                   3000: 		    }
                   3001: 		    if ($active) { return 1; }
                   3002: 		}
                   3003: 	    }
                   3004: 	}
                   3005:     }
                   3006:     return 0;
1.9       www      3007: }
1.1       albertel 3008: 
1.103     harris41 3009: # -------------------------------------------------------- Get user privileges
1.11      www      3010: 
                   3011: sub rolesinit {
                   3012:     my ($domain,$username,$authhost)=@_;
                   3013:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.12      www      3014:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
1.11      www      3015:     my %allroles=();
1.678     raeburn  3016:     my %allgroups=();   
1.11      www      3017:     my $now=time;
1.743     albertel 3018:     my %userroles = ('user.login.time' => $now);
1.678     raeburn  3019:     my $group_privs;
1.11      www      3020: 
                   3021:     if ($rolesdump ne '') {
1.800     albertel 3022:         foreach my $entry (split(/&/,$rolesdump)) {
                   3023: 	  if ($entry!~/^rolesdef_/) {
                   3024:             my ($area,$role)=split(/=/,$entry);
1.587     albertel 3025: 	    $area=~s/\_\w\w$//;
1.678     raeburn  3026:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 3027: 	    if ($role=~/^cr/) { 
1.807     albertel 3028: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   3029: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655     albertel 3030: 		    ($tend,$tstart)=split('_',$trest);
                   3031: 		} else {
                   3032: 		    $trole=$role;
                   3033: 		}
1.678     raeburn  3034:             } elsif ($role =~ m|^gr/|) {
                   3035:                 ($trole,$tend,$tstart) = split(/_/,$role);
                   3036:                 ($trole,$group_privs) = split(/\//,$trole);
                   3037:                 $group_privs = &unescape($group_privs);
1.587     albertel 3038: 	    } else {
                   3039: 		($trole,$tend,$tstart)=split(/_/,$role);
                   3040: 	    }
1.743     albertel 3041: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   3042: 					 $username);
                   3043: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  3044:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   3045:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      3046:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 3047: 		my $spec=$trole.'.'.$area;
                   3048: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   3049: 		if ($trole =~ /^cr\//) {
1.567     raeburn  3050:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  3051:                 } elsif ($trole eq 'gr') {
                   3052:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 3053: 		} else {
1.567     raeburn  3054:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 3055: 		}
1.12      www      3056:             }
1.662     raeburn  3057:           }
1.191     harris41 3058:         }
1.743     albertel 3059:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   3060:         $userroles{'user.adv'}    = $adv;
                   3061: 	$userroles{'user.author'} = $author;
1.620     albertel 3062:         $env{'user.adv'}=$adv;
1.11      www      3063:     }
1.743     albertel 3064:     return \%userroles;  
1.11      www      3065: }
                   3066: 
1.567     raeburn  3067: sub set_arearole {
                   3068:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   3069: # log the associated role with the area
                   3070:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 3071:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  3072: }
                   3073: 
                   3074: sub custom_roleprivs {
                   3075:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   3076:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   3077:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 3078:     if (&hostname($homsvr) ne '') {
1.567     raeburn  3079:         my ($rdummy,$roledef)=
                   3080:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   3081:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   3082:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   3083:             if (defined($syspriv)) {
                   3084:                 $$allroles{'cm./'}.=':'.$syspriv;
                   3085:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   3086:             }
                   3087:             if ($tdomain ne '') {
                   3088:                 if (defined($dompriv)) {
                   3089:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   3090:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   3091:                 }
                   3092:                 if (($trest ne '') && (defined($coursepriv))) {
                   3093:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   3094:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   3095:                 }
                   3096:             }
                   3097:         }
                   3098:     }
                   3099: }
                   3100: 
1.678     raeburn  3101: sub group_roleprivs {
                   3102:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   3103:     my $access = 1;
                   3104:     my $now = time;
                   3105:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   3106:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   3107:     if ($access) {
1.811     albertel 3108:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  3109:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   3110:     }
                   3111: }
1.567     raeburn  3112: 
                   3113: sub standard_roleprivs {
                   3114:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   3115:     if (defined($pr{$trole.':s'})) {
                   3116:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   3117:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   3118:     }
                   3119:     if ($tdomain ne '') {
                   3120:         if (defined($pr{$trole.':d'})) {
                   3121:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3122:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3123:         }
                   3124:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   3125:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   3126:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   3127:         }
                   3128:     }
                   3129: }
                   3130: 
                   3131: sub set_userprivs {
1.678     raeburn  3132:     my ($userroles,$allroles,$allgroups) = @_; 
1.567     raeburn  3133:     my $author=0;
                   3134:     my $adv=0;
1.678     raeburn  3135:     my %grouproles = ();
                   3136:     if (keys(%{$allgroups}) > 0) {
                   3137:         foreach my $role (keys %{$allroles}) {
1.681     raeburn  3138:             my ($trole,$area,$sec,$extendedarea);
1.881     raeburn  3139:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
1.678     raeburn  3140:                 $trole = $1;
                   3141:                 $area = $2;
1.681     raeburn  3142:                 $sec = $3;
                   3143:                 $extendedarea = $area.$sec;
                   3144:                 if (exists($$allgroups{$area})) {
                   3145:                     foreach my $group (keys(%{$$allgroups{$area}})) {
                   3146:                         my $spec = $trole.'.'.$extendedarea;
                   3147:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
                   3148:                                                 $$allgroups{$area}{$group};
1.678     raeburn  3149:                     }
                   3150:                 }
                   3151:             }
                   3152:         }
                   3153:     }
1.800     albertel 3154:     foreach my $group (keys(%grouproles)) {
                   3155:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  3156:     }
1.800     albertel 3157:     foreach my $role (keys(%{$allroles})) {
                   3158:         my %thesepriv;
                   3159:         if (($role=~/^au/) || ($role=~/^ca/)) { $author=1; }
                   3160:         foreach my $item (split(/:/,$$allroles{$role})) {
                   3161:             if ($item ne '') {
                   3162:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  3163:                 if ($restrictions eq '') {
                   3164:                     $thesepriv{$privilege}='F';
                   3165:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   3166:                     $thesepriv{$privilege}.=$restrictions;
                   3167:                 }
                   3168:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   3169:             }
                   3170:         }
                   3171:         my $thesestr='';
1.800     albertel 3172:         foreach my $priv (keys(%thesepriv)) {
                   3173: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   3174: 	}
                   3175:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  3176:     }
                   3177:     return ($author,$adv);
                   3178: }
                   3179: 
1.12      www      3180: # --------------------------------------------------------------- get interface
                   3181: 
                   3182: sub get {
1.131     albertel 3183:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3184:    my $items='';
1.800     albertel 3185:    foreach my $item (@$storearr) {
                   3186:        $items.=&escape($item).'&';
1.191     harris41 3187:    }
1.12      www      3188:    $items=~s/\&$//;
1.620     albertel 3189:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3190:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 3191:    my $uhome=&homeserver($uname,$udomain);
                   3192: 
1.133     albertel 3193:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3194:    my @pairs=split(/\&/,$rep);
1.273     albertel 3195:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   3196:      return @pairs;
                   3197:    }
1.15      www      3198:    my %returnhash=();
1.42      www      3199:    my $i=0;
1.800     albertel 3200:    foreach my $item (@$storearr) {
                   3201:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      3202:       $i++;
1.191     harris41 3203:    }
1.15      www      3204:    return %returnhash;
1.27      www      3205: }
                   3206: 
                   3207: # --------------------------------------------------------------- del interface
                   3208: 
                   3209: sub del {
1.133     albertel 3210:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      3211:    my $items='';
1.800     albertel 3212:    foreach my $item (@$storearr) {
                   3213:        $items.=&escape($item).'&';
1.191     harris41 3214:    }
1.27      www      3215:    $items=~s/\&$//;
1.620     albertel 3216:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3217:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3218:    my $uhome=&homeserver($uname,$udomain);
                   3219: 
                   3220:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3221: }
                   3222: 
                   3223: # -------------------------------------------------------------- dump interface
                   3224: 
                   3225: sub dump {
1.755     albertel 3226:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   3227:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3228:     if (!$uname) { $uname=$env{'user.name'}; }
                   3229:     my $uhome=&homeserver($uname,$udomain);
                   3230:     if ($regexp) {
                   3231: 	$regexp=&escape($regexp);
                   3232:     } else {
                   3233: 	$regexp='.';
                   3234:     }
                   3235:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3236:     my @pairs=split(/\&/,$rep);
                   3237:     my %returnhash=();
                   3238:     foreach my $item (@pairs) {
                   3239: 	my ($key,$value)=split(/=/,$item,2);
                   3240: 	$key = &unescape($key);
                   3241: 	next if ($key =~ /^error: 2 /);
                   3242: 	$returnhash{$key}=&thaw_unescape($value);
                   3243:     }
                   3244:     return %returnhash;
1.407     www      3245: }
                   3246: 
1.717     albertel 3247: # --------------------------------------------------------- dumpstore interface
                   3248: 
                   3249: sub dumpstore {
                   3250:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822     albertel 3251:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3252:    if (!$uname) { $uname=$env{'user.name'}; }
                   3253:    my $uhome=&homeserver($uname,$udomain);
                   3254:    if ($regexp) {
                   3255:        $regexp=&escape($regexp);
                   3256:    } else {
                   3257:        $regexp='.';
                   3258:    }
                   3259:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3260:    my @pairs=split(/\&/,$rep);
                   3261:    my %returnhash=();
                   3262:    foreach my $item (@pairs) {
                   3263:        my ($key,$value)=split(/=/,$item,2);
                   3264:        next if ($key =~ /^error: 2 /);
                   3265:        $returnhash{$key}=&thaw_unescape($value);
                   3266:    }
                   3267:    return %returnhash;
1.717     albertel 3268: }
                   3269: 
1.407     www      3270: # -------------------------------------------------------------- keys interface
                   3271: 
                   3272: sub getkeys {
                   3273:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 3274:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3275:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      3276:    my $uhome=&homeserver($uname,$udomain);
                   3277:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   3278:    my @keyarray=();
1.800     albertel 3279:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  3280:       next if ($key =~ /^error: 2 /);
1.800     albertel 3281:       push(@keyarray,&unescape($key));
1.407     www      3282:    }
                   3283:    return @keyarray;
1.318     matthew  3284: }
                   3285: 
1.319     matthew  3286: # --------------------------------------------------------------- currentdump
                   3287: sub currentdump {
1.328     matthew  3288:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 3289:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   3290:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   3291:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  3292:    my $uhome = &homeserver($sname,$sdom);
                   3293:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  3294:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  3295:    #
1.318     matthew  3296:    my %returnhash=();
1.319     matthew  3297:    #
                   3298:    if ($rep eq "unknown_cmd") { 
                   3299:        # an old lond will not know currentdump
                   3300:        # Do a dump and make it look like a currentdump
1.822     albertel 3301:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  3302:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   3303:        my %hash = @tmp;
                   3304:        @tmp=();
1.424     matthew  3305:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  3306:    } else {
                   3307:        my @pairs=split(/\&/,$rep);
1.800     albertel 3308:        foreach my $pair (@pairs) {
                   3309:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  3310:            my ($symb,$param) = split(/:/,$key);
                   3311:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 3312:                                                         &thaw_unescape($value);
1.319     matthew  3313:        }
1.191     harris41 3314:    }
1.12      www      3315:    return %returnhash;
1.424     matthew  3316: }
                   3317: 
                   3318: sub convert_dump_to_currentdump{
                   3319:     my %hash = %{shift()};
                   3320:     my %returnhash;
                   3321:     # Code ripped from lond, essentially.  The only difference
                   3322:     # here is the unescaping done by lonnet::dump().  Conceivably
                   3323:     # we might run in to problems with parameter names =~ /^v\./
                   3324:     while (my ($key,$value) = each(%hash)) {
                   3325:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 3326: 	$symb  = &unescape($symb);
                   3327: 	$param = &unescape($param);
1.424     matthew  3328:         next if ($v eq 'version' || $symb eq 'keys');
                   3329:         next if (exists($returnhash{$symb}) &&
                   3330:                  exists($returnhash{$symb}->{$param}) &&
                   3331:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   3332:         $returnhash{$symb}->{$param}=$value;
                   3333:         $returnhash{$symb}->{'v.'.$param}=$v;
                   3334:     }
                   3335:     #
                   3336:     # Remove all of the keys in the hashes which keep track of
                   3337:     # the version of the parameter.
                   3338:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   3339:         # use a foreach because we are going to delete from the hash.
                   3340:         foreach my $key (keys(%$param_hash)) {
                   3341:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   3342:         }
                   3343:     }
                   3344:     return \%returnhash;
1.12      www      3345: }
                   3346: 
1.627     albertel 3347: # ------------------------------------------------------ critical inc interface
                   3348: 
                   3349: sub cinc {
                   3350:     return &inc(@_,'critical');
                   3351: }
                   3352: 
1.449     matthew  3353: # --------------------------------------------------------------- inc interface
                   3354: 
                   3355: sub inc {
1.627     albertel 3356:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 3357:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3358:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  3359:     my $uhome=&homeserver($uname,$udomain);
                   3360:     my $items='';
                   3361:     if (! ref($store)) {
                   3362:         # got a single value, so use that instead
                   3363:         $items = &escape($store).'=&';
                   3364:     } elsif (ref($store) eq 'SCALAR') {
                   3365:         $items = &escape($$store).'=&';        
                   3366:     } elsif (ref($store) eq 'ARRAY') {
                   3367:         $items = join('=&',map {&escape($_);} @{$store});
                   3368:     } elsif (ref($store) eq 'HASH') {
                   3369:         while (my($key,$value) = each(%{$store})) {
                   3370:             $items.= &escape($key).'='.&escape($value).'&';
                   3371:         }
                   3372:     }
                   3373:     $items=~s/\&$//;
1.627     albertel 3374:     if ($critical) {
                   3375: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3376:     } else {
                   3377: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3378:     }
1.449     matthew  3379: }
                   3380: 
1.12      www      3381: # --------------------------------------------------------------- put interface
                   3382: 
                   3383: sub put {
1.134     albertel 3384:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3385:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3386:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3387:    my $uhome=&homeserver($uname,$udomain);
1.12      www      3388:    my $items='';
1.800     albertel 3389:    foreach my $item (keys(%$storehash)) {
                   3390:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 3391:    }
1.12      www      3392:    $items=~s/\&$//;
1.134     albertel 3393:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      3394: }
                   3395: 
1.631     albertel 3396: # ------------------------------------------------------------ newput interface
                   3397: 
                   3398: sub newput {
                   3399:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   3400:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3401:    if (!$uname) { $uname=$env{'user.name'}; }
                   3402:    my $uhome=&homeserver($uname,$udomain);
                   3403:    my $items='';
                   3404:    foreach my $key (keys(%$storehash)) {
                   3405:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   3406:    }
                   3407:    $items=~s/\&$//;
                   3408:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   3409: }
                   3410: 
                   3411: # ---------------------------------------------------------  putstore interface
                   3412: 
1.524     raeburn  3413: sub putstore {
1.715     albertel 3414:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 3415:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3416:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  3417:    my $uhome=&homeserver($uname,$udomain);
                   3418:    my $items='';
1.715     albertel 3419:    foreach my $key (keys(%$storehash)) {
                   3420:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  3421:    }
1.715     albertel 3422:    $items=~s/\&$//;
1.716     albertel 3423:    my $esc_symb=&escape($symb);
                   3424:    my $esc_v=&escape($version);
1.715     albertel 3425:    my $reply =
1.716     albertel 3426:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 3427: 	      $uhome);
                   3428:    if ($reply eq 'unknown_cmd') {
1.716     albertel 3429:        # gfall back to way things use to be done
1.715     albertel 3430:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   3431: 			    $uname);
1.524     raeburn  3432:    }
1.715     albertel 3433:    return $reply;
                   3434: }
                   3435: 
                   3436: sub old_putstore {
1.716     albertel 3437:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   3438:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3439:     if (!$uname) { $uname=$env{'user.name'}; }
                   3440:     my $uhome=&homeserver($uname,$udomain);
                   3441:     my %newstorehash;
1.800     albertel 3442:     foreach my $item (keys(%$storehash)) {
                   3443: 	my $key = $version.':'.&escape($symb).':'.$item;
                   3444: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 3445:     }
                   3446:     my $items='';
                   3447:     my %allitems = ();
1.800     albertel 3448:     foreach my $item (keys(%newstorehash)) {
                   3449: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 3450: 	    my $key = $1.':keys:'.$2;
                   3451: 	    $allitems{$key} .= $3.':';
                   3452: 	}
1.800     albertel 3453: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 3454:     }
1.800     albertel 3455:     foreach my $item (keys(%allitems)) {
                   3456: 	$allitems{$item} =~ s/\:$//;
                   3457: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 3458:     }
                   3459:     $items=~s/\&$//;
                   3460:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  3461: }
                   3462: 
1.47      www      3463: # ------------------------------------------------------ critical put interface
                   3464: 
                   3465: sub cput {
1.134     albertel 3466:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3467:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3468:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3469:    my $uhome=&homeserver($uname,$udomain);
1.47      www      3470:    my $items='';
1.800     albertel 3471:    foreach my $item (keys(%$storehash)) {
                   3472:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 3473:    }
1.47      www      3474:    $items=~s/\&$//;
1.134     albertel 3475:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3476: }
                   3477: 
                   3478: # -------------------------------------------------------------- eget interface
                   3479: 
                   3480: sub eget {
1.133     albertel 3481:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3482:    my $items='';
1.800     albertel 3483:    foreach my $item (@$storearr) {
                   3484:        $items.=&escape($item).'&';
1.191     harris41 3485:    }
1.12      www      3486:    $items=~s/\&$//;
1.620     albertel 3487:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3488:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3489:    my $uhome=&homeserver($uname,$udomain);
                   3490:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3491:    my @pairs=split(/\&/,$rep);
                   3492:    my %returnhash=();
1.42      www      3493:    my $i=0;
1.800     albertel 3494:    foreach my $item (@$storearr) {
                   3495:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      3496:       $i++;
1.191     harris41 3497:    }
1.12      www      3498:    return %returnhash;
                   3499: }
                   3500: 
1.667     albertel 3501: # ------------------------------------------------------------ tmpput interface
                   3502: sub tmpput {
1.802     raeburn  3503:     my ($storehash,$server,$context)=@_;
1.667     albertel 3504:     my $items='';
1.800     albertel 3505:     foreach my $item (keys(%$storehash)) {
                   3506: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 3507:     }
                   3508:     $items=~s/\&$//;
1.802     raeburn  3509:     if (defined($context)) {
                   3510:         $items .= ':'.&escape($context);
                   3511:     }
1.667     albertel 3512:     return &reply("tmpput:$items",$server);
                   3513: }
                   3514: 
                   3515: # ------------------------------------------------------------ tmpget interface
                   3516: sub tmpget {
1.688     albertel 3517:     my ($token,$server)=@_;
                   3518:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3519:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 3520:     my %returnhash;
                   3521:     foreach my $item (split(/\&/,$rep)) {
                   3522: 	my ($key,$value)=split(/=/,$item);
                   3523: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   3524:     }
                   3525:     return %returnhash;
                   3526: }
                   3527: 
1.688     albertel 3528: # ------------------------------------------------------------ tmpget interface
                   3529: sub tmpdel {
                   3530:     my ($token,$server)=@_;
                   3531:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3532:     return &reply("tmpdel:$token",$server);
                   3533: }
                   3534: 
1.765     albertel 3535: # -------------------------------------------------- portfolio access checking
                   3536: 
                   3537: sub portfolio_access {
1.766     albertel 3538:     my ($requrl) = @_;
1.765     albertel 3539:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   3540:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  3541:     if ($result) {
                   3542:         my %setters;
                   3543:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   3544:             my ($startblock,$endblock) =
                   3545:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   3546:             if ($startblock && $endblock) {
                   3547:                 return 'B';
                   3548:             }
                   3549:         } else {
                   3550:             my ($startblock,$endblock) =
                   3551:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   3552:             if ($startblock && $endblock) {
                   3553:                 return 'B';
                   3554:             }
                   3555:         }
                   3556:     }
1.765     albertel 3557:     if ($result eq 'ok') {
1.766     albertel 3558:        return 'F';
1.765     albertel 3559:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 3560:        return 'A';
1.765     albertel 3561:     }
1.766     albertel 3562:     return '';
1.765     albertel 3563: }
                   3564: 
                   3565: sub get_portfolio_access {
1.767     albertel 3566:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   3567: 
                   3568:     if (!ref($access_hash)) {
                   3569: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   3570: 	my %access_controls = &get_access_controls($current_perms,$group,
                   3571: 						   $file_name);
                   3572: 	$access_hash = $access_controls{$file_name};
                   3573:     }
                   3574: 
1.765     albertel 3575:     my ($public,$guest,@domains,@users,@courses,@groups);
                   3576:     my $now = time;
                   3577:     if (ref($access_hash) eq 'HASH') {
                   3578:         foreach my $key (keys(%{$access_hash})) {
                   3579:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   3580:             if ($start > $now) {
                   3581:                 next;
                   3582:             }
                   3583:             if ($end && $end<$now) {
                   3584:                 next;
                   3585:             }
                   3586:             if ($scope eq 'public') {
                   3587:                 $public = $key;
                   3588:                 last;
                   3589:             } elsif ($scope eq 'guest') {
                   3590:                 $guest = $key;
                   3591:             } elsif ($scope eq 'domains') {
                   3592:                 push(@domains,$key);
                   3593:             } elsif ($scope eq 'users') {
                   3594:                 push(@users,$key);
                   3595:             } elsif ($scope eq 'course') {
                   3596:                 push(@courses,$key);
                   3597:             } elsif ($scope eq 'group') {
                   3598:                 push(@groups,$key);
                   3599:             }
                   3600:         }
                   3601:         if ($public) {
                   3602:             return 'ok';
                   3603:         }
                   3604:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   3605:             if ($guest) {
                   3606:                 return $guest;
                   3607:             }
                   3608:         } else {
                   3609:             if (@domains > 0) {
                   3610:                 foreach my $domkey (@domains) {
                   3611:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   3612:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   3613:                             return 'ok';
                   3614:                         }
                   3615:                     }
                   3616:                 }
                   3617:             }
                   3618:             if (@users > 0) {
                   3619:                 foreach my $userkey (@users) {
1.865     raeburn  3620:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   3621:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   3622:                             if (ref($item) eq 'HASH') {
                   3623:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   3624:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   3625:                                     return 'ok';
                   3626:                                 }
                   3627:                             }
                   3628:                         }
                   3629:                     } 
1.765     albertel 3630:                 }
                   3631:             }
                   3632:             my %roleshash;
                   3633:             my @courses_and_groups = @courses;
                   3634:             push(@courses_and_groups,@groups); 
                   3635:             if (@courses_and_groups > 0) {
                   3636:                 my (%allgroups,%allroles); 
                   3637:                 my ($start,$end,$role,$sec,$group);
                   3638:                 foreach my $envkey (%env) {
1.811     albertel 3639:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 3640:                         my $cid = $2.'_'.$3; 
                   3641:                         if ($1 eq 'gr') {
                   3642:                             $group = $4;
                   3643:                             $allgroups{$cid}{$group} = $env{$envkey};
                   3644:                         } else {
                   3645:                             if ($4 eq '') {
                   3646:                                 $sec = 'none';
                   3647:                             } else {
                   3648:                                 $sec = $4;
                   3649:                             }
                   3650:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   3651:                         }
1.811     albertel 3652:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 3653:                         my $cid = $2.'_'.$3;
                   3654:                         if ($4 eq '') {
                   3655:                             $sec = 'none';
                   3656:                         } else {
                   3657:                             $sec = $4;
                   3658:                         }
                   3659:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   3660:                     }
                   3661:                 }
                   3662:                 if (keys(%allroles) == 0) {
                   3663:                     return;
                   3664:                 }
                   3665:                 foreach my $key (@courses_and_groups) {
                   3666:                     my %content = %{$$access_hash{$key}};
                   3667:                     my $cnum = $content{'number'};
                   3668:                     my $cdom = $content{'domain'};
                   3669:                     my $cid = $cdom.'_'.$cnum;
                   3670:                     if (!exists($allroles{$cid})) {
                   3671:                         next;
                   3672:                     }    
                   3673:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   3674:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   3675:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   3676:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   3677:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   3678:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   3679:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   3680:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   3681:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   3682:                                         if (grep/^all$/,@sections) {
                   3683:                                             return 'ok';
                   3684:                                         } else {
                   3685:                                             if (grep/^$sec$/,@sections) {
                   3686:                                                 return 'ok';
                   3687:                                             }
                   3688:                                         }
                   3689:                                     }
                   3690:                                 }
                   3691:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   3692:                                     if (grep/^none$/,@groups) {
                   3693:                                         return 'ok';
                   3694:                                     }
                   3695:                                 } else {
                   3696:                                     if (grep/^all$/,@groups) {
                   3697:                                         return 'ok';
                   3698:                                     } 
                   3699:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   3700:                                         if (grep/^$group$/,@groups) {
                   3701:                                             return 'ok';
                   3702:                                         }
                   3703:                                     }
                   3704:                                 } 
                   3705:                             }
                   3706:                         }
                   3707:                     }
                   3708:                 }
                   3709:             }
                   3710:             if ($guest) {
                   3711:                 return $guest;
                   3712:             }
                   3713:         }
                   3714:     }
                   3715:     return;
                   3716: }
                   3717: 
                   3718: sub course_group_datechecker {
                   3719:     my ($dates,$now,$status) = @_;
                   3720:     my ($start,$end) = split(/\./,$dates);
                   3721:     if (!$start && !$end) {
                   3722:         return 'ok';
                   3723:     }
                   3724:     if (grep/^active$/,@{$status}) {
                   3725:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   3726:             return 'ok';
                   3727:         }
                   3728:     }
                   3729:     if (grep/^previous$/,@{$status}) {
                   3730:         if ($end > $now ) {
                   3731:             return 'ok';
                   3732:         }
                   3733:     }
                   3734:     if (grep/^future$/,@{$status}) {
                   3735:         if ($start > $now) {
                   3736:             return 'ok';
                   3737:         }
                   3738:     }
                   3739:     return; 
                   3740: }
                   3741: 
                   3742: sub parse_portfolio_url {
                   3743:     my ($url) = @_;
                   3744: 
                   3745:     my ($type,$udom,$unum,$group,$file_name);
                   3746:     
1.823     albertel 3747:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 3748: 	$type = 1;
                   3749:         $udom = $1;
                   3750:         $unum = $2;
                   3751:         $file_name = $3;
1.823     albertel 3752:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 3753: 	$type = 2;
                   3754:         $udom = $1;
                   3755:         $unum = $2;
                   3756:         $group = $3;
                   3757:         $file_name = $3.'/'.$4;
                   3758:     }
                   3759:     if (wantarray) {
                   3760: 	return ($type,$udom,$unum,$file_name,$group);
                   3761:     }
                   3762:     return $type;
                   3763: }
                   3764: 
                   3765: sub is_portfolio_url {
                   3766:     my ($url) = @_;
                   3767:     return scalar(&parse_portfolio_url($url));
                   3768: }
                   3769: 
1.798     raeburn  3770: sub is_portfolio_file {
                   3771:     my ($file) = @_;
1.820     raeburn  3772:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  3773:         return 1;
                   3774:     }
                   3775:     return;
                   3776: }
                   3777: 
                   3778: 
1.341     www      3779: # ---------------------------------------------- Custom access rule evaluation
                   3780: 
                   3781: sub customaccess {
                   3782:     my ($priv,$uri)=@_;
1.807     albertel 3783:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      3784:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 3785:     $udom = &LONCAPA::clean_domain($udom);
                   3786:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      3787:     my $access=0;
1.800     albertel 3788:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
                   3789: 	my ($effect,$realm,$role)=split(/\:/,$right);
1.343     www      3790:         if ($role) {
                   3791: 	   if ($role ne $urole) { next; }
                   3792:         }
1.800     albertel 3793:         foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   3794:             my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
1.343     www      3795:             if ($tdom) {
                   3796: 		if ($tdom ne $udom) { next; }
                   3797:             }
                   3798:             if ($tcrs) {
                   3799: 		if ($tcrs ne $ucrs) { next; }
                   3800:             }
                   3801:             if ($tsec) {
                   3802: 		if ($tsec ne $usec) { next; }
                   3803:             }
                   3804:             $access=($effect eq 'allow');
                   3805:             last;
1.342     www      3806:         }
1.402     bowersj2 3807: 	if ($realm eq '' && $role eq '') {
                   3808:             $access=($effect eq 'allow');
                   3809: 	}
1.341     www      3810:     }
                   3811:     return $access;
                   3812: }
                   3813: 
1.103     harris41 3814: # ------------------------------------------------- Check for a user privilege
1.12      www      3815: 
                   3816: sub allowed {
1.810     raeburn  3817:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 3818:     my $ver_orguri=$uri;
1.439     www      3819:     $uri=&deversion($uri);
1.152     www      3820:     my $orguri=$uri;
1.52      www      3821:     $uri=&declutter($uri);
1.809     raeburn  3822: 
1.810     raeburn  3823:     if ($priv eq 'evb') {
                   3824: # Evade communication block restrictions for specified role in a course
                   3825:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   3826:             return $1;
                   3827:         } else {
                   3828:             return;
                   3829:         }
                   3830:     }
                   3831: 
1.620     albertel 3832:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      3833: # Free bre access to adm and meta resources
1.775     albertel 3834:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 3835: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   3836: 	&& ($priv eq 'bre')) {
1.14      www      3837: 	return 'F';
1.159     www      3838:     }
                   3839: 
1.545     banghart 3840: # Free bre access to user's own portfolio contents
1.714     raeburn  3841:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  3842:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  3843: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  3844:         my %setters;
                   3845:         my ($startblock,$endblock) = 
                   3846:             &Apache::loncommon::blockcheck(\%setters,'port');
                   3847:         if ($startblock && $endblock) {
                   3848:             return 'B';
                   3849:         } else {
                   3850:             return 'F';
                   3851:         }
1.545     banghart 3852:     }
                   3853: 
1.762     raeburn  3854: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  3855:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   3856:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   3857:         if (exists($env{'request.course.id'})) {
                   3858:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3859:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3860:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   3861:                 my $courseprivid=$env{'request.course.id'};
                   3862:                 $courseprivid=~s/\_/\//;
                   3863:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   3864:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   3865:                     return $1; 
1.762     raeburn  3866:                 } else {
                   3867:                     if ($env{'request.course.sec'}) {
                   3868:                         $courseprivid.='/'.$env{'request.course.sec'};
                   3869:                     }
                   3870:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   3871:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   3872:                         return $2;
                   3873:                     }
1.714     raeburn  3874:                 }
                   3875:             }
                   3876:         }
                   3877:     }
                   3878: 
1.159     www      3879: # Free bre to public access
                   3880: 
                   3881:     if ($priv eq 'bre') {
1.238     www      3882:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 3883: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      3884:            return 'F'; 
                   3885:         }
1.238     www      3886:         if ($copyright eq 'priv') {
                   3887:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 3888: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      3889: 		return '';
                   3890:             }
                   3891:         }
                   3892:         if ($copyright eq 'domain') {
                   3893:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 3894: 	    unless (($env{'user.domain'} eq $1) ||
                   3895:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      3896: 		return '';
                   3897:             }
1.262     matthew  3898:         }
1.620     albertel 3899:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  3900:             # Library role, so allow browsing of resources in this domain.
                   3901:             return 'F';
1.238     www      3902:         }
1.341     www      3903:         if ($copyright eq 'custom') {
                   3904: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   3905:         }
1.14      www      3906:     }
1.264     matthew  3907:     # Domain coordinator is trying to create a course
1.620     albertel 3908:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  3909:         # uri is the requested domain in this case.
                   3910:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  3911:         # a role of dc for the domain in question.
1.620     albertel 3912:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  3913:     }
1.29      www      3914: 
1.52      www      3915:     my $thisallowed='';
                   3916:     my $statecond=0;
                   3917:     my $courseprivid='';
                   3918: 
                   3919: # Course
                   3920: 
1.620     albertel 3921:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3922:        $thisallowed.=$1;
                   3923:     }
1.29      www      3924: 
1.52      www      3925: # Domain
                   3926: 
1.620     albertel 3927:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 3928:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      3929:        $thisallowed.=$1;
                   3930:     }
1.52      www      3931: 
                   3932: # Course: uri itself is a course
1.66      www      3933:     my $courseuri=$uri;
                   3934:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      3935:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      3936: 
1.620     albertel 3937:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 3938:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      3939:        $thisallowed.=$1;
                   3940:     }
1.29      www      3941: 
1.665     albertel 3942: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 3943: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 3944:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 3945: 	$thisallowed='';
1.671     raeburn  3946:         my ($match)=&is_on_map($uri);
                   3947:         if ($match) {
                   3948:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   3949:                   =~/\Q$priv\E\&([^\:]*)/) {
                   3950:                 $thisallowed.=$1;
                   3951:             }
                   3952:         } else {
1.705     albertel 3953:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  3954:             if ($refuri) {
                   3955:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  3956:                     $thisallowed='F';
1.671     raeburn  3957:                 } else {
                   3958:                     $refuri=&declutter($refuri);
                   3959:                     my ($match) = &is_on_map($refuri);
                   3960:                     if ($match) {
                   3961:                         $thisallowed='F';
                   3962:                     }
1.669     raeburn  3963:                 }
1.671     raeburn  3964:             }
                   3965:         }
1.314     www      3966:     }
1.492     albertel 3967: 
1.766     albertel 3968:     if ($priv eq 'bre'
                   3969: 	&& $thisallowed ne 'F' 
                   3970: 	&& $thisallowed ne '2'
                   3971: 	&& &is_portfolio_url($uri)) {
                   3972: 	$thisallowed = &portfolio_access($uri);
                   3973:     }
                   3974:     
1.52      www      3975: # Full access at system, domain or course-wide level? Exit.
1.29      www      3976: 
                   3977:     if ($thisallowed=~/F/) {
                   3978: 	return 'F';
                   3979:     }
                   3980: 
1.52      www      3981: # If this is generating or modifying users, exit with special codes
1.29      www      3982: 
1.643     www      3983:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   3984: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 3985: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      3986: # no author name given, so this just checks on the general right to make a co-author in this domain
                   3987: 	    unless ($auname) { return $thisallowed; }
                   3988: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 3989: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   3990: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   3991: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   3992: 	}
1.52      www      3993: 	return $thisallowed;
                   3994:     }
                   3995: #
1.103     harris41 3996: # Gathered so far: system, domain and course wide privileges
1.52      www      3997: #
                   3998: # Course: See if uri or referer is an individual resource that is part of 
                   3999: # the course
                   4000: 
1.620     albertel 4001:     if ($env{'request.course.id'}) {
1.232     www      4002: 
1.620     albertel 4003:        $courseprivid=$env{'request.course.id'};
                   4004:        if ($env{'request.course.sec'}) {
                   4005:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      4006:        }
                   4007:        $courseprivid=~s/\_/\//;
                   4008:        my $checkreferer=1;
1.232     www      4009:        my ($match,$cond)=&is_on_map($uri);
                   4010:        if ($match) {
                   4011:            $statecond=$cond;
1.620     albertel 4012:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 4013:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4014:                $thisallowed.=$1;
                   4015:                $checkreferer=0;
                   4016:            }
1.29      www      4017:        }
1.83      www      4018:        
1.148     www      4019:        if ($checkreferer) {
1.620     albertel 4020: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      4021:             unless ($refuri) {
1.800     albertel 4022:                 foreach my $key (keys(%env)) {
                   4023: 		    if ($key=~/^httpref\..*\*/) {
                   4024: 			my $pattern=$key;
1.156     www      4025:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      4026:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   4027:                         $pattern=~s/\//\\\//g;
1.152     www      4028:                         if ($orguri=~/$pattern/) {
1.800     albertel 4029: 			    $refuri=$env{$key};
1.148     www      4030:                         }
                   4031:                     }
1.191     harris41 4032:                 }
1.148     www      4033:             }
1.232     www      4034: 
1.148     www      4035:          if ($refuri) { 
1.152     www      4036: 	  $refuri=&declutter($refuri);
1.232     www      4037:           my ($match,$cond)=&is_on_map($refuri);
                   4038:             if ($match) {
                   4039:               my $refstatecond=$cond;
1.620     albertel 4040:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 4041:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4042:                   $thisallowed.=$1;
1.53      www      4043:                   $uri=$refuri;
                   4044:                   $statecond=$refstatecond;
1.52      www      4045:               }
                   4046:           }
1.148     www      4047:         }
1.29      www      4048:        }
1.52      www      4049:    }
1.29      www      4050: 
1.52      www      4051: #
1.103     harris41 4052: # Gathered now: all privileges that could apply, and condition number
1.52      www      4053: # 
                   4054: #
                   4055: # Full or no access?
                   4056: #
1.29      www      4057: 
1.52      www      4058:     if ($thisallowed=~/F/) {
                   4059: 	return 'F';
                   4060:     }
1.29      www      4061: 
1.52      www      4062:     unless ($thisallowed) {
                   4063:         return '';
                   4064:     }
1.29      www      4065: 
1.52      www      4066: # Restrictions exist, deal with them
                   4067: #
                   4068: #   C:according to course preferences
                   4069: #   R:according to resource settings
                   4070: #   L:unless locked
                   4071: #   X:according to user session state
                   4072: #
                   4073: 
                   4074: # Possibly locked functionality, check all courses
1.54      www      4075: # Locks might take effect only after 10 minutes cache expiration for other
                   4076: # courses, and 2 minutes for current course
1.52      www      4077: 
                   4078:     my $envkey;
                   4079:     if ($thisallowed=~/L/) {
1.620     albertel 4080:         foreach $envkey (keys %env) {
1.54      www      4081:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   4082:                my $courseid=$2;
                   4083:                my $roleid=$1.'.'.$2;
1.92      www      4084:                $courseid=~s/^\///;
1.54      www      4085:                my $expiretime=600;
1.620     albertel 4086:                if ($env{'request.role'} eq $roleid) {
1.54      www      4087: 		  $expiretime=120;
                   4088:                }
                   4089: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   4090:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 4091:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 4092: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      4093:                }
1.620     albertel 4094:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   4095:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   4096: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   4097:                        &log($env{'user.domain'},$env{'user.name'},
                   4098:                             $env{'user.home'},
1.57      www      4099:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      4100:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 4101:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      4102: 		       return '';
                   4103:                    }
                   4104:                }
1.620     albertel 4105:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   4106:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   4107: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   4108:                        &log($env{'user.domain'},$env{'user.name'},
                   4109:                             $env{'user.home'},
1.57      www      4110:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      4111:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 4112:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      4113: 		       return '';
                   4114:                    }
                   4115:                }
                   4116: 	   }
1.29      www      4117:        }
1.52      www      4118:     }
                   4119:    
                   4120: #
                   4121: # Rest of the restrictions depend on selected course
                   4122: #
                   4123: 
1.620     albertel 4124:     unless ($env{'request.course.id'}) {
1.766     albertel 4125: 	if ($thisallowed eq 'A') {
                   4126: 	    return 'A';
1.814     raeburn  4127:         } elsif ($thisallowed eq 'B') {
                   4128:             return 'B';
1.766     albertel 4129: 	} else {
                   4130: 	    return '1';
                   4131: 	}
1.52      www      4132:     }
1.29      www      4133: 
1.52      www      4134: #
                   4135: # Now user is definitely in a course
                   4136: #
1.53      www      4137: 
                   4138: 
                   4139: # Course preferences
                   4140: 
                   4141:    if ($thisallowed=~/C/) {
1.620     albertel 4142:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   4143:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   4144:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 4145: 	   =~/\Q$rolecode\E/) {
1.689     albertel 4146: 	   if ($priv ne 'pch') { 
                   4147: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   4148: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   4149: 			$env{'request.course.id'});
                   4150: 	   }
1.237     www      4151:            return '';
                   4152:        }
                   4153: 
1.620     albertel 4154:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 4155: 	   =~/\Q$unamedom\E/) {
1.689     albertel 4156: 	   if ($priv ne 'pch') { 
                   4157: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   4158: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   4159: 			$env{'request.course.id'});
                   4160: 	   }
1.54      www      4161:            return '';
                   4162:        }
1.53      www      4163:    }
                   4164: 
                   4165: # Resource preferences
                   4166: 
                   4167:    if ($thisallowed=~/R/) {
1.620     albertel 4168:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 4169:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689     albertel 4170: 	   if ($priv ne 'pch') { 
                   4171: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   4172: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   4173: 	   }
                   4174: 	   return '';
1.54      www      4175:        }
1.53      www      4176:    }
1.30      www      4177: 
1.246     www      4178: # Restricted by state or randomout?
1.30      www      4179: 
1.52      www      4180:    if ($thisallowed=~/X/) {
1.620     albertel 4181:       if ($env{'acc.randomout'}) {
1.579     albertel 4182: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 4183:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      4184:             return ''; 
                   4185:          }
1.247     www      4186:       }
                   4187:       if (&condval($statecond)) {
1.52      www      4188: 	 return '2';
                   4189:       } else {
                   4190:          return '';
                   4191:       }
                   4192:    }
1.30      www      4193: 
1.766     albertel 4194:     if ($thisallowed eq 'A') {
                   4195: 	return 'A';
1.814     raeburn  4196:     } elsif ($thisallowed eq 'B') {
                   4197:         return 'B';
1.766     albertel 4198:     }
1.52      www      4199:    return 'F';
1.232     www      4200: }
                   4201: 
1.710     albertel 4202: sub split_uri_for_cond {
                   4203:     my $uri=&deversion(&declutter(shift));
                   4204:     my @uriparts=split(/\//,$uri);
                   4205:     my $filename=pop(@uriparts);
                   4206:     my $pathname=join('/',@uriparts);
                   4207:     return ($pathname,$filename);
                   4208: }
1.232     www      4209: # --------------------------------------------------- Is a resource on the map?
                   4210: 
                   4211: sub is_on_map {
1.710     albertel 4212:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 4213:     #Trying to find the conditional for the file
1.620     albertel 4214:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 4215: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      4216:     if ($match) {
1.289     bowersj2 4217: 	return (1,$1);
                   4218:     } else {
1.434     www      4219: 	return (0,0);
1.289     bowersj2 4220:     }
1.12      www      4221: }
                   4222: 
1.427     www      4223: # --------------------------------------------------------- Get symb from alias
                   4224: 
                   4225: sub get_symb_from_alias {
                   4226:     my $symb=shift;
                   4227:     my ($map,$resid,$url)=&decode_symb($symb);
                   4228: # Already is a symb
                   4229:     if ($url) { return $symb; }
                   4230: # Must be an alias
                   4231:     my $aliassymb='';
                   4232:     my %bighash;
1.620     albertel 4233:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      4234:                             &GDBM_READER(),0640)) {
                   4235:         my $rid=$bighash{'mapalias_'.$symb};
                   4236: 	if ($rid) {
                   4237: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 4238: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   4239: 				    $resid,$bighash{'src_'.$rid});
1.427     www      4240: 	}
                   4241:         untie %bighash;
                   4242:     }
                   4243:     return $aliassymb;
                   4244: }
                   4245: 
1.12      www      4246: # ----------------------------------------------------------------- Define Role
                   4247: 
                   4248: sub definerole {
                   4249:   if (allowed('mcr','/')) {
                   4250:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 4251:     foreach my $role (split(':',$sysrole)) {
                   4252: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4253:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   4254:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   4255: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      4256:                return "refused:s:$crole&$cqual"; 
                   4257:             }
                   4258:         }
1.191     harris41 4259:     }
1.800     albertel 4260:     foreach my $role (split(':',$domrole)) {
                   4261: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4262:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   4263:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   4264: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      4265:                return "refused:d:$crole&$cqual"; 
                   4266:             }
                   4267:         }
1.191     harris41 4268:     }
1.800     albertel 4269:     foreach my $role (split(':',$courole)) {
                   4270: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4271:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   4272:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   4273: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      4274:                return "refused:c:$crole&$cqual"; 
                   4275:             }
                   4276:         }
1.191     harris41 4277:     }
1.620     albertel 4278:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   4279:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      4280: 	        "rolesdef_$rolename=".
                   4281:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 4282:     return reply($command,$env{'user.home'});
1.12      www      4283:   } else {
                   4284:     return 'refused';
                   4285:   }
1.105     harris41 4286: }
                   4287: 
                   4288: # ---------------- Make a metadata query against the network of library servers
                   4289: 
                   4290: sub metadata_query {
1.244     matthew  4291:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 4292:     my %rhash;
1.845     albertel 4293:     my %libserv = &all_library();
1.244     matthew  4294:     my @server_list = (defined($server_array) ? @$server_array
                   4295:                                               : keys(%libserv) );
                   4296:     for my $server (@server_list) {
1.118     harris41 4297: 	unless ($custom or $customshow) {
                   4298: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   4299: 	    $rhash{$server}=$reply;
                   4300: 	}
                   4301: 	else {
                   4302: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   4303: 			     &escape($custom).':'.&escape($customshow),
                   4304: 			     $server);
                   4305: 	    $rhash{$server}=$reply;
                   4306: 	}
1.112     harris41 4307:     }
1.118     harris41 4308:     return \%rhash;
1.240     www      4309: }
                   4310: 
                   4311: # ----------------------------------------- Send log queries and wait for reply
                   4312: 
                   4313: sub log_query {
                   4314:     my ($uname,$udom,$query,%filters)=@_;
                   4315:     my $uhome=&homeserver($uname,$udom);
                   4316:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 4317:     my $uhost=&hostname($uhome);
1.800     albertel 4318:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      4319:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   4320:                        $uhome);
1.479     albertel 4321:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      4322:     return get_query_reply($queryid);
                   4323: }
                   4324: 
1.818     raeburn  4325: # -------------------------- Update MySQL table for portfolio file
                   4326: 
                   4327: sub update_portfolio_table {
1.821     raeburn  4328:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.818     raeburn  4329:     my $homeserver = &homeserver($uname,$udom);
                   4330:     my $queryid=
1.821     raeburn  4331:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   4332:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  4333:     my $reply = &get_query_reply($queryid);
                   4334:     return $reply;
                   4335: }
                   4336: 
1.508     raeburn  4337: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  4338: 
                   4339: sub fetch_enrollment_query {
1.511     raeburn  4340:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  4341:     my $homeserver;
1.547     raeburn  4342:     my $maxtries = 1;
1.508     raeburn  4343:     if ($context eq 'automated') {
                   4344:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  4345:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  4346:     } else {
                   4347:         $homeserver = &homeserver($cnum,$dom);
                   4348:     }
1.838     albertel 4349:     my $host=&hostname($homeserver);
1.506     raeburn  4350:     my $cmd = '';
1.800     albertel 4351:     foreach my $affiliate (keys %{$affiliatesref}) {
                   4352:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  4353:     }
                   4354:     $cmd =~ s/%%$//;
                   4355:     $cmd = &escape($cmd);
                   4356:     my $query = 'fetchenrollment';
1.620     albertel 4357:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  4358:     unless ($queryid=~/^\Q$host\E\_/) { 
                   4359:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   4360:         return 'error: '.$queryid;
                   4361:     }
1.506     raeburn  4362:     my $reply = &get_query_reply($queryid);
1.547     raeburn  4363:     my $tries = 1;
                   4364:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   4365:         $reply = &get_query_reply($queryid);
                   4366:         $tries ++;
                   4367:     }
1.526     raeburn  4368:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 4369:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  4370:     } else {
1.515     raeburn  4371:         my @responses = split/:/,$reply;
                   4372:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 4373:             foreach my $line (@responses) {
                   4374:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  4375:                 $$replyref{$key} = $value;
                   4376:             }
                   4377:         } else {
1.506     raeburn  4378:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800     albertel 4379:             foreach my $line (@responses) {
                   4380:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  4381:                 $$replyref{$key} = $value;
                   4382:                 if ($value > 0) {
1.800     albertel 4383:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   4384:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  4385:                         my $destname = $pathname.'/'.$filename;
                   4386:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  4387:                         if ($xml_classlist =~ /^error/) {
                   4388:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   4389:                         } else {
1.506     raeburn  4390:                             if ( open(FILE,">$destname") ) {
                   4391:                                 print FILE &unescape($xml_classlist);
                   4392:                                 close(FILE);
1.526     raeburn  4393:                             } else {
                   4394:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  4395:                             }
                   4396:                         }
                   4397:                     }
                   4398:                 }
                   4399:             }
                   4400:         }
                   4401:         return 'ok';
                   4402:     }
                   4403:     return 'error';
                   4404: }
                   4405: 
1.242     www      4406: sub get_query_reply {
                   4407:     my $queryid=shift;
1.240     www      4408:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   4409:     my $reply='';
                   4410:     for (1..100) {
                   4411: 	sleep 2;
                   4412:         if (-e $replyfile.'.end') {
1.448     albertel 4413: 	    if (open(my $fh,$replyfile)) {
1.240     www      4414:                $reply.=<$fh>;
1.448     albertel 4415:                close($fh);
1.240     www      4416: 	   } else { return 'error: reply_file_error'; }
1.242     www      4417:            return &unescape($reply);
                   4418: 	}
1.240     www      4419:     }
1.242     www      4420:     return 'timeout:'.$queryid;
1.240     www      4421: }
                   4422: 
                   4423: sub courselog_query {
1.241     www      4424: #
                   4425: # possible filters:
                   4426: # url: url or symb
                   4427: # username
                   4428: # domain
                   4429: # action: view, submit, grade
                   4430: # start: timestamp
                   4431: # end: timestamp
                   4432: #
1.240     www      4433:     my (%filters)=@_;
1.620     albertel 4434:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      4435:     if ($filters{'url'}) {
                   4436: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   4437:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   4438:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   4439:     }
1.620     albertel 4440:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4441:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      4442:     return &log_query($cname,$cdom,'courselog',%filters);
                   4443: }
                   4444: 
                   4445: sub userlog_query {
1.858     raeburn  4446: #
                   4447: # possible filters:
                   4448: # action: log check role
                   4449: # start: timestamp
                   4450: # end: timestamp
                   4451: #
1.240     www      4452:     my ($uname,$udom,%filters)=@_;
                   4453:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      4454: }
                   4455: 
1.506     raeburn  4456: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   4457: 
                   4458: sub auto_run {
1.508     raeburn  4459:     my ($cnum,$cdom) = @_;
1.876     raeburn  4460:     my $response = 0;
                   4461:     my $settings;
                   4462:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   4463:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   4464:         $settings = $domconfig{'autoenroll'};
                   4465:         if ($settings->{'run'} eq '1') {
                   4466:             $response = 1;
                   4467:         }
                   4468:     } else {
                   4469:         my $homeserver = &homeserver($cnum,$cdom);
                   4470:         $response = &reply('autorun:'.$cdom,$homeserver);
                   4471:     }
1.506     raeburn  4472:     return $response;
                   4473: }
1.776     albertel 4474: 
1.506     raeburn  4475: sub auto_get_sections {
1.508     raeburn  4476:     my ($cnum,$cdom,$inst_coursecode) = @_;
                   4477:     my $homeserver = &homeserver($cnum,$cdom);
1.506     raeburn  4478:     my @secs = ();
1.511     raeburn  4479:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506     raeburn  4480:     unless ($response eq 'refused') {
                   4481:         @secs = split/:/,$response;
                   4482:     }
                   4483:     return @secs;
                   4484: }
1.776     albertel 4485: 
1.506     raeburn  4486: sub auto_new_course {
1.508     raeburn  4487:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
                   4488:     my $homeserver = &homeserver($cnum,$cdom);
1.515     raeburn  4489:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506     raeburn  4490:     return $response;
                   4491: }
1.776     albertel 4492: 
1.506     raeburn  4493: sub auto_validate_courseID {
1.508     raeburn  4494:     my ($cnum,$cdom,$inst_course_id) = @_;
                   4495:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  4496:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  4497:     return $response;
                   4498: }
1.776     albertel 4499: 
1.506     raeburn  4500: sub auto_create_password {
1.873     raeburn  4501:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   4502:     my ($homeserver,$response);
1.506     raeburn  4503:     my $create_passwd = 0;
                   4504:     my $authchk = '';
1.873     raeburn  4505:     if ($udom =~ /^$match_domain$/) {
                   4506:         $homeserver = &domain($udom,'primary');
                   4507:     }
                   4508:     if ($homeserver eq '') {
                   4509:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   4510:             $homeserver = &homeserver($cnum,$cdom);
                   4511:         }
                   4512:     }
                   4513:     if ($homeserver eq '') {
                   4514:         $authchk = 'nodomain';
1.506     raeburn  4515:     } else {
1.873     raeburn  4516:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   4517:         if ($response eq 'refused') {
                   4518:             $authchk = 'refused';
                   4519:         } else {
                   4520:             ($authparam,$create_passwd,$authchk) = split/:/,$response;
                   4521:         }
1.506     raeburn  4522:     }
                   4523:     return ($authparam,$create_passwd,$authchk);
                   4524: }
                   4525: 
1.706     raeburn  4526: sub auto_photo_permission {
                   4527:     my ($cnum,$cdom,$students) = @_;
                   4528:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 4529:     my ($outcome,$perm_reqd,$conditions) = 
                   4530: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 4531:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4532: 	return (undef,undef);
                   4533:     }
1.706     raeburn  4534:     return ($outcome,$perm_reqd,$conditions);
                   4535: }
                   4536: 
                   4537: sub auto_checkphotos {
                   4538:     my ($uname,$udom,$pid) = @_;
                   4539:     my $homeserver = &homeserver($uname,$udom);
                   4540:     my ($result,$resulttype);
                   4541:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 4542: 				   &escape($uname).':'.&escape($pid),
                   4543: 				   $homeserver));
1.709     albertel 4544:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4545: 	return (undef,undef);
                   4546:     }
1.706     raeburn  4547:     if ($outcome) {
                   4548:         ($result,$resulttype) = split(/:/,$outcome);
                   4549:     } 
                   4550:     return ($result,$resulttype);
                   4551: }
                   4552: 
                   4553: sub auto_photochoice {
                   4554:     my ($cnum,$cdom) = @_;
                   4555:     my $homeserver = &homeserver($cnum,$cdom);
                   4556:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 4557: 						       &escape($cdom),
                   4558: 						       $homeserver)));
1.709     albertel 4559:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4560: 	return (undef,undef);
                   4561:     }
1.706     raeburn  4562:     return ($update,$comment);
                   4563: }
                   4564: 
                   4565: sub auto_photoupdate {
                   4566:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   4567:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 4568:     my $host=&hostname($homeserver);
1.706     raeburn  4569:     my $cmd = '';
                   4570:     my $maxtries = 1;
1.800     albertel 4571:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   4572:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  4573:     }
                   4574:     $cmd =~ s/%%$//;
                   4575:     $cmd = &escape($cmd);
                   4576:     my $query = 'institutionalphotos';
                   4577:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   4578:     unless ($queryid=~/^\Q$host\E\_/) {
                   4579:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   4580:         return 'error: '.$queryid;
                   4581:     }
                   4582:     my $reply = &get_query_reply($queryid);
                   4583:     my $tries = 1;
                   4584:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   4585:         $reply = &get_query_reply($queryid);
                   4586:         $tries ++;
                   4587:     }
                   4588:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   4589:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   4590:     } else {
                   4591:         my @responses = split(/:/,$reply);
                   4592:         my $outcome = shift(@responses); 
                   4593:         foreach my $item (@responses) {
                   4594:             my ($key,$value) = split(/=/,$item);
                   4595:             $$photo{$key} = $value;
                   4596:         }
                   4597:         return $outcome;
                   4598:     }
                   4599:     return 'error';
                   4600: }
                   4601: 
1.521     raeburn  4602: sub auto_instcode_format {
1.793     albertel 4603:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   4604: 	$cat_order) = @_;
1.521     raeburn  4605:     my $courses = '';
1.772     raeburn  4606:     my @homeservers;
1.521     raeburn  4607:     if ($caller eq 'global') {
1.841     albertel 4608: 	my %servers = &get_servers($codedom,'library');
                   4609: 	foreach my $tryserver (keys(%servers)) {
                   4610: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   4611: 		push(@homeservers,$tryserver);
                   4612: 	    }
1.584     raeburn  4613:         }
1.521     raeburn  4614:     } else {
1.772     raeburn  4615:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  4616:     }
1.793     albertel 4617:     foreach my $code (keys(%{$instcodes})) {
                   4618:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  4619:     }
                   4620:     chop($courses);
1.772     raeburn  4621:     my $ok_response = 0;
                   4622:     my $response;
                   4623:     while (@homeservers > 0 && $ok_response == 0) {
                   4624:         my $server = shift(@homeservers); 
                   4625:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   4626:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   4627:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.793     albertel 4628: 		split/:/,$response;
1.772     raeburn  4629:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   4630:             push(@{$codetitles},&str2array($codetitles_str));
                   4631:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   4632:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   4633:             $ok_response = 1;
                   4634:         }
                   4635:     }
                   4636:     if ($ok_response) {
1.521     raeburn  4637:         return 'ok';
1.772     raeburn  4638:     } else {
                   4639:         return $response;
1.521     raeburn  4640:     }
                   4641: }
                   4642: 
1.792     raeburn  4643: sub auto_instcode_defaults {
                   4644:     my ($domain,$returnhash,$code_order) = @_;
                   4645:     my @homeservers;
1.841     albertel 4646: 
                   4647:     my %servers = &get_servers($domain,'library');
                   4648:     foreach my $tryserver (keys(%servers)) {
                   4649: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   4650: 	    push(@homeservers,$tryserver);
                   4651: 	}
1.792     raeburn  4652:     }
1.841     albertel 4653: 
1.792     raeburn  4654:     my $response;
1.841     albertel 4655:     foreach my $server (@homeservers) {
1.792     raeburn  4656:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 4657:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   4658: 	
                   4659: 	foreach my $pair (split(/\&/,$response)) {
                   4660: 	    my ($name,$value)=split(/\=/,$pair);
                   4661: 	    if ($name eq 'code_order') {
                   4662: 		@{$code_order} = split(/\&/,&unescape($value));
                   4663: 	    } else {
                   4664: 		$returnhash->{&unescape($name)}=&unescape($value);
                   4665: 	    }
                   4666: 	}
                   4667: 	return 'ok';
1.792     raeburn  4668:     }
1.841     albertel 4669: 
                   4670:     return $response;
1.792     raeburn  4671: } 
                   4672: 
1.777     albertel 4673: sub auto_validate_class_sec {
1.773     raeburn  4674:     my ($cdom,$cnum,$owner,$inst_class) = @_;
                   4675:     my $homeserver = &homeserver($cnum,$cdom);
                   4676:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.774     banghart 4677:                         &escape($owner).':'.$cdom,$homeserver);
1.773     raeburn  4678:     return $response;
                   4679: }
                   4680: 
1.679     raeburn  4681: # ------------------------------------------------------- Course Group routines
                   4682: 
                   4683: sub get_coursegroups {
1.809     raeburn  4684:     my ($cdom,$cnum,$group,$namespace) = @_;
                   4685:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  4686: }
                   4687: 
1.679     raeburn  4688: sub modify_coursegroup {
                   4689:     my ($cdom,$cnum,$groupsettings) = @_;
                   4690:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   4691: }
                   4692: 
1.809     raeburn  4693: sub toggle_coursegroup_status {
                   4694:     my ($cdom,$cnum,$group,$action) = @_;
                   4695:     my ($from_namespace,$to_namespace);
                   4696:     if ($action eq 'delete') {
                   4697:         $from_namespace = 'coursegroups';
                   4698:         $to_namespace = 'deleted_groups';
                   4699:     } else {
                   4700:         $from_namespace = 'deleted_groups';
                   4701:         $to_namespace = 'coursegroups';
                   4702:     }
                   4703:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  4704:     if (my $tmp = &error(%curr_group)) {
                   4705:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   4706:         return ('read error',$tmp);
                   4707:     } else {
                   4708:         my %savedsettings = %curr_group; 
1.809     raeburn  4709:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  4710:         my $deloutcome;
                   4711:         if ($result eq 'ok') {
1.809     raeburn  4712:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  4713:         } else {
                   4714:             return ('write error',$result);
                   4715:         }
                   4716:         if ($deloutcome eq 'ok') {
                   4717:             return 'ok';
                   4718:         } else {
                   4719:             return ('delete error',$deloutcome);
                   4720:         }
                   4721:     }
                   4722: }
                   4723: 
1.679     raeburn  4724: sub modify_group_roles {
                   4725:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
                   4726:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   4727:     my $role = 'gr/'.&escape($userprivs);
                   4728:     my ($uname,$udom) = split(/:/,$user);
                   4729:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
1.684     raeburn  4730:     if ($result eq 'ok') {
                   4731:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   4732:     }
1.679     raeburn  4733:     return $result;
                   4734: }
                   4735: 
                   4736: sub modify_coursegroup_membership {
                   4737:     my ($cdom,$cnum,$membership) = @_;
                   4738:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   4739:     return $result;
                   4740: }
                   4741: 
1.682     raeburn  4742: sub get_active_groups {
                   4743:     my ($udom,$uname,$cdom,$cnum) = @_;
                   4744:     my $now = time;
                   4745:     my %groups = ();
                   4746:     foreach my $key (keys(%env)) {
1.811     albertel 4747:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  4748:             my ($start,$end) = split(/\./,$env{$key});
                   4749:             if (($end!=0) && ($end<$now)) { next; }
                   4750:             if (($start!=0) && ($start>$now)) { next; }
                   4751:             if ($1 eq $cdom && $2 eq $cnum) {
                   4752:                 $groups{$3} = $env{$key} ;
                   4753:             }
                   4754:         }
                   4755:     }
                   4756:     return %groups;
                   4757: }
                   4758: 
1.683     raeburn  4759: sub get_group_membership {
                   4760:     my ($cdom,$cnum,$group) = @_;
                   4761:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   4762: }
                   4763: 
                   4764: sub get_users_groups {
                   4765:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  4766:     my @usersgroups;
1.683     raeburn  4767:     my $cachetime=1800;
                   4768: 
                   4769:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  4770:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   4771:     if (defined($cached)) {
1.734     albertel 4772:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  4773:     } else {  
                   4774:         $grouplist = '';
1.816     raeburn  4775:         my $courseurl = &courseid_to_courseurl($courseid);
                   4776:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  4777:         my $access_end = $env{'course.'.$courseid.
                   4778:                               '.default_enrollment_end_date'};
                   4779:         my $now = time;
                   4780:         foreach my $key (keys(%roleshash)) {
                   4781:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   4782:                 my $group = $1;
                   4783:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   4784:                     my $start = $2;
                   4785:                     my $end = $1;
                   4786:                     if ($start == -1) { next; } # deleted from group
                   4787:                     if (($start!=0) && ($start>$now)) { next; }
                   4788:                     if (($end!=0) && ($end<$now)) {
                   4789:                         if ($access_end && $access_end < $now) {
                   4790:                             if ($access_end - $end < 86400) {
                   4791:                                 push(@usersgroups,$group);
1.733     raeburn  4792:                             }
                   4793:                         }
1.817     raeburn  4794:                         next;
1.733     raeburn  4795:                     }
1.817     raeburn  4796:                     push(@usersgroups,$group);
1.683     raeburn  4797:                 }
                   4798:             }
                   4799:         }
1.817     raeburn  4800:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   4801:         $grouplist = join(':',@usersgroups);
                   4802:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  4803:     }
1.733     raeburn  4804:     return @usersgroups;
1.683     raeburn  4805: }
                   4806: 
                   4807: sub devalidate_getgroups_cache {
                   4808:     my ($udom,$uname,$cdom,$cnum)=@_;
                   4809:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 4810: 
1.683     raeburn  4811:     my $hashid="$udom:$uname:$courseid";
                   4812:     &devalidate_cache_new('getgroups',$hashid);
                   4813: }
                   4814: 
1.12      www      4815: # ------------------------------------------------------------------ Plain Text
                   4816: 
                   4817: sub plaintext {
1.742     raeburn  4818:     my ($short,$type,$cid) = @_;
1.758     albertel 4819:     if ($short =~ /^cr/) {
                   4820: 	return (split('/',$short))[-1];
                   4821:     }
1.742     raeburn  4822:     if (!defined($cid)) {
                   4823:         $cid = $env{'request.course.id'};
                   4824:     }
                   4825:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
                   4826:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
                   4827:                                           '.plaintext'});
                   4828:     }
                   4829:     my %rolenames = (
                   4830:                       Course => 'std',
                   4831:                       Group => 'alt1',
                   4832:                     );
                   4833:     if (defined($type) && 
                   4834:          defined($rolenames{$type}) && 
                   4835:          defined($prp{$short}{$rolenames{$type}})) {
                   4836:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
                   4837:     } else {
                   4838:         return &Apache::lonlocal::mt($prp{$short}{'std'});
                   4839:     }
1.12      www      4840: }
                   4841: 
                   4842: # ----------------------------------------------------------------- Assign Role
                   4843: 
                   4844: sub assignrole {
1.357     www      4845:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
1.21      www      4846:     my $mrole;
                   4847:     if ($role =~ /^cr\//) {
1.393     www      4848:         my $cwosec=$url;
1.811     albertel 4849:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      4850: 	unless (&allowed('ccr',$cwosec)) {
1.104     www      4851:            &logthis('Refused custom assignrole: '.
                   4852:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 4853: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      4854:            return 'refused'; 
                   4855:         }
1.21      www      4856:         $mrole='cr';
1.678     raeburn  4857:     } elsif ($role =~ /^gr\//) {
                   4858:         my $cwogrp=$url;
1.811     albertel 4859:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  4860:         unless (&allowed('mdg',$cwogrp)) {
                   4861:             &logthis('Refused group assignrole: '.
                   4862:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   4863:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   4864:             return 'refused';
                   4865:         }
                   4866:         $mrole='gr';
1.21      www      4867:     } else {
1.82      www      4868:         my $cwosec=$url;
1.811     albertel 4869:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.373     www      4870:         unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) { 
1.104     www      4871:            &logthis('Refused assignrole: '.
                   4872:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 4873: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      4874:            return 'refused'; 
                   4875:         }
1.21      www      4876:         $mrole=$role;
                   4877:     }
1.620     albertel 4878:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      4879:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      4880:     if ($end) { $command.='_'.$end; }
1.21      www      4881:     if ($start) {
                   4882: 	if ($end) { 
1.81      www      4883:            $command.='_'.$start; 
1.21      www      4884:         } else {
1.81      www      4885:            $command.='_0_'.$start;
1.21      www      4886:         }
                   4887:     }
1.739     raeburn  4888:     my $origstart = $start;
                   4889:     my $origend = $end;
1.357     www      4890: # actually delete
                   4891:     if ($deleteflag) {
1.373     www      4892: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      4893: # modify command to delete the role
1.620     albertel 4894:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      4895:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 4896: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      4897: # set start and finish to negative values for userrolelog
                   4898:            $start=-1;
                   4899:            $end=-1;
                   4900:         }
                   4901:     }
                   4902: # send command
1.349     www      4903:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      4904: # log new user role if status is ok
1.349     www      4905:     if ($answer eq 'ok') {
1.663     raeburn  4906: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  4907: # for course roles, perform group memberships changes triggered by role change.
                   4908:         unless ($role =~ /^gr/) {
                   4909:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   4910:                                              $origstart);
                   4911:         }
1.349     www      4912:     }
                   4913:     return $answer;
1.169     harris41 4914: }
                   4915: 
                   4916: # -------------------------------------------------- Modify user authentication
1.197     www      4917: # Overrides without validation
                   4918: 
1.169     harris41 4919: sub modifyuserauth {
                   4920:     my ($udom,$uname,$umode,$upass)=@_;
                   4921:     my $uhome=&homeserver($uname,$udom);
1.197     www      4922:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   4923:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 4924:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   4925:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 4926:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   4927: 		     &escape($upass),$uhome);
1.620     albertel 4928:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      4929:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   4930:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   4931:     &log($udom,,$uname,$uhome,
1.620     albertel 4932:         'Authentication changed by '.$env{'user.domain'}.', '.
                   4933:                                      $env{'user.name'}.', '.$umode.
1.197     www      4934:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 4935:     unless ($reply eq 'ok') {
1.197     www      4936:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 4937: 	return 'error: '.$reply;
                   4938:     }   
1.170     harris41 4939:     return 'ok';
1.80      www      4940: }
                   4941: 
1.81      www      4942: # --------------------------------------------------------------- Modify a user
1.80      www      4943: 
1.81      www      4944: sub modifyuser {
1.206     matthew  4945:     my ($udom,    $uname, $uid,
                   4946:         $umode,   $upass, $first,
                   4947:         $middle,  $last,  $gene,
1.387     www      4948:         $forceid, $desiredhome, $email)=@_;
1.807     albertel 4949:     $udom= &LONCAPA::clean_domain($udom);
                   4950:     $uname=&LONCAPA::clean_username($uname);
1.81      www      4951:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      4952:              $umode.', '.$first.', '.$middle.', '.
1.206     matthew  4953: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
                   4954:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   4955:                                      ' desiredhome not specified'). 
1.620     albertel 4956:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   4957:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 4958:     my $uhome=&homeserver($uname,$udom,'true');
1.80      www      4959: # ----------------------------------------------------------------- Create User
1.406     albertel 4960:     if (($uhome eq 'no_host') && 
                   4961: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      4962:         my $unhome='';
1.844     albertel 4963:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  4964:             $unhome = $desiredhome;
1.620     albertel 4965: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   4966: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  4967:         } else { # load balancing routine for determining $unhome
1.81      www      4968:             my $loadm=10000000;
1.841     albertel 4969: 	    my %servers = &get_servers($udom,'library');
                   4970: 	    foreach my $tryserver (keys(%servers)) {
                   4971: 		my $answer=reply('load',$tryserver);
                   4972: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   4973: 		    $loadm=$answer;
                   4974: 		    $unhome=$tryserver;
                   4975: 		}
1.80      www      4976: 	    }
                   4977:         }
                   4978:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  4979: 	    return 'error: unable to find a home server for '.$uname.
                   4980:                    ' in domain '.$udom;
1.80      www      4981:         }
                   4982:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   4983:                          &escape($upass),$unhome);
                   4984: 	unless ($reply eq 'ok') {
                   4985:             return 'error: '.$reply;
                   4986:         }   
1.230     stredwic 4987:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      4988:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  4989: 	    return 'error: unable verify users home machine.';
1.80      www      4990:         }
1.209     matthew  4991:     }   # End of creation of new user
1.80      www      4992: # ---------------------------------------------------------------------- Add ID
                   4993:     if ($uid) {
                   4994:        $uid=~tr/A-Z/a-z/;
                   4995:        my %uidhash=&idrget($udom,$uname);
1.196     www      4996:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   4997:          && (!$forceid)) {
1.80      www      4998: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  4999: 	      return 'error: user id "'.$uid.'" does not match '.
                   5000:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      5001:           }
                   5002:        } else {
                   5003: 	  &idput($udom,($uname => $uid));
                   5004:        }
                   5005:     }
                   5006: # -------------------------------------------------------------- Add names, etc
1.313     matthew  5007:     my @tmp=&get('environment',
1.134     albertel 5008: 		   ['firstname','middlename','lastname','generation'],
                   5009: 		   $udom,$uname);
1.313     matthew  5010:     my %names;
                   5011:     if ($tmp[0] =~ m/^error:.*/) { 
                   5012:         %names=(); 
                   5013:     } else {
                   5014:         %names = @tmp;
                   5015:     }
1.388     www      5016: #
                   5017: # Make sure to not trash student environment if instructor does not bother
                   5018: # to supply name and email information
                   5019: #
                   5020:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  5021:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      5022:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  5023:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      5024:     if ($email) {
                   5025:        $email=~s/[^\w\@\.\-\,]//gs;
                   5026:        if ($email=~/\@/) { $names{'notification'} = $email;
                   5027: 			   $names{'critnotification'} = $email;
                   5028: 			   $names{'permanentemail'} = $email; }
                   5029:     }
1.134     albertel 5030:     my $reply = &put('environment', \%names, $udom,$uname);
                   5031:     if ($reply ne 'ok') { return 'error: '.$reply; }
1.680     www      5032:     &devalidate_cache_new('namescache',$uname.':'.$udom);
1.81      www      5033:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      5034:              $umode.', '.$first.', '.$middle.', '.
                   5035: 	     $last.', '.$gene.' by '.
1.620     albertel 5036:              $env{'user.name'}.' at '.$env{'user.domain'});
1.134     albertel 5037:     return 'ok';
1.80      www      5038: }
                   5039: 
1.81      www      5040: # -------------------------------------------------------------- Modify student
1.80      www      5041: 
1.81      www      5042: sub modifystudent {
                   5043:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.515     raeburn  5044:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
1.455     albertel 5045:     if (!$cid) {
1.620     albertel 5046: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 5047: 	    return 'not_in_class';
                   5048: 	}
1.80      www      5049:     }
                   5050: # --------------------------------------------------------------- Make the user
1.81      www      5051:     my $reply=&modifyuser
1.209     matthew  5052: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387     www      5053:          $desiredhome,$email);
1.80      www      5054:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  5055:     # This will cause &modify_student_enrollment to get the uid from the
                   5056:     # students environment
                   5057:     $uid = undef if (!$forceid);
1.455     albertel 5058:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.515     raeburn  5059: 					$gene,$usec,$end,$start,$type,$locktype,$cid);
1.297     matthew  5060:     return $reply;
                   5061: }
                   5062: 
                   5063: sub modify_student_enrollment {
1.515     raeburn  5064:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
1.455     albertel 5065:     my ($cdom,$cnum,$chome);
                   5066:     if (!$cid) {
1.620     albertel 5067: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 5068: 	    return 'not_in_class';
                   5069: 	}
1.620     albertel 5070: 	$cdom=$env{'course.'.$cid.'.domain'};
                   5071: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 5072:     } else {
                   5073: 	($cdom,$cnum)=split(/_/,$cid);
                   5074:     }
1.620     albertel 5075:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 5076:     if (!$chome) {
1.457     raeburn  5077: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  5078:     }
1.455     albertel 5079:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  5080:     # Make sure the user exists
1.81      www      5081:     my $uhome=&homeserver($uname,$udom);
                   5082:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   5083: 	return 'error: no such user';
                   5084:     }
1.297     matthew  5085:     # Get student data if we were not given enough information
                   5086:     if (!defined($first)  || $first  eq '' || 
                   5087:         !defined($last)   || $last   eq '' || 
                   5088:         !defined($uid)    || $uid    eq '' || 
                   5089:         !defined($middle) || $middle eq '' || 
                   5090:         !defined($gene)   || $gene   eq '') {
1.294     matthew  5091:         # They did not supply us with enough data to enroll the student, so
                   5092:         # we need to pick up more information.
1.297     matthew  5093:         my %tmp = &get('environment',
1.294     matthew  5094:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  5095:                        ,$udom,$uname);
                   5096: 
1.800     albertel 5097:         #foreach my $key (keys(%tmp)) {
                   5098:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 5099:         #}
1.294     matthew  5100:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   5101:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   5102:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  5103:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  5104:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   5105:     }
1.556     albertel 5106:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 5107:     my $reply=cput('classlist',
                   5108: 		   {"$uname:$udom" => 
1.515     raeburn  5109: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 5110: 		   $cdom,$cnum);
1.81      www      5111:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   5112: 	return 'error: '.$reply;
1.652     albertel 5113:     } else {
                   5114: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      5115:     }
1.297     matthew  5116:     # Add student role to user
1.83      www      5117:     my $uurl='/'.$cid;
1.81      www      5118:     $uurl=~s/\_/\//g;
                   5119:     if ($usec) {
                   5120: 	$uurl.='/'.$usec;
                   5121:     }
                   5122:     return &assignrole($udom,$uname,$uurl,'st',$end,$start);
1.21      www      5123: }
                   5124: 
1.556     albertel 5125: sub format_name {
                   5126:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   5127:     my $name;
                   5128:     if ($first ne 'lastname') {
                   5129: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   5130:     } else {
                   5131: 	if ($lastname=~/\S/) {
                   5132: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   5133: 	    $name=~s/\s+,/,/;
                   5134: 	} else {
                   5135: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   5136: 	}
                   5137:     }
                   5138:     $name=~s/^\s+//;
                   5139:     $name=~s/\s+$//;
                   5140:     $name=~s/\s+/ /g;
                   5141:     return $name;
                   5142: }
                   5143: 
1.84      www      5144: # ------------------------------------------------- Write to course preferences
                   5145: 
                   5146: sub writecoursepref {
                   5147:     my ($courseid,%prefs)=@_;
                   5148:     $courseid=~s/^\///;
                   5149:     $courseid=~s/\_/\//g;
                   5150:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   5151:     my $chome=homeserver($cnum,$cdomain);
                   5152:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   5153: 	return 'error: no such course';
                   5154:     }
                   5155:     my $cstring='';
1.800     albertel 5156:     foreach my $pref (keys(%prefs)) {
                   5157: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 5158:     }
1.84      www      5159:     $cstring=~s/\&$//;
                   5160:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   5161: }
                   5162: 
                   5163: # ---------------------------------------------------------- Make/modify course
                   5164: 
                   5165: sub createcourse {
1.741     raeburn  5166:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
                   5167:         $course_owner,$crstype)=@_;
1.84      www      5168:     $url=&declutter($url);
                   5169:     my $cid='';
1.264     matthew  5170:     unless (&allowed('ccc',$udom)) {
1.84      www      5171:         return 'refused';
                   5172:     }
                   5173: # ------------------------------------------------------------------- Create ID
1.674     www      5174:    my $uname=int(1+rand(9)).
                   5175:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   5176:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
1.84      www      5177:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   5178: # ----------------------------------------------- Make sure that does not exist
1.230     stredwic 5179:    my $uhome=&homeserver($uname,$udom,'true');
1.84      www      5180:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   5181:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   5182:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230     stredwic 5183:        $uhome=&homeserver($uname,$udom,'true');       
1.84      www      5184:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   5185:            return 'error: unable to generate unique course-ID';
                   5186:        } 
                   5187:    }
1.264     matthew  5188: # ------------------------------------------------ Check supplied server name
1.620     albertel 5189:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.845     albertel 5190:     if (! &is_library($course_server)) {
1.264     matthew  5191:         return 'error:bad server name '.$course_server;
                   5192:     }
1.84      www      5193: # ------------------------------------------------------------- Make the course
                   5194:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  5195:                       $course_server);
1.84      www      5196:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230     stredwic 5197:     $uhome=&homeserver($uname,$udom,'true');
1.84      www      5198:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   5199: 	return 'error: no such course';
                   5200:     }
1.271     www      5201: # ----------------------------------------------------------------- Course made
1.516     raeburn  5202: # log existence
                   5203:     &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description).
1.741     raeburn  5204:                  ':'.&escape($inst_code).':'.&escape($course_owner).':'.
                   5205:                   &escape($crstype),$uhome);
1.358     www      5206:     &flushcourselogs();
                   5207: # set toplevel url
1.271     www      5208:     my $topurl=$url;
                   5209:     unless ($nonstandard) {
                   5210: # ------------------------------------------ For standard courses, make top url
                   5211:         my $mapurl=&clutter($url);
1.278     www      5212:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 5213:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      5214: <map>
                   5215: <resource id="1" type="start"></resource>
                   5216: <resource id="2" src="$mapurl"></resource>
                   5217: <resource id="3" type="finish"></resource>
                   5218: <link index="1" from="1" to="2"></link>
                   5219: <link index="2" from="2" to="3"></link>
                   5220: </map>
                   5221: ENDINITMAP
                   5222:         $topurl=&declutter(
1.638     albertel 5223:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      5224:                           );
                   5225:     }
                   5226: # ----------------------------------------------------------- Write preferences
1.84      www      5227:     &writecoursepref($udom.'_'.$uname,
                   5228:                      ('description' => $description,
1.271     www      5229:                       'url'         => $topurl));
1.84      www      5230:     return '/'.$udom.'/'.$uname;
                   5231: }
                   5232: 
1.813     albertel 5233: sub is_course {
                   5234:     my ($cdom,$cnum) = @_;
                   5235:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
                   5236: 				undef,'.');
                   5237:     if (exists($courses{$cdom.'_'.$cnum})) {
                   5238:         return 1;
                   5239:     }
                   5240:     return 0;
                   5241: }
                   5242: 
1.21      www      5243: # ---------------------------------------------------------- Assign Custom Role
                   5244: 
                   5245: sub assigncustomrole {
1.357     www      5246:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
1.21      www      5247:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.357     www      5248:                        $end,$start,$deleteflag);
1.21      www      5249: }
                   5250: 
                   5251: # ----------------------------------------------------------------- Revoke Role
                   5252: 
                   5253: sub revokerole {
1.357     www      5254:     my ($udom,$uname,$url,$role,$deleteflag)=@_;
1.21      www      5255:     my $now=time;
1.357     www      5256:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
1.21      www      5257: }
                   5258: 
                   5259: # ---------------------------------------------------------- Revoke Custom Role
                   5260: 
                   5261: sub revokecustomrole {
1.357     www      5262:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
1.21      www      5263:     my $now=time;
1.357     www      5264:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
                   5265:            $deleteflag);
1.17      www      5266: }
                   5267: 
1.533     banghart 5268: # ------------------------------------------------------------ Disk usage
1.535     albertel 5269: sub diskusage {
1.533     banghart 5270:     my ($udom,$uname,$directoryRoot)=@_;
                   5271:     $directoryRoot =~ s/\/$//;
1.535     albertel 5272:     my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
1.514     albertel 5273:     return $listing;
1.512     banghart 5274: }
                   5275: 
1.566     banghart 5276: sub is_locked {
                   5277:     my ($file_name, $domain, $user) = @_;
                   5278:     my @check;
                   5279:     my $is_locked;
                   5280:     push @check, $file_name;
1.613     albertel 5281:     my %locked = &get('file_permissions',\@check,
1.620     albertel 5282: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 5283:     my ($tmp)=keys(%locked);
                   5284:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  5285:     
1.566     banghart 5286:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  5287:         $is_locked = 'false';
                   5288:         foreach my $entry (@{$locked{$file_name}}) {
                   5289:            if (ref($entry) eq 'ARRAY') { 
1.746     raeburn  5290:                $is_locked = 'true';
                   5291:                last;
1.745     raeburn  5292:            }
                   5293:        }
1.566     banghart 5294:     } else {
                   5295:         $is_locked = 'false';
                   5296:     }
                   5297: }
                   5298: 
1.759     albertel 5299: sub declutter_portfile {
                   5300:     my ($file) = @_;
1.833     albertel 5301:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 5302:     return $file;
                   5303: }
                   5304: 
1.559     banghart 5305: # ------------------------------------------------------------- Mark as Read Only
                   5306: 
                   5307: sub mark_as_readonly {
                   5308:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 5309:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 5310:     my ($tmp)=keys(%current_permissions);
                   5311:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 5312:     foreach my $file (@{$files}) {
1.759     albertel 5313: 	$file = &declutter_portfile($file);
1.561     banghart 5314:         push(@{$current_permissions{$file}},$what);
1.559     banghart 5315:     }
1.613     albertel 5316:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 5317:     return;
                   5318: }
                   5319: 
1.572     banghart 5320: # ------------------------------------------------------------Save Selected Files
                   5321: 
                   5322: sub save_selected_files {
                   5323:     my ($user, $path, @files) = @_;
                   5324:     my $filename = $user."savedfiles";
1.573     banghart 5325:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 5326:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 5327:     foreach my $file (@files) {
1.620     albertel 5328:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 5329:     }
                   5330:     foreach my $file (@other_files) {
1.574     banghart 5331:         print (OUT $file."\n");
1.572     banghart 5332:     }
1.574     banghart 5333:     close (OUT);
1.572     banghart 5334:     return 'ok';
                   5335: }
                   5336: 
1.574     banghart 5337: sub clear_selected_files {
                   5338:     my ($user) = @_;
                   5339:     my $filename = $user."savedfiles";
                   5340:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   5341:     print (OUT undef);
                   5342:     close (OUT);
                   5343:     return ("ok");    
                   5344: }
                   5345: 
1.572     banghart 5346: sub files_in_path {
                   5347:     my ($user, $path) = @_;
                   5348:     my $filename = $user."savedfiles";
                   5349:     my %return_files;
1.574     banghart 5350:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 5351:     while (my $line_in = <IN>) {
1.574     banghart 5352:         chomp ($line_in);
                   5353:         my @paths_and_file = split (m!/!, $line_in);
                   5354:         my $file_part = pop (@paths_and_file);
                   5355:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 5356:         $path_part.='/';
                   5357:         my $path_and_file = $path_part.$file_part;
                   5358:         if ($path_part eq $path) {
                   5359:             $return_files{$file_part}= 'selected';
                   5360:         }
                   5361:     }
1.574     banghart 5362:     close (IN);
                   5363:     return (\%return_files);
1.572     banghart 5364: }
                   5365: 
                   5366: # called in portfolio select mode, to show files selected NOT in current directory
                   5367: sub files_not_in_path {
                   5368:     my ($user, $path) = @_;
                   5369:     my $filename = $user."savedfiles";
                   5370:     my @return_files;
                   5371:     my $path_part;
1.800     albertel 5372:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   5373:     while (my $line = <IN>) {
1.572     banghart 5374:         #ok, I know it's clunky, but I want it to work
1.800     albertel 5375:         my @paths_and_file = split(m|/|, $line);
                   5376:         my $file_part = pop(@paths_and_file);
                   5377:         chomp($file_part);
                   5378:         my $path_part = join('/', @paths_and_file);
1.572     banghart 5379:         $path_part .= '/';
                   5380:         my $path_and_file = $path_part.$file_part;
                   5381:         if ($path_part ne $path) {
1.800     albertel 5382:             push(@return_files, ($path_and_file));
1.572     banghart 5383:         }
                   5384:     }
1.800     albertel 5385:     close(OUT);
1.574     banghart 5386:     return (@return_files);
1.572     banghart 5387: }
                   5388: 
1.745     raeburn  5389: #----------------------------------------------Get portfolio file permissions
1.629     banghart 5390: 
1.745     raeburn  5391: sub get_portfile_permissions {
                   5392:     my ($domain,$user) = @_;
1.613     albertel 5393:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 5394:     my ($tmp)=keys(%current_permissions);
                   5395:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  5396:     return \%current_permissions;
                   5397: }
                   5398: 
                   5399: #---------------------------------------------Get portfolio file access controls
                   5400: 
1.749     raeburn  5401: sub get_access_controls {
1.745     raeburn  5402:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 5403:     my %access;
                   5404:     my $real_file = $file;
                   5405:     $file =~ s/\.meta$//;
1.745     raeburn  5406:     if (defined($file)) {
1.749     raeburn  5407:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   5408:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 5409:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  5410:             }
                   5411:         }
1.745     raeburn  5412:     } else {
1.749     raeburn  5413:         foreach my $key (keys(%{$current_permissions})) {
                   5414:             if ($key =~ /\0accesscontrol$/) {
                   5415:                 if (defined($group)) {
                   5416:                     if ($key !~ m-^\Q$group\E/-) {
                   5417:                         next;
                   5418:                     }
                   5419:                 }
                   5420:                 my ($fullpath) = split(/\0/,$key);
                   5421:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   5422:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   5423:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   5424:                     }
                   5425:                 }
                   5426:             }
                   5427:         }
                   5428:     }
                   5429:     return %access;
                   5430: }
                   5431: 
                   5432: sub modify_access_controls {
                   5433:     my ($file_name,$changes,$domain,$user)=@_;
                   5434:     my ($outcome,$deloutcome);
                   5435:     my %store_permissions;
                   5436:     my %new_values;
                   5437:     my %new_control;
                   5438:     my %translation;
                   5439:     my @deletions = ();
                   5440:     my $now = time;
                   5441:     if (exists($$changes{'activate'})) {
                   5442:         if (ref($$changes{'activate'}) eq 'HASH') {
                   5443:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   5444:             my $numnew = scalar(@newitems);
                   5445:             for (my $i=0; $i<$numnew; $i++) {
                   5446:                 my $newkey = $newitems[$i];
                   5447:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  5448:                 if ($newkey =~ /^\d+:/) { 
                   5449:                     $newkey =~ s/^(\d+)/$newid/;
                   5450:                     $translation{$1} = $newid;
                   5451:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   5452:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   5453:                     $translation{$1} = $newid;
                   5454:                 }
1.749     raeburn  5455:                 $new_values{$file_name."\0".$newkey} = 
                   5456:                                           $$changes{'activate'}{$newitems[$i]};
                   5457:                 $new_control{$newkey} = $now;
                   5458:             }
                   5459:         }
                   5460:     }
                   5461:     my %todelete;
                   5462:     my %changed_items;
                   5463:     foreach my $action ('delete','update') {
                   5464:         if (exists($$changes{$action})) {
                   5465:             if (ref($$changes{$action}) eq 'HASH') {
                   5466:                 foreach my $key (keys(%{$$changes{$action}})) {
                   5467:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   5468:                     if ($action eq 'delete') { 
                   5469:                         $todelete{$itemnum} = 1;
                   5470:                     } else {
                   5471:                         $changed_items{$itemnum} = $key;
                   5472:                     }
                   5473:                 }
1.745     raeburn  5474:             }
                   5475:         }
1.749     raeburn  5476:     }
                   5477:     # get lock on access controls for file.
                   5478:     my $lockhash = {
                   5479:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   5480:                                                        ':'.$env{'user.domain'},
                   5481:                    }; 
                   5482:     my $tries = 0;
                   5483:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   5484:    
                   5485:     while (($gotlock ne 'ok') && $tries <3) {
                   5486:         $tries ++;
                   5487:         sleep 1;
                   5488:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   5489:     }
                   5490:     if ($gotlock eq 'ok') {
                   5491:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   5492:         my ($tmp)=keys(%curr_permissions);
                   5493:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   5494:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   5495:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   5496:             if (ref($curr_controls) eq 'HASH') {
                   5497:                 foreach my $control_item (keys(%{$curr_controls})) {
                   5498:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   5499:                     if (defined($todelete{$itemnum})) {
                   5500:                         push(@deletions,$file_name."\0".$control_item);
                   5501:                     } else {
                   5502:                         if (defined($changed_items{$itemnum})) {
                   5503:                             $new_control{$changed_items{$itemnum}} = $now;
                   5504:                             push(@deletions,$file_name."\0".$control_item);
                   5505:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   5506:                         } else {
                   5507:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   5508:                         }
                   5509:                     }
1.745     raeburn  5510:                 }
                   5511:             }
                   5512:         }
1.749     raeburn  5513:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   5514:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   5515:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   5516:         #  remove lock
                   5517:         my @del_lock = ($file_name."\0".'locked_access_records');
                   5518:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  5519:         my ($file,$group);
                   5520:         if (&is_course($domain,$user)) {
                   5521:             ($group,$file) = split(/\//,$file_name,2);
                   5522:         } else {
                   5523:             $file = $file_name;
                   5524:         }
                   5525:         my $sqlresult =
                   5526:             &update_portfolio_table($user,$domain,$file,'portfolio_access',
                   5527:                                     $group);
1.749     raeburn  5528:     } else {
                   5529:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  5530:     }
1.749     raeburn  5531:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  5532: }
                   5533: 
1.827     raeburn  5534: sub make_public_indefinitely {
                   5535:     my ($requrl) = @_;
                   5536:     my $now = time;
                   5537:     my $action = 'activate';
                   5538:     my $aclnum = 0;
                   5539:     if (&is_portfolio_url($requrl)) {
                   5540:         my (undef,$udom,$unum,$file_name,$group) =
                   5541:             &parse_portfolio_url($requrl);
                   5542:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   5543:         my %access_controls = &get_access_controls($current_perms,
                   5544:                                                    $group,$file_name);
                   5545:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   5546:             my ($num,$scope,$end,$start) = 
                   5547:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   5548:             if ($scope eq 'public') {
                   5549:                 if ($start <= $now && $end == 0) {
                   5550:                     $action = 'none';
                   5551:                 } else {
                   5552:                     $action = 'update';
                   5553:                     $aclnum = $num;
                   5554:                 }
                   5555:                 last;
                   5556:             }
                   5557:         }
                   5558:         if ($action eq 'none') {
                   5559:              return 'ok';
                   5560:         } else {
                   5561:             my %changes;
                   5562:             my $newend = 0;
                   5563:             my $newstart = $now;
                   5564:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   5565:             $changes{$action}{$newkey} = {
                   5566:                 type => 'public',
                   5567:                 time => {
                   5568:                     start => $newstart,
                   5569:                     end   => $newend,
                   5570:                 },
                   5571:             };
                   5572:             my ($outcome,$deloutcome,$new_values,$translation) =
                   5573:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   5574:             return $outcome;
                   5575:         }
                   5576:     } else {
                   5577:         return 'invalid';
                   5578:     }
                   5579: }
                   5580: 
1.745     raeburn  5581: #------------------------------------------------------Get Marked as Read Only
                   5582: 
                   5583: sub get_marked_as_readonly {
                   5584:     my ($domain,$user,$what,$group) = @_;
                   5585:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 5586:     my @readonly_files;
1.629     banghart 5587:     my $cmp1=$what;
                   5588:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  5589:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   5590:         if (defined($group)) {
                   5591:             if ($file_name !~ m-^\Q$group\E/-) {
                   5592:                 next;
                   5593:             }
                   5594:         }
1.561     banghart 5595:         if (ref($value) eq "ARRAY"){
                   5596:             foreach my $stored_what (@{$value}) {
1.629     banghart 5597:                 my $cmp2=$stored_what;
1.759     albertel 5598:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  5599:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  5600:                 }
1.629     banghart 5601:                 if ($cmp1 eq $cmp2) {
1.561     banghart 5602:                     push(@readonly_files, $file_name);
1.745     raeburn  5603:                     last;
1.563     banghart 5604:                 } elsif (!defined($what)) {
                   5605:                     push(@readonly_files, $file_name);
1.745     raeburn  5606:                     last;
1.561     banghart 5607:                 }
                   5608:             }
1.745     raeburn  5609:         }
1.561     banghart 5610:     }
                   5611:     return @readonly_files;
                   5612: }
1.577     banghart 5613: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 5614: 
1.577     banghart 5615: sub get_marked_as_readonly_hash {
1.745     raeburn  5616:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 5617:     my %readonly_files;
1.745     raeburn  5618:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   5619:         if (defined($group)) {
                   5620:             if ($file_name !~ m-^\Q$group\E/-) {
                   5621:                 next;
                   5622:             }
                   5623:         }
1.577     banghart 5624:         if (ref($value) eq "ARRAY"){
                   5625:             foreach my $stored_what (@{$value}) {
1.745     raeburn  5626:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 5627:                     foreach my $lock_descriptor(@{$stored_what}) {
                   5628:                         if ($lock_descriptor eq 'graded') {
                   5629:                             $readonly_files{$file_name} = 'graded';
                   5630:                         } elsif ($lock_descriptor eq 'handback') {
                   5631:                             $readonly_files{$file_name} = 'handback';
                   5632:                         } else {
                   5633:                             if (!exists($readonly_files{$file_name})) {
                   5634:                                 $readonly_files{$file_name} = 'locked';
                   5635:                             }
                   5636:                         }
1.745     raeburn  5637:                     }
1.750     banghart 5638:                 } 
1.577     banghart 5639:             }
                   5640:         } 
                   5641:     }
                   5642:     return %readonly_files;
                   5643: }
1.559     banghart 5644: # ------------------------------------------------------------ Unmark as Read Only
                   5645: 
                   5646: sub unmark_as_readonly {
1.629     banghart 5647:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   5648:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  5649:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 5650:     $file_name = &declutter_portfile($file_name);
1.634     albertel 5651:     my $symb_crs = $what;
                   5652:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  5653:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 5654:     my ($tmp)=keys(%current_permissions);
                   5655:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  5656:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 5657:     foreach my $file (@readonly_files) {
1.759     albertel 5658: 	my $clean_file = &declutter_portfile($file);
                   5659: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 5660: 	my $current_locks = $current_permissions{$file};
1.563     banghart 5661:         my @new_locks;
                   5662:         my @del_keys;
                   5663:         if (ref($current_locks) eq "ARRAY"){
                   5664:             foreach my $locker (@{$current_locks}) {
1.632     albertel 5665:                 my $compare=$locker;
1.749     raeburn  5666:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  5667:                     $compare=join('',@{$locker});
1.746     raeburn  5668:                     if ($compare ne $symb_crs) {
                   5669:                         push(@new_locks, $locker);
                   5670:                     }
1.563     banghart 5671:                 }
                   5672:             }
1.650     albertel 5673:             if (scalar(@new_locks) > 0) {
1.563     banghart 5674:                 $current_permissions{$file} = \@new_locks;
                   5675:             } else {
                   5676:                 push(@del_keys, $file);
1.613     albertel 5677:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 5678:                 delete($current_permissions{$file});
1.563     banghart 5679:             }
                   5680:         }
1.561     banghart 5681:     }
1.613     albertel 5682:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 5683:     return;
                   5684: }
1.512     banghart 5685: 
1.17      www      5686: # ------------------------------------------------------------ Directory lister
                   5687: 
                   5688: sub dirlist {
1.253     stredwic 5689:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
                   5690: 
1.18      www      5691:     $uri=~s/^\///;
                   5692:     $uri=~s/\/$//;
1.253     stredwic 5693:     my ($udom, $uname);
                   5694:     (undef,$udom,$uname)=split(/\//,$uri);
                   5695:     if(defined($userdomain)) {
                   5696:         $udom = $userdomain;
                   5697:     }
                   5698:     if(defined($username)) {
                   5699:         $uname = $username;
                   5700:     }
                   5701: 
                   5702:     my $dirRoot = $perlvar{'lonDocRoot'};
                   5703:     if(defined($alternateDirectoryRoot)) {
                   5704:         $dirRoot = $alternateDirectoryRoot;
                   5705:         $dirRoot =~ s/\/$//;
1.751     banghart 5706:     }
1.253     stredwic 5707: 
                   5708:     if($udom) {
                   5709:         if($uname) {
1.800     albertel 5710:             my $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
                   5711: 				 &homeserver($uname,$udom));
1.605     matthew  5712:             my @listing_results;
                   5713:             if ($listing eq 'unknown_cmd') {
1.800     albertel 5714:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
                   5715: 				  &homeserver($uname,$udom));
1.605     matthew  5716:                 @listing_results = split(/:/,$listing);
                   5717:             } else {
                   5718:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   5719:             }
                   5720:             return @listing_results;
1.253     stredwic 5721:         } elsif(!defined($alternateDirectoryRoot)) {
1.800     albertel 5722:             my %allusers;
1.841     albertel 5723: 	    my %servers = &get_servers($udom,'library');
                   5724: 	    foreach my $tryserver (keys(%servers)) {
                   5725: 		my $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   5726: 				     $udom, $tryserver);
                   5727: 		my @listing_results;
                   5728: 		if ($listing eq 'unknown_cmd') {
                   5729: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   5730: 				      $udom, $tryserver);
                   5731: 		    @listing_results = split(/:/,$listing);
                   5732: 		} else {
                   5733: 		    @listing_results =
                   5734: 			map { &unescape($_); } split(/:/,$listing);
                   5735: 		}
                   5736: 		if ($listing_results[0] ne 'no_such_dir' && 
                   5737: 		    $listing_results[0] ne 'empty'       &&
                   5738: 		    $listing_results[0] ne 'con_lost') {
                   5739: 		    foreach my $line (@listing_results) {
                   5740: 			my ($entry) = split(/&/,$line,2);
                   5741: 			$allusers{$entry} = 1;
                   5742: 		    }
                   5743: 		}
1.253     stredwic 5744:             }
                   5745:             my $alluserstr='';
1.800     albertel 5746:             foreach my $user (sort(keys(%allusers))) {
                   5747:                 $alluserstr.=$user.'&user:';
1.253     stredwic 5748:             }
                   5749:             $alluserstr=~s/:$//;
                   5750:             return split(/:/,$alluserstr);
                   5751:         } else {
1.800     albertel 5752:             return ('missing user name');
1.253     stredwic 5753:         }
                   5754:     } elsif(!defined($alternateDirectoryRoot)) {
1.841     albertel 5755:         my @all_domains = sort(&all_domains());
                   5756:          foreach my $domain (@all_domains) {
                   5757:              $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
                   5758:          }
                   5759:          return @all_domains;
                   5760:      } else {
1.800     albertel 5761:         return ('missing domain');
1.275     stredwic 5762:     }
                   5763: }
                   5764: 
                   5765: # --------------------------------------------- GetFileTimestamp
                   5766: # This function utilizes dirlist and returns the date stamp for
                   5767: # when it was last modified.  It will also return an error of -1
                   5768: # if an error occurs
                   5769: 
1.410     matthew  5770: ##
                   5771: ## FIXME: This subroutine assumes its caller knows something about the
                   5772: ## directory structure of the home server for the student ($root).
                   5773: ## Not a good assumption to make.  Since this is for looking up files
                   5774: ## in user directories, the full path should be constructed by lond, not
                   5775: ## whatever machine we request data from.
                   5776: ##
1.275     stredwic 5777: sub GetFileTimestamp {
                   5778:     my ($studentDomain,$studentName,$filename,$root)=@_;
1.807     albertel 5779:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   5780:     $studentName   = &LONCAPA::clean_username($studentName);
1.275     stredwic 5781:     my $subdir=$studentName.'__';
                   5782:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   5783:     my $proname="$studentDomain/$subdir/$studentName";
                   5784:     $proname .= '/'.$filename;
1.375     matthew  5785:     my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain, 
                   5786:                                               $studentName, $root);
1.275     stredwic 5787:     my @stats = split('&', $fileStat);
                   5788:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  5789:         # @stats contains first the filename, then the stat output
                   5790:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 5791:     } else {
                   5792:         return -1;
1.253     stredwic 5793:     }
1.26      www      5794: }
                   5795: 
1.712     albertel 5796: sub stat_file {
                   5797:     my ($uri) = @_;
1.787     albertel 5798:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 5799: 
1.712     albertel 5800:     my ($udom,$uname,$file,$dir);
                   5801:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   5802: 	($udom,$uname,$file) =
1.811     albertel 5803: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 5804: 	$file = 'userfiles/'.$file;
1.740     www      5805: 	$dir = &propath($udom,$uname);
1.712     albertel 5806:     }
                   5807:     if ($uri =~ m-^/res/-) {
                   5808: 	($udom,$uname) = 
1.807     albertel 5809: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 5810: 	$file = $uri;
                   5811:     }
                   5812: 
                   5813:     if (!$udom || !$uname || !$file) {
                   5814: 	# unable to handle the uri
                   5815: 	return ();
                   5816:     }
                   5817: 
                   5818:     my ($result) = &dirlist($file,$udom,$uname,$dir);
                   5819:     my @stats = split('&', $result);
1.721     banghart 5820:     
1.712     albertel 5821:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   5822: 	shift(@stats); #filename is first
                   5823: 	return @stats;
                   5824:     }
                   5825:     return ();
                   5826: }
                   5827: 
1.26      www      5828: # -------------------------------------------------------- Value of a Condition
                   5829: 
1.713     albertel 5830: # gets the value of a specific preevaluated condition
                   5831: #    stored in the string  $env{user.state.<cid>}
                   5832: # or looks up a condition reference in the bighash and if if hasn't
                   5833: # already been evaluated recurses into docondval to get the value of
                   5834: # the condition, then memoizing it to 
                   5835: #   $env{user.state.<cid>.<condition>}
1.40      www      5836: sub directcondval {
                   5837:     my $number=shift;
1.620     albertel 5838:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 5839: 	&Apache::lonuserstate::evalstate();
                   5840:     }
1.713     albertel 5841:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   5842: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   5843:     } elsif ($number =~ /^_/) {
                   5844: 	my $sub_condition;
                   5845: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   5846: 		&GDBM_READER(),0640)) {
                   5847: 	    $sub_condition=$bighash{'conditions'.$number};
                   5848: 	    untie(%bighash);
                   5849: 	}
                   5850: 	my $value = &docondval($sub_condition);
                   5851: 	&appenv('user.state.'.$env{'request.course.id'}.".$number" => $value);
                   5852: 	return $value;
                   5853:     }
1.620     albertel 5854:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   5855:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      5856:     } else {
                   5857:        return 2;
                   5858:     }
                   5859: }
                   5860: 
1.713     albertel 5861: # get the collection of conditions for this resource
1.26      www      5862: sub condval {
                   5863:     my $condidx=shift;
1.54      www      5864:     my $allpathcond='';
1.713     albertel 5865:     foreach my $cond (split(/\|/,$condidx)) {
                   5866: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   5867: 	    $allpathcond.=
                   5868: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   5869: 	}
1.191     harris41 5870:     }
1.54      www      5871:     $allpathcond=~s/\|$//;
1.713     albertel 5872:     return &docondval($allpathcond);
                   5873: }
                   5874: 
                   5875: #evaluates an expression of conditions
                   5876: sub docondval {
                   5877:     my ($allpathcond) = @_;
                   5878:     my $result=0;
                   5879:     if ($env{'request.course.id'}
                   5880: 	&& defined($allpathcond)) {
                   5881: 	my $operand='|';
                   5882: 	my @stack;
                   5883: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   5884: 	    if ($chunk eq '(') {
                   5885: 		push @stack,($operand,$result);
                   5886: 	    } elsif ($chunk eq ')') {
                   5887: 		my $before=pop @stack;
                   5888: 		if (pop @stack eq '&') {
                   5889: 		    $result=$result>$before?$before:$result;
                   5890: 		} else {
                   5891: 		    $result=$result>$before?$result:$before;
                   5892: 		}
                   5893: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   5894: 		$operand=$chunk;
                   5895: 	    } else {
                   5896: 		my $new=directcondval($chunk);
                   5897: 		if ($operand eq '&') {
                   5898: 		    $result=$result>$new?$new:$result;
                   5899: 		} else {
                   5900: 		    $result=$result>$new?$result:$new;
                   5901: 		}
                   5902: 	    }
                   5903: 	}
1.26      www      5904:     }
                   5905:     return $result;
1.421     albertel 5906: }
                   5907: 
                   5908: # ---------------------------------------------------- Devalidate courseresdata
                   5909: 
                   5910: sub devalidatecourseresdata {
                   5911:     my ($coursenum,$coursedomain)=@_;
                   5912:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 5913:     &devalidate_cache_new('courseres',$hashid);
1.28      www      5914: }
                   5915: 
1.763     www      5916: 
1.200     www      5917: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     5918: #
                   5919: #  Parameters:
                   5920: #      $coursenum    - Number of the course.
                   5921: #      $coursedomain - Domain at which the course was created.
                   5922: #  Returns:
                   5923: #     A hash of the course parameters along (I think) with timestamps
                   5924: #     and version info.
1.877     foxr     5925: 
1.624     albertel 5926: sub get_courseresdata {
                   5927:     my ($coursenum,$coursedomain)=@_;
1.200     www      5928:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   5929:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 5930:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 5931:     my %dumpreply;
1.417     albertel 5932:     unless (defined($cached)) {
1.624     albertel 5933: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 5934: 	$result=\%dumpreply;
1.251     albertel 5935: 	my ($tmp) = keys(%dumpreply);
                   5936: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 5937: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 5938: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   5939: 	    return $tmp;
1.416     albertel 5940: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 5941: 	    $result=undef;
1.599     albertel 5942: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 5943: 	}
                   5944:     }
1.624     albertel 5945:     return $result;
                   5946: }
                   5947: 
1.633     albertel 5948: sub devalidateuserresdata {
                   5949:     my ($uname,$udom)=@_;
                   5950:     my $hashid="$udom:$uname";
                   5951:     &devalidate_cache_new('userres',$hashid);
                   5952: }
                   5953: 
1.624     albertel 5954: sub get_userresdata {
                   5955:     my ($uname,$udom)=@_;
                   5956:     #most student don\'t have any data set, check if there is some data
                   5957:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   5958: 
                   5959:     my $hashid="$udom:$uname";
                   5960:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   5961:     if (!defined($cached)) {
                   5962: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   5963: 	$result=\%resourcedata;
                   5964: 	&do_cache_new('userres',$hashid,$result,600);
                   5965:     }
                   5966:     my ($tmp)=keys(%$result);
                   5967:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   5968: 	return $result;
                   5969:     }
                   5970:     #error 2 occurs when the .db doesn't exist
                   5971:     if ($tmp!~/error: 2 /) {
1.672     albertel 5972: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 5973: 		 " Trying to get resource data for ".
                   5974: 		 $uname." at ".$udom.": ".
                   5975: 		 $tmp."</font>");
                   5976:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 5977: 	#&EXT_cache_set($udom,$uname);
                   5978: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 5979: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 5980:     }
                   5981:     return $tmp;
                   5982: }
1.879     foxr     5983: #----------------------------------------------- resdata - return resource data
                   5984: #  Purpose:
                   5985: #    Return resource data for either users or for a course.
                   5986: #  Parameters:
                   5987: #     $name      - Course/user name.
                   5988: #     $domain    - Name of the domain the user/course is registered on.
                   5989: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   5990: #     @which     - Array of names of resources desired.
                   5991: #  Returns:
                   5992: #     The value of the first reasource in @which that is found in the
                   5993: #     resource hash.
                   5994: #  Exceptional Conditions:
                   5995: #     If the $type passed in is not valid (not the string 'course' or 
                   5996: #     'user', an undefined  reference is returned.
                   5997: #     If none of the resources are found, an undef is returned
1.624     albertel 5998: sub resdata {
                   5999:     my ($name,$domain,$type,@which)=@_;
                   6000:     my $result;
                   6001:     if ($type eq 'course') {
                   6002: 	$result=&get_courseresdata($name,$domain);
                   6003:     } elsif ($type eq 'user') {
                   6004: 	$result=&get_userresdata($name,$domain);
                   6005:     }
                   6006:     if (!ref($result)) { return $result; }    
1.251     albertel 6007:     foreach my $item (@which) {
1.417     albertel 6008: 	if (defined($result->{$item})) {
                   6009: 	    return $result->{$item};
1.251     albertel 6010: 	}
1.250     albertel 6011:     }
1.291     albertel 6012:     return undef;
1.200     www      6013: }
                   6014: 
1.379     matthew  6015: #
                   6016: # EXT resource caching routines
                   6017: #
                   6018: 
                   6019: sub clear_EXT_cache_status {
1.383     albertel 6020:     &delenv('cache.EXT.');
1.379     matthew  6021: }
                   6022: 
                   6023: sub EXT_cache_status {
                   6024:     my ($target_domain,$target_user) = @_;
1.383     albertel 6025:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 6026:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  6027:         # We know already the user has no data
                   6028:         return 1;
                   6029:     } else {
                   6030:         return 0;
                   6031:     }
                   6032: }
                   6033: 
                   6034: sub EXT_cache_set {
                   6035:     my ($target_domain,$target_user) = @_;
1.383     albertel 6036:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.633     albertel 6037:     #&appenv($cachename => time);
1.379     matthew  6038: }
                   6039: 
1.28      www      6040: # --------------------------------------------------------- Value of a Variable
1.58      www      6041: sub EXT {
1.715     albertel 6042: 
1.395     albertel 6043:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      6044:     unless ($varname) { return ''; }
1.218     albertel 6045:     #get real user name/domain, courseid and symb
                   6046:     my $courseid;
1.359     albertel 6047:     my $publicuser;
1.427     www      6048:     if ($symbparm) {
                   6049: 	$symbparm=&get_symb_from_alias($symbparm);
                   6050:     }
1.218     albertel 6051:     if (!($uname && $udom)) {
1.790     albertel 6052:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 6053:       if (!$symbparm) {	$symbparm=$cursymb; }
                   6054:     } else {
1.620     albertel 6055: 	$courseid=$env{'request.course.id'};
1.218     albertel 6056:     }
1.48      www      6057:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   6058:     my $rest;
1.320     albertel 6059:     if (defined($therest[0])) {
1.48      www      6060:        $rest=join('.',@therest);
                   6061:     } else {
                   6062:        $rest='';
                   6063:     }
1.320     albertel 6064: 
1.57      www      6065:     my $qualifierrest=$qualifier;
                   6066:     if ($rest) { $qualifierrest.='.'.$rest; }
                   6067:     my $spacequalifierrest=$space;
                   6068:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      6069:     if ($realm eq 'user') {
1.48      www      6070: # --------------------------------------------------------------- user.resource
                   6071: 	if ($space eq 'resource') {
1.651     albertel 6072: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   6073: 		  || defined($Apache::lonhomework::parsing_a_task))
                   6074: 		 &&
1.744     albertel 6075: 		 ($symbparm eq &symbread()) ) {	
                   6076: 		# if we are in the middle of processing the resource the
                   6077: 		# get the value we are planning on committing
                   6078:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   6079:                     return $Apache::lonhomework::results{$qualifierrest};
                   6080:                 } else {
                   6081:                     return $Apache::lonhomework::history{$qualifierrest};
                   6082:                 }
1.335     albertel 6083: 	    } else {
1.359     albertel 6084: 		my %restored;
1.620     albertel 6085: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 6086: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   6087: 		} else {
                   6088: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   6089: 		}
1.335     albertel 6090: 		return $restored{$qualifierrest};
                   6091: 	    }
1.48      www      6092: # ----------------------------------------------------------------- user.access
                   6093:         } elsif ($space eq 'access') {
1.218     albertel 6094: 	    # FIXME - not supporting calls for a specific user
1.48      www      6095:             return &allowed($qualifier,$rest);
                   6096: # ------------------------------------------ user.preferences, user.environment
                   6097:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 6098: 	    if (($uname eq $env{'user.name'}) &&
                   6099: 		($udom eq $env{'user.domain'})) {
                   6100: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 6101: 	    } else {
1.359     albertel 6102: 		my %returnhash;
                   6103: 		if (!$publicuser) {
                   6104: 		    %returnhash=&userenvironment($udom,$uname,
                   6105: 						 $qualifierrest);
                   6106: 		}
1.218     albertel 6107: 		return $returnhash{$qualifierrest};
                   6108: 	    }
1.48      www      6109: # ----------------------------------------------------------------- user.course
                   6110:         } elsif ($space eq 'course') {
1.218     albertel 6111: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 6112:             return $env{join('.',('request.course',$qualifier))};
1.48      www      6113: # ------------------------------------------------------------------- user.role
                   6114:         } elsif ($space eq 'role') {
1.218     albertel 6115: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 6116:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      6117:             if ($qualifier eq 'value') {
                   6118: 		return $role;
                   6119:             } elsif ($qualifier eq 'extent') {
                   6120:                 return $where;
                   6121:             }
                   6122: # ----------------------------------------------------------------- user.domain
                   6123:         } elsif ($space eq 'domain') {
1.218     albertel 6124:             return $udom;
1.48      www      6125: # ------------------------------------------------------------------- user.name
                   6126:         } elsif ($space eq 'name') {
1.218     albertel 6127:             return $uname;
1.48      www      6128: # ---------------------------------------------------- Any other user namespace
1.29      www      6129:         } else {
1.359     albertel 6130: 	    my %reply;
                   6131: 	    if (!$publicuser) {
                   6132: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   6133: 	    }
                   6134: 	    return $reply{$qualifierrest};
1.48      www      6135:         }
1.236     www      6136:     } elsif ($realm eq 'query') {
                   6137: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 6138:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   6139: 						[$spacequalifierrest]);
1.620     albertel 6140: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      6141:    } elsif ($realm eq 'request') {
1.48      www      6142: # ------------------------------------------------------------- request.browser
                   6143:         if ($space eq 'browser') {
1.430     www      6144: 	    if ($qualifier eq 'textremote') {
1.676     albertel 6145: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      6146: 		    return 1;
                   6147: 		} else {
                   6148: 		    return 0;
                   6149: 		}
                   6150: 	    } else {
1.620     albertel 6151: 		return $env{'browser.'.$qualifier};
1.430     www      6152: 	    }
1.57      www      6153: # ------------------------------------------------------------ request.filename
                   6154:         } else {
1.620     albertel 6155:             return $env{'request.'.$spacequalifierrest};
1.29      www      6156:         }
1.28      www      6157:     } elsif ($realm eq 'course') {
1.48      www      6158: # ---------------------------------------------------------- course.description
1.620     albertel 6159:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      6160:     } elsif ($realm eq 'resource') {
1.165     www      6161: 
1.620     albertel 6162: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 6163: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   6164: 	}
1.693     albertel 6165: 
                   6166: 	if ($space eq 'title') {
                   6167: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   6168: 	    return &gettitle($symbparm);
                   6169: 	}
                   6170: 	
                   6171: 	if ($space eq 'map') {
                   6172: 	    my ($map) = &decode_symb($symbparm);
                   6173: 	    return &symbread($map);
                   6174: 	}
                   6175: 
                   6176: 	my ($section, $group, @groups);
1.593     albertel 6177: 	my ($courselevelm,$courselevel);
1.539     albertel 6178: 	if ($symbparm && defined($courseid) && 
1.620     albertel 6179: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      6180: 
1.218     albertel 6181: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      6182: 
1.60      www      6183: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 6184: 	    my $symbp=$symbparm;
1.735     albertel 6185: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 6186: 
                   6187: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   6188: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   6189: 
1.620     albertel 6190: 	    if (($env{'user.name'} eq $uname) &&
                   6191: 		($env{'user.domain'} eq $udom)) {
                   6192: 		$section=$env{'request.course.sec'};
1.733     raeburn  6193:                 @groups = split(/:/,$env{'request.course.groups'});  
                   6194:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 6195: 	    } else {
1.539     albertel 6196: 		if (! defined($usection)) {
1.551     albertel 6197: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 6198: 		} else {
                   6199: 		    $section = $usection;
                   6200: 		}
1.733     raeburn  6201:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 6202: 	    }
                   6203: 
                   6204: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   6205: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   6206: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   6207: 
1.593     albertel 6208: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 6209: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 6210: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      6211: 
1.60      www      6212: # ----------------------------------------------------------- first, check user
1.624     albertel 6213: 
                   6214: 	    my $userreply=&resdata($uname,$udom,'user',
                   6215: 				       ($courselevelr,$courselevelm,
                   6216: 					$courselevel));
                   6217: 	    if (defined($userreply)) { return $userreply; }
1.95      www      6218: 
1.594     albertel 6219: # ------------------------------------------------ second, check some of course
1.684     raeburn  6220:             my $coursereply;
1.691     raeburn  6221:             if (@groups > 0) {
                   6222:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   6223:                                        $mapparm,$spacequalifierrest);
1.684     raeburn  6224:                 if (defined($coursereply)) { return $coursereply; }
                   6225:             }
1.96      www      6226: 
1.684     raeburn  6227: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.624     albertel 6228: 				     $env{'course.'.$courseid.'.domain'},
                   6229: 				     'course',
                   6230: 				     ($seclevelr,$seclevelm,$seclevel,
                   6231: 				      $courselevelr));
1.287     albertel 6232: 	    if (defined($coursereply)) { return $coursereply; }
1.200     www      6233: 
1.60      www      6234: # ------------------------------------------------------ third, check map parms
1.218     albertel 6235: 	    my %parmhash=();
                   6236: 	    my $thisparm='';
                   6237: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 6238: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 6239: 		    &GDBM_READER(),0640)) {
1.218     albertel 6240: 		$thisparm=$parmhash{$symbparm};
                   6241: 		untie(%parmhash);
                   6242: 	    }
                   6243: 	    if ($thisparm) { return $thisparm; }
                   6244: 	}
1.594     albertel 6245: # ------------------------------------------ fourth, look in resource metadata
1.71      www      6246: 
1.218     albertel 6247: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 6248: 	my $filename;
                   6249: 	if (!$symbparm) { $symbparm=&symbread(); }
                   6250: 	if ($symbparm) {
1.409     www      6251: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 6252: 	} else {
1.620     albertel 6253: 	    $filename=$env{'request.filename'};
1.282     albertel 6254: 	}
                   6255: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.288     albertel 6256: 	if (defined($metadata)) { return $metadata; }
1.282     albertel 6257: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.288     albertel 6258: 	if (defined($metadata)) { return $metadata; }
1.142     www      6259: 
1.594     albertel 6260: # ---------------------------------------------- fourth, look in rest pf course
1.593     albertel 6261: 	if ($symbparm && defined($courseid) && 
1.620     albertel 6262: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 6263: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   6264: 				     $env{'course.'.$courseid.'.domain'},
                   6265: 				     'course',
                   6266: 				     ($courselevelm,$courselevel));
1.593     albertel 6267: 	    if (defined($coursereply)) { return $coursereply; }
                   6268: 	}
1.145     www      6269: # ------------------------------------------------------------------ Cascade up
1.218     albertel 6270: 	unless ($space eq '0') {
1.336     albertel 6271: 	    my @parts=split(/_/,$space);
                   6272: 	    my $id=pop(@parts);
                   6273: 	    my $part=join('_',@parts);
                   6274: 	    if ($part eq '') { $part='0'; }
                   6275: 	    my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 6276: 				 $symbparm,$udom,$uname,$section,1);
1.337     albertel 6277: 	    if (defined($partgeneral)) { return $partgeneral; }
1.218     albertel 6278: 	}
1.395     albertel 6279: 	if ($recurse) { return undef; }
                   6280: 	my $pack_def=&packages_tab_default($filename,$varname);
                   6281: 	if (defined($pack_def)) { return $pack_def; }
1.71      www      6282: 
1.48      www      6283: # ---------------------------------------------------- Any other user namespace
                   6284:     } elsif ($realm eq 'environment') {
                   6285: # ----------------------------------------------------------------- environment
1.620     albertel 6286: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   6287: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 6288: 	} else {
1.770     albertel 6289: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   6290: 		return '';
                   6291: 	    }
1.219     albertel 6292: 	    my %returnhash=&userenvironment($udom,$uname,
                   6293: 					    $spacequalifierrest);
                   6294: 	    return $returnhash{$spacequalifierrest};
                   6295: 	}
1.28      www      6296:     } elsif ($realm eq 'system') {
1.48      www      6297: # ----------------------------------------------------------------- system.time
                   6298: 	if ($space eq 'time') {
                   6299: 	    return time;
                   6300:         }
1.696     albertel 6301:     } elsif ($realm eq 'server') {
                   6302: # ----------------------------------------------------------------- system.time
                   6303: 	if ($space eq 'name') {
                   6304: 	    return $ENV{'SERVER_NAME'};
                   6305:         }
1.28      www      6306:     }
1.48      www      6307:     return '';
1.61      www      6308: }
                   6309: 
1.691     raeburn  6310: sub check_group_parms {
                   6311:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   6312:     my @groupitems = ();
                   6313:     my $resultitem;
                   6314:     my @levels = ($symbparm,$mapparm,$what);
                   6315:     foreach my $group (@{$groups}) {
                   6316:         foreach my $level (@levels) {
                   6317:              my $item = $courseid.'.['.$group.'].'.$level;
                   6318:              push(@groupitems,$item);
                   6319:         }
                   6320:     }
                   6321:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   6322:                             $env{'course.'.$courseid.'.domain'},
                   6323:                                      'course',@groupitems);
                   6324:     return $coursereply;
                   6325: }
                   6326: 
                   6327: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  6328:     my ($courseid,@groups) = @_;
                   6329:     @groups = sort(@groups);
1.691     raeburn  6330:     return @groups;
                   6331: }
                   6332: 
1.395     albertel 6333: sub packages_tab_default {
                   6334:     my ($uri,$varname)=@_;
                   6335:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 6336: 
                   6337:     my (@extension,@specifics,$do_default);
                   6338:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 6339: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 6340: 	if ($pack_type eq 'default') {
                   6341: 	    $do_default=1;
                   6342: 	} elsif ($pack_type eq 'extension') {
                   6343: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 6344: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 6345: 	    # only look at packages defaults for packages that this id is
1.738     albertel 6346: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   6347: 	}
                   6348:     }
                   6349:     # first look for a package that matches the requested part id
                   6350:     foreach my $package (@specifics) {
                   6351: 	my (undef,$pack_type,$pack_part)=@{$package};
                   6352: 	next if ($pack_part ne $part);
                   6353: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6354: 	    return $packagetab{"$pack_type&$name&default"};
                   6355: 	}
                   6356:     }
                   6357:     # look for any possible matching non extension_ package
                   6358:     foreach my $package (@specifics) {
                   6359: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 6360: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6361: 	    return $packagetab{"$pack_type&$name&default"};
                   6362: 	}
1.585     albertel 6363: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 6364: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   6365: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 6366: 	}
                   6367:     }
1.738     albertel 6368:     # look for any posible extension_ match
                   6369:     foreach my $package (@extension) {
                   6370: 	my ($package,$pack_type)=@{$package};
                   6371: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6372: 	    return $packagetab{"$pack_type&$name&default"};
                   6373: 	}
                   6374: 	if (defined($packagetab{$package."&$name&default"})) {
                   6375: 	    return $packagetab{$package."&$name&default"};
                   6376: 	}
                   6377:     }
                   6378:     # look for a global default setting
                   6379:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   6380: 	return $packagetab{"default&$name&default"};
                   6381:     }
1.395     albertel 6382:     return undef;
                   6383: }
                   6384: 
1.334     albertel 6385: sub add_prefix_and_part {
                   6386:     my ($prefix,$part)=@_;
                   6387:     my $keyroot;
                   6388:     if (defined($prefix) && $prefix !~ /^__/) {
                   6389: 	# prefix that has a part already
                   6390: 	$keyroot=$prefix;
                   6391:     } elsif (defined($prefix)) {
                   6392: 	# prefix that is missing a part
                   6393: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   6394:     } else {
                   6395: 	# no prefix at all
                   6396: 	if (defined($part)) { $keyroot='_'.$part; }
                   6397:     }
                   6398:     return $keyroot;
                   6399: }
                   6400: 
1.71      www      6401: # ---------------------------------------------------------------- Get metadata
                   6402: 
1.599     albertel 6403: my %metaentry;
1.71      www      6404: sub metadata {
1.176     www      6405:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      6406:     $uri=&declutter($uri);
1.288     albertel 6407:     # if it is a non metadata possible uri return quickly
1.529     albertel 6408:     if (($uri eq '') || 
                   6409: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 6410: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.423     albertel 6411:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) ||
1.807     albertel 6412: 	($uri =~ m|home/$match_username/public_html/|)) {
1.468     albertel 6413: 	return undef;
1.288     albertel 6414:     }
1.73      www      6415:     my $filename=$uri;
                   6416:     $uri=~s/\.meta$//;
1.172     www      6417: #
                   6418: # Is the metadata already cached?
1.177     www      6419: # Look at timestamp of caching
1.172     www      6420: # Everything is cached by the main uri, libraries are never directly cached
                   6421: #
1.428     albertel 6422:     if (!defined($liburi)) {
1.599     albertel 6423: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 6424: 	if (defined($cached)) { return $result->{':'.$what}; }
                   6425:     }
                   6426:     {
1.172     www      6427: #
                   6428: # Is this a recursive call for a library?
                   6429: #
1.599     albertel 6430: #	if (! exists($metacache{$uri})) {
                   6431: #	    $metacache{$uri}={};
                   6432: #	}
1.171     www      6433:         if ($liburi) {
                   6434: 	    $liburi=&declutter($liburi);
                   6435:             $filename=$liburi;
1.401     bowersj2 6436:         } else {
1.599     albertel 6437: 	    &devalidate_cache_new('meta',$uri);
                   6438: 	    undef(%metaentry);
1.401     bowersj2 6439: 	}
1.140     www      6440:         my %metathesekeys=();
1.73      www      6441:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 6442: 	my $metastring;
1.768     albertel 6443: 	if ($uri !~ m -^(editupload)/-) {
1.543     albertel 6444: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 6445: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 6446: 	    $metastring=&getfile($file);
1.489     albertel 6447: 	}
1.208     albertel 6448:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      6449:         my $token;
1.140     www      6450:         undef %metathesekeys;
1.71      www      6451:         while ($token=$parser->get_token) {
1.339     albertel 6452: 	    if ($token->[0] eq 'S') {
                   6453: 		if (defined($token->[2]->{'package'})) {
1.172     www      6454: #
                   6455: # This is a package - get package info
                   6456: #
1.339     albertel 6457: 		    my $package=$token->[2]->{'package'};
                   6458: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   6459: 		    if (defined($token->[2]->{'id'})) { 
                   6460: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   6461: 		    }
1.599     albertel 6462: 		    if ($metaentry{':packages'}) {
                   6463: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 6464: 		    } else {
1.599     albertel 6465: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 6466: 		    }
1.736     albertel 6467: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 6468: 			my $part=$keyroot;
                   6469: 			$part=~s/^\_//;
1.736     albertel 6470: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   6471: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   6472: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 6473: 			    # ignore package.tab specified default values
                   6474:                             # here &package_tab_default() will fetch those
                   6475: 			    if ($subp eq 'default') { next; }
1.736     albertel 6476: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 6477: 			    my $unikey;
                   6478: 			    if ($pack =~ /_0$/) {
                   6479: 				$unikey='parameter_0_'.$name;
                   6480: 				$part=0;
                   6481: 			    } else {
                   6482: 				$unikey='parameter'.$keyroot.'_'.$name;
                   6483: 			    }
1.339     albertel 6484: 			    if ($subp eq 'display') {
                   6485: 				$value.=' [Part: '.$part.']';
                   6486: 			    }
1.599     albertel 6487: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 6488: 			    $metathesekeys{$unikey}=1;
1.599     albertel 6489: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   6490: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 6491: 			    }
1.599     albertel 6492: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   6493: 				$metaentry{':'.$unikey}=
                   6494: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 6495: 			    }
1.339     albertel 6496: 			}
                   6497: 		    }
                   6498: 		} else {
1.172     www      6499: #
                   6500: # This is not a package - some other kind of start tag
1.339     albertel 6501: #
                   6502: 		    my $entry=$token->[1];
                   6503: 		    my $unikey;
                   6504: 		    if ($entry eq 'import') {
                   6505: 			$unikey='';
                   6506: 		    } else {
                   6507: 			$unikey=$entry;
                   6508: 		    }
                   6509: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   6510: 
                   6511: 		    if (defined($token->[2]->{'id'})) { 
                   6512: 			$unikey.='_'.$token->[2]->{'id'}; 
                   6513: 		    }
1.175     www      6514: 
1.339     albertel 6515: 		    if ($entry eq 'import') {
1.175     www      6516: #
                   6517: # Importing a library here
1.339     albertel 6518: #
                   6519: 			if ($depthcount<20) {
                   6520: 			    my $location=$parser->get_text('/import');
                   6521: 			    my $dir=$filename;
                   6522: 			    $dir=~s|[^/]*$||;
                   6523: 			    $location=&filelocation($dir,$location);
1.736     albertel 6524: 			    my $metadata = 
                   6525: 				&metadata($uri,'keys', $location,$unikey,
                   6526: 					  $depthcount+1);
                   6527: 			    foreach my $meta (split(',',$metadata)) {
                   6528: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   6529: 				$metathesekeys{$meta}=1;
1.339     albertel 6530: 			    }
                   6531: 			}
                   6532: 		    } else { 
                   6533: 			
                   6534: 			if (defined($token->[2]->{'name'})) { 
                   6535: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   6536: 			}
                   6537: 			$metathesekeys{$unikey}=1;
1.736     albertel 6538: 			foreach my $param (@{$token->[3]}) {
                   6539: 			    $metaentry{':'.$unikey.'.'.$param} =
                   6540: 				$token->[2]->{$param};
1.339     albertel 6541: 			}
                   6542: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 6543: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 6544: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   6545: 		 # only ws inside the tag, and not in default, so use default
                   6546: 		 # as value
1.599     albertel 6547: 			    $metaentry{':'.$unikey}=$default;
1.339     albertel 6548: 			} else {
1.321     albertel 6549: 		  # either something interesting inside the tag or default
                   6550:                   # uninteresting
1.599     albertel 6551: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 6552: 			}
1.172     www      6553: # end of not-a-package not-a-library import
1.339     albertel 6554: 		    }
1.172     www      6555: # end of not-a-package start tag
1.339     albertel 6556: 		}
1.172     www      6557: # the next is the end of "start tag"
1.339     albertel 6558: 	    }
                   6559: 	}
1.483     albertel 6560: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 6561: 	$extension = lc($extension);
                   6562: 	if ($extension eq 'htm') { $extension='html'; }
                   6563: 
1.737     albertel 6564: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 6565: 	    #no specific packages #how's our extension
                   6566: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 6567: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 6568: 					 \%metathesekeys);
                   6569: 	}
1.883     albertel 6570: 
                   6571: 	if (!exists($metaentry{':packages'})
                   6572: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 6573: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 6574: 		#no specific packages well let's get default then
                   6575: 		if ($key!~/^default&/) { next; }
1.488     albertel 6576: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 6577: 					     \%metathesekeys);
                   6578: 	    }
                   6579: 	}
1.338     www      6580: # are there custom rights to evaluate
1.599     albertel 6581: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 6582: 
1.338     www      6583:     #
                   6584:     # Importing a rights file here
1.339     albertel 6585:     #
                   6586: 	    unless ($depthcount) {
1.599     albertel 6587: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 6588: 		my $dir=$filename;
                   6589: 		$dir=~s|[^/]*$||;
                   6590: 		$location=&filelocation($dir,$location);
1.736     albertel 6591: 		my $rights_metadata =
                   6592: 		    &metadata($uri,'keys',$location,'_rights',
                   6593: 			      $depthcount+1);
                   6594: 		foreach my $rights (split(',',$rights_metadata)) {
                   6595: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   6596: 		    $metathesekeys{$rights}=1;
1.339     albertel 6597: 		}
                   6598: 	    }
                   6599: 	}
1.737     albertel 6600: 	# uniqifiy package listing
                   6601: 	my %seen;
                   6602: 	my @uniq_packages =
                   6603: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   6604: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   6605: 
                   6606: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 6607: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   6608: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.699     albertel 6609: 	&do_cache_new('meta',$uri,\%metaentry,60*60);
1.177     www      6610: # this is the end of "was not already recently cached
1.71      www      6611:     }
1.599     albertel 6612:     return $metaentry{':'.$what};
1.261     albertel 6613: }
                   6614: 
1.488     albertel 6615: sub metadata_create_package_def {
1.483     albertel 6616:     my ($uri,$key,$package,$metathesekeys)=@_;
                   6617:     my ($pack,$name,$subp)=split(/\&/,$key);
                   6618:     if ($subp eq 'default') { next; }
                   6619:     
1.599     albertel 6620:     if (defined($metaentry{':packages'})) {
                   6621: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 6622:     } else {
1.599     albertel 6623: 	$metaentry{':packages'}=$package;
1.483     albertel 6624:     }
                   6625:     my $value=$packagetab{$key};
                   6626:     my $unikey;
                   6627:     $unikey='parameter_0_'.$name;
1.599     albertel 6628:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 6629:     $$metathesekeys{$unikey}=1;
1.599     albertel 6630:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   6631: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 6632:     }
1.599     albertel 6633:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   6634: 	$metaentry{':'.$unikey}=
                   6635: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 6636:     }
                   6637: }
                   6638: 
1.261     albertel 6639: sub metadata_generate_part0 {
                   6640:     my ($metadata,$metacache,$uri) = @_;
                   6641:     my %allnames;
1.737     albertel 6642:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 6643: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 6644: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   6645: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 6646: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 6647: 	    $allnames{$name}=$part;
                   6648: 	  }
                   6649: 	}
                   6650:     }
                   6651:     foreach my $name (keys(%allnames)) {
                   6652:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 6653:       my $key=":parameter_0_$name";
1.261     albertel 6654:       $$metacache{"$key.part"}='0';
                   6655:       $$metacache{"$key.name"}=$name;
1.428     albertel 6656:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 6657: 					   $allnames{$name}.'_'.$name.
                   6658: 					   '.type'};
1.428     albertel 6659:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 6660: 			     '.display'};
1.644     www      6661:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 6662:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 6663:       $$metacache{"$key.display"}=$olddis;
                   6664:     }
1.71      www      6665: }
                   6666: 
1.764     albertel 6667: # ------------------------------------------------------ Devalidate title cache
                   6668: 
                   6669: sub devalidate_title_cache {
                   6670:     my ($url)=@_;
                   6671:     if (!$env{'request.course.id'}) { return; }
                   6672:     my $symb=&symbread($url);
                   6673:     if (!$symb) { return; }
                   6674:     my $key=$env{'request.course.id'}."\0".$symb;
                   6675:     &devalidate_cache_new('title',$key);
                   6676: }
                   6677: 
1.301     www      6678: # ------------------------------------------------- Get the title of a resource
                   6679: 
                   6680: sub gettitle {
                   6681:     my $urlsymb=shift;
                   6682:     my $symb=&symbread($urlsymb);
1.534     albertel 6683:     if ($symb) {
1.620     albertel 6684: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 6685: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 6686: 	if (defined($cached)) { 
                   6687: 	    return $result;
                   6688: 	}
1.534     albertel 6689: 	my ($map,$resid,$url)=&decode_symb($symb);
                   6690: 	my $title='';
                   6691: 	my %bighash;
1.620     albertel 6692: 	if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.534     albertel 6693: 		&GDBM_READER(),0640)) {
                   6694: 	    my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   6695: 	    $title=$bighash{'title_'.$mapid.'.'.$resid};
                   6696: 	    untie %bighash;
                   6697: 	}
                   6698: 	$title=~s/\&colon\;/\:/gs;
                   6699: 	if ($title) {
1.599     albertel 6700: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 6701: 	}
                   6702: 	$urlsymb=$url;
                   6703:     }
                   6704:     my $title=&metadata($urlsymb,'title');
                   6705:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   6706:     return $title;
1.301     www      6707: }
1.613     albertel 6708: 
1.614     albertel 6709: sub get_slot {
                   6710:     my ($which,$cnum,$cdom)=@_;
                   6711:     if (!$cnum || !$cdom) {
1.790     albertel 6712: 	(undef,my $courseid)=&whichuser();
1.620     albertel 6713: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   6714: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 6715:     }
1.703     albertel 6716:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   6717:     my %slotinfo;
                   6718:     if (exists($remembered{$key})) {
                   6719: 	$slotinfo{$which} = $remembered{$key};
                   6720:     } else {
                   6721: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   6722: 	&Apache::lonhomework::showhash(%slotinfo);
                   6723: 	my ($tmp)=keys(%slotinfo);
                   6724: 	if ($tmp=~/^error:/) { return (); }
                   6725: 	$remembered{$key} = $slotinfo{$which};
                   6726:     }
1.616     albertel 6727:     if (ref($slotinfo{$which}) eq 'HASH') {
                   6728: 	return %{$slotinfo{$which}};
                   6729:     }
                   6730:     return $slotinfo{$which};
1.614     albertel 6731: }
1.31      www      6732: # ------------------------------------------------- Update symbolic store links
                   6733: 
                   6734: sub symblist {
                   6735:     my ($mapname,%newhash)=@_;
1.438     www      6736:     $mapname=&deversion(&declutter($mapname));
1.31      www      6737:     my %hash;
1.620     albertel 6738:     if (($env{'request.course.fn'}) && (%newhash)) {
                   6739:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 6740:                       &GDBM_WRCREAT(),0640)) {
1.711     albertel 6741: 	    foreach my $url (keys %newhash) {
                   6742: 		next if ($url eq 'last_known'
                   6743: 			 && $env{'form.no_update_last_known'});
                   6744: 		$hash{declutter($url)}=&encode_symb($mapname,
                   6745: 						    $newhash{$url}->[1],
                   6746: 						    $newhash{$url}->[0]);
1.191     harris41 6747:             }
1.31      www      6748:             if (untie(%hash)) {
                   6749: 		return 'ok';
                   6750:             }
                   6751:         }
                   6752:     }
                   6753:     return 'error';
1.212     www      6754: }
                   6755: 
                   6756: # --------------------------------------------------------------- Verify a symb
                   6757: 
                   6758: sub symbverify {
1.510     www      6759:     my ($symb,$thisurl)=@_;
                   6760:     my $thisfn=$thisurl;
1.439     www      6761:     $thisfn=&declutter($thisfn);
1.215     www      6762: # direct jump to resource in page or to a sequence - will construct own symbs
                   6763:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   6764: # check URL part
1.409     www      6765:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      6766: 
1.431     www      6767:     unless ($url eq $thisfn) { return 0; }
1.213     www      6768: 
1.216     www      6769:     $symb=&symbclean($symb);
1.510     www      6770:     $thisurl=&deversion($thisurl);
1.439     www      6771:     $thisfn=&deversion($thisfn);
1.213     www      6772: 
                   6773:     my %bighash;
                   6774:     my $okay=0;
1.431     www      6775: 
1.620     albertel 6776:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 6777:                             &GDBM_READER(),0640)) {
1.510     www      6778:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      6779:         unless ($ids) { 
1.510     www      6780:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      6781:         }
                   6782:         if ($ids) {
                   6783: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 6784: 	    foreach my $id (split(/\,/,$ids)) {
                   6785: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      6786:                if (
                   6787:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   6788:    eq $symb) { 
1.620     albertel 6789: 		   if (($env{'request.role.adv'}) ||
1.800     albertel 6790: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582     albertel 6791: 		       $okay=1; 
                   6792: 		   }
                   6793: 	       }
1.216     www      6794: 	   }
                   6795:         }
1.213     www      6796: 	untie(%bighash);
                   6797:     }
                   6798:     return $okay;
1.31      www      6799: }
                   6800: 
1.210     www      6801: # --------------------------------------------------------------- Clean-up symb
                   6802: 
                   6803: sub symbclean {
                   6804:     my $symb=shift;
1.568     albertel 6805:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      6806: # remove version from map
                   6807:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      6808: 
1.210     www      6809: # remove version from URL
                   6810:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      6811: 
1.507     www      6812: # remove wrapper
                   6813: 
1.510     www      6814:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 6815:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      6816:     return $symb;
1.409     www      6817: }
                   6818: 
                   6819: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 6820: 
                   6821: sub encode_symb {
                   6822:     my ($map,$resid,$url)=@_;
                   6823:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   6824: }
1.409     www      6825: 
                   6826: sub decode_symb {
1.568     albertel 6827:     my $symb=shift;
                   6828:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   6829:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      6830:     return (&fixversion($map),$resid,&fixversion($url));
                   6831: }
                   6832: 
                   6833: sub fixversion {
                   6834:     my $fn=shift;
1.609     banghart 6835:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      6836:     my %bighash;
                   6837:     my $uri=&clutter($fn);
1.620     albertel 6838:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      6839: # is this cached?
1.599     albertel 6840:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      6841:     if (defined($cached)) { return $result; }
                   6842: # unfortunately not cached, or expired
1.620     albertel 6843:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      6844: 	    &GDBM_READER(),0640)) {
                   6845:  	if ($bighash{'version_'.$uri}) {
                   6846:  	    my $version=$bighash{'version_'.$uri};
1.444     www      6847:  	    unless (($version eq 'mostrecent') || 
                   6848: 		    ($version==&getversion($uri))) {
1.440     www      6849:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   6850:  	    }
                   6851:  	}
                   6852:  	untie %bighash;
1.413     www      6853:     }
1.599     albertel 6854:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      6855: }
                   6856: 
                   6857: sub deversion {
                   6858:     my $url=shift;
                   6859:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   6860:     return $url;
1.210     www      6861: }
                   6862: 
1.31      www      6863: # ------------------------------------------------------ Return symb list entry
                   6864: 
                   6865: sub symbread {
1.249     www      6866:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 6867:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 6868:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      6869: # no filename provided? try from environment
1.44      www      6870:     unless ($thisfn) {
1.620     albertel 6871:         if ($env{'request.symb'}) {
                   6872: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 6873: 	}
1.620     albertel 6874: 	$thisfn=$env{'request.filename'};
1.44      www      6875:     }
1.569     albertel 6876:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      6877: # is that filename actually a symb? Verify, clean, and return
                   6878:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 6879: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 6880: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 6881: 	}
1.242     www      6882:     }
1.44      www      6883:     $thisfn=declutter($thisfn);
1.31      www      6884:     my %hash;
1.37      www      6885:     my %bighash;
                   6886:     my $syval='';
1.620     albertel 6887:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  6888:         my $targetfn = $thisfn;
1.609     banghart 6889:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  6890:             $targetfn = 'adm/wrapper/'.$thisfn;
                   6891:         }
1.687     albertel 6892: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   6893: 	    $targetfn=$1;
                   6894: 	}
1.620     albertel 6895:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 6896:                       &GDBM_READER(),0640)) {
1.481     raeburn  6897: 	    $syval=$hash{$targetfn};
1.37      www      6898:             untie(%hash);
                   6899:         }
                   6900: # ---------------------------------------------------------- There was an entry
                   6901:         if ($syval) {
1.601     albertel 6902: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 6903: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.601     albertel 6904: 		    #&appenv('request.ambiguous' => $thisfn);
1.620     albertel 6905: 		    #return $env{$cache_str}='';
1.601     albertel 6906: 		#}    
                   6907: 		#$syval.=$1;
                   6908: 	    #}
1.37      www      6909:         } else {
                   6910: # ------------------------------------------------------- Was not in symb table
1.620     albertel 6911:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 6912:                             &GDBM_READER(),0640)) {
1.37      www      6913: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      6914:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      6915:               unless ($ids) { 
                   6916:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      6917:               }
                   6918:               unless ($ids) {
                   6919: # alias?
                   6920: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      6921:               }
1.37      www      6922:               if ($ids) {
                   6923: # ------------------------------------------------------------------- Has ID(s)
                   6924:                  my @possibilities=split(/\,/,$ids);
1.39      www      6925:                  if ($#possibilities==0) {
                   6926: # ----------------------------------------------- There is only one possibility
1.37      www      6927: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 6928: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   6929: 						    $resid,$thisfn);
1.249     www      6930:                  } elsif (!$donotrecurse) {
1.39      www      6931: # ------------------------------------------ There is more than one possibility
                   6932:                      my $realpossible=0;
1.800     albertel 6933:                      foreach my $id (@possibilities) {
                   6934: 			 my $file=$bighash{'src_'.$id};
1.39      www      6935:                          if (&allowed('bre',$file)) {
1.800     albertel 6936:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      6937:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   6938: 				$realpossible++;
1.626     albertel 6939:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   6940: 						    $resid,$thisfn);
1.39      www      6941:                             }
                   6942: 			 }
1.191     harris41 6943:                      }
1.39      www      6944: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      6945:                  } else {
                   6946:                      $syval='';
1.37      www      6947:                  }
                   6948: 	      }
                   6949:               untie(%bighash)
1.481     raeburn  6950:            }
1.31      www      6951:         }
1.62      www      6952:         if ($syval) {
1.620     albertel 6953: 	    return $env{$cache_str}=$syval;
1.62      www      6954:         }
1.31      www      6955:     }
1.44      www      6956:     &appenv('request.ambiguous' => $thisfn);
1.620     albertel 6957:     return $env{$cache_str}='';
1.31      www      6958: }
                   6959: 
                   6960: # ---------------------------------------------------------- Return random seed
                   6961: 
1.32      www      6962: sub numval {
                   6963:     my $txt=shift;
                   6964:     $txt=~tr/A-J/0-9/;
                   6965:     $txt=~tr/a-j/0-9/;
                   6966:     $txt=~tr/K-T/0-9/;
                   6967:     $txt=~tr/k-t/0-9/;
                   6968:     $txt=~tr/U-Z/0-5/;
                   6969:     $txt=~tr/u-z/0-5/;
                   6970:     $txt=~s/\D//g;
1.564     albertel 6971:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      6972:     return int($txt);
1.368     albertel 6973: }
                   6974: 
1.484     albertel 6975: sub numval2 {
                   6976:     my $txt=shift;
                   6977:     $txt=~tr/A-J/0-9/;
                   6978:     $txt=~tr/a-j/0-9/;
                   6979:     $txt=~tr/K-T/0-9/;
                   6980:     $txt=~tr/k-t/0-9/;
                   6981:     $txt=~tr/U-Z/0-5/;
                   6982:     $txt=~tr/u-z/0-5/;
                   6983:     $txt=~s/\D//g;
                   6984:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   6985:     my $total;
                   6986:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 6987:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 6988:     return int($total);
                   6989: }
                   6990: 
1.575     albertel 6991: sub numval3 {
                   6992:     use integer;
                   6993:     my $txt=shift;
                   6994:     $txt=~tr/A-J/0-9/;
                   6995:     $txt=~tr/a-j/0-9/;
                   6996:     $txt=~tr/K-T/0-9/;
                   6997:     $txt=~tr/k-t/0-9/;
                   6998:     $txt=~tr/U-Z/0-5/;
                   6999:     $txt=~tr/u-z/0-5/;
                   7000:     $txt=~s/\D//g;
                   7001:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   7002:     my $total;
                   7003:     foreach my $val (@txts) { $total+=$val; }
                   7004:     if ($_64bit) { $total=(($total<<32)>>32); }
                   7005:     return $total;
                   7006: }
                   7007: 
1.675     albertel 7008: sub digest {
                   7009:     my ($data)=@_;
                   7010:     my $digest=&Digest::MD5::md5($data);
                   7011:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   7012:     my ($e,$f);
                   7013:     {
                   7014:         use integer;
                   7015:         $e=($a+$b);
                   7016:         $f=($c+$d);
                   7017:         if ($_64bit) {
                   7018:             $e=(($e<<32)>>32);
                   7019:             $f=(($f<<32)>>32);
                   7020:         }
                   7021:     }
                   7022:     if (wantarray) {
                   7023: 	return ($e,$f);
                   7024:     } else {
                   7025: 	my $g;
                   7026: 	{
                   7027: 	    use integer;
                   7028: 	    $g=($e+$f);
                   7029: 	    if ($_64bit) {
                   7030: 		$g=(($g<<32)>>32);
                   7031: 	    }
                   7032: 	}
                   7033: 	return $g;
                   7034:     }
                   7035: }
                   7036: 
1.368     albertel 7037: sub latest_rnd_algorithm_id {
1.675     albertel 7038:     return '64bit5';
1.366     albertel 7039: }
1.32      www      7040: 
1.503     albertel 7041: sub get_rand_alg {
                   7042:     my ($courseid)=@_;
1.790     albertel 7043:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 7044:     if ($courseid) {
1.620     albertel 7045: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 7046:     }
                   7047:     return &latest_rnd_algorithm_id();
                   7048: }
                   7049: 
1.562     albertel 7050: sub validCODE {
                   7051:     my ($CODE)=@_;
                   7052:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   7053:     return 0;
                   7054: }
                   7055: 
1.491     albertel 7056: sub getCODE {
1.620     albertel 7057:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 7058:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   7059: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   7060: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 7061: 	return $Apache::lonhomework::history{'resource.CODE'};
                   7062:     }
                   7063:     return undef;
                   7064: }
                   7065: 
1.31      www      7066: sub rndseed {
1.155     albertel 7067:     my ($symb,$courseid,$domain,$username)=@_;
1.790     albertel 7068:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.155     albertel 7069:     if (!$symb) {
1.366     albertel 7070: 	unless ($symb=$wsymb) { return time; }
                   7071:     }
                   7072:     if (!$courseid) { $courseid=$wcourseid; }
                   7073:     if (!$domain) { $domain=$wdomain; }
                   7074:     if (!$username) { $username=$wusername }
1.503     albertel 7075:     my $which=&get_rand_alg();
1.803     albertel 7076: 
1.491     albertel 7077:     if (defined(&getCODE())) {
1.675     albertel 7078: 	if ($which eq '64bit5') {
                   7079: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   7080: 	} elsif ($which eq '64bit4') {
1.575     albertel 7081: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   7082: 	} else {
                   7083: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   7084: 	}
1.675     albertel 7085:     } elsif ($which eq '64bit5') {
                   7086: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 7087:     } elsif ($which eq '64bit4') {
                   7088: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 7089:     } elsif ($which eq '64bit3') {
                   7090: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 7091:     } elsif ($which eq '64bit2') {
                   7092: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 7093:     } elsif ($which eq '64bit') {
                   7094: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   7095:     }
                   7096:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   7097: }
                   7098: 
                   7099: sub rndseed_32bit {
                   7100:     my ($symb,$courseid,$domain,$username)=@_;
                   7101:     {
                   7102: 	use integer;
                   7103: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   7104: 	my $symbseed=numval($symb) << 22;
                   7105: 	my $namechck=unpack("%32C*",$username) << 17;
                   7106: 	my $nameseed=numval($username) << 12;
                   7107: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   7108: 	my $courseseed=unpack("%32C*",$courseid);
                   7109: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 7110: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7111: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 7112: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 7113: 	return $num;
                   7114:     }
                   7115: }
                   7116: 
                   7117: sub rndseed_64bit {
                   7118:     my ($symb,$courseid,$domain,$username)=@_;
                   7119:     {
                   7120: 	use integer;
                   7121: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   7122: 	my $symbseed=numval($symb) << 10;
                   7123: 	my $namechck=unpack("%32S*",$username);
                   7124: 	
                   7125: 	my $nameseed=numval($username) << 21;
                   7126: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   7127: 	my $courseseed=unpack("%32S*",$courseid);
                   7128: 	
                   7129: 	my $num1=$symbchck+$symbseed+$namechck;
                   7130: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7131: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7132: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 7133: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 7134: 	return "$num1,$num2";
1.155     albertel 7135:     }
1.366     albertel 7136: }
                   7137: 
1.443     albertel 7138: sub rndseed_64bit2 {
                   7139:     my ($symb,$courseid,$domain,$username)=@_;
                   7140:     {
                   7141: 	use integer;
                   7142: 	# strings need to be an even # of cahracters long, it it is odd the
                   7143:         # last characters gets thrown away
                   7144: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   7145: 	my $symbseed=numval($symb) << 10;
                   7146: 	my $namechck=unpack("%32S*",$username.' ');
                   7147: 	
                   7148: 	my $nameseed=numval($username) << 21;
1.501     albertel 7149: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7150: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7151: 	
                   7152: 	my $num1=$symbchck+$symbseed+$namechck;
                   7153: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7154: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7155: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 7156: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 7157: 	return "$num1,$num2";
                   7158:     }
                   7159: }
                   7160: 
                   7161: sub rndseed_64bit3 {
                   7162:     my ($symb,$courseid,$domain,$username)=@_;
                   7163:     {
                   7164: 	use integer;
                   7165: 	# strings need to be an even # of cahracters long, it it is odd the
                   7166:         # last characters gets thrown away
                   7167: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   7168: 	my $symbseed=numval2($symb) << 10;
                   7169: 	my $namechck=unpack("%32S*",$username.' ');
                   7170: 	
                   7171: 	my $nameseed=numval2($username) << 21;
1.443     albertel 7172: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7173: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7174: 	
                   7175: 	my $num1=$symbchck+$symbseed+$namechck;
                   7176: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7177: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7178: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 7179: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   7180: 	
1.503     albertel 7181: 	return "$num1:$num2";
1.443     albertel 7182:     }
                   7183: }
                   7184: 
1.575     albertel 7185: sub rndseed_64bit4 {
                   7186:     my ($symb,$courseid,$domain,$username)=@_;
                   7187:     {
                   7188: 	use integer;
                   7189: 	# strings need to be an even # of cahracters long, it it is odd the
                   7190:         # last characters gets thrown away
                   7191: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   7192: 	my $symbseed=numval3($symb) << 10;
                   7193: 	my $namechck=unpack("%32S*",$username.' ');
                   7194: 	
                   7195: 	my $nameseed=numval3($username) << 21;
                   7196: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7197: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7198: 	
                   7199: 	my $num1=$symbchck+$symbseed+$namechck;
                   7200: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7201: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7202: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 7203: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   7204: 	
                   7205: 	return "$num1:$num2";
                   7206:     }
                   7207: }
                   7208: 
1.675     albertel 7209: sub rndseed_64bit5 {
                   7210:     my ($symb,$courseid,$domain,$username)=@_;
                   7211:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   7212:     return "$num1:$num2";
                   7213: }
                   7214: 
1.366     albertel 7215: sub rndseed_CODE_64bit {
                   7216:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 7217:     {
1.366     albertel 7218: 	use integer;
1.443     albertel 7219: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 7220: 	my $symbseed=numval2($symb);
1.491     albertel 7221: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   7222: 	my $CODEseed=numval(&getCODE());
1.443     albertel 7223: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 7224: 	my $num1=$symbseed+$CODEchck;
                   7225: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 7226: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   7227: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 7228: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   7229: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 7230: 	return "$num1:$num2";
1.366     albertel 7231:     }
                   7232: }
                   7233: 
1.575     albertel 7234: sub rndseed_CODE_64bit4 {
                   7235:     my ($symb,$courseid,$domain,$username)=@_;
                   7236:     {
                   7237: 	use integer;
                   7238: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   7239: 	my $symbseed=numval3($symb);
                   7240: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   7241: 	my $CODEseed=numval3(&getCODE());
                   7242: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7243: 	my $num1=$symbseed+$CODEchck;
                   7244: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 7245: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   7246: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 7247: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   7248: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   7249: 	return "$num1:$num2";
                   7250:     }
                   7251: }
                   7252: 
1.675     albertel 7253: sub rndseed_CODE_64bit5 {
                   7254:     my ($symb,$courseid,$domain,$username)=@_;
                   7255:     my $code = &getCODE();
                   7256:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   7257:     return "$num1:$num2";
                   7258: }
                   7259: 
1.366     albertel 7260: sub setup_random_from_rndseed {
                   7261:     my ($rndseed)=@_;
1.503     albertel 7262:     if ($rndseed =~/([,:])/) {
                   7263: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 7264: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   7265:     } else {
                   7266: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 7267:     }
1.36      albertel 7268: }
                   7269: 
1.474     albertel 7270: sub latest_receipt_algorithm_id {
1.835     albertel 7271:     return 'receipt3';
1.474     albertel 7272: }
                   7273: 
1.480     www      7274: sub recunique {
                   7275:     my $fucourseid=shift;
                   7276:     my $unique;
1.835     albertel 7277:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   7278: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 7279: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      7280:     } else {
                   7281: 	$unique=$perlvar{'lonReceipt'};
                   7282:     }
                   7283:     return unpack("%32C*",$unique);
                   7284: }
                   7285: 
                   7286: sub recprefix {
                   7287:     my $fucourseid=shift;
                   7288:     my $prefix;
1.835     albertel 7289:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   7290: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 7291: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      7292:     } else {
                   7293: 	$prefix=$perlvar{'lonHostID'};
                   7294:     }
                   7295:     return unpack("%32C*",$prefix);
                   7296: }
                   7297: 
1.76      www      7298: sub ireceipt {
1.474     albertel 7299:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 7300: 
                   7301:     my $return =&recprefix($fucourseid).'-';
                   7302: 
                   7303:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   7304: 	$env{'request.state'} eq 'construct') {
                   7305: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   7306: 	return $return;
                   7307:     }
                   7308: 
1.76      www      7309:     my $cuname=unpack("%32C*",$funame);
                   7310:     my $cudom=unpack("%32C*",$fudom);
                   7311:     my $cucourseid=unpack("%32C*",$fucourseid);
                   7312:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      7313:     my $cunique=&recunique($fucourseid);
1.474     albertel 7314:     my $cpart=unpack("%32S*",$part);
1.835     albertel 7315:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   7316: 
1.790     albertel 7317: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 7318: 			       
                   7319: 	$return.= ($cunique%$cuname+
                   7320: 		   $cunique%$cudom+
                   7321: 		   $cusymb%$cuname+
                   7322: 		   $cusymb%$cudom+
                   7323: 		   $cucourseid%$cuname+
                   7324: 		   $cucourseid%$cudom+
                   7325: 		   $cpart%$cuname+
                   7326: 		   $cpart%$cudom);
                   7327:     } else {
                   7328: 	$return.= ($cunique%$cuname+
                   7329: 		   $cunique%$cudom+
                   7330: 		   $cusymb%$cuname+
                   7331: 		   $cusymb%$cudom+
                   7332: 		   $cucourseid%$cuname+
                   7333: 		   $cucourseid%$cudom);
                   7334:     }
                   7335:     return $return;
1.76      www      7336: }
                   7337: 
                   7338: sub receipt {
1.474     albertel 7339:     my ($part)=@_;
1.790     albertel 7340:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 7341:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      7342: }
1.260     ng       7343: 
1.790     albertel 7344: sub whichuser {
                   7345:     my ($passedsymb)=@_;
                   7346:     my ($symb,$courseid,$domain,$name,$publicuser);
                   7347:     if (defined($env{'form.grade_symb'})) {
                   7348: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   7349: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   7350: 	if (!$allowed &&
                   7351: 	    exists($env{'request.course.sec'}) &&
                   7352: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   7353: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   7354: 			      '/'.$env{'request.course.sec'});
                   7355: 	}
                   7356: 	if ($allowed) {
                   7357: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   7358: 	    $courseid=$tmp_courseid;
                   7359: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   7360: 	    ($name)=&get_env_multiple('form.grade_username');
                   7361: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   7362: 	}
                   7363:     }
                   7364:     if (!$passedsymb) {
                   7365: 	$symb=&symbread();
                   7366:     } else {
                   7367: 	$symb=$passedsymb;
                   7368:     }
                   7369:     $courseid=$env{'request.course.id'};
                   7370:     $domain=$env{'user.domain'};
                   7371:     $name=$env{'user.name'};
                   7372:     if ($name eq 'public' && $domain eq 'public') {
                   7373: 	if (!defined($env{'form.username'})) {
                   7374: 	    $env{'form.username'}.=time.rand(10000000);
                   7375: 	}
                   7376: 	$name.=$env{'form.username'};
                   7377:     }
                   7378:     return ($symb,$courseid,$domain,$name,$publicuser);
                   7379: 
                   7380: }
                   7381: 
1.36      albertel 7382: # ------------------------------------------------------------ Serves up a file
1.472     albertel 7383: # returns either the contents of the file or 
                   7384: # -1 if the file doesn't exist
1.481     raeburn  7385: #
                   7386: # if the target is a file that was uploaded via DOCS, 
                   7387: # a check will be made to see if a current copy exists on the local server,
                   7388: # if it does this will be served, otherwise a copy will be retrieved from
                   7389: # the home server for the course and stored in /home/httpd/html/userfiles on
                   7390: # the local server.   
1.472     albertel 7391: 
1.36      albertel 7392: sub getfile {
1.538     albertel 7393:     my ($file) = @_;
1.609     banghart 7394:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 7395:     &repcopy($file);
                   7396:     return &readfile($file);
                   7397: }
                   7398: 
                   7399: sub repcopy_userfile {
                   7400:     my ($file)=@_;
1.609     banghart 7401:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 7402:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 7403:     my ($cdom,$cnum,$filename) = 
1.811     albertel 7404: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 7405:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   7406:     if (-e "$file") {
1.828     www      7407: # we already have a local copy, check it out
1.538     albertel 7408: 	my @fileinfo = stat($file);
1.828     www      7409: 	my $rtncode;
                   7410: 	my $info;
1.538     albertel 7411: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 7412: 	if ($lwpresp ne 'ok') {
1.828     www      7413: # there is no such file anymore, even though we had a local copy
1.482     albertel 7414: 	    if ($rtncode eq '404') {
1.538     albertel 7415: 		unlink($file);
1.482     albertel 7416: 	    }
                   7417: 	    return -1;
                   7418: 	}
                   7419: 	if ($info < $fileinfo[9]) {
1.828     www      7420: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  7421: 	    return 'ok';
1.828     www      7422: 	} else {
                   7423: # the file is outdated, get rid of it
                   7424: 	    unlink($file);
1.482     albertel 7425: 	}
1.828     www      7426:     }
                   7427: # one way or the other, at this point, we don't have the file
                   7428: # construct the correct path for the file
                   7429:     my @parts = ($cdom,$cnum); 
                   7430:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   7431: 	push @parts, split(/\//,$1);
                   7432:     }
                   7433:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   7434:     foreach my $part (@parts) {
                   7435: 	$path .= '/'.$part;
                   7436: 	if (!-e $path) {
                   7437: 	    mkdir($path,0770);
1.482     albertel 7438: 	}
                   7439:     }
1.828     www      7440: # now the path exists for sure
                   7441: # get a user agent
                   7442:     my $ua=new LWP::UserAgent;
                   7443:     my $transferfile=$file.'.in.transfer';
                   7444: # FIXME: this should flock
                   7445:     if (-e $transferfile) { return 'ok'; }
                   7446:     my $request;
                   7447:     $uri=~s/^\///;
1.838     albertel 7448:     $request=new HTTP::Request('GET','http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri);
1.828     www      7449:     my $response=$ua->request($request,$transferfile);
                   7450: # did it work?
                   7451:     if ($response->is_error()) {
                   7452: 	unlink($transferfile);
                   7453: 	&logthis("Userfile repcopy failed for $uri");
                   7454: 	return -1;
                   7455:     }
                   7456: # worked, rename the transfer file
                   7457:     rename($transferfile,$file);
1.607     raeburn  7458:     return 'ok';
1.481     raeburn  7459: }
                   7460: 
1.517     albertel 7461: sub tokenwrapper {
                   7462:     my $uri=shift;
1.552     albertel 7463:     $uri=~s|^http\://([^/]+)||;
                   7464:     $uri=~s|^/||;
1.620     albertel 7465:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 7466:     my $token=$1;
1.552     albertel 7467:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   7468:     if ($udom && $uname && $file) {
                   7469: 	$file=~s|(\?\.*)*$||;
1.620     albertel 7470:         &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
1.838     albertel 7471:         return 'http://'.&hostname(&homeserver($uname,$udom)).'/'.$uri.
1.517     albertel 7472:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   7473:                                '&tokenissued='.$perlvar{'lonHostID'};
                   7474:     } else {
                   7475:         return '/adm/notfound.html';
                   7476:     }
                   7477: }
                   7478: 
1.828     www      7479: # call with reqtype HEAD: get last modification time
                   7480: # call with reqtype GET: get the file contents
                   7481: # Do not call this with reqtype GET for large files! It loads everything into memory
                   7482: #
1.481     raeburn  7483: sub getuploaded {
                   7484:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   7485:     $uri=~s/^\///;
1.838     albertel 7486:     $uri = 'http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri;
1.481     raeburn  7487:     my $ua=new LWP::UserAgent;
                   7488:     my $request=new HTTP::Request($reqtype,$uri);
                   7489:     my $response=$ua->request($request);
                   7490:     $$rtncode = $response->code;
1.482     albertel 7491:     if (! $response->is_success()) {
                   7492: 	return 'failed';
                   7493:     }      
                   7494:     if ($reqtype eq 'HEAD') {
1.486     www      7495: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 7496:     } elsif ($reqtype eq 'GET') {
                   7497: 	$$info = $response->content;
1.472     albertel 7498:     }
1.482     albertel 7499:     return 'ok';
1.36      albertel 7500: }
                   7501: 
1.481     raeburn  7502: sub readfile {
                   7503:     my $file = shift;
                   7504:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   7505:     my $fh;
                   7506:     open($fh,"<$file");
                   7507:     my $a='';
1.800     albertel 7508:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  7509:     return $a;
                   7510: }
                   7511: 
1.36      albertel 7512: sub filelocation {
1.590     banghart 7513:     my ($dir,$file) = @_;
                   7514:     my $location;
                   7515:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 7516: 
                   7517:     if ($file =~ m-^/adm/-) {
                   7518: 	$file=~s-^/adm/wrapper/-/-;
                   7519: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   7520:     }
1.882     albertel 7521: 
1.590     banghart 7522:     if ($file=~m:^/~:) { # is a contruction space reference
                   7523:         $location = $file;
                   7524:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807     albertel 7525:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649     albertel 7526: 	# is a correct contruction space reference
                   7527:         $location = $file;
1.609     banghart 7528:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 7529:         my ($udom,$uname,$filename)=
1.811     albertel 7530:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 7531:         my $home=&homeserver($uname,$udom);
                   7532:         my $is_me=0;
                   7533:         my @ids=&current_machine_ids();
                   7534:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   7535:         if ($is_me) {
1.740     www      7536:   	    $location=&propath($udom,$uname).
1.590     banghart 7537:   	      '/userfiles/'.$filename;
                   7538:         } else {
                   7539:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   7540:   	      $udom.'/'.$uname.'/'.$filename;
                   7541:         }
1.882     albertel 7542:     } elsif ($file =~ m-^/adm/-) {
                   7543: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 7544:     } else {
                   7545:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   7546:         $file=~s:^/res/:/:;
                   7547:         if ( !( $file =~ m:^/:) ) {
                   7548:             $location = $dir. '/'.$file;
                   7549:         } else {
                   7550:             $location = '/home/httpd/html/res'.$file;
                   7551:         }
1.59      albertel 7552:     }
1.590     banghart 7553:     $location=~s://+:/:g; # remove duplicate /
                   7554:     while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
                   7555:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   7556:     return $location;
1.46      www      7557: }
1.36      albertel 7558: 
1.46      www      7559: sub hreflocation {
                   7560:     my ($dir,$file)=@_;
1.460     albertel 7561:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
1.666     albertel 7562: 	$file=filelocation($dir,$file);
1.700     albertel 7563:     } elsif ($file=~m-^/adm/-) {
                   7564: 	$file=~s-^/adm/wrapper/-/-;
                   7565: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 7566:     }
                   7567:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   7568: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807     albertel 7569:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
                   7570: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666     albertel 7571:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811     albertel 7572: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666     albertel 7573: 	    -/uploaded/$1/$2/-x;
1.46      www      7574:     }
1.462     albertel 7575:     return $file;
1.465     albertel 7576: }
                   7577: 
                   7578: sub current_machine_domains {
1.853     albertel 7579:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   7580: }
                   7581: 
                   7582: sub machine_domains {
                   7583:     my ($hostname) = @_;
1.465     albertel 7584:     my @domains;
1.838     albertel 7585:     my %hostname = &all_hostnames();
1.465     albertel 7586:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  7587: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 7588: 	if ($hostname eq $name) {
1.844     albertel 7589: 	    push(@domains,&host_domain($id));
1.465     albertel 7590: 	}
                   7591:     }
                   7592:     return @domains;
                   7593: }
                   7594: 
                   7595: sub current_machine_ids {
1.853     albertel 7596:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   7597: }
                   7598: 
                   7599: sub machine_ids {
                   7600:     my ($hostname) = @_;
                   7601:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 7602:     my @ids;
1.888     albertel 7603:     my %name_to_host = &all_names();
1.889     albertel 7604:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   7605: 	return @{ $name_to_host{$hostname} };
                   7606:     }
                   7607:     return;
1.31      www      7608: }
                   7609: 
1.824     raeburn  7610: sub additional_machine_domains {
                   7611:     my @domains;
                   7612:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   7613:     while( my $line = <$fh>) {
                   7614:         $line =~ s/\s//g;
                   7615:         push(@domains,$line);
                   7616:     }
                   7617:     return @domains;
                   7618: }
                   7619: 
                   7620: sub default_login_domain {
                   7621:     my $domain = $perlvar{'lonDefDomain'};
                   7622:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   7623:     foreach my $posdom (&current_machine_domains(),
                   7624:                         &additional_machine_domains()) {
                   7625:         if (lc($posdom) eq lc($testdomain)) {
                   7626:             $domain=$posdom;
                   7627:             last;
                   7628:         }
                   7629:     }
                   7630:     return $domain;
                   7631: }
                   7632: 
1.31      www      7633: # ------------------------------------------------------------- Declutters URLs
                   7634: 
                   7635: sub declutter {
                   7636:     my $thisfn=shift;
1.569     albertel 7637:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 7638:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      7639:     $thisfn=~s/^\///;
1.697     albertel 7640:     $thisfn=~s|^adm/wrapper/||;
                   7641:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      7642:     $thisfn=~s/^res\///;
1.235     www      7643:     $thisfn=~s/\?.+$//;
1.268     www      7644:     return $thisfn;
                   7645: }
                   7646: 
                   7647: # ------------------------------------------------------------- Clutter up URLs
                   7648: 
                   7649: sub clutter {
                   7650:     my $thisfn='/'.&declutter(shift);
1.887     albertel 7651:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 7652: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      7653:        $thisfn='/res'.$thisfn; 
                   7654:     }
1.694     albertel 7655:     if ($thisfn !~m|/adm|) {
1.695     albertel 7656: 	if ($thisfn =~ m|/ext/|) {
1.694     albertel 7657: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 7658: 	} else {
                   7659: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   7660: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 7661: 	    if ($embstyle eq 'ssi'
                   7662: 		|| ($embstyle eq 'hdn')
                   7663: 		|| ($embstyle eq 'rat')
                   7664: 		|| ($embstyle eq 'prv')
                   7665: 		|| ($embstyle eq 'ign')) {
                   7666: 		#do nothing with these
                   7667: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 7668: 		|| ($embstyle eq 'emb')
                   7669: 		|| ($embstyle eq 'wrp')) {
                   7670: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 7671: 	    } elsif ($embstyle eq 'unk'
                   7672: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 7673: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 7674: 	    } else {
1.718     www      7675: #		&logthis("Got a blank emb style");
1.695     albertel 7676: 	    }
1.694     albertel 7677: 	}
                   7678:     }
1.31      www      7679:     return $thisfn;
1.12      www      7680: }
                   7681: 
1.787     albertel 7682: sub clutter_with_no_wrapper {
                   7683:     my $uri = &clutter(shift);
                   7684:     if ($uri =~ m-^/adm/-) {
                   7685: 	$uri =~ s-^/adm/wrapper/-/-;
                   7686: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   7687:     }
                   7688:     return $uri;
                   7689: }
                   7690: 
1.557     albertel 7691: sub freeze_escape {
                   7692:     my ($value)=@_;
                   7693:     if (ref($value)) {
                   7694: 	$value=&nfreeze($value);
                   7695: 	return '__FROZEN__'.&escape($value);
                   7696:     }
                   7697:     return &escape($value);
                   7698: }
                   7699: 
1.11      www      7700: 
1.557     albertel 7701: sub thaw_unescape {
                   7702:     my ($value)=@_;
                   7703:     if ($value =~ /^__FROZEN__/) {
                   7704: 	substr($value,0,10,undef);
                   7705: 	$value=&unescape($value);
                   7706: 	return &thaw($value);
                   7707:     }
                   7708:     return &unescape($value);
                   7709: }
                   7710: 
1.436     albertel 7711: sub correct_line_ends {
                   7712:     my ($result)=@_;
                   7713:     $$result =~s/\r\n/\n/mg;
                   7714:     $$result =~s/\r/\n/mg;
1.415     albertel 7715: }
1.1       albertel 7716: # ================================================================ Main Program
                   7717: 
1.184     www      7718: sub goodbye {
1.204     albertel 7719:    &logthis("Starting Shut down");
1.443     albertel 7720: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 7721:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 7722: #converted
1.599     albertel 7723: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 7724:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   7725: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   7726: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 7727: #1.1 only
1.870     albertel 7728: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   7729: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   7730: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   7731: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   7732:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 7733:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   7734:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      7735:    &flushcourselogs();
                   7736:    &logthis("Shutting down");
                   7737: }
                   7738: 
1.852     albertel 7739: sub get_dns {
1.869     albertel 7740:     my ($url,$func,$ignore_cache) = @_;
                   7741:     if (!$ignore_cache) {
                   7742: 	my ($content,$cached)=
                   7743: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   7744: 	if ($cached) {
                   7745: 	    &$func($content);
                   7746: 	    return;
                   7747: 	}
                   7748:     }
                   7749: 
                   7750:     my %alldns;
1.852     albertel 7751:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   7752:     foreach my $dns (<$config>) {
                   7753: 	next if ($dns !~ /^\^(\S*)/x);
1.869     albertel 7754: 	$alldns{$1} = 1;
                   7755:     }
                   7756:     while (%alldns) {
                   7757: 	my ($dns) = keys(%alldns);
                   7758: 	delete($alldns{$dns});
1.852     albertel 7759: 	my $ua=new LWP::UserAgent;
                   7760: 	my $request=new HTTP::Request('GET',"http://$dns$url");
                   7761: 	my $response=$ua->request($request);
                   7762: 	next if ($response->is_error());
                   7763: 	my @content = split("\n",$response->content);
1.869     albertel 7764: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852     albertel 7765: 	&$func(\@content);
1.869     albertel 7766: 	return;
1.852     albertel 7767:     }
                   7768:     close($config);
1.871     albertel 7769:     my $which = (split('/',$url))[3];
                   7770:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   7771:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 7772:     my @content = <$config>;
                   7773:     &$func(\@content);
                   7774:     return;
1.852     albertel 7775: }
1.327     albertel 7776: # ------------------------------------------------------------ Read domain file
                   7777: {
1.852     albertel 7778:     my $loaded;
1.846     albertel 7779:     my %domain;
                   7780: 
1.852     albertel 7781:     sub parse_domain_tab {
                   7782: 	my ($lines) = @_;
                   7783: 	foreach my $line (@$lines) {
                   7784: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      7785: 
1.846     albertel 7786: 	    chomp($line);
1.852     albertel 7787: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 7788: 	    my %this_domain;
                   7789: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   7790: 			       'lang_def', 'city', 'longi', 'lati',
                   7791: 			       'primary') {
                   7792: 		$this_domain{$field} = shift(@elements);
                   7793: 	    }
                   7794: 	    $domain{$name} = \%this_domain;
1.852     albertel 7795: 	}
                   7796:     }
1.864     albertel 7797: 
                   7798:     sub reset_domain_info {
                   7799: 	undef($loaded);
                   7800: 	undef(%domain);
                   7801:     }
                   7802: 
1.852     albertel 7803:     sub load_domain_tab {
1.869     albertel 7804: 	my ($ignore_cache) = @_;
                   7805: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 7806: 	my $fh;
                   7807: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   7808: 	    my @lines = <$fh>;
                   7809: 	    &parse_domain_tab(\@lines);
1.448     albertel 7810: 	}
1.852     albertel 7811: 	close($fh);
                   7812: 	$loaded = 1;
1.327     albertel 7813:     }
1.846     albertel 7814: 
                   7815:     sub domain {
1.852     albertel 7816: 	&load_domain_tab() if (!$loaded);
                   7817: 
1.846     albertel 7818: 	my ($name,$what) = @_;
                   7819: 	return if ( !exists($domain{$name}) );
                   7820: 
                   7821: 	if (!$what) {
                   7822: 	    return $domain{$name}{'description'};
                   7823: 	}
                   7824: 	return $domain{$name}{$what};
                   7825:     }
1.327     albertel 7826: }
                   7827: 
                   7828: 
1.1       albertel 7829: # ------------------------------------------------------------- Read hosts file
                   7830: {
1.838     albertel 7831:     my %hostname;
1.844     albertel 7832:     my %hostdom;
1.845     albertel 7833:     my %libserv;
1.852     albertel 7834:     my $loaded;
1.888     albertel 7835:     my %name_to_host;
1.852     albertel 7836: 
                   7837:     sub parse_hosts_tab {
                   7838: 	my ($file) = @_;
                   7839: 	foreach my $configline (@$file) {
                   7840: 	    next if ($configline =~ /^(\#|\s*$ )/x);
                   7841: 	    next if ($configline =~ /^\^/);
                   7842: 	    chomp($configline);
                   7843: 	    my ($id,$domain,$role,$name)=split(/:/,$configline);
                   7844: 	    $name=~s/\s//g;
                   7845: 	    if ($id && $domain && $role && $name) {
                   7846: 		$hostname{$id}=$name;
1.888     albertel 7847: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 7848: 		$hostdom{$id}=$domain;
                   7849: 		if ($role eq 'library') { $libserv{$id}=$name; }
                   7850: 	    }
                   7851: 	}
                   7852:     }
1.864     albertel 7853:     
                   7854:     sub reset_hosts_info {
                   7855: 	&reset_domain_info();
                   7856: 	&reset_hosts_ip_info();
                   7857: 	undef(%hostname);
                   7858: 	undef(%hostdom);
                   7859: 	undef(%libserv);
                   7860: 	undef($loaded);
                   7861:     }
1.1       albertel 7862: 
1.852     albertel 7863:     sub load_hosts_tab {
1.869     albertel 7864: 	my ($ignore_cache) = @_;
                   7865: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 7866: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   7867: 	my @config = <$config>;
                   7868: 	&parse_hosts_tab(\@config);
                   7869: 	close($config);
                   7870: 	$loaded=1;
1.1       albertel 7871:     }
1.852     albertel 7872: 
1.838     albertel 7873:     sub hostname {
1.852     albertel 7874: 	&load_hosts_tab() if (!$loaded);
                   7875: 
1.838     albertel 7876: 	my ($lonid) = @_;
                   7877: 	return $hostname{$lonid};
                   7878:     }
1.845     albertel 7879: 
1.838     albertel 7880:     sub all_hostnames {
1.852     albertel 7881: 	&load_hosts_tab() if (!$loaded);
                   7882: 
1.838     albertel 7883: 	return %hostname;
                   7884:     }
1.845     albertel 7885: 
1.888     albertel 7886:     sub all_names {
                   7887: 	&load_hosts_tab() if (!$loaded);
                   7888: 
                   7889: 	return %name_to_host;
                   7890:     }
                   7891: 
1.845     albertel 7892:     sub is_library {
1.852     albertel 7893: 	&load_hosts_tab() if (!$loaded);
                   7894: 
1.845     albertel 7895: 	return exists($libserv{$_[0]});
                   7896:     }
                   7897: 
                   7898:     sub all_library {
1.852     albertel 7899: 	&load_hosts_tab() if (!$loaded);
                   7900: 
1.845     albertel 7901: 	return %libserv;
                   7902:     }
                   7903: 
1.841     albertel 7904:     sub get_servers {
1.852     albertel 7905: 	&load_hosts_tab() if (!$loaded);
                   7906: 
1.841     albertel 7907: 	my ($domain,$type) = @_;
                   7908: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   7909: 	                                          : %hostname;
                   7910: 	my %result;
1.842     albertel 7911: 	if (ref($domain) eq 'ARRAY') {
                   7912: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 7913: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 7914: 		    $result{$host} = $hostname;
                   7915: 		}
                   7916: 	    }
                   7917: 	} else {
                   7918: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   7919: 		if ($hostdom{$host} eq $domain) {
                   7920: 		    $result{$host} = $hostname;
                   7921: 		}
1.841     albertel 7922: 	    }
                   7923: 	}
                   7924: 	return %result;
                   7925:     }
1.845     albertel 7926: 
1.844     albertel 7927:     sub host_domain {
1.852     albertel 7928: 	&load_hosts_tab() if (!$loaded);
                   7929: 
1.844     albertel 7930: 	my ($lonid) = @_;
                   7931: 	return $hostdom{$lonid};
                   7932:     }
                   7933: 
1.841     albertel 7934:     sub all_domains {
1.852     albertel 7935: 	&load_hosts_tab() if (!$loaded);
                   7936: 
1.841     albertel 7937: 	my %seen;
                   7938: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   7939: 	return @uniq;
                   7940:     }
1.1       albertel 7941: }
                   7942: 
1.847     albertel 7943: { 
                   7944:     my %iphost;
1.856     albertel 7945:     my %name_to_ip;
                   7946:     my %lonid_to_ip;
1.869     albertel 7947: 
                   7948:     my %valid_ip;
                   7949:     sub valid_ip {
                   7950: 	my ($ip) = @_;
                   7951: 	if (exists($iphost{$ip}) || exists($valid_ip{$ip})) {
                   7952: 	    return 1;	
                   7953: 	}
                   7954: 	my $name = gethostbyip($ip);
                   7955: 	my $lonid = &hostname($name);
                   7956: 	if (defined($lonid)) {
                   7957: 	    $valid_ip{$ip} = $lonid;
                   7958: 	    return 1;
                   7959: 	}
                   7960: 	my %iphosts = &get_iphost();
                   7961: 	if (ref($iphost{$ip})) {
                   7962: 	    return 1;	
                   7963: 	}
                   7964:     }
                   7965: 
1.847     albertel 7966:     sub get_hosts_from_ip {
                   7967: 	my ($ip) = @_;
                   7968: 	my %iphosts = &get_iphost();
                   7969: 	if (ref($iphosts{$ip})) {
                   7970: 	    return @{$iphosts{$ip}};
                   7971: 	}
                   7972: 	return;
1.839     albertel 7973:     }
1.864     albertel 7974:     
                   7975:     sub reset_hosts_ip_info {
                   7976: 	undef(%iphost);
                   7977: 	undef(%name_to_ip);
                   7978: 	undef(%lonid_to_ip);
                   7979:     }
1.856     albertel 7980: 
                   7981:     sub get_host_ip {
                   7982: 	my ($lonid) = @_;
                   7983: 	if (exists($lonid_to_ip{$lonid})) {
                   7984: 	    return $lonid_to_ip{$lonid};
                   7985: 	}
                   7986: 	my $name=&hostname($lonid);
                   7987:    	my $ip = gethostbyname($name);
                   7988: 	return if (!$ip || length($ip) ne 4);
                   7989: 	$ip=inet_ntoa($ip);
                   7990: 	$name_to_ip{$name}   = $ip;
                   7991: 	$lonid_to_ip{$lonid} = $ip;
                   7992: 	return $ip;
                   7993:     }
1.847     albertel 7994:     
                   7995:     sub get_iphost {
1.869     albertel 7996: 	my ($ignore_cache) = @_;
                   7997: 	if (!$ignore_cache) {
                   7998: 	    if (%iphost) {
                   7999: 		return %iphost;
                   8000: 	    }
                   8001: 	    my ($ip_info,$cached)=
                   8002: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   8003: 	    if ($cached) {
                   8004: 		%iphost      = %{$ip_info->[0]};
                   8005: 		%name_to_ip  = %{$ip_info->[1]};
                   8006: 		%lonid_to_ip = %{$ip_info->[2]};
                   8007: 		return %iphost;
                   8008: 	    }
                   8009: 	}
1.888     albertel 8010: 	my %name_to_host = &all_names();
                   8011: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 8012: 	    my $ip;
                   8013: 	    if (!exists($name_to_ip{$name})) {
                   8014: 		$ip = gethostbyname($name);
                   8015: 		if (!$ip || length($ip) ne 4) {
1.888     albertel 8016: 		    &logthis("Skipping name $name no IP found");
1.847     albertel 8017: 		    next;
                   8018: 		}
                   8019: 		$ip=inet_ntoa($ip);
                   8020: 		$name_to_ip{$name} = $ip;
                   8021: 	    } else {
                   8022: 		$ip = $name_to_ip{$name};
1.653     albertel 8023: 	    }
1.888     albertel 8024: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   8025: 		$lonid_to_ip{$id} = $ip;
                   8026: 	    }
                   8027: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 8028: 	}
1.869     albertel 8029: 	&Apache::lonnet::do_cache_new('iphost','iphost',
                   8030: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   8031: 				      24*60*60);
                   8032: 
1.847     albertel 8033: 	return %iphost;
1.598     albertel 8034:     }
                   8035: }
                   8036: 
1.862     albertel 8037: BEGIN {
                   8038: 
                   8039: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   8040:     unless ($readit) {
                   8041: {
                   8042:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   8043:     %perlvar = (%perlvar,%{$configvars});
                   8044: }
                   8045: 
                   8046: 
1.1       albertel 8047: # ------------------------------------------------------ Read spare server file
                   8048: {
1.448     albertel 8049:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 8050: 
                   8051:     while (my $configline=<$config>) {
                   8052:        chomp($configline);
1.284     matthew  8053:        if ($configline) {
1.784     albertel 8054: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 8055: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 8056: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 8057:        }
                   8058:     }
1.448     albertel 8059:     close($config);
1.1       albertel 8060: }
1.11      www      8061: # ------------------------------------------------------------ Read permissions
                   8062: {
1.448     albertel 8063:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      8064: 
                   8065:     while (my $configline=<$config>) {
1.448     albertel 8066: 	chomp($configline);
                   8067: 	if ($configline) {
                   8068: 	    my ($role,$perm)=split(/ /,$configline);
                   8069: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   8070: 	}
1.11      www      8071:     }
1.448     albertel 8072:     close($config);
1.11      www      8073: }
                   8074: 
                   8075: # -------------------------------------------- Read plain texts for permissions
                   8076: {
1.448     albertel 8077:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      8078: 
                   8079:     while (my $configline=<$config>) {
1.448     albertel 8080: 	chomp($configline);
                   8081: 	if ($configline) {
1.742     raeburn  8082: 	    my ($short,@plain)=split(/:/,$configline);
                   8083:             %{$prp{$short}} = ();
                   8084: 	    if (@plain > 0) {
                   8085:                 $prp{$short}{'std'} = $plain[0];
                   8086:                 for (my $i=1; $i<@plain; $i++) {
                   8087:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   8088:                 }
                   8089:             }
1.448     albertel 8090: 	}
1.135     www      8091:     }
1.448     albertel 8092:     close($config);
1.135     www      8093: }
                   8094: 
                   8095: # ---------------------------------------------------------- Read package table
                   8096: {
1.448     albertel 8097:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      8098: 
                   8099:     while (my $configline=<$config>) {
1.483     albertel 8100: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 8101: 	chomp($configline);
                   8102: 	my ($short,$plain)=split(/:/,$configline);
                   8103: 	my ($pack,$name)=split(/\&/,$short);
                   8104: 	if ($plain ne '') {
                   8105: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   8106: 	    $packagetab{$short}=$plain; 
                   8107: 	}
1.11      www      8108:     }
1.448     albertel 8109:     close($config);
1.329     matthew  8110: }
                   8111: 
                   8112: # ------------- set up temporary directory
                   8113: {
                   8114:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   8115: 
1.11      www      8116: }
                   8117: 
1.794     albertel 8118: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   8119: 				'compress_threshold'=> 20_000,
                   8120:  			        });
1.185     www      8121: 
1.281     www      8122: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      8123: $dumpcount=0;
1.22      www      8124: 
1.163     harris41 8125: &logtouch();
1.672     albertel 8126: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      8127: $readit=1;
1.564     albertel 8128:     {
                   8129: 	use integer;
                   8130: 	my $test=(2**32)+1;
1.568     albertel 8131: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 8132: 	&logthis(" Detected 64bit platform ($_64bit)");
                   8133:     }
1.195     www      8134: }
1.1       albertel 8135: }
1.179     www      8136: 
1.1       albertel 8137: 1;
1.191     harris41 8138: __END__
                   8139: 
1.243     albertel 8140: =pod
                   8141: 
1.191     harris41 8142: =head1 NAME
                   8143: 
1.243     albertel 8144: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 8145: 
                   8146: =head1 SYNOPSIS
                   8147: 
1.243     albertel 8148: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 8149: 
                   8150:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   8151: 
1.243     albertel 8152: Common parameters:
                   8153: 
                   8154: =over 4
                   8155: 
                   8156: =item *
                   8157: 
                   8158: $uname : an internal username (if $cname expecting a course Id specifically)
                   8159: 
                   8160: =item *
                   8161: 
                   8162: $udom : a domain (if $cdom expecting a course's domain specifically)
                   8163: 
                   8164: =item *
                   8165: 
                   8166: $symb : a resource instance identifier
                   8167: 
                   8168: =item *
                   8169: 
                   8170: $namespace : the name of a .db file that contains the data needed or
                   8171: being set.
                   8172: 
                   8173: =back
                   8174: 
1.394     bowersj2 8175: =head1 OVERVIEW
1.191     harris41 8176: 
1.394     bowersj2 8177: lonnet provides subroutines which interact with the
                   8178: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   8179: about classes, users, and resources.
1.243     albertel 8180: 
                   8181: For many of these objects you can also use this to store data about
                   8182: them or modify them in various ways.
1.191     harris41 8183: 
1.394     bowersj2 8184: =head2 Symbs
1.191     harris41 8185: 
1.394     bowersj2 8186: To identify a specific instance of a resource, LON-CAPA uses symbols
                   8187: or "symbs"X<symb>. These identifiers are built from the URL of the
                   8188: map, the resource number of the resource in the map, and the URL of
                   8189: the resource itself. The latter is somewhat redundant, but might help
                   8190: if maps change.
                   8191: 
                   8192: An example is
                   8193: 
                   8194:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   8195: 
                   8196: The respective map entry is
                   8197: 
                   8198:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   8199:   title="Problem 2">
                   8200:  </resource>
                   8201: 
                   8202: Symbs are used by the random number generator, as well as to store and
                   8203: restore data specific to a certain instance of for example a problem.
                   8204: 
                   8205: =head2 Storing And Retrieving Data
                   8206: 
                   8207: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   8208: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   8209: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   8210: is is the non-critical message twin of cstore. These functions are for
                   8211: handlers to store a perl hash to a user's permanent data space in an
                   8212: easy manner, and to retrieve it again on another call. It is expected
                   8213: that a handler would use this once at the beginning to retrieve data,
                   8214: and then again once at the end to send only the new data back.
                   8215: 
                   8216: The data is stored in the user's data directory on the user's
                   8217: homeserver under the ID of the course.
                   8218: 
                   8219: The hash that is returned by restore will have all of the previous
                   8220: value for all of the elements of the hash.
                   8221: 
                   8222: Example:
                   8223: 
                   8224:  #creating a hash
                   8225:  my %hash;
                   8226:  $hash{'foo'}='bar';
                   8227: 
                   8228:  #storing it
                   8229:  &Apache::lonnet::cstore(\%hash);
                   8230: 
                   8231:  #changing a value
                   8232:  $hash{'foo'}='notbar';
                   8233: 
                   8234:  #adding a new value
                   8235:  $hash{'bar'}='foo';
                   8236:  &Apache::lonnet::cstore(\%hash);
                   8237: 
                   8238:  #retrieving the hash
                   8239:  my %history=&Apache::lonnet::restore();
                   8240: 
                   8241:  #print the hash
                   8242:  foreach my $key (sort(keys(%history))) {
                   8243:    print("\%history{$key} = $history{$key}");
                   8244:  }
                   8245: 
                   8246: Will print out:
1.191     harris41 8247: 
1.394     bowersj2 8248:  %history{1:foo} = bar
                   8249:  %history{1:keys} = foo:timestamp
                   8250:  %history{1:timestamp} = 990455579
                   8251:  %history{2:bar} = foo
                   8252:  %history{2:foo} = notbar
                   8253:  %history{2:keys} = foo:bar:timestamp
                   8254:  %history{2:timestamp} = 990455580
                   8255:  %history{bar} = foo
                   8256:  %history{foo} = notbar
                   8257:  %history{timestamp} = 990455580
                   8258:  %history{version} = 2
                   8259: 
                   8260: Note that the special hash entries C<keys>, C<version> and
                   8261: C<timestamp> were added to the hash. C<version> will be equal to the
                   8262: total number of versions of the data that have been stored. The
                   8263: C<timestamp> attribute will be the UNIX time the hash was
                   8264: stored. C<keys> is available in every historical section to list which
                   8265: keys were added or changed at a specific historical revision of a
                   8266: hash.
                   8267: 
                   8268: B<Warning>: do not store the hash that restore returns directly. This
                   8269: will cause a mess since it will restore the historical keys as if the
                   8270: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 8271: 
1.394     bowersj2 8272: Calling convention:
1.191     harris41 8273: 
1.394     bowersj2 8274:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   8275:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 8276: 
1.394     bowersj2 8277: For more detailed information, see lonnet specific documentation.
1.191     harris41 8278: 
1.394     bowersj2 8279: =head1 RETURN MESSAGES
1.191     harris41 8280: 
1.394     bowersj2 8281: =over 4
1.191     harris41 8282: 
1.394     bowersj2 8283: =item * B<con_lost>: unable to contact remote host
1.191     harris41 8284: 
1.394     bowersj2 8285: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   8286: when the connection is brought back up
1.191     harris41 8287: 
1.394     bowersj2 8288: =item * B<con_failed>: unable to contact remote host and unable to save message
                   8289: for later delivery
1.191     harris41 8290: 
1.394     bowersj2 8291: =item * B<error:>: an error a occured, a description of the error follows the :
1.191     harris41 8292: 
1.394     bowersj2 8293: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 8294: that was requested
1.191     harris41 8295: 
1.243     albertel 8296: =back
1.191     harris41 8297: 
1.243     albertel 8298: =head1 PUBLIC SUBROUTINES
1.191     harris41 8299: 
1.243     albertel 8300: =head2 Session Environment Functions
1.191     harris41 8301: 
1.243     albertel 8302: =over 4
1.191     harris41 8303: 
1.394     bowersj2 8304: =item * 
                   8305: X<appenv()>
                   8306: B<appenv(%hash)>: the value of %hash is written to
                   8307: the user envirnoment file, and will be restored for each access this
1.620     albertel 8308: user makes during this session, also modifies the %env for the current
1.394     bowersj2 8309: process
1.191     harris41 8310: 
                   8311: =item *
1.394     bowersj2 8312: X<delenv()>
                   8313: B<delenv($regexp)>: removes all items from the session
                   8314: environment file that matches the regular expression in $regexp. The
1.620     albertel 8315: values are also delted from the current processes %env.
1.191     harris41 8316: 
1.795     albertel 8317: =item * get_env_multiple($name) 
                   8318: 
                   8319: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   8320: values may be defined and end up as an array ref.
                   8321: 
                   8322: returns an array of values
                   8323: 
1.243     albertel 8324: =back
                   8325: 
                   8326: =head2 User Information
1.191     harris41 8327: 
1.243     albertel 8328: =over 4
1.191     harris41 8329: 
                   8330: =item *
1.394     bowersj2 8331: X<queryauthenticate()>
                   8332: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 8333: authentication scheme
                   8334: 
                   8335: =item *
1.394     bowersj2 8336: X<authenticate()>
                   8337: B<authenticate($uname,$upass,$udom)>: try to
                   8338: authenticate user from domain's lib servers (first use the current
                   8339: one). C<$upass> should be the users password.
1.191     harris41 8340: 
                   8341: =item *
1.394     bowersj2 8342: X<homeserver()>
                   8343: B<homeserver($uname,$udom)>: find the server which has
                   8344: the user's directory and files (there must be only one), this caches
                   8345: the answer, and also caches if there is a borken connection.
1.191     harris41 8346: 
                   8347: =item *
1.394     bowersj2 8348: X<idget()>
                   8349: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   8350: (IDs are a unique resource in a domain, there must be only 1 ID per
                   8351: username, and only 1 username per ID in a specific domain) (returns
                   8352: hash: id=>name,id=>name)
1.191     harris41 8353: 
                   8354: =item *
1.394     bowersj2 8355: X<idrget()>
                   8356: B<idrget($udom,@unames)>: find the IDs behind a list of
                   8357: usernames (returns hash: name=>id,name=>id)
1.191     harris41 8358: 
                   8359: =item *
1.394     bowersj2 8360: X<idput()>
                   8361: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 8362: 
                   8363: =item *
1.394     bowersj2 8364: X<rolesinit()>
                   8365: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 8366: 
                   8367: =item *
1.551     albertel 8368: X<getsection()>
                   8369: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 8370: course $cname, return section name/number or '' for "not in course"
                   8371: and '-1' for "no section"
                   8372: 
                   8373: =item *
1.394     bowersj2 8374: X<userenvironment()>
                   8375: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 8376: passed in @what from the requested user's environment, returns a hash
                   8377: 
1.858     raeburn  8378: =item * 
                   8379: X<userlog_query()>
1.859     albertel 8380: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   8381: activity.log file. %filters defines filters applied when parsing the
                   8382: log file. These can be start or end timestamps, or the type of action
                   8383: - log to look for Login or Logout events, check for Checkin or
                   8384: Checkout, role for role selection. The response is in the form
                   8385: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   8386: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  8387: 
1.243     albertel 8388: =back
                   8389: 
                   8390: =head2 User Roles
                   8391: 
                   8392: =over 4
                   8393: 
                   8394: =item *
                   8395: 
1.810     raeburn  8396: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 8397:  F: full access
                   8398:  U,I,K: authentication modes (cxx only)
                   8399:  '': forbidden
                   8400:  1: user needs to choose course
                   8401:  2: browse allowed
1.766     albertel 8402:  A: passphrase authentication needed
1.243     albertel 8403: 
                   8404: =item *
                   8405: 
                   8406: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   8407: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   8408: and course level
                   8409: 
                   8410: =item *
                   8411: 
                   8412: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
                   8413: explanation of a user role term
                   8414: 
1.832     raeburn  8415: =item *
                   8416: 
1.858     raeburn  8417: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms) :
                   8418: All arguments are optional. Returns a hash of a roles, either for
                   8419: co-author/assistant author roles for a user's Construction Space
                   8420: (default), or if $context is 'user', roles for the user himself,
                   8421: In the hash, keys are set to colon-sparated $uname,$udom,and $role,
                   8422: and value is set to colon-separated start and end times for the role.
                   8423: If no username and domain are specified, will default to current
                   8424: user/domain. Types, roles, and roledoms are references to arrays,
                   8425: of role statuses (active, future or previous), roles 
                   8426: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   8427: to restrict the list of roles reported. If no array ref is 
                   8428: provided for types, will default to return only active roles.
1.834     albertel 8429: 
1.243     albertel 8430: =back
                   8431: 
                   8432: =head2 User Modification
                   8433: 
                   8434: =over 4
                   8435: 
                   8436: =item *
                   8437: 
                   8438: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
                   8439: user for the level given by URL.  Optional start and end dates (leave empty
                   8440: string or zero for "no date")
1.191     harris41 8441: 
                   8442: =item *
                   8443: 
1.243     albertel 8444: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   8445: change a users, password, possible return values are: ok,
                   8446: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   8447: refused
1.191     harris41 8448: 
                   8449: =item *
                   8450: 
1.243     albertel 8451: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 8452: 
                   8453: =item *
                   8454: 
1.243     albertel 8455: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
                   8456: modify user
1.191     harris41 8457: 
                   8458: =item *
                   8459: 
1.286     matthew  8460: modifystudent
                   8461: 
                   8462: modify a students enrollment and identification information.
                   8463: The course id is resolved based on the current users environment.  
                   8464: This means the envoking user must be a course coordinator or otherwise
                   8465: associated with a course.
                   8466: 
1.297     matthew  8467: This call is essentially a wrapper for lonnet::modifyuser and
                   8468: lonnet::modify_student_enrollment
1.286     matthew  8469: 
                   8470: Inputs: 
                   8471: 
                   8472: =over 4
                   8473: 
                   8474: =item B<$udom> Students loncapa domain
                   8475: 
                   8476: =item B<$uname> Students loncapa login name
                   8477: 
                   8478: =item B<$uid> Students id/student number
                   8479: 
                   8480: =item B<$umode> Students authentication mode
                   8481: 
                   8482: =item B<$upass> Students password
                   8483: 
                   8484: =item B<$first> Students first name
                   8485: 
                   8486: =item B<$middle> Students middle name
                   8487: 
                   8488: =item B<$last> Students last name
                   8489: 
                   8490: =item B<$gene> Students generation
                   8491: 
                   8492: =item B<$usec> Students section in course
                   8493: 
                   8494: =item B<$end> Unix time of the roles expiration
                   8495: 
                   8496: =item B<$start> Unix time of the roles start date
                   8497: 
                   8498: =item B<$forceid> If defined, allow $uid to be changed
                   8499: 
                   8500: =item B<$desiredhome> server to use as home server for student
                   8501: 
                   8502: =back
1.297     matthew  8503: 
                   8504: =item *
                   8505: 
                   8506: modify_student_enrollment
                   8507: 
                   8508: Change a students enrollment status in a class.  The environment variable
                   8509: 'role.request.course' must be defined for this function to proceed.
                   8510: 
                   8511: Inputs:
                   8512: 
                   8513: =over 4
                   8514: 
                   8515: =item $udom, students domain
                   8516: 
                   8517: =item $uname, students name
                   8518: 
                   8519: =item $uid, students user id
                   8520: 
                   8521: =item $first, students first name
                   8522: 
                   8523: =item $middle
                   8524: 
                   8525: =item $last
                   8526: 
                   8527: =item $gene
                   8528: 
                   8529: =item $usec
                   8530: 
                   8531: =item $end
                   8532: 
                   8533: =item $start
                   8534: 
                   8535: =back
                   8536: 
1.191     harris41 8537: 
                   8538: =item *
                   8539: 
1.243     albertel 8540: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   8541: custom role; give a custom role to a user for the level given by URL.  Specify
                   8542: name and domain of role author, and role name
1.191     harris41 8543: 
                   8544: =item *
                   8545: 
1.243     albertel 8546: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 8547: 
                   8548: =item *
                   8549: 
1.243     albertel 8550: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   8551: 
                   8552: =back
                   8553: 
                   8554: =head2 Course Infomation
                   8555: 
                   8556: =over 4
1.191     harris41 8557: 
                   8558: =item *
                   8559: 
1.631     albertel 8560: coursedescription($courseid) : returns a hash of information about the
                   8561: specified course id, including all environment settings for the
                   8562: course, the description of the course will be in the hash under the
                   8563: key 'description'
1.191     harris41 8564: 
                   8565: =item *
                   8566: 
1.624     albertel 8567: resdata($name,$domain,$type,@which) : request for current parameter
                   8568: setting for a specific $type, where $type is either 'course' or 'user',
                   8569: @what should be a list of parameters to ask about. This routine caches
                   8570: answers for 5 minutes.
1.243     albertel 8571: 
1.877     foxr     8572: =item *
                   8573: 
                   8574: get_courseresdata($courseid, $domain) : dump the entire course resource
                   8575: data base, returning a hash that is keyed by the resource name and has
                   8576: values that are the resource value.  I believe that the timestamps and
                   8577: versions are also returned.
                   8578: 
                   8579: 
1.243     albertel 8580: =back
                   8581: 
                   8582: =head2 Course Modification
                   8583: 
                   8584: =over 4
1.191     harris41 8585: 
                   8586: =item *
                   8587: 
1.243     albertel 8588: writecoursepref($courseid,%prefs) : write preferences (environment
                   8589: database) for a course
1.191     harris41 8590: 
                   8591: =item *
                   8592: 
1.243     albertel 8593: createcourse($udom,$description,$url) : make/modify course
                   8594: 
                   8595: =back
                   8596: 
                   8597: =head2 Resource Subroutines
                   8598: 
                   8599: =over 4
1.191     harris41 8600: 
                   8601: =item *
                   8602: 
1.243     albertel 8603: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 8604: 
                   8605: =item *
                   8606: 
1.243     albertel 8607: repcopy($filename) : subscribes to the requested file, and attempts to
                   8608: replicate from the owning library server, Might return
1.607     raeburn  8609: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   8610: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 8611: resource. Expects the local filesystem pathname
                   8612: (/home/httpd/html/res/....)
                   8613: 
                   8614: =back
                   8615: 
                   8616: =head2 Resource Information
                   8617: 
                   8618: =over 4
1.191     harris41 8619: 
                   8620: =item *
                   8621: 
1.243     albertel 8622: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   8623: a vairety of different possible values, $varname should be a request
                   8624: string, and the other parameters can be used to specify who and what
                   8625: one is asking about.
                   8626: 
                   8627: Possible values for $varname are environment.lastname (or other item
                   8628: from the envirnment hash), user.name (or someother aspect about the
                   8629: user), resource.0.maxtries (or some other part and parameter of a
                   8630: resource)
1.204     albertel 8631: 
                   8632: =item *
                   8633: 
1.243     albertel 8634: directcondval($number) : get current value of a condition; reads from a state
                   8635: string
1.204     albertel 8636: 
                   8637: =item *
                   8638: 
1.243     albertel 8639: condval($condidx) : value of condition index based on state
1.204     albertel 8640: 
                   8641: =item *
                   8642: 
1.243     albertel 8643: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   8644: resource's metadata, $what should be either a specific key, or either
                   8645: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   8646: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   8647: 
                   8648: this function automatically caches all requests
1.191     harris41 8649: 
                   8650: =item *
                   8651: 
1.243     albertel 8652: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   8653: network of library servers; returns file handle of where SQL and regex results
                   8654: will be stored for query
1.191     harris41 8655: 
                   8656: =item *
                   8657: 
1.243     albertel 8658: symbread($filename) : return symbolic list entry (filename argument optional);
                   8659: returns the data handle
1.191     harris41 8660: 
                   8661: =item *
                   8662: 
1.243     albertel 8663: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 8664: a possible symb for the URL in $thisfn, and if is an encryypted
                   8665: resource that the user accessed using /enc/ returns a 1 on success, 0
                   8666: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 8667: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 8668: 
1.191     harris41 8669: 
                   8670: =item *
                   8671: 
1.243     albertel 8672: symbclean($symb) : removes versions numbers from a symb, returns the
                   8673: cleaned symb
1.191     harris41 8674: 
                   8675: =item *
                   8676: 
1.243     albertel 8677: is_on_map($uri) : checks if the $uri is somewhere on the current
                   8678: course map, user must be in a course for it to work.
1.191     harris41 8679: 
                   8680: =item *
                   8681: 
1.243     albertel 8682: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 8683: 
                   8684: =item *
                   8685: 
1.243     albertel 8686: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   8687: a random seed, all arguments are optional, if they aren't sent it uses the
                   8688: environment to derive them. Note: if symb isn't sent and it can't get one
                   8689: from &symbread it will use the current time as its return value
1.191     harris41 8690: 
                   8691: =item *
                   8692: 
1.243     albertel 8693: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   8694: unfakeable, receipt
1.191     harris41 8695: 
                   8696: =item *
                   8697: 
1.620     albertel 8698: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 8699: 
                   8700: =item *
                   8701: 
1.243     albertel 8702: countacc($url) : count the number of accesses to a given URL
1.191     harris41 8703: 
                   8704: =item *
                   8705: 
1.243     albertel 8706: 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 8707: 
                   8708: =item *
                   8709: 
1.243     albertel 8710: 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 8711: 
                   8712: =item *
                   8713: 
1.243     albertel 8714: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 8715: 
                   8716: =item *
                   8717: 
1.243     albertel 8718: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   8719: forcing spreadsheet to reevaluate the resource scores next time.
                   8720: 
                   8721: =back
                   8722: 
                   8723: =head2 Storing/Retreiving Data
                   8724: 
                   8725: =over 4
1.191     harris41 8726: 
                   8727: =item *
                   8728: 
1.243     albertel 8729: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   8730: for this url; hashref needs to be given and should be a \%hashname; the
                   8731: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 8732: be derived from the env
1.191     harris41 8733: 
                   8734: =item *
                   8735: 
1.243     albertel 8736: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   8737: uses critical subroutine
1.191     harris41 8738: 
                   8739: =item *
                   8740: 
1.243     albertel 8741: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   8742: all args are optional
1.191     harris41 8743: 
                   8744: =item *
                   8745: 
1.717     albertel 8746: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   8747: dumps the complete (or key matching regexp) namespace into a hash
                   8748: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   8749: normally &store()ed into
                   8750: 
                   8751: $range should be either an integer '100' (give me the first 100
                   8752:                                            matching records)
                   8753:               or be  two integers sperated by a - with no spaces
                   8754:                  '30-50' (give me the 30th through the 50th matching
                   8755:                           records)
                   8756: 
                   8757: 
                   8758: =item *
                   8759: 
                   8760: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   8761: replaces a &store() version of data with a replacement set of data
                   8762: for a particular resource in a namespace passed in the $storehash hash 
                   8763: reference
                   8764: 
                   8765: =item *
                   8766: 
1.243     albertel 8767: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   8768: works very similar to store/cstore, but all data is stored in a
                   8769: temporary location and can be reset using tmpreset, $storehash should
                   8770: be a hash reference, returns nothing on success
1.191     harris41 8771: 
                   8772: =item *
                   8773: 
1.243     albertel 8774: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   8775: similar to restore, but all data is stored in a temporary location and
                   8776: can be reset using tmpreset. Returns a hash of values on success,
                   8777: error string otherwise.
1.191     harris41 8778: 
                   8779: =item *
                   8780: 
1.243     albertel 8781: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   8782: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 8783: 
                   8784: =item *
                   8785: 
1.243     albertel 8786: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   8787: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 8788: 
                   8789: =item *
                   8790: 
1.243     albertel 8791: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   8792: namesp ($udom and $uname are optional)
1.191     harris41 8793: 
                   8794: =item *
                   8795: 
1.702     albertel 8796: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 8797: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 8798: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  8799: 
1.702     albertel 8800: $range should be either an integer '100' (give me the first 100
                   8801:                                            matching records)
                   8802:               or be  two integers sperated by a - with no spaces
                   8803:                  '30-50' (give me the 30th through the 50th matching
                   8804:                           records)
1.449     matthew  8805: =item *
                   8806: 
                   8807: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   8808: $store can be a scalar, an array reference, or if the amount to be 
                   8809: incremented is > 1, a hash reference.
                   8810: 
                   8811: ($udom and $uname are optional)
1.191     harris41 8812: 
                   8813: =item *
                   8814: 
1.243     albertel 8815: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   8816: ($udom and $uname are optional)
1.191     harris41 8817: 
                   8818: =item *
                   8819: 
1.243     albertel 8820: cput($namespace,$storehash,$udom,$uname) : critical put
                   8821: ($udom and $uname are optional)
1.191     harris41 8822: 
                   8823: =item *
                   8824: 
1.748     albertel 8825: newput($namespace,$storehash,$udom,$uname) :
                   8826: 
                   8827: Attempts to store the items in the $storehash, but only if they don't
                   8828: currently exist, if this succeeds you can be certain that you have 
                   8829: successfully created a new key value pair in the $namespace db.
                   8830: 
                   8831: 
                   8832: Args:
                   8833:  $namespace: name of database to store values to
                   8834:  $storehash: hashref to store to the db
                   8835:  $udom: (optional) domain of user containing the db
                   8836:  $uname: (optional) name of user caontaining the db
                   8837: 
                   8838: Returns:
                   8839:  'ok' -> succeeded in storing all keys of $storehash
                   8840:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   8841:                         least <key> already existed in the db (other
                   8842:                         requested keys may also already exist)
                   8843:  'error: <msg>' -> unable to tie the DB or other erorr occured
                   8844:  'con_lost' -> unable to contact request server
                   8845:  'refused' -> action was not allowed by remote machine
                   8846: 
                   8847: 
                   8848: =item *
                   8849: 
1.243     albertel 8850: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   8851: reference filled in from namesp (encrypts the return communication)
                   8852: ($udom and $uname are optional)
1.191     harris41 8853: 
                   8854: =item *
                   8855: 
1.243     albertel 8856: log($udom,$name,$home,$message) : write to permanent log for user; use
                   8857: critical subroutine
                   8858: 
1.806     raeburn  8859: =item *
                   8860: 
1.860     raeburn  8861: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   8862: array reference filled in from namespace found in domain level on either
                   8863: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  8864: 
                   8865: =item *
                   8866: 
1.860     raeburn  8867: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   8868: domain level either on specified domain server ($uhome) or primary domain 
                   8869: server ($udom and $uhome are optional)
1.806     raeburn  8870: 
1.243     albertel 8871: =back
                   8872: 
                   8873: =head2 Network Status Functions
                   8874: 
                   8875: =over 4
1.191     harris41 8876: 
                   8877: =item *
                   8878: 
                   8879: dirlist($uri) : return directory list based on URI
                   8880: 
                   8881: =item *
                   8882: 
1.243     albertel 8883: spareserver() : find server with least workload from spare.tab
                   8884: 
                   8885: =back
                   8886: 
                   8887: =head2 Apache Request
                   8888: 
                   8889: =over 4
1.191     harris41 8890: 
                   8891: =item *
                   8892: 
1.243     albertel 8893: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   8894: localhost, posts hash
                   8895: 
                   8896: =back
                   8897: 
                   8898: =head2 Data to String to Data
                   8899: 
                   8900: =over 4
1.191     harris41 8901: 
                   8902: =item *
                   8903: 
1.243     albertel 8904: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   8905: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 8906: 
                   8907: =item *
                   8908: 
1.243     albertel 8909: hashref2str($hashref) : convert a hashref into a string complete with
                   8910: escaping and '=' and '&' separators, supports elements that are
                   8911: arrayrefs and hashrefs
1.191     harris41 8912: 
                   8913: =item *
                   8914: 
1.243     albertel 8915: arrayref2str($arrayref) : convert an arrayref into a string complete
                   8916: with escaping and '&' separators, supports elements that are arrayrefs
                   8917: and hashrefs
1.191     harris41 8918: 
                   8919: =item *
                   8920: 
1.243     albertel 8921: str2hash($string) : convert string to hash using unescaping and
                   8922: splitting on '=' and '&', supports elements that are arrayrefs and
                   8923: hashrefs
1.191     harris41 8924: 
                   8925: =item *
                   8926: 
1.243     albertel 8927: str2array($string) : convert string to hash using unescaping and
                   8928: splitting on '&', supports elements that are arrayrefs and hashrefs
                   8929: 
                   8930: =back
                   8931: 
                   8932: =head2 Logging Routines
                   8933: 
                   8934: =over 4
                   8935: 
                   8936: These routines allow one to make log messages in the lonnet.log and
                   8937: lonnet.perm logfiles.
1.191     harris41 8938: 
                   8939: =item *
                   8940: 
1.243     albertel 8941: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 8942: 
                   8943: =item *
                   8944: 
1.243     albertel 8945: logthis() : append message to the normal lonnet.log file, it gets
                   8946: preiodically rolled over and deleted.
1.191     harris41 8947: 
                   8948: =item *
                   8949: 
1.243     albertel 8950: logperm() : append a permanent message to lonnet.perm.log, this log
                   8951: file never gets deleted by any automated portion of the system, only
                   8952: messages of critical importance should go in here.
                   8953: 
                   8954: =back
                   8955: 
                   8956: =head2 General File Helper Routines
                   8957: 
                   8958: =over 4
1.191     harris41 8959: 
                   8960: =item *
                   8961: 
1.481     raeburn  8962: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   8963: (a) files in /uploaded
                   8964:   (i) If a local copy of the file exists - 
                   8965:       compares modification date of local copy with last-modified date for 
                   8966:       definitive version stored on home server for course. If local copy is 
                   8967:       stale, requests a new version from the home server and stores it. 
                   8968:       If the original has been removed from the home server, then local copy 
                   8969:       is unlinked.
                   8970:   (ii) If local copy does not exist -
                   8971:       requests the file from the home server and stores it. 
                   8972:   
                   8973:   If $caller is 'uploadrep':  
                   8974:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   8975:     for request for files originally uploaded via DOCS. 
                   8976:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   8977:   
                   8978:   Otherwise:
                   8979:      This indicates a call from the content generation phase of the request.
                   8980:      -  returns the entire contents of the file or -1.
                   8981:      
                   8982: (b) files in /res
                   8983:    - returns the entire contents of a file or -1; 
                   8984:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 8985: 
1.712     albertel 8986: 
                   8987: =item *
                   8988: 
                   8989: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   8990:                   reference
                   8991: 
                   8992: returns either a stat() list of data about the file or an empty list
                   8993: if the file doesn't exist or couldn't find out about it (connection
                   8994: problems or user unknown)
                   8995: 
1.191     harris41 8996: =item *
                   8997: 
1.243     albertel 8998: filelocation($dir,$file) : returns file system location of a file
                   8999: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   9000: directory that relative $file lookups are to looked in ($dir of /a/dir
                   9001: and a file of ../bob will become /a/bob)
1.191     harris41 9002: 
                   9003: =item *
                   9004: 
                   9005: hreflocation($dir,$file) : returns file system location or a URL; same as
                   9006: filelocation except for hrefs
                   9007: 
                   9008: =item *
                   9009: 
                   9010: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   9011: 
1.243     albertel 9012: =back
                   9013: 
1.608     albertel 9014: =head2 Usererfile file routines (/uploaded*)
                   9015: 
                   9016: =over 4
                   9017: 
                   9018: =item *
                   9019: 
                   9020: userfileupload(): main rotine for putting a file in a user or course's
                   9021:                   filespace, arguments are,
                   9022: 
1.620     albertel 9023:  formname - required - this is the name of the element in $env where the
1.608     albertel 9024:            filename, and the contents of the file to create/modifed exist
1.620     albertel 9025:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   9026:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 9027:  coursedoc - if true, store the file in the course of the active role
                   9028:              of the current user
                   9029:  subdir - required - subdirectory to put the file in under ../userfiles/
                   9030:          if undefined, it will be placed in "unknown"
                   9031: 
                   9032:  (This routine calls clean_filename() to remove any dangerous
                   9033:  characters from the filename, and then calls finuserfileupload() to
                   9034:  complete the transaction)
                   9035: 
                   9036:  returns either the url of the uploaded file (/uploaded/....) if successful
                   9037:  and /adm/notfound.html if unsuccessful
                   9038: 
                   9039: =item *
                   9040: 
                   9041: clean_filename(): routine for cleaing a filename up for storage in
                   9042:                  userfile space, argument is:
                   9043: 
                   9044:  filename - proposed filename
                   9045: 
                   9046: returns: the new clean filename
                   9047: 
                   9048: =item *
                   9049: 
                   9050: finishuserfileupload(): routine that creaes and sends the file to
                   9051: userspace, probably shouldn't be called directly
                   9052: 
                   9053:   docuname: username or courseid of destination for the file
                   9054:   docudom: domain of user/course of destination for the file
                   9055:   formname: same as for userfileupload()
                   9056:   fname: filename (inculding subdirectories) for the file
                   9057: 
                   9058:  returns either the url of the uploaded file (/uploaded/....) if successful
                   9059:  and /adm/notfound.html if unsuccessful
                   9060: 
                   9061: =item *
                   9062: 
                   9063: renameuserfile(): renames an existing userfile to a new name
                   9064: 
                   9065:   Args:
                   9066:    docuname: username or courseid of destination for the file
                   9067:    docudom: domain of user/course of destination for the file
                   9068:    old: current file name (including any subdirs under userfiles)
                   9069:    new: desired file name (including any subdirs under userfiles)
                   9070: 
                   9071: =item *
                   9072: 
                   9073: mkdiruserfile(): creates a directory is a userfiles dir
                   9074: 
                   9075:   Args:
                   9076:    docuname: username or courseid of destination for the file
                   9077:    docudom: domain of user/course of destination for the file
                   9078:    dir: dir to create (including any subdirs under userfiles)
                   9079: 
                   9080: =item *
                   9081: 
                   9082: removeuserfile(): removes a file that exists in userfiles
                   9083: 
                   9084:   Args:
                   9085:    docuname: username or courseid of destination for the file
                   9086:    docudom: domain of user/course of destination for the file
                   9087:    fname: filname to delete (including any subdirs under userfiles)
                   9088: 
                   9089: =item *
                   9090: 
                   9091: removeuploadedurl(): convience function for removeuserfile()
                   9092: 
                   9093:   Args:
                   9094:    url:  a full /uploaded/... url to delete
                   9095: 
1.747     albertel 9096: =item * 
                   9097: 
                   9098: get_portfile_permissions():
                   9099:   Args:
                   9100:     domain: domain of user or course contain the portfolio files
                   9101:     user: name of user or num of course contain the portfolio files
                   9102:   Returns:
                   9103:     hashref of a dump of the proper file_permissions.db
                   9104:    
                   9105: 
                   9106: =item * 
                   9107: 
                   9108: get_access_controls():
                   9109: 
                   9110: Args:
                   9111:   current_permissions: the hash ref returned from get_portfile_permissions()
                   9112:   group: (optional) the group you want the files associated with
                   9113:   file: (optional) the file you want access info on
                   9114: 
                   9115: Returns:
1.749     raeburn  9116:     a hash (keys are file names) of hashes containing
                   9117:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   9118:         values are XML containing access control settings (see below) 
1.747     albertel 9119: 
                   9120: Internal notes:
                   9121: 
1.749     raeburn  9122:  access controls are stored in file_permissions.db as key=value pairs.
                   9123:     key -> path to file/file_name\0uniqueID:scope_end_start
                   9124:         where scope -> public,guest,course,group,domains or users.
                   9125:               end -> UNIX time for end of access (0 -> no end date)
                   9126:               start -> UNIX time for start of access
                   9127: 
                   9128:     value -> XML description of access control
                   9129:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   9130:             <start></start>
                   9131:             <end></end>
                   9132: 
                   9133:             <password></password>  for scope type = guest
                   9134: 
                   9135:             <domain></domain>     for scope type = course or group
                   9136:             <number></number>
                   9137:             <roles id="">
                   9138:              <role></role>
                   9139:              <access></access>
                   9140:              <section></section>
                   9141:              <group></group>
                   9142:             </roles>
                   9143: 
                   9144:             <dom></dom>         for scope type = domains
                   9145: 
                   9146:             <users>             for scope type = users
                   9147:              <user>
                   9148:               <uname></uname>
                   9149:               <udom></udom>
                   9150:              </user>
                   9151:             </users>
                   9152:            </scope> 
                   9153:               
                   9154:  Access data is also aggregated for each file in an additional key=value pair:
                   9155:  key -> path to file/file_name\0accesscontrol 
                   9156:  value -> reference to hash
                   9157:           hash contains key = value pairs
                   9158:           where key = uniqueID:scope_end_start
                   9159:                 value = UNIX time record was last updated
                   9160: 
                   9161:           Used to improve speed of look-ups of access controls for each file.  
                   9162:  
                   9163:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   9164: 
                   9165: modify_access_controls():
                   9166: 
                   9167: Modifies access controls for a portfolio file
                   9168: Args
                   9169: 1. file name
                   9170: 2. reference to hash of required changes,
                   9171: 3. domain
                   9172: 4. username
                   9173:   where domain,username are the domain of the portfolio owner 
                   9174:   (either a user or a course) 
                   9175: 
                   9176: Returns:
                   9177: 1. result of additions or updates ('ok' or 'error', with error message). 
                   9178: 2. result of deletions ('ok' or 'error', with error message).
                   9179: 3. reference to hash of any new or updated access controls.
                   9180: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   9181:    key = integer (inbound ID)
                   9182:    value = uniqueID  
1.747     albertel 9183: 
1.608     albertel 9184: =back
                   9185: 
1.243     albertel 9186: =head2 HTTP Helper Routines
                   9187: 
                   9188: =over 4
                   9189: 
1.191     harris41 9190: =item *
                   9191: 
                   9192: escape() : unpack non-word characters into CGI-compatible hex codes
                   9193: 
                   9194: =item *
                   9195: 
                   9196: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   9197: 
1.243     albertel 9198: =back
                   9199: 
                   9200: =head1 PRIVATE SUBROUTINES
                   9201: 
                   9202: =head2 Underlying communication routines (Shouldn't call)
                   9203: 
                   9204: =over 4
                   9205: 
                   9206: =item *
                   9207: 
                   9208: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   9209: 
                   9210: =item *
                   9211: 
                   9212: reply() : uses subreply to send a message to remote machine, logs all failures
                   9213: 
                   9214: =item *
                   9215: 
                   9216: critical() : passes a critical message to another server; if cannot
                   9217: get through then place message in connection buffer directory and
                   9218: returns con_delayed, if incapable of saving message, returns
                   9219: con_failed
                   9220: 
                   9221: =item *
                   9222: 
                   9223: reconlonc() : tries to reconnect lonc client processes.
                   9224: 
                   9225: =back
                   9226: 
                   9227: =head2 Resource Access Logging
                   9228: 
                   9229: =over 4
                   9230: 
                   9231: =item *
                   9232: 
                   9233: flushcourselogs() : flush (save) buffer logs and access logs
                   9234: 
                   9235: =item *
                   9236: 
                   9237: courselog($what) : save message for course in hash
                   9238: 
                   9239: =item *
                   9240: 
                   9241: courseacclog($what) : save message for course using &courselog().  Perform
                   9242: special processing for specific resource types (problems, exams, quizzes, etc).
                   9243: 
1.191     harris41 9244: =item *
                   9245: 
                   9246: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   9247: as a PerlChildExitHandler
1.243     albertel 9248: 
                   9249: =back
                   9250: 
                   9251: =head2 Other
                   9252: 
                   9253: =over 4
                   9254: 
                   9255: =item *
                   9256: 
                   9257: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 9258: 
                   9259: =back
                   9260: 
                   9261: =cut
1.877     foxr     9262: 

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