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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.854   ! albertel    4: # $Id: lonnet.pm,v 1.853 2007/03/28 20:28:31 albertel Exp $
1.178     www         5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.169     harris41   28: ###
                     29: 
1.1       albertel   30: package Apache::lonnet;
                     31: 
                     32: use strict;
1.8       www        33: use LWP::UserAgent();
1.15      www        34: use HTTP::Headers;
1.486     www        35: use HTTP::Date;
                     36: # use Date::Parse;
1.11      www        37: use vars 
1.847     albertel   38: qw(%perlvar %badServerCache %spareid 
1.845     albertel   39:    %pr %prp $memcache %packagetab 
1.662     raeburn    40:    %courselogs %accesshash %userrolehash %domainrolehash $processmarker $dumpcount 
1.741     raeburn    41:    %coursedombuf %coursenumbuf %coursehombuf %coursedescrbuf %courseinstcodebuf %courseownerbuf %coursetypebuf
1.685     raeburn    42:    $tmpdir $_64bit %env);
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.637     raeburn    47: use HTML::Parser;
1.88      www        48: use Fcntl qw(:flock);
1.557     albertel   49: use Storable qw(lock_store lock_nstore lock_retrieve freeze thaw nfreeze);
1.539     albertel   50: use Time::HiRes qw( gettimeofday tv_interval );
1.599     albertel   51: use Cache::Memcached;
1.676     albertel   52: use Digest::MD5;
1.790     albertel   53: use Math::Random;
1.807     albertel   54: use LONCAPA qw(:DEFAULT :match);
1.740     www        55: use LONCAPA::Configuration;
1.854   ! albertel   56: use Apache::lonhosts;
1.676     albertel   57: 
1.195     www        58: my $readit;
1.550     foxr       59: my $max_connection_retries = 10;     # Or some such value.
1.1       albertel   60: 
1.619     albertel   61: require Exporter;
                     62: 
                     63: our @ISA = qw (Exporter);
                     64: our @EXPORT = qw(%env);
                     65: 
1.449     matthew    66: =pod
                     67: 
                     68: =head1 Package Variables
                     69: 
                     70: These are largely undocumented, so if you decipher one please note it here.
                     71: 
                     72: =over 4
                     73: 
                     74: =item $processmarker
                     75: 
                     76: Contains the time this process was started and this servers host id.
                     77: 
                     78: =item $dumpcount
                     79: 
                     80: Counts the number of times a message log flush has been attempted (regardless
                     81: of success) by this process.  Used as part of the filename when messages are
                     82: delayed.
                     83: 
                     84: =back
                     85: 
                     86: =cut
                     87: 
                     88: 
1.1       albertel   89: # --------------------------------------------------------------------- Logging
1.729     www        90: {
                     91:     my $logid;
                     92:     sub instructor_log {
                     93: 	my ($hash_name,$storehash,$delflag,$uname,$udom)=@_;
                     94: 	$logid++;
                     95: 	my $id=time().'00000'.$$.'00000'.$logid;
                     96: 	return &Apache::lonnet::put('nohist_'.$hash_name,
1.730     www        97: 				    { $id => {
                     98: 					'exe_uname' => $env{'user.name'},
                     99: 					'exe_udom'  => $env{'user.domain'},
                    100: 					'exe_time'  => time(),
                    101: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    102: 					'delflag'   => $delflag,
                    103: 					'logentry'  => $storehash,
                    104: 					'uname'     => $uname,
                    105: 					'udom'      => $udom,
                    106: 				    }
                    107: 				  },
1.729     www       108: 				    $env{'course.'.$env{'request.course.id'}.'.domain'},
                    109: 				    $env{'course.'.$env{'request.course.id'}.'.num'}
                    110: 				    );
                    111:     }
                    112: }
1.1       albertel  113: 
1.163     harris41  114: sub logtouch {
                    115:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  116:     unless (-e "$execdir/logs/lonnet.log") {	
                    117: 	open(my $fh,">>$execdir/logs/lonnet.log");
1.163     harris41  118: 	close $fh;
                    119:     }
                    120:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    121:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    122: }
                    123: 
1.1       albertel  124: sub logthis {
                    125:     my $message=shift;
                    126:     my $execdir=$perlvar{'lonDaemons'};
                    127:     my $now=time;
                    128:     my $local=localtime($now);
1.448     albertel  129:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
                    130: 	print $fh "$local ($$): $message\n";
                    131: 	close($fh);
                    132:     }
1.1       albertel  133:     return 1;
                    134: }
                    135: 
                    136: sub logperm {
                    137:     my $message=shift;
                    138:     my $execdir=$perlvar{'lonDaemons'};
                    139:     my $now=time;
                    140:     my $local=localtime($now);
1.448     albertel  141:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
                    142: 	print $fh "$now:$message:$local\n";
                    143: 	close($fh);
                    144:     }
1.1       albertel  145:     return 1;
                    146: }
                    147: 
1.850     albertel  148: sub create_connection {
1.853     albertel  149:     my ($hostname,$lonid) = @_;
1.851     albertel  150:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
1.850     albertel  151: 				     Type    => SOCK_STREAM,
                    152: 				     Timeout => 10);
                    153:     return 0 if (!$client);
1.854   ! albertel  154:     print $client (join(':',$hostname,$lonid,&machine_ids($lonid))."\n");
1.850     albertel  155:     my $result = <$client>;
                    156:     chomp($result);
                    157:     return 1 if ($result eq 'done');
                    158:     return 0;
                    159: }
                    160: 
                    161: 
1.1       albertel  162: # -------------------------------------------------- Non-critical communication
                    163: sub subreply {
                    164:     my ($cmd,$server)=@_;
1.838     albertel  165:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      166:     #
                    167:     #  With loncnew process trimming, there's a timing hole between lonc server
                    168:     #  process exit and the master server picking up the listen on the AF_UNIX
                    169:     #  socket.  In that time interval, a lock file will exist:
                    170: 
                    171:     my $lockfile=$peerfile.".lock";
                    172:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
                    173: 	sleep(1);
                    174:     }
                    175:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      176:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      177:     #
1.550     foxr      178:     #   We'll give the connection a few tries before abandoning it.  If
                    179:     #   connection is not possible, we'll con_lost back to the client.
                    180:     #   
                    181:     my $client;
                    182:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    183: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    184: 				      Type    => SOCK_STREAM,
                    185: 				      Timeout => 10);
                    186: 	if($client) {
                    187: 	    last;		# Connected!
1.850     albertel  188: 	} else {
1.853     albertel  189: 	    &create_connection(&hostname($server),$server);
1.550     foxr      190: 	}
1.850     albertel  191:         sleep(1);		# Try again later if failed connection.
1.550     foxr      192:     }
                    193:     my $answer;
                    194:     if ($client) {
1.704     albertel  195: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      196: 	$answer=<$client>;
                    197: 	if (!$answer) { $answer="con_lost"; }
                    198: 	chomp($answer);
                    199:     } else {
                    200: 	$answer = 'con_lost';	# Failed connection.
                    201:     }
1.1       albertel  202:     return $answer;
                    203: }
                    204: 
                    205: sub reply {
                    206:     my ($cmd,$server)=@_;
1.838     albertel  207:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  208:     my $answer=subreply($cmd,$server);
1.65      www       209:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  210:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       211:                 " $cmd to $server returned $answer</font>");
                    212:     }
1.1       albertel  213:     return $answer;
                    214: }
                    215: 
                    216: # ----------------------------------------------------------- Send USR1 to lonc
                    217: 
                    218: sub reconlonc {
1.836     www       219:     &logthis("Trying to reconnect lonc");
1.1       albertel  220:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  221:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  222: 	my $loncpid=<$fh>;
                    223:         chomp($loncpid);
                    224:         if (kill 0 => $loncpid) {
                    225: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    226:             kill USR1 => $loncpid;
                    227:             sleep 1;
1.836     www       228:          } else {
1.12      www       229: 	    &logthis(
1.672     albertel  230:                "<font color=\"blue\">WARNING:".
1.12      www       231:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  232:         }
                    233:     } else {
1.836     www       234: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  235:     }
                    236: }
                    237: 
                    238: # ------------------------------------------------------ Critical communication
1.12      www       239: 
1.1       albertel  240: sub critical {
                    241:     my ($cmd,$server)=@_;
1.838     albertel  242:     unless (&hostname($server)) {
1.672     albertel  243:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       244:                " Critical message to unknown server ($server)</font>");
                    245:         return 'no_such_host';
                    246:     }
1.1       albertel  247:     my $answer=reply($cmd,$server);
                    248:     if ($answer eq 'con_lost') {
                    249: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
1.589     albertel  250: 	my $answer=reply($cmd,$server);
1.1       albertel  251:         if ($answer eq 'con_lost') {
                    252:             my $now=time;
                    253:             my $middlename=$cmd;
1.5       www       254:             $middlename=substr($middlename,0,16);
1.1       albertel  255:             $middlename=~s/\W//g;
                    256:             my $dfilename=
1.305     www       257:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    258:             $dumpcount++;
1.1       albertel  259:             {
1.448     albertel  260: 		my $dfh;
                    261: 		if (open($dfh,">$dfilename")) {
                    262: 		    print $dfh "$cmd\n"; 
                    263: 		    close($dfh);
                    264: 		}
1.1       albertel  265:             }
                    266:             sleep 2;
                    267:             my $wcmd='';
                    268:             {
1.448     albertel  269: 		my $dfh;
                    270: 		if (open($dfh,"<$dfilename")) {
                    271: 		    $wcmd=<$dfh>; 
                    272: 		    close($dfh);
                    273: 		}
1.1       albertel  274:             }
                    275:             chomp($wcmd);
1.7       www       276:             if ($wcmd eq $cmd) {
1.672     albertel  277: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       278:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  279:                 &logperm("D:$server:$cmd");
                    280: 	        return 'con_delayed';
                    281:             } else {
1.672     albertel  282:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       283:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  284:                 &logperm("F:$server:$cmd");
                    285:                 return 'con_failed';
                    286:             }
                    287:         }
                    288:     }
                    289:     return $answer;
1.405     albertel  290: }
                    291: 
1.755     albertel  292: # ------------------------------------------- check if return value is an error
                    293: 
                    294: sub error {
                    295:     my ($result) = @_;
1.756     albertel  296:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  297: 	if ($2 == 2) { return undef; }
                    298: 	return $1;
                    299:     }
                    300:     return undef;
                    301: }
                    302: 
1.783     albertel  303: sub convert_and_load_session_env {
                    304:     my ($lonidsdir,$handle)=@_;
                    305:     my @profile;
                    306:     {
                    307: 	open(my $idf,"$lonidsdir/$handle.id");
                    308: 	flock($idf,LOCK_SH);
                    309: 	@profile=<$idf>;
                    310: 	close($idf);
                    311:     }
                    312:     my %temp_env;
                    313:     foreach my $line (@profile) {
1.786     albertel  314: 	if ($line !~ m/=/) {
                    315: 	    return 0;
                    316: 	}
1.783     albertel  317: 	chomp($line);
                    318: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    319: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    320:     }
                    321:     unlink("$lonidsdir/$handle.id");
                    322:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    323: 	    0640)) {
                    324: 	%disk_env = %temp_env;
                    325: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    326: 	untie(%disk_env);
                    327:     }
1.786     albertel  328:     return 1;
1.783     albertel  329: }
                    330: 
1.374     www       331: # ------------------------------------------- Transfer profile into environment
1.780     albertel  332: my $env_loaded;
                    333: sub transfer_profile_to_env {
1.788     albertel  334:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    335:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       336: 
1.720     albertel  337:     if (!defined($lonidsdir)) {
                    338: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    339:     }
                    340:     if (!defined($handle)) {
                    341:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    342:     }
                    343: 
1.786     albertel  344:     my $convert;
                    345:     {
                    346:     	open(my $idf,"$lonidsdir/$handle.id");
                    347: 	flock($idf,LOCK_SH);
                    348: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    349: 		&GDBM_READER(),0640)) {
                    350: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    351: 	    untie(%disk_env);
                    352: 	} else {
                    353: 	    $convert = 1;
                    354: 	}
                    355:     }
                    356:     if ($convert) {
                    357: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    358: 	    &logthis("Failed to load session, or convert session.");
                    359: 	}
1.374     www       360:     }
1.783     albertel  361: 
1.786     albertel  362:     my %remove;
1.783     albertel  363:     while ( my $envname = each(%env) ) {
1.433     matthew   364:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    365:             if ($time < time-300) {
1.783     albertel  366:                 $remove{$key}++;
1.433     matthew   367:             }
                    368:         }
                    369:     }
1.783     albertel  370: 
1.619     albertel  371:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  372:     $env_loaded=1;
1.783     albertel  373:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   374:         &delenv($expired_key);
1.374     www       375:     }
1.1       albertel  376: }
                    377: 
1.830     albertel  378: sub timed_flock {
                    379:     my ($file,$lock_type) = @_;
                    380:     my $failed=0;
                    381:     eval {
                    382: 	local $SIG{__DIE__}='DEFAULT';
                    383: 	local $SIG{ALRM}=sub {
                    384: 	    $failed=1;
                    385: 	    die("failed lock");
                    386: 	};
                    387: 	alarm(13);
                    388: 	flock($file,$lock_type);
                    389: 	alarm(0);
                    390:     };
                    391:     if ($failed) {
                    392: 	return undef;
                    393:     } else {
                    394: 	return 1;
                    395:     }
                    396: }
                    397: 
1.5       www       398: # ---------------------------------------------------------- Append Environment
                    399: 
                    400: sub appenv {
1.6       www       401:     my %newenv=@_;
1.692     albertel  402:     foreach my $key (keys(%newenv)) {
                    403: 	if (($newenv{$key}=~/^user\.role/) || ($newenv{$key}=~/^user\.priv/)) {
1.672     albertel  404:             &logthis("<font color=\"blue\">WARNING: ".
1.692     albertel  405:                 "Attempt to modify environment ".$key." to ".$newenv{$key}
1.151     www       406:                 .'</font>');
1.692     albertel  407: 	    delete($newenv{$key});
1.35      www       408:         } else {
1.692     albertel  409:             $env{$key}=$newenv{$key};
1.35      www       410:         }
1.191     harris41  411:     }
1.830     albertel  412:     open(my $env_file,$env{'user.environment'});
                    413:     if (&timed_flock($env_file,LOCK_EX)
                    414: 	&&
                    415: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    416: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  417: 	while (my ($key,$value) = each(%newenv)) {
                    418: 	    $disk_env{$key} = $value;
1.448     albertel  419: 	}
1.783     albertel  420: 	untie(%disk_env);
1.56      www       421:     }
                    422:     return 'ok';
                    423: }
                    424: # ----------------------------------------------------- Delete from Environment
                    425: 
                    426: sub delenv {
                    427:     my $delthis=shift;
                    428:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
1.672     albertel  429:         &logthis("<font color=\"blue\">WARNING: ".
1.56      www       430:                 "Attempt to delete from environment ".$delthis);
                    431:         return 'error';
                    432:     }
1.830     albertel  433:     open(my $env_file,$env{'user.environment'});
                    434:     if (&timed_flock($env_file,LOCK_EX)
                    435: 	&&
                    436: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    437: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  438: 	foreach my $key (keys(%disk_env)) {
                    439: 	    if ($key=~/^$delthis/) { 
1.619     albertel  440:                 delete($env{$key});
1.783     albertel  441:                 delete($disk_env{$key});
1.473     matthew   442:             }
1.448     albertel  443: 	}
1.783     albertel  444: 	untie(%disk_env);
1.5       www       445:     }
                    446:     return 'ok';
1.369     albertel  447: }
                    448: 
1.790     albertel  449: sub get_env_multiple {
                    450:     my ($name) = @_;
                    451:     my @values;
                    452:     if (defined($env{$name})) {
                    453:         # exists is it an array
                    454:         if (ref($env{$name})) {
                    455:             @values=@{ $env{$name} };
                    456:         } else {
                    457:             $values[0]=$env{$name};
                    458:         }
                    459:     }
                    460:     return(@values);
                    461: }
                    462: 
1.369     albertel  463: # ------------------------------------------ Find out current server userload
                    464: # there is a copy in lond
                    465: sub userload {
                    466:     my $numusers=0;
                    467:     {
                    468: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    469: 	my $filename;
                    470: 	my $curtime=time;
                    471: 	while ($filename=readdir(LONIDS)) {
                    472: 	    if ($filename eq '.' || $filename eq '..') {next;}
1.404     albertel  473: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  474: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  475: 	}
                    476: 	closedir(LONIDS);
                    477:     }
                    478:     my $userloadpercent=0;
                    479:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    480:     if ($maxuserload) {
1.371     albertel  481: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  482:     }
1.372     albertel  483:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  484:     return $userloadpercent;
1.283     www       485: }
                    486: 
                    487: # ------------------------------------------ Fight off request when overloaded
                    488: 
                    489: sub overloaderror {
                    490:     my ($r,$checkserver)=@_;
                    491:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
                    492:     my $loadavg;
                    493:     if ($checkserver eq $perlvar{'lonHostID'}) {
1.448     albertel  494:        open(my $loadfile,'/proc/loadavg');
1.283     www       495:        $loadavg=<$loadfile>;
                    496:        $loadavg =~ s/\s.*//g;
1.285     matthew   497:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
1.448     albertel  498:        close($loadfile);
1.283     www       499:     } else {
                    500:        $loadavg=&reply('load',$checkserver);
                    501:     }
1.285     matthew   502:     my $overload=$loadavg-100;
1.283     www       503:     if ($overload>0) {
1.285     matthew   504: 	$r->err_headers_out->{'Retry-After'}=$overload;
1.283     www       505:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
1.554     www       506:         return 413;
1.283     www       507:     }    
                    508:     return '';
1.5       www       509: }
1.1       albertel  510: 
                    511: # ------------------------------ Find server with least workload from spare.tab
1.11      www       512: 
1.1       albertel  513: sub spareserver {
1.670     albertel  514:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
1.784     albertel  515:     my $spare_server;
1.370     albertel  516:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  517:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    518:                                                      :  $userloadpercent;
                    519:     
                    520:     foreach my $try_server (@{ $spareid{'primary'} }) {
                    521: 	($spare_server, $lowest_load) =
                    522: 	    &compare_server_load($try_server, $spare_server, $lowest_load);
                    523:     }
                    524: 
                    525:     my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    526: 
                    527:     if (!$found_server) {
                    528: 	foreach my $try_server (@{ $spareid{'default'} }) {
                    529: 	    ($spare_server, $lowest_load) =
                    530: 		&compare_server_load($try_server, $spare_server, $lowest_load);
                    531: 	}
                    532:     }
                    533: 
                    534:     if (!$want_server_name) {
1.838     albertel  535: 	$spare_server="http://".&hostname($spare_server);
1.784     albertel  536:     }
                    537:     return $spare_server;
                    538: }
                    539: 
                    540: sub compare_server_load {
                    541:     my ($try_server, $spare_server, $lowest_load) = @_;
                    542: 
                    543:     my $loadans     = &reply('load',    $try_server);
                    544:     my $userloadans = &reply('userload',$try_server);
                    545: 
                    546:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
                    547: 	next; #didn't get a number from the server
                    548:     }
                    549: 
                    550:     my $load;
                    551:     if ($loadans =~ /\d/) {
                    552: 	if ($userloadans =~ /\d/) {
                    553: 	    #both are numbers, pick the bigger one
                    554: 	    $load = ($loadans > $userloadans) ? $loadans 
                    555: 		                              : $userloadans;
1.411     albertel  556: 	} else {
1.784     albertel  557: 	    $load = $loadans;
1.411     albertel  558: 	}
1.784     albertel  559:     } else {
                    560: 	$load = $userloadans;
                    561:     }
                    562: 
                    563:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    564: 	$spare_server = $try_server;
                    565: 	$lowest_load  = $load;
1.370     albertel  566:     }
1.784     albertel  567:     return ($spare_server,$lowest_load);
1.202     matthew   568: }
                    569: # --------------------------------------------- Try to change a user's password
                    570: 
                    571: sub changepass {
1.799     raeburn   572:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew   573:     $currentpass = &escape($currentpass);
                    574:     $newpass     = &escape($newpass);
1.799     raeburn   575:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context",
1.202     matthew   576: 		       $server);
                    577:     if (! $answer) {
                    578: 	&logthis("No reply on password change request to $server ".
                    579: 		 "by $uname in domain $udom.");
                    580:     } elsif ($answer =~ "^ok") {
                    581:         &logthis("$uname in $udom successfully changed their password ".
                    582: 		 "on $server.");
                    583:     } elsif ($answer =~ "^pwchange_failure") {
                    584: 	&logthis("$uname in $udom was unable to change their password ".
                    585: 		 "on $server.  The action was blocked by either lcpasswd ".
                    586: 		 "or pwchange");
                    587:     } elsif ($answer =~ "^non_authorized") {
                    588:         &logthis("$uname in $udom did not get their password correct when ".
                    589: 		 "attempting to change it on $server.");
                    590:     } elsif ($answer =~ "^auth_mode_error") {
                    591:         &logthis("$uname in $udom attempted to change their password despite ".
                    592: 		 "not being locally or internally authenticated on $server.");
                    593:     } elsif ($answer =~ "^unknown_user") {
                    594:         &logthis("$uname in $udom attempted to change their password ".
                    595: 		 "on $server but were unable to because $server is not ".
                    596: 		 "their home server.");
                    597:     } elsif ($answer =~ "^refused") {
                    598: 	&logthis("$server refused to change $uname in $udom password because ".
                    599: 		 "it was sent an unencrypted request to change the password.");
                    600:     }
                    601:     return $answer;
1.1       albertel  602: }
                    603: 
1.169     harris41  604: # ----------------------- Try to determine user's current authentication scheme
                    605: 
                    606: sub queryauthenticate {
                    607:     my ($uname,$udom)=@_;
1.456     albertel  608:     my $uhome=&homeserver($uname,$udom);
                    609:     if (!$uhome) {
                    610: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                    611: 	return 'no_host';
                    612:     }
                    613:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                    614:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                    615: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41  616:     }
1.456     albertel  617:     return $answer;
1.169     harris41  618: }
                    619: 
1.1       albertel  620: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www       621: 
1.1       albertel  622: sub authenticate {
                    623:     my ($uname,$upass,$udom)=@_;
1.807     albertel  624:     $upass=&escape($upass);
                    625:     $uname= &LONCAPA::clean_username($uname);
1.836     www       626:     my $uhome=&homeserver($uname,$udom,1);
                    627:     if ((!$uhome) || ($uhome eq 'no_host')) {
                    628: # Maybe the machine was offline and only re-appeared again recently?
                    629:         &reconlonc();
                    630: # One more
                    631: 	my $uhome=&homeserver($uname,$udom,1);
                    632: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                    633: 	    &logthis("User $uname at $udom is unknown in authenticate");
                    634: 	}
1.471     albertel  635: 	return 'no_host';
1.1       albertel  636:     }
1.471     albertel  637:     my $answer=reply("encrypt:auth:$udom:$uname:$upass",$uhome);
                    638:     if ($answer eq 'authorized') {
                    639: 	&logthis("User $uname at $udom authorized by $uhome"); 
                    640: 	return $uhome; 
                    641:     }
                    642:     if ($answer eq 'non_authorized') {
                    643: 	&logthis("User $uname at $udom rejected by $uhome");
                    644: 	return 'no_host'; 
1.9       www       645:     }
1.471     albertel  646:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel  647:     return 'no_host';
                    648: }
                    649: 
                    650: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www       651: 
1.599     albertel  652: my %homecache;
1.1       albertel  653: sub homeserver {
1.230     stredwic  654:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel  655:     my $index="$uname:$udom";
1.426     albertel  656: 
1.599     albertel  657:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel  658: 
                    659:     my %servers = &get_servers($udom,'library');
                    660:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic  661:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic  662: 		 exists($badServerCache{$tryserver}));
1.841     albertel  663: 
                    664: 	my $answer=reply("home:$udom:$uname",$tryserver);
                    665: 	if ($answer eq 'found') {
                    666: 	    delete($badServerCache{$tryserver}); 
                    667: 	    return $homecache{$index}=$tryserver;
                    668: 	} elsif ($answer eq 'no_host') {
                    669: 	    $badServerCache{$tryserver}=1;
                    670: 	}
1.1       albertel  671:     }    
                    672:     return 'no_host';
1.70      www       673: }
                    674: 
                    675: # ------------------------------------- Find the usernames behind a list of IDs
                    676: 
                    677: sub idget {
                    678:     my ($udom,@ids)=@_;
                    679:     my %returnhash=();
                    680:     
1.841     albertel  681:     my %servers = &get_servers($udom,'library');
                    682:     foreach my $tryserver (keys(%servers)) {
                    683: 	my $idlist=join('&',@ids);
                    684: 	$idlist=~tr/A-Z/a-z/; 
                    685: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                    686: 	my @answer=();
                    687: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                    688: 	    @answer=split(/\&/,$reply);
                    689: 	}                    ;
                    690: 	my $i;
                    691: 	for ($i=0;$i<=$#ids;$i++) {
                    692: 	    if ($answer[$i]) {
                    693: 		$returnhash{$ids[$i]}=$answer[$i];
                    694: 	    } 
                    695: 	}
                    696:     } 
1.70      www       697:     return %returnhash;
                    698: }
                    699: 
                    700: # ------------------------------------- Find the IDs behind a list of usernames
                    701: 
                    702: sub idrget {
                    703:     my ($udom,@unames)=@_;
                    704:     my %returnhash=();
1.800     albertel  705:     foreach my $uname (@unames) {
                    706:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41  707:     }
1.70      www       708:     return %returnhash;
                    709: }
                    710: 
                    711: # ------------------------------- Store away a list of names and associated IDs
                    712: 
                    713: sub idput {
                    714:     my ($udom,%ids)=@_;
                    715:     my %servers=();
1.800     albertel  716:     foreach my $uname (keys(%ids)) {
                    717: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                    718:         my $uhom=&homeserver($uname,$udom);
1.70      www       719:         if ($uhom ne 'no_host') {
1.800     albertel  720:             my $id=&escape($ids{$uname});
1.70      www       721:             $id=~tr/A-Z/a-z/;
1.800     albertel  722:             my $esc_unam=&escape($uname);
1.70      www       723: 	    if ($servers{$uhom}) {
1.800     albertel  724: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www       725:             } else {
1.800     albertel  726:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www       727:             }
                    728:         }
1.191     harris41  729:     }
1.800     albertel  730:     foreach my $server (keys(%servers)) {
                    731:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41  732:     }
1.344     www       733: }
                    734: 
1.806     raeburn   735: # ------------------------------------------- get items from domain db files   
                    736: 
                    737: sub get_dom {
                    738:     my ($namespace,$storearr,$udom)=@_;
                    739:     my $items='';
                    740:     foreach my $item (@$storearr) {
                    741:         $items.=&escape($item).'&';
                    742:     }
                    743:     $items=~s/\&$//;
                    744:     if (!$udom) { $udom=$env{'user.domain'}; }
1.846     albertel  745:     if (defined(&domain($udom,'primary'))) {
                    746:         my $uhome=&domain($udom,'primary');
1.806     raeburn   747:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
                    748:         my @pairs=split(/\&/,$rep);
                    749:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                    750:             return @pairs;
                    751:         }
                    752:         my %returnhash=();
                    753:         my $i=0;
                    754:         foreach my $item (@$storearr) {
                    755:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                    756:             $i++;
                    757:         }
                    758:         return %returnhash;
                    759:     } else {
                    760:         &logthis("get_dom failed - no primary domain server for $udom");
                    761:     }
                    762: }
                    763: 
                    764: # -------------------------------------------- put items in domain db files 
                    765: 
                    766: sub put_dom {
                    767:     my ($namespace,$storehash,$udom)=@_;
                    768:     if (!$udom) { $udom=$env{'user.domain'}; }
1.846     albertel  769:     if (defined(&domain($udom,'primary'))) {
                    770:         my $uhome=&domain($udom,'primary');
1.806     raeburn   771:         my $items='';
                    772:         foreach my $item (keys(%$storehash)) {
                    773:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                    774:         }
                    775:         $items=~s/\&$//;
                    776:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                    777:     } else {
                    778:         &logthis("put_dom failed - no primary domain server for $udom");
                    779:     }
                    780: }
                    781: 
1.837     raeburn   782: sub retrieve_inst_usertypes {
                    783:     my ($udom) = @_;
                    784:     my (%returnhash,@order);
1.846     albertel  785:     if (defined(&domain($udom,'primary'))) {
                    786:         my $uhome=&domain($udom,'primary');
1.837     raeburn   787:         my $rep=&reply("inst_usertypes:$udom",$uhome);
                    788:         my ($hashitems,$orderitems) = split(/:/,$rep); 
                    789:         my @pairs=split(/\&/,$hashitems);
                    790:         foreach my $item (@pairs) {
                    791:             my ($key,$value)=split(/=/,$item,2);
                    792:             $key = &unescape($key);
                    793:             next if ($key =~ /^error: 2 /);
                    794:             $returnhash{$key}=&thaw_unescape($value);
                    795:         }
                    796:         my @esc_order = split(/\&/,$orderitems);
                    797:         foreach my $item (@esc_order) {
                    798:             push(@order,&unescape($item));
                    799:         }
                    800:     } else {
                    801:         &logthis("get_dom failed - no primary domain server for $udom");
                    802:     }
                    803:     return (\%returnhash,\@order);
                    804: }
                    805: 
1.344     www       806: # --------------------------------------------------- Assign a key to a student
                    807: 
                    808: sub assign_access_key {
1.364     www       809: #
                    810: # a valid key looks like uname:udom#comments
                    811: # comments are being appended
                    812: #
1.498     www       813:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                    814:     $kdom=
1.620     albertel  815:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www       816:     $knum=
1.620     albertel  817:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www       818:     $cdom=
1.620     albertel  819:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       820:     $cnum=
1.620     albertel  821:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                    822:     $udom=$env{'user.name'} unless (defined($udom));
                    823:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www       824:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www       825:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel  826:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www       827:                                                   # assigned to this person
                    828:                                                   # - this should not happen,
1.345     www       829:                                                   # unless something went wrong
                    830:                                                   # the first time around
                    831: # ready to assign
1.364     www       832:         $logentry=$1.'; '.$logentry;
1.496     www       833:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www       834:                                                  $kdom,$knum) eq 'ok') {
1.345     www       835: # key now belongs to user
1.346     www       836: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www       837:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
                    838:                 &appenv('environment.'.$envkey => $ckey);
                    839:                 return 'ok';
                    840:             } else {
                    841:                 return 
                    842:   'error: Count not permanently assign key, will need to be re-entered later.';
                    843: 	    }
                    844:         } else {
                    845:             return 'error: Could not assign key, try again later.';
                    846:         }
1.364     www       847:     } elsif (!$existing{$ckey}) {
1.345     www       848: # the key does not exist
                    849: 	return 'error: The key does not exist';
                    850:     } else {
                    851: # the key is somebody else's
                    852: 	return 'error: The key is already in use';
                    853:     }
1.344     www       854: }
                    855: 
1.364     www       856: # ------------------------------------------ put an additional comment on a key
                    857: 
                    858: sub comment_access_key {
                    859: #
                    860: # a valid key looks like uname:udom#comments
                    861: # comments are being appended
                    862: #
                    863:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                    864:     $cdom=
1.620     albertel  865:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www       866:     $cnum=
1.620     albertel  867:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www       868:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                    869:     if ($existing{$ckey}) {
                    870:         $existing{$ckey}.='; '.$logentry;
                    871: # ready to assign
1.367     www       872:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www       873:                                                  $cdom,$cnum) eq 'ok') {
                    874: 	    return 'ok';
                    875:         } else {
                    876: 	    return 'error: Count not store comment.';
                    877:         }
                    878:     } else {
                    879: # the key does not exist
                    880: 	return 'error: The key does not exist';
                    881:     }
                    882: }
                    883: 
1.344     www       884: # ------------------------------------------------------ Generate a set of keys
                    885: 
                    886: sub generate_access_keys {
1.364     www       887:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www       888:     $cdom=
1.620     albertel  889:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       890:     $cnum=
1.620     albertel  891:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www       892:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www       893:     unless (($cdom) && ($cnum)) { return 0; }
                    894:     if ($number>10000) { return 0; }
                    895:     sleep(2); # make sure don't get same seed twice
                    896:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                    897:     my $total=0;
                    898:     for (my $i=1;$i<=$number;$i++) {
                    899:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                    900:                   sprintf("%lx",int(100000*rand)).'-'.
                    901:                   sprintf("%lx",int(100000*rand));
                    902:        $newkey=~s/1/g/g; # folks mix up 1 and l
                    903:        $newkey=~s/0/h/g; # and also 0 and O
                    904:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                    905:        if ($existing{$newkey}) {
                    906:            $i--;
                    907:        } else {
1.364     www       908: 	  if (&put('accesskeys',
                    909:               { $newkey => '# generated '.localtime().
1.620     albertel  910:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www       911:                            '; '.$logentry },
                    912: 		   $cdom,$cnum) eq 'ok') {
1.344     www       913:               $total++;
                    914: 	  }
                    915:        }
                    916:     }
1.620     albertel  917:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www       918:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                    919:     return $total;
                    920: }
                    921: 
                    922: # ------------------------------------------------------- Validate an accesskey
                    923: 
                    924: sub validate_access_key {
                    925:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                    926:     $cdom=
1.620     albertel  927:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       928:     $cnum=
1.620     albertel  929:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                    930:     $udom=$env{'user.domain'} unless (defined($udom));
                    931:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www       932:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel  933:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www       934: }
                    935: 
                    936: # ------------------------------------- Find the section of student in a course
1.652     albertel  937: sub devalidate_getsection_cache {
                    938:     my ($udom,$unam,$courseid)=@_;
                    939:     my $hashid="$udom:$unam:$courseid";
                    940:     &devalidate_cache_new('getsection',$hashid);
                    941: }
1.298     matthew   942: 
1.815     albertel  943: sub courseid_to_courseurl {
                    944:     my ($courseid) = @_;
                    945:     #already url style courseid
                    946:     return $courseid if ($courseid =~ m{^/});
                    947: 
                    948:     if (exists($env{'course.'.$courseid.'.num'})) {
                    949: 	my $cnum = $env{'course.'.$courseid.'.num'};
                    950: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                    951: 	return "/$cdom/$cnum";
                    952:     }
                    953: 
                    954:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                    955:     if (exists($courseinfo{'num'})) {
                    956: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                    957:     }
                    958: 
                    959:     return undef;
                    960: }
                    961: 
1.298     matthew   962: sub getsection {
                    963:     my ($udom,$unam,$courseid)=@_;
1.599     albertel  964:     my $cachetime=1800;
1.551     albertel  965: 
                    966:     my $hashid="$udom:$unam:$courseid";
1.599     albertel  967:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel  968:     if (defined($cached)) { return $result; }
                    969: 
1.298     matthew   970:     my %Pending; 
                    971:     my %Expired;
                    972:     #
                    973:     # Each role can either have not started yet (pending), be active, 
                    974:     #    or have expired.
                    975:     #
                    976:     # If there is an active role, we are done.
                    977:     #
                    978:     # If there is more than one role which has not started yet, 
                    979:     #     choose the one which will start sooner
                    980:     # If there is one role which has not started yet, return it.
                    981:     #
                    982:     # If there is more than one expired role, choose the one which ended last.
                    983:     # If there is a role which has expired, return it.
                    984:     #
1.815     albertel  985:     $courseid = &courseid_to_courseurl($courseid);
1.817     raeburn   986:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
                    987:     foreach my $key (keys(%roleshash)) {
1.479     albertel  988:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew   989:         my $section=$1;
                    990:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn   991:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew   992:         my $now=time;
1.548     albertel  993:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew   994:             $Expired{$end}=$section;
                    995:             next;
                    996:         }
1.548     albertel  997:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew   998:             $Pending{$start}=$section;
                    999:             next;
                   1000:         }
1.599     albertel 1001:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  1002:     }
                   1003:     #
                   1004:     # Presumedly there will be few matching roles from the above
                   1005:     # loop and the sorting time will be negligible.
                   1006:     if (scalar(keys(%Pending))) {
                   1007:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 1008:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  1009:     } 
                   1010:     if (scalar(keys(%Expired))) {
                   1011:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   1012:         my $time = pop(@sorted);
1.599     albertel 1013:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  1014:     }
1.599     albertel 1015:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  1016: }
1.70      www      1017: 
1.599     albertel 1018: sub save_cache {
                   1019:     &purge_remembered();
1.722     albertel 1020:     #&Apache::loncommon::validate_page();
1.620     albertel 1021:     undef(%env);
1.780     albertel 1022:     undef($env_loaded);
1.599     albertel 1023: }
1.452     albertel 1024: 
1.599     albertel 1025: my $to_remember=-1;
                   1026: my %remembered;
                   1027: my %accessed;
                   1028: my $kicks=0;
                   1029: my $hits=0;
1.849     albertel 1030: sub make_key {
                   1031:     my ($name,$id) = @_;
                   1032:     if (length($id) > 200) { $id=length($id).':'.&Digest::MD5::md5_hex($id); }
                   1033:     return &escape($name.':'.$id);
                   1034: }
                   1035: 
1.599     albertel 1036: sub devalidate_cache_new {
                   1037:     my ($name,$id,$debug) = @_;
                   1038:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 1039:     $id=&make_key($name,$id);
1.599     albertel 1040:     $memcache->delete($id);
                   1041:     delete($remembered{$id});
                   1042:     delete($accessed{$id});
                   1043: }
                   1044: 
                   1045: sub is_cached_new {
                   1046:     my ($name,$id,$debug) = @_;
1.849     albertel 1047:     $id=&make_key($name,$id);
1.599     albertel 1048:     if (exists($remembered{$id})) {
                   1049: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                   1050: 	$accessed{$id}=[&gettimeofday()];
                   1051: 	$hits++;
                   1052: 	return ($remembered{$id},1);
                   1053:     }
                   1054:     my $value = $memcache->get($id);
                   1055:     if (!(defined($value))) {
                   1056: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 1057: 	return (undef,undef);
1.416     albertel 1058:     }
1.599     albertel 1059:     if ($value eq '__undef__') {
                   1060: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   1061: 	$value=undef;
                   1062:     }
                   1063:     &make_room($id,$value,$debug);
                   1064:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   1065:     return ($value,1);
                   1066: }
                   1067: 
                   1068: sub do_cache_new {
                   1069:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 1070:     $id=&make_key($name,$id);
1.599     albertel 1071:     my $setvalue=$value;
                   1072:     if (!defined($setvalue)) {
                   1073: 	$setvalue='__undef__';
                   1074:     }
1.623     albertel 1075:     if (!defined($time) ) {
                   1076: 	$time=600;
                   1077:     }
1.599     albertel 1078:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.600     albertel 1079:     $memcache->set($id,$setvalue,$time);
                   1080:     # need to make a copy of $value
                   1081:     #&make_room($id,$value,$debug);
1.599     albertel 1082:     return $value;
                   1083: }
                   1084: 
                   1085: sub make_room {
                   1086:     my ($id,$value,$debug)=@_;
                   1087:     $remembered{$id}=$value;
                   1088:     if ($to_remember<0) { return; }
                   1089:     $accessed{$id}=[&gettimeofday()];
                   1090:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   1091:     my $to_kick;
                   1092:     my $max_time=0;
                   1093:     foreach my $other (keys(%accessed)) {
                   1094: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   1095: 	    $to_kick=$other;
                   1096: 	    $max_time=&tv_interval($accessed{$other});
                   1097: 	}
                   1098:     }
                   1099:     delete($remembered{$to_kick});
                   1100:     delete($accessed{$to_kick});
                   1101:     $kicks++;
                   1102:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 1103:     return;
                   1104: }
                   1105: 
1.599     albertel 1106: sub purge_remembered {
1.604     albertel 1107:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   1108:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 1109:     undef(%remembered);
                   1110:     undef(%accessed);
1.428     albertel 1111: }
1.70      www      1112: # ------------------------------------- Read an entry from a user's environment
                   1113: 
                   1114: sub userenvironment {
                   1115:     my ($udom,$unam,@what)=@_;
                   1116:     my %returnhash=();
                   1117:     my @answer=split(/\&/,
                   1118:                 &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
                   1119:                       &homeserver($unam,$udom)));
                   1120:     my $i;
                   1121:     for ($i=0;$i<=$#what;$i++) {
                   1122: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
                   1123:     }
                   1124:     return %returnhash;
1.1       albertel 1125: }
                   1126: 
1.617     albertel 1127: # ---------------------------------------------------------- Get a studentphoto
                   1128: sub studentphoto {
                   1129:     my ($udom,$unam,$ext) = @_;
                   1130:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  1131:     if (defined($env{'request.course.id'})) {
1.708     raeburn  1132:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  1133:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   1134:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   1135:             } else {
                   1136:                 my ($result,$perm_reqd)=
1.707     albertel 1137: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1138:                 if ($result eq 'ok') {
                   1139:                     if (!($perm_reqd eq 'yes')) {
                   1140:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   1141:                     }
                   1142:                 }
                   1143:             }
                   1144:         }
                   1145:     } else {
                   1146:         my ($result,$perm_reqd) = 
1.707     albertel 1147: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1148:         if ($result eq 'ok') {
                   1149:             if (!($perm_reqd eq 'yes')) {
                   1150:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   1151:             }
                   1152:         }
                   1153:     }
                   1154:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   1155: }
                   1156: 
                   1157: sub retrievestudentphoto {
                   1158:     my ($udom,$unam,$ext,$type) = @_;
                   1159:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   1160:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   1161:     if ($ret eq 'ok') {
                   1162:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   1163:         if ($type eq 'thumbnail') {
                   1164:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   1165:         }
                   1166:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   1167:         return $tokenurl;
                   1168:     } else {
                   1169:         if ($type eq 'thumbnail') {
                   1170:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   1171:         } else { 
                   1172:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   1173:         }
1.617     albertel 1174:     }
                   1175: }
                   1176: 
1.263     www      1177: # -------------------------------------------------------------------- New chat
                   1178: 
                   1179: sub chatsend {
1.724     raeburn  1180:     my ($newentry,$anon,$group)=@_;
1.620     albertel 1181:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1182:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1183:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      1184:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 1185: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  1186: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      1187: }
                   1188: 
                   1189: # ------------------------------------------ Find current version of a resource
                   1190: 
                   1191: sub getversion {
                   1192:     my $fname=&clutter(shift);
                   1193:     unless ($fname=~/^\/res\//) { return -1; }
                   1194:     return &currentversion(&filelocation('',$fname));
                   1195: }
                   1196: 
                   1197: sub currentversion {
                   1198:     my $fname=shift;
1.599     albertel 1199:     my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440     www      1200:     if (defined($cached)) { return $result; }
1.292     www      1201:     my $author=$fname;
                   1202:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1203:     my ($udom,$uname)=split(/\//,$author);
                   1204:     my $home=homeserver($uname,$udom);
                   1205:     if ($home eq 'no_host') { 
                   1206:         return -1; 
                   1207:     }
                   1208:     my $answer=reply("currentversion:$fname",$home);
                   1209:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1210: 	return -1;
                   1211:     }
1.599     albertel 1212:     return &do_cache_new('resversion',$fname,$answer,600);
1.263     www      1213: }
                   1214: 
1.1       albertel 1215: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      1216: 
1.1       albertel 1217: sub subscribe {
                   1218:     my $fname=shift;
1.761     raeburn  1219:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 1220:     $fname=~s/[\n\r]//g;
1.1       albertel 1221:     my $author=$fname;
                   1222:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1223:     my ($udom,$uname)=split(/\//,$author);
                   1224:     my $home=homeserver($uname,$udom);
1.335     albertel 1225:     if ($home eq 'no_host') {
                   1226:         return 'not_found';
1.1       albertel 1227:     }
                   1228:     my $answer=reply("sub:$fname",$home);
1.64      www      1229:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1230: 	$answer.=' by '.$home;
                   1231:     }
1.1       albertel 1232:     return $answer;
                   1233: }
                   1234:     
1.8       www      1235: # -------------------------------------------------------------- Replicate file
                   1236: 
                   1237: sub repcopy {
                   1238:     my $filename=shift;
1.23      www      1239:     $filename=~s/\/+/\//g;
1.607     raeburn  1240:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   1241:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 1242:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 1243: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 1244: 	return &repcopy_userfile($filename);
                   1245:     }
1.532     albertel 1246:     $filename=~s/[\n\r]//g;
1.8       www      1247:     my $transname="$filename.in.transfer";
1.828     www      1248: # FIXME: this should flock
1.607     raeburn  1249:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      1250:     my $remoteurl=subscribe($filename);
1.64      www      1251:     if ($remoteurl =~ /^con_lost by/) {
                   1252: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1253:            return 'unavailable';
1.8       www      1254:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 1255: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  1256: 	   return 'not_found';
1.64      www      1257:     } elsif ($remoteurl =~ /^rejected by/) {
                   1258: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1259:            return 'forbidden';
1.20      www      1260:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  1261:            return 'ok';
1.8       www      1262:     } else {
1.290     www      1263:         my $author=$filename;
                   1264:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1265:         my ($udom,$uname)=split(/\//,$author);
                   1266:         my $home=homeserver($uname,$udom);
                   1267:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      1268:            my @parts=split(/\//,$filename);
                   1269:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   1270:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   1271:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  1272: 	       return 'bad_request';
1.8       www      1273:            }
                   1274:            my $count;
                   1275:            for ($count=5;$count<$#parts;$count++) {
                   1276:                $path.="/$parts[$count]";
                   1277:                if ((-e $path)!=1) {
                   1278: 		   mkdir($path,0777);
                   1279:                }
                   1280:            }
                   1281:            my $ua=new LWP::UserAgent;
                   1282:            my $request=new HTTP::Request('GET',"$remoteurl");
                   1283:            my $response=$ua->request($request,$transname);
                   1284:            if ($response->is_error()) {
                   1285: 	       unlink($transname);
                   1286:                my $message=$response->status_line;
1.672     albertel 1287:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      1288:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  1289:                return 'unavailable';
1.8       www      1290:            } else {
1.16      www      1291: 	       if ($remoteurl!~/\.meta$/) {
                   1292:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   1293:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   1294:                   if ($mresponse->is_error()) {
                   1295: 		      unlink($filename.'.meta');
                   1296:                       &logthis(
1.672     albertel 1297:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      1298:                   }
                   1299: 	       }
1.8       www      1300:                rename($transname,$filename);
1.607     raeburn  1301:                return 'ok';
1.8       www      1302:            }
1.290     www      1303:        }
1.8       www      1304:     }
1.330     www      1305: }
                   1306: 
                   1307: # ------------------------------------------------ Get server side include body
                   1308: sub ssi_body {
1.381     albertel 1309:     my ($filelink,%form)=@_;
1.606     matthew  1310:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   1311:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   1312:     }
1.330     www      1313:     my $output=($filelink=~/^http\:/?&externalssi($filelink):
1.381     albertel 1314:                                      &ssi($filelink,%form));
1.778     albertel 1315:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 1316:     $output=~s/^.*?\<body[^\>]*\>//si;
                   1317:     $output=~s/(.*)\<\/body\s*\>.*?$/$1/si;
1.330     www      1318:     return $output;
1.8       www      1319: }
                   1320: 
1.15      www      1321: # --------------------------------------------------------- Server Side Include
                   1322: 
1.782     albertel 1323: sub absolute_url {
                   1324:     my ($host_name) = @_;
                   1325:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   1326:     if ($host_name eq '') {
                   1327: 	$host_name = $ENV{'SERVER_NAME'};
                   1328:     }
                   1329:     return $protocol.$host_name;
                   1330: }
                   1331: 
1.15      www      1332: sub ssi {
                   1333: 
1.23      www      1334:     my ($fn,%form)=@_;
1.15      www      1335: 
                   1336:     my $ua=new LWP::UserAgent;
1.23      www      1337:     
                   1338:     my $request;
1.711     albertel 1339: 
                   1340:     $form{'no_update_last_known'}=1;
                   1341: 
1.23      www      1342:     if (%form) {
1.782     albertel 1343:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.201     albertel 1344:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1.23      www      1345:     } else {
1.782     albertel 1346:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      1347:     }
                   1348: 
1.15      www      1349:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   1350:     my $response=$ua->request($request);
                   1351: 
1.324     www      1352:     return $response->content;
                   1353: }
                   1354: 
                   1355: sub externalssi {
                   1356:     my ($url)=@_;
                   1357:     my $ua=new LWP::UserAgent;
                   1358:     my $request=new HTTP::Request('GET',$url);
                   1359:     my $response=$ua->request($request);
1.15      www      1360:     return $response->content;
                   1361: }
1.254     www      1362: 
1.492     albertel 1363: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   1364: 
                   1365: sub allowuploaded {
                   1366:     my ($srcurl,$url)=@_;
                   1367:     $url=&clutter(&declutter($url));
                   1368:     my $dir=$url;
                   1369:     $dir=~s/\/[^\/]+$//;
                   1370:     my %httpref=();
                   1371:     my $httpurl=&hreflocation('',$url);
                   1372:     $httpref{'httpref.'.$httpurl}=$srcurl;
                   1373:     &Apache::lonnet::appenv(%httpref);
1.254     www      1374: }
1.477     raeburn  1375: 
1.478     albertel 1376: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 1377: # input: action, courseID, current domain, intended
1.637     raeburn  1378: #        path to file, source of file, instruction to parse file for objects,
                   1379: #        ref to hash for embedded objects,
                   1380: #        ref to hash for codebase of java objects.
                   1381: #
1.485     raeburn  1382: # output: url to file (if action was uploaddoc), 
                   1383: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  1384: #
1.478     albertel 1385: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   1386: # course.
1.477     raeburn  1387: #
1.478     albertel 1388: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1389: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   1390: #          course's home server.
1.477     raeburn  1391: #
1.478     albertel 1392: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   1393: #          be copied from $source (current location) to 
                   1394: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1395: #         and will then be copied to
                   1396: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   1397: #         course's home server.
1.485     raeburn  1398: #
1.481     raeburn  1399: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 1400: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  1401: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1402: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   1403: #         in course's home server.
1.637     raeburn  1404: #
1.477     raeburn  1405: 
                   1406: sub process_coursefile {
1.638     albertel 1407:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477     raeburn  1408:     my $fetchresult;
1.638     albertel 1409:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  1410:     if ($action eq 'propagate') {
1.638     albertel 1411:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   1412: 			     $home);
1.481     raeburn  1413:     } else {
1.477     raeburn  1414:         my $fpath = '';
                   1415:         my $fname = $file;
1.478     albertel 1416:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  1417:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  1418:         my $filepath = &build_filepath($fpath);
1.481     raeburn  1419:         if ($action eq 'copy') {
                   1420:             if ($source eq '') {
                   1421:                 $fetchresult = 'no source file';
                   1422:                 return $fetchresult;
                   1423:             } else {
                   1424:                 my $destination = $filepath.'/'.$fname;
                   1425:                 rename($source,$destination);
                   1426:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1427:                                  $home);
1.481     raeburn  1428:             }
                   1429:         } elsif ($action eq 'uploaddoc') {
                   1430:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 1431:             print $fh $env{'form.'.$source};
1.481     raeburn  1432:             close($fh);
1.637     raeburn  1433:             if ($parser eq 'parse') {
                   1434:                 my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
                   1435:                 unless ($parse_result eq 'ok') {
                   1436:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   1437:                 }
                   1438:             }
1.477     raeburn  1439:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1440:                                  $home);
1.481     raeburn  1441:             if ($fetchresult eq 'ok') {
                   1442:                 return '/uploaded/'.$fpath.'/'.$fname;
                   1443:             } else {
                   1444:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1445:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  1446:                 return '/adm/notfound.html';
                   1447:             }
1.477     raeburn  1448:         }
                   1449:     }
1.485     raeburn  1450:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  1451:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1452:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  1453:     }
                   1454:     return $fetchresult;
                   1455: }
                   1456: 
1.637     raeburn  1457: sub build_filepath {
                   1458:     my ($fpath) = @_;
                   1459:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   1460:     unless ($fpath eq '') {
                   1461:         my @parts=split('/',$fpath);
                   1462:         foreach my $part (@parts) {
                   1463:             $filepath.= '/'.$part;
                   1464:             if ((-e $filepath)!=1) {
                   1465:                 mkdir($filepath,0777);
                   1466:             }
                   1467:         }
                   1468:     }
                   1469:     return $filepath;
                   1470: }
                   1471: 
                   1472: sub store_edited_file {
1.638     albertel 1473:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  1474:     my $file = $primary_url;
                   1475:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   1476:     my $fpath = '';
                   1477:     my $fname = $file;
                   1478:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   1479:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   1480:     my $filepath = &build_filepath($fpath);
                   1481:     open(my $fh,'>'.$filepath.'/'.$fname);
                   1482:     print $fh $content;
                   1483:     close($fh);
1.638     albertel 1484:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  1485:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1486: 			  $home);
1.637     raeburn  1487:     if ($$fetchresult eq 'ok') {
                   1488:         return '/uploaded/'.$fpath.'/'.$fname;
                   1489:     } else {
1.638     albertel 1490:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   1491: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  1492:         return '/adm/notfound.html';
                   1493:     }
                   1494: }
                   1495: 
1.531     albertel 1496: sub clean_filename {
1.831     albertel 1497:     my ($fname,$args)=@_;
1.315     www      1498: # Replace Windows backslashes by forward slashes
1.257     www      1499:     $fname=~s/\\/\//g;
1.831     albertel 1500:     if (!$args->{'keep_path'}) {
                   1501:         # Get rid of everything but the actual filename
                   1502: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   1503:     }
1.315     www      1504: # Replace spaces by underscores
                   1505:     $fname=~s/\s+/\_/g;
                   1506: # Replace all other weird characters by nothing
1.831     albertel 1507:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 1508: # Replace all .\d. sequences with _\d. so they no longer look like version
                   1509: # numbers
                   1510:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 1511:     return $fname;
                   1512: }
                   1513: 
1.608     albertel 1514: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 1515: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719     banghart 1516: #                    the desired filenam is in $env{"form.$formname.filename"}
1.686     albertel 1517: #        $coursedoc - if true up to the current course
                   1518: #                     if false
                   1519: #        $subdir - directory in userfile to store the file into
                   1520: #        $parser, $allfiles, $codebase - unknown
                   1521: #
                   1522: # output: url of file in userspace, or error: <message> 
                   1523: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 1524: 
                   1525: 
1.531     albertel 1526: sub userfileupload {
1.719     banghart 1527:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,$destudom)=@_;
1.531     albertel 1528:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 1529:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 1530:     $fname=&clean_filename($fname);
1.315     www      1531: # See if there is anything left
1.257     www      1532:     unless ($fname) { return 'error: no uploaded file'; }
1.620     albertel 1533:     chop($env{'form.'.$formname});
1.523     raeburn  1534:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
                   1535:         my $now = time;
                   1536:         my $filepath = 'tmp/helprequests/'.$now;
                   1537:         my @parts=split(/\//,$filepath);
                   1538:         my $fullpath = $perlvar{'lonDaemons'};
                   1539:         for (my $i=0;$i<@parts;$i++) {
                   1540:             $fullpath .= '/'.$parts[$i];
                   1541:             if ((-e $fullpath)!=1) {
                   1542:                 mkdir($fullpath,0777);
                   1543:             }
                   1544:         }
                   1545:         open(my $fh,'>'.$fullpath.'/'.$fname);
1.620     albertel 1546:         print $fh $env{'form.'.$formname};
1.523     raeburn  1547:         close($fh);
1.741     raeburn  1548:         return $fullpath.'/'.$fname;
                   1549:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
                   1550:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   1551:                        '_'.$env{'user.domain'}.'/pending';
                   1552:         my @parts=split(/\//,$filepath);
                   1553:         my $fullpath = $perlvar{'lonDaemons'};
                   1554:         for (my $i=0;$i<@parts;$i++) {
                   1555:             $fullpath .= '/'.$parts[$i];
                   1556:             if ((-e $fullpath)!=1) {
                   1557:                 mkdir($fullpath,0777);
                   1558:             }
                   1559:         }
                   1560:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   1561:         print $fh $env{'form.'.$formname};
                   1562:         close($fh);
                   1563:         return $fullpath.'/'.$fname;
1.523     raeburn  1564:     }
1.719     banghart 1565:     
1.258     www      1566: # Create the directory if not present
1.493     albertel 1567:     $fname="$subdir/$fname";
1.259     www      1568:     if ($coursedoc) {
1.638     albertel 1569: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1570: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  1571:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 1572:             return &finishuserfileupload($docuname,$docudom,
                   1573: 					 $formname,$fname,$parser,$allfiles,
                   1574: 					 $codebase);
1.481     raeburn  1575:         } else {
1.620     albertel 1576:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 1577:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   1578: 				       $fname,$formname,$parser,
                   1579: 				       $allfiles,$codebase);
1.481     raeburn  1580:         }
1.719     banghart 1581:     } elsif (defined($destuname)) {
                   1582:         my $docuname=$destuname;
                   1583:         my $docudom=$destudom;
                   1584: 	return &finishuserfileupload($docuname,$docudom,$formname,
                   1585: 				     $fname,$parser,$allfiles,$codebase);
                   1586:         
1.259     www      1587:     } else {
1.638     albertel 1588:         my $docuname=$env{'user.name'};
                   1589:         my $docudom=$env{'user.domain'};
1.714     raeburn  1590:         if (exists($env{'form.group'})) {
                   1591:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1592:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1593:         }
1.638     albertel 1594: 	return &finishuserfileupload($docuname,$docudom,$formname,
                   1595: 				     $fname,$parser,$allfiles,$codebase);
1.259     www      1596:     }
1.271     www      1597: }
                   1598: 
                   1599: sub finishuserfileupload {
1.638     albertel 1600:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase) = @_;
1.477     raeburn  1601:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      1602:     my $filepath=$perlvar{'lonDocRoot'};
1.494     albertel 1603:     my ($fnamepath,$file);
                   1604:     $file=$fname;
                   1605:     if ($fname=~m|/|) {
                   1606:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   1607: 	$path.=$fnamepath.'/';
                   1608:     }
1.259     www      1609:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      1610:     my $count;
                   1611:     for ($count=4;$count<=$#parts;$count++) {
                   1612:         $filepath.="/$parts[$count]";
                   1613:         if ((-e $filepath)!=1) {
                   1614: 	    mkdir($filepath,0777);
                   1615:         }
                   1616:     }
                   1617: # Save the file
                   1618:     {
1.701     albertel 1619: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   1620: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   1621: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   1622: 	    return '/adm/notfound.html';
                   1623: 	}
                   1624: 	if (!print FH ($env{'form.'.$formname})) {
                   1625: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   1626: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   1627: 	    return '/adm/notfound.html';
                   1628: 	}
1.570     albertel 1629: 	close(FH);
1.258     www      1630:     }
1.637     raeburn  1631:     if ($parser eq 'parse') {
1.638     albertel 1632:         my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
                   1633: 						   $codebase);
1.637     raeburn  1634:         unless ($parse_result eq 'ok') {
1.638     albertel 1635:             &logthis('Failed to parse '.$filepath.$file.
                   1636: 		     ' for embedded media: '.$parse_result); 
1.637     raeburn  1637:         }
                   1638:     }
1.259     www      1639: # Notify homeserver to grep it
                   1640: #
1.638     albertel 1641:     my $docuhome=&homeserver($docuname,$docudom);
1.494     albertel 1642:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      1643:     if ($fetchresult eq 'ok') {
1.259     www      1644: #
1.258     www      1645: # Return the URL to it
1.494     albertel 1646:         return '/uploaded/'.$path.$file;
1.263     www      1647:     } else {
1.494     albertel 1648:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   1649: 		 ': '.$fetchresult);
1.263     www      1650:         return '/adm/notfound.html';
                   1651:     }    
1.493     albertel 1652: }
                   1653: 
1.637     raeburn  1654: sub extract_embedded_items {
1.648     raeburn  1655:     my ($filepath,$file,$allfiles,$codebase,$content) = @_;
1.637     raeburn  1656:     my @state = ();
                   1657:     my %javafiles = (
                   1658:                       codebase => '',
                   1659:                       code => '',
                   1660:                       archive => ''
                   1661:                     );
                   1662:     my %mediafiles = (
                   1663:                       src => '',
                   1664:                       movie => '',
                   1665:                      );
1.648     raeburn  1666:     my $p;
                   1667:     if ($content) {
                   1668:         $p = HTML::LCParser->new($content);
                   1669:     } else {
                   1670:         $p = HTML::LCParser->new($filepath.'/'.$file);
                   1671:     }
1.641     albertel 1672:     while (my $t=$p->get_token()) {
1.640     albertel 1673: 	if ($t->[0] eq 'S') {
                   1674: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
                   1675: 	    push (@state, $tagname);
1.648     raeburn  1676:             if (lc($tagname) eq 'allow') {
                   1677:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   1678:             }
1.640     albertel 1679: 	    if (lc($tagname) eq 'img') {
                   1680: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   1681: 	    }
1.645     raeburn  1682:             if (lc($tagname) eq 'script') {
                   1683:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   1684:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   1685:                 } else {
                   1686:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   1687:                 }
                   1688:             }
                   1689:             if (lc($tagname) eq 'link') {
                   1690:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   1691:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   1692:                 }
                   1693:             }
1.640     albertel 1694: 	    if (lc($tagname) eq 'object' ||
                   1695: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   1696: 		foreach my $item (keys(%javafiles)) {
                   1697: 		    $javafiles{$item} = '';
                   1698: 		}
                   1699: 	    }
                   1700: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   1701: 		my $name = lc($attr->{'name'});
                   1702: 		foreach my $item (keys(%javafiles)) {
                   1703: 		    if ($name eq $item) {
                   1704: 			$javafiles{$item} = $attr->{'value'};
                   1705: 			last;
                   1706: 		    }
                   1707: 		}
                   1708: 		foreach my $item (keys(%mediafiles)) {
                   1709: 		    if ($name eq $item) {
                   1710: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   1711: 			last;
                   1712: 		    }
                   1713: 		}
                   1714: 	    }
                   1715: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   1716: 		foreach my $item (keys(%javafiles)) {
                   1717: 		    if ($attr->{$item}) {
                   1718: 			$javafiles{$item} = $attr->{$item};
                   1719: 			last;
                   1720: 		    }
                   1721: 		}
                   1722: 		foreach my $item (keys(%mediafiles)) {
                   1723: 		    if ($attr->{$item}) {
                   1724: 			&add_filetype($allfiles,$attr->{$item},$item);
                   1725: 			last;
                   1726: 		    }
                   1727: 		}
                   1728: 	    }
                   1729: 	} elsif ($t->[0] eq 'E') {
                   1730: 	    my ($tagname) = ($t->[1]);
                   1731: 	    if ($javafiles{'codebase'} ne '') {
                   1732: 		$javafiles{'codebase'} .= '/';
                   1733: 	    }  
                   1734: 	    if (lc($tagname) eq 'applet' ||
                   1735: 		lc($tagname) eq 'object' ||
                   1736: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   1737: 		) {
                   1738: 		foreach my $item (keys(%javafiles)) {
                   1739: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   1740: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   1741: 			&add_filetype($allfiles,$file,$item);
                   1742: 		    }
                   1743: 		}
                   1744: 	    } 
                   1745: 	    pop @state;
                   1746: 	}
                   1747:     }
1.637     raeburn  1748:     return 'ok';
                   1749: }
                   1750: 
1.639     albertel 1751: sub add_filetype {
                   1752:     my ($allfiles,$file,$type)=@_;
                   1753:     if (exists($allfiles->{$file})) {
                   1754: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   1755: 	    push(@{$allfiles->{$file}}, &escape($type));
                   1756: 	}
                   1757:     } else {
                   1758: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  1759:     }
                   1760: }
                   1761: 
1.493     albertel 1762: sub removeuploadedurl {
                   1763:     my ($url)=@_;
                   1764:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613     albertel 1765:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 1766: }
                   1767: 
                   1768: sub removeuserfile {
                   1769:     my ($docuname,$docudom,$fname)=@_;
                   1770:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  1771:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
                   1772:     if ($result eq 'ok') {
                   1773:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   1774:             my $metafile = $fname.'.meta';
                   1775:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 1776: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
                   1777:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  1778:             my $sqlresult = 
1.823     albertel 1779:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  1780:                                         'portfolio_metadata',$group,
                   1781:                                         'delete');
1.798     raeburn  1782:         }
                   1783:     }
                   1784:     return $result;
1.257     www      1785: }
1.15      www      1786: 
1.530     albertel 1787: sub mkdiruserfile {
                   1788:     my ($docuname,$docudom,$dir)=@_;
                   1789:     my $home=&homeserver($docuname,$docudom);
                   1790:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   1791: }
                   1792: 
1.531     albertel 1793: sub renameuserfile {
                   1794:     my ($docuname,$docudom,$old,$new)=@_;
                   1795:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  1796:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   1797:                         &escape("$old").':'.&escape("$new"),$home);
                   1798:     if ($result eq 'ok') {
                   1799:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   1800:             my $oldmeta = $old.'.meta';
                   1801:             my $newmeta = $new.'.meta';
                   1802:             my $metaresult = 
                   1803:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 1804: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   1805:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  1806:             my $sqlresult = 
1.823     albertel 1807:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  1808:                                         'portfolio_metadata',$group,
                   1809:                                         'delete');
1.798     raeburn  1810:         }
                   1811:     }
                   1812:     return $result;
1.531     albertel 1813: }
                   1814: 
1.14      www      1815: # ------------------------------------------------------------------------- Log
                   1816: 
                   1817: sub log {
                   1818:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      1819:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      1820: }
                   1821: 
                   1822: # ------------------------------------------------------------------ Course Log
1.352     www      1823: #
                   1824: # This routine flushes several buffers of non-mission-critical nature
                   1825: #
1.157     www      1826: 
                   1827: sub flushcourselogs {
1.352     www      1828:     &logthis('Flushing log buffers');
                   1829: #
                   1830: # course logs
                   1831: # This is a log of all transactions in a course, which can be used
                   1832: # for data mining purposes
                   1833: #
                   1834: # It also collects the courseid database, which lists last transaction
                   1835: # times and course titles for all courseids
                   1836: #
                   1837:     my %courseidbuffer=();
1.800     albertel 1838:     foreach my $crsid (keys %courselogs) {
1.352     www      1839:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      1840: 		          &escape($courselogs{$crsid}),
                   1841: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      1842: 	    delete $courselogs{$crsid};
                   1843:         } else {
                   1844:             &logthis('Failed to flush log buffer for '.$crsid);
                   1845:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 1846:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      1847:                         " exceeded maximum size, deleting.</font>");
                   1848:                delete $courselogs{$crsid};
                   1849:             }
1.352     www      1850:         }
                   1851:         if ($courseidbuffer{$coursehombuf{$crsid}}) {
                   1852:            $courseidbuffer{$coursehombuf{$crsid}}.='&'.
1.516     raeburn  1853: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.741     raeburn  1854:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1.352     www      1855:         } else {
                   1856:            $courseidbuffer{$coursehombuf{$crsid}}=
1.516     raeburn  1857: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.741     raeburn  1858:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1.571     raeburn  1859:         }
1.191     harris41 1860:     }
1.352     www      1861: #
                   1862: # Write course id database (reverse lookup) to homeserver of courses 
                   1863: # Is used in pickcourse
                   1864: #
1.840     albertel 1865:     foreach my $crs_home (keys(%courseidbuffer)) {
1.844     albertel 1866:         &courseidput(&host_domain($crs_home),$courseidbuffer{$crs_home},
1.840     albertel 1867: 		     $crs_home);
1.352     www      1868:     }
                   1869: #
                   1870: # File accesses
                   1871: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   1872: #
1.449     matthew  1873:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  1874:         if ($entry =~ /___count$/) {
                   1875:             my ($dom,$name);
1.807     albertel 1876:             ($dom,$name,undef)=
1.811     albertel 1877: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  1878:             if (! defined($dom) || $dom eq '' || 
                   1879:                 ! defined($name) || $name eq '') {
1.620     albertel 1880:                 my $cid = $env{'request.course.id'};
                   1881:                 $dom  = $env{'request.'.$cid.'.domain'};
                   1882:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  1883:             }
1.450     matthew  1884:             my $value = $accesshash{$entry};
                   1885:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   1886:             my %temphash=($url => $value);
1.449     matthew  1887:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   1888:             if ($result eq 'ok') {
                   1889:                 delete $accesshash{$entry};
                   1890:             } elsif ($result eq 'unknown_cmd') {
                   1891:                 # Target server has old code running on it.
1.450     matthew  1892:                 my %temphash=($entry => $value);
1.449     matthew  1893:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   1894:                     delete $accesshash{$entry};
                   1895:                 }
                   1896:             }
                   1897:         } else {
1.811     albertel 1898:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450     matthew  1899:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  1900:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   1901:                 delete $accesshash{$entry};
                   1902:             }
1.185     www      1903:         }
1.191     harris41 1904:     }
1.352     www      1905: #
                   1906: # Roles
                   1907: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   1908: #
1.800     albertel 1909:     foreach my $entry (keys(%userrolehash)) {
1.351     www      1910:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      1911: 	    split(/\:/,$entry);
                   1912:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      1913:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      1914:                 $rudom,$runame) eq 'ok') {
                   1915: 	    delete $userrolehash{$entry};
                   1916:         }
                   1917:     }
1.662     raeburn  1918: #
                   1919: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   1920: #
                   1921:     my %domrolebuffer = ();
                   1922:     foreach my $entry (keys %domainrolehash) {
                   1923:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split/:/,$entry;
                   1924:         if ($domrolebuffer{$rudom}) {
                   1925:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   1926:                       '='.&escape($domainrolehash{$entry});
                   1927:         } else {
                   1928:             $domrolebuffer{$rudom}.=&escape($entry).
                   1929:                       '='.&escape($domainrolehash{$entry});
                   1930:         }
                   1931:         delete $domainrolehash{$entry};
                   1932:     }
                   1933:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 1934: 	my %servers = &get_servers($dom,'library');
                   1935: 	foreach my $tryserver (keys(%servers)) {
                   1936: 	    unless (&reply('domroleput:'.$dom.':'.
                   1937: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   1938: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   1939: 	    }
1.662     raeburn  1940:         }
                   1941:     }
1.186     www      1942:     $dumpcount++;
1.157     www      1943: }
                   1944: 
                   1945: sub courselog {
                   1946:     my $what=shift;
1.158     www      1947:     $what=time.':'.$what;
1.620     albertel 1948:     unless ($env{'request.course.id'}) { return ''; }
                   1949:     $coursedombuf{$env{'request.course.id'}}=
                   1950:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   1951:     $coursenumbuf{$env{'request.course.id'}}=
                   1952:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   1953:     $coursehombuf{$env{'request.course.id'}}=
                   1954:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   1955:     $coursedescrbuf{$env{'request.course.id'}}=
                   1956:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   1957:     $courseinstcodebuf{$env{'request.course.id'}}=
                   1958:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   1959:     $courseownerbuf{$env{'request.course.id'}}=
                   1960:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  1961:     $coursetypebuf{$env{'request.course.id'}}=
                   1962:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 1963:     if (defined $courselogs{$env{'request.course.id'}}) {
                   1964: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      1965:     } else {
1.620     albertel 1966: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      1967:     }
1.620     albertel 1968:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      1969: 	&flushcourselogs();
                   1970:     }
1.158     www      1971: }
                   1972: 
                   1973: sub courseacclog {
                   1974:     my $fnsymb=shift;
1.620     albertel 1975:     unless ($env{'request.course.id'}) { return ''; }
                   1976:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 1977:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      1978:         $what.=':POST';
1.583     matthew  1979:         # FIXME: Probably ought to escape things....
1.800     albertel 1980: 	foreach my $key (keys(%env)) {
                   1981:             if ($key=~/^form\.(.*)/) {
                   1982: 		$what.=':'.$1.'='.$env{$key};
1.158     www      1983:             }
1.191     harris41 1984:         }
1.583     matthew  1985:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   1986:         # FIXME: We should not be depending on a form parameter that someone
                   1987:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 1988:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  1989:             $what.= ':POST';
                   1990:             # FIXME: Probably ought to escape things....
                   1991:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   1992:                                  'crsdiscuss') {
1.620     albertel 1993:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  1994:             }
                   1995:         }
1.158     www      1996:     }
                   1997:     &courselog($what);
1.149     www      1998: }
                   1999: 
1.185     www      2000: sub countacc {
                   2001:     my $url=&declutter(shift);
1.458     matthew  2002:     return if (! defined($url) || $url eq '');
1.620     albertel 2003:     unless ($env{'request.course.id'}) { return ''; }
                   2004:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      2005:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  2006:     $accesshash{$key}++;
1.185     www      2007: }
1.349     www      2008: 
1.361     www      2009: sub linklog {
                   2010:     my ($from,$to)=@_;
                   2011:     $from=&declutter($from);
                   2012:     $to=&declutter($to);
                   2013:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   2014:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   2015: }
                   2016:   
1.349     www      2017: sub userrolelog {
                   2018:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  2019:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  2020:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  2021:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
                   2022:         ($trole=~/^ta/)) {
1.350     www      2023:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2024:        $userrolehash
                   2025:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      2026:                     =$tend.':'.$tstart;
1.662     raeburn  2027:     }
                   2028:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   2029:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   2030:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   2031:         ($trole=~/^sc/)) {
                   2032:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2033:        $domainrolehash
                   2034:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   2035:                     = $tend.':'.$tstart;
                   2036:     }
1.351     www      2037: }
                   2038: 
                   2039: sub get_course_adv_roles {
                   2040:     my $cid=shift;
1.620     albertel 2041:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      2042:     my %coursehash=&coursedescription($cid);
1.470     www      2043:     my %nothide=();
1.800     albertel 2044:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   2045: 	$nothide{join(':',split(/[\@\:]/,$user))}=1;
1.470     www      2046:     }
1.351     www      2047:     my %returnhash=();
                   2048:     my %dumphash=
                   2049:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   2050:     my $now=time;
1.800     albertel 2051:     foreach my $entry (keys %dumphash) {
                   2052: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      2053:         if (($tstart) && ($tstart<0)) { next; }
                   2054:         if (($tend) && ($tend<$now)) { next; }
                   2055:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 2056:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 2057: 	if ($username eq '' || $domain eq '') { next; }
1.470     www      2058: 	if ((&privileged($username,$domain)) && 
                   2059: 	    (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 2060: 	if ($role eq 'cr') { next; }
1.351     www      2061:         my $key=&plaintext($role);
                   2062:         if ($section) { $key.=' (Sec/Grp '.$section.')'; }
                   2063:         if ($returnhash{$key}) {
                   2064: 	    $returnhash{$key}.=','.$username.':'.$domain;
                   2065:         } else {
                   2066:             $returnhash{$key}=$username.':'.$domain;
                   2067:         }
1.400     www      2068:      }
                   2069:     return %returnhash;
                   2070: }
                   2071: 
                   2072: sub get_my_roles {
1.832     raeburn  2073:     my ($uname,$udom,$types,$roles,$roledoms)=@_;
1.620     albertel 2074:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   2075:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.400     www      2076:     my %dumphash=
                   2077:             &dump('nohist_userroles',$udom,$uname);
                   2078:     my %returnhash=();
                   2079:     my $now=time;
1.800     albertel 2080:     foreach my $entry (keys(%dumphash)) {
                   2081: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.400     www      2082:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  2083:         my $status = 'active';
                   2084:         if (($tend) && ($tend<$now)) {
                   2085:             $status = 'previous';
                   2086:         } 
                   2087:         if (($tstart) && ($now<$tstart)) {
                   2088:             $status = 'future';
                   2089:         }
                   2090:         if (ref($types) eq 'ARRAY') {
                   2091:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   2092:                 next;
                   2093:             } 
                   2094:         } else {
                   2095:             if ($status ne 'active') {
                   2096:                 next;
                   2097:             }
                   2098:         }
1.800     albertel 2099:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.832     raeburn  2100:         if (ref($roledoms) eq 'ARRAY') {
                   2101:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   2102:                 next;
                   2103:             }
                   2104:         }
                   2105:         if (ref($roles) eq 'ARRAY') {
                   2106:             if (!grep(/^\Q$role\E$/,@{$roles})) {
                   2107:                 next;
                   2108:             }
                   2109:         } 
1.400     www      2110: 	$returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
1.832     raeburn  2111:     }
1.373     www      2112:     return %returnhash;
1.399     www      2113: }
                   2114: 
                   2115: # ----------------------------------------------------- Frontpage Announcements
                   2116: #
                   2117: #
                   2118: 
                   2119: sub postannounce {
                   2120:     my ($server,$text)=@_;
1.844     albertel 2121:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      2122:     unless ($text=~/\w/) { $text=''; }
                   2123:     return &reply('setannounce:'.&escape($text),$server);
                   2124: }
                   2125: 
                   2126: sub getannounce {
1.448     albertel 2127: 
                   2128:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      2129: 	my $announcement='';
1.800     albertel 2130: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 2131: 	close($fh);
1.399     www      2132: 	if ($announcement=~/\w/) { 
                   2133: 	    return 
                   2134:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 2135:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      2136: 	} else {
                   2137: 	    return '';
                   2138: 	}
                   2139:     } else {
                   2140: 	return '';
                   2141:     }
1.351     www      2142: }
1.353     www      2143: 
                   2144: # ---------------------------------------------------------- Course ID routines
                   2145: # Deal with domain's nohist_courseid.db files
                   2146: #
                   2147: 
                   2148: sub courseidput {
                   2149:     my ($domain,$what,$coursehome)=@_;
                   2150:     return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   2151: }
                   2152: 
                   2153: sub courseiddump {
1.791     raeburn  2154:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,$coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok)=@_;
1.353     www      2155:     my %returnhash=();
1.355     www      2156:     unless ($domfilter) { $domfilter=''; }
1.845     albertel 2157:     my %libserv = &all_library();
                   2158:     foreach my $tryserver (keys(%libserv)) {
                   2159:         if ( (  $hostidflag == 1 
                   2160: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   2161: 	     || (!defined($hostidflag)) ) {
                   2162: 
                   2163: 	    if ($domfilter eq ''
                   2164: 		|| (&host_domain($tryserver) eq $domfilter)) {
1.800     albertel 2165: 	        foreach my $line (
1.844     albertel 2166:                  split(/\&/,&reply('courseiddump:'.&host_domain($tryserver).':'.
1.571     raeburn  2167: 			       $sincefilter.':'.&escape($descfilter).':'.
1.791     raeburn  2168:                                &escape($instcodefilter).':'.&escape($ownerfilter).':'.&escape($coursefilter).':'.&escape($typefilter).':'.&escape($regexp_ok),
1.354     www      2169:                                $tryserver))) {
1.800     albertel 2170: 		    my ($key,$value)=split(/\=/,$line,2);
1.506     raeburn  2171:                     if (($key) && ($value)) {
1.516     raeburn  2172: 		        $returnhash{&unescape($key)}=$value;
1.506     raeburn  2173:                     }
1.353     www      2174:                 }
                   2175:             }
                   2176:         }
                   2177:     }
                   2178:     return %returnhash;
                   2179: }
                   2180: 
1.658     raeburn  2181: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  2182: 
                   2183: sub dcmailput {
1.685     raeburn  2184:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  2185:     my $status = &Apache::lonnet::critical(
1.740     www      2186:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   2187:        &escape($message),$server);
1.662     raeburn  2188:     return $status;
                   2189: }
                   2190: 
1.658     raeburn  2191: sub dcmaildump {
                   2192:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  2193:     my %returnhash=();
1.846     albertel 2194: 
                   2195:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  2196:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   2197:                                                          &escape($enddate).':';
                   2198: 	my @esc_senders=map { &escape($_)} @$senders;
                   2199: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 2200: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 2201:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  2202:             if (($key) && ($value)) {
                   2203:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  2204:             }
                   2205:         }
                   2206:     }
                   2207:     return %returnhash;
                   2208: }
1.662     raeburn  2209: # ---------------------------------------------------------- Domain roles
                   2210: 
                   2211: sub get_domain_roles {
                   2212:     my ($dom,$roles,$startdate,$enddate)=@_;
                   2213:     if (undef($startdate) || $startdate eq '') {
                   2214:         $startdate = '.';
                   2215:     }
                   2216:     if (undef($enddate) || $enddate eq '') {
                   2217:         $enddate = '.';
                   2218:     }
                   2219:     my $rolelist = join(':',@{$roles});
                   2220:     my %personnel = ();
1.841     albertel 2221: 
                   2222:     my %servers = &get_servers($dom,'library');
                   2223:     foreach my $tryserver (keys(%servers)) {
                   2224: 	%{$personnel{$tryserver}}=();
                   2225: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   2226: 					    &escape($startdate).':'.
                   2227: 					    &escape($enddate).':'.
                   2228: 					    &escape($rolelist), $tryserver))) {
                   2229: 	    my ($key,$value) = split(/\=/,$line,2);
                   2230: 	    if (($key) && ($value)) {
                   2231: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   2232: 	    }
                   2233: 	}
1.662     raeburn  2234:     }
                   2235:     return %personnel;
                   2236: }
1.658     raeburn  2237: 
1.149     www      2238: # ----------------------------------------------------------- Check out an item
                   2239: 
1.504     albertel 2240: sub get_first_access {
                   2241:     my ($type,$argsymb)=@_;
1.790     albertel 2242:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2243:     if ($argsymb) { $symb=$argsymb; }
                   2244:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 2245:     if ($type eq 'map') {
                   2246: 	$res=&symbread($map);
                   2247:     } else {
                   2248: 	$res=$symb;
                   2249:     }
                   2250:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   2251:     return $times{"$courseid\0$res"};
1.504     albertel 2252: }
                   2253: 
                   2254: sub set_first_access {
                   2255:     my ($type)=@_;
1.790     albertel 2256:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2257:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 2258:     if ($type eq 'map') {
                   2259: 	$res=&symbread($map);
                   2260:     } else {
                   2261: 	$res=$symb;
                   2262:     }
                   2263:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 2264:     if (!$firstaccess) {
1.588     albertel 2265: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 2266:     }
                   2267:     return 'already_set';
1.504     albertel 2268: }
                   2269: 
1.149     www      2270: sub checkout {
                   2271:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   2272:     my $now=time;
                   2273:     my $lonhost=$perlvar{'lonHostID'};
                   2274:     my $infostr=&escape(
1.234     www      2275:                  'CHECKOUTTOKEN&'.
1.149     www      2276:                  $tuname.'&'.
                   2277:                  $tudom.'&'.
                   2278:                  $tcrsid.'&'.
                   2279:                  $symb.'&'.
                   2280: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                   2281:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www      2282:     if ($token=~/^error\:/) { 
1.672     albertel 2283:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2284:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2285:                  "</font>");
                   2286:         return ''; 
                   2287:     }
                   2288: 
1.149     www      2289:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   2290:     $token=~tr/a-z/A-Z/;
                   2291: 
1.153     www      2292:     my %infohash=('resource.0.outtoken' => $token,
                   2293:                   'resource.0.checkouttime' => $now,
                   2294:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www      2295: 
                   2296:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2297:        return '';
1.151     www      2298:     } else {
1.672     albertel 2299:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2300:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2301:                  "</font>");
1.149     www      2302:     }    
                   2303: 
                   2304:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2305:                          &escape('Checkout '.$infostr.' - '.
                   2306:                                                  $token)) ne 'ok') {
                   2307: 	return '';
1.151     www      2308:     } else {
1.672     albertel 2309:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2310:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2311:                  "</font>");
1.149     www      2312:     }
1.151     www      2313:     return $token;
1.149     www      2314: }
                   2315: 
                   2316: # ------------------------------------------------------------ Check in an item
                   2317: 
                   2318: sub checkin {
                   2319:     my $token=shift;
1.150     www      2320:     my $now=time;
                   2321:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   2322:     $lonhost=~tr/A-Z/a-z/;
1.838     albertel 2323:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
1.150     www      2324:     $dtoken=~s/\W/\_/g;
1.234     www      2325:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www      2326:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   2327: 
1.154     www      2328:     unless (($tuname) && ($tudom)) {
                   2329:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   2330:         return '';
                   2331:     }
                   2332:     
                   2333:     unless (&allowed('mgr',$tcrsid)) {
                   2334:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620     albertel 2335:                  $env{'user.name'}.' - '.$env{'user.domain'});
1.154     www      2336:         return '';
                   2337:     }
                   2338: 
1.153     www      2339:     my %infohash=('resource.0.intoken' => $token,
                   2340:                   'resource.0.checkintime' => $now,
                   2341:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      2342: 
                   2343:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2344:        return '';
                   2345:     }    
                   2346: 
                   2347:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2348:                          &escape('Checkin - '.$token)) ne 'ok') {
                   2349: 	return '';
                   2350:     }
                   2351: 
                   2352:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      2353: }
                   2354: 
                   2355: # --------------------------------------------- Set Expire Date for Spreadsheet
                   2356: 
                   2357: sub expirespread {
                   2358:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 2359:     my $cid=$env{'request.course.id'}; 
1.110     www      2360:     if ($cid) {
                   2361:        my $now=time;
                   2362:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 2363:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   2364:                             $env{'course.'.$cid.'.num'}.
1.110     www      2365: 	        	    ':nohist_expirationdates:'.
                   2366:                             &escape($key).'='.$now,
1.620     albertel 2367:                             $env{'course.'.$cid.'.home'})
1.110     www      2368:     }
                   2369:     return 'ok';
1.14      www      2370: }
                   2371: 
1.109     www      2372: # ----------------------------------------------------- Devalidate Spreadsheets
                   2373: 
                   2374: sub devalidate {
1.325     www      2375:     my ($symb,$uname,$udom)=@_;
1.620     albertel 2376:     my $cid=$env{'request.course.id'}; 
1.109     www      2377:     if ($cid) {
1.391     matthew  2378:         # delete the stored spreadsheets for
                   2379:         # - the student level sheet of this user in course's homespace
                   2380:         # - the assessment level sheet for this resource 
                   2381:         #   for this user in user's homespace
1.553     albertel 2382: 	# - current conditional state info
1.325     www      2383: 	my $key=$uname.':'.$udom.':';
1.109     www      2384:         my $status=
1.299     matthew  2385: 	    &del('nohist_calculatedsheets',
1.391     matthew  2386: 		 [$key.'studentcalc:'],
1.620     albertel 2387: 		 $env{'course.'.$cid.'.domain'},
                   2388: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 2389: 		.' '.
                   2390: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  2391: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      2392:         unless ($status eq 'ok ok') {
                   2393:            &logthis('Could not devalidate spreadsheet '.
1.325     www      2394:                     $uname.' at '.$udom.' for '.
1.109     www      2395: 		    $symb.': '.$status);
1.133     albertel 2396:         }
1.553     albertel 2397: 	&delenv('user.state.'.$cid);
1.109     www      2398:     }
                   2399: }
                   2400: 
1.265     albertel 2401: sub get_scalar {
                   2402:     my ($string,$end) = @_;
                   2403:     my $value;
                   2404:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   2405: 	$value = $1;
                   2406:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   2407: 	$value = $1;
                   2408:     }
                   2409:     return &unescape($value);
                   2410: }
                   2411: 
                   2412: sub array2str {
                   2413:   my (@array) = @_;
                   2414:   my $result=&arrayref2str(\@array);
                   2415:   $result=~s/^__ARRAY_REF__//;
                   2416:   $result=~s/__END_ARRAY_REF__$//;
                   2417:   return $result;
                   2418: }
                   2419: 
1.204     albertel 2420: sub arrayref2str {
                   2421:   my ($arrayref) = @_;
1.265     albertel 2422:   my $result='__ARRAY_REF__';
1.204     albertel 2423:   foreach my $elem (@$arrayref) {
1.265     albertel 2424:     if(ref($elem) eq 'ARRAY') {
                   2425:       $result.=&arrayref2str($elem).'&';
                   2426:     } elsif(ref($elem) eq 'HASH') {
                   2427:       $result.=&hashref2str($elem).'&';
                   2428:     } elsif(ref($elem)) {
                   2429:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 2430:     } else {
                   2431:       $result.=&escape($elem).'&';
                   2432:     }
                   2433:   }
                   2434:   $result=~s/\&$//;
1.265     albertel 2435:   $result .= '__END_ARRAY_REF__';
1.204     albertel 2436:   return $result;
                   2437: }
                   2438: 
1.168     albertel 2439: sub hash2str {
1.204     albertel 2440:   my (%hash) = @_;
                   2441:   my $result=&hashref2str(\%hash);
1.265     albertel 2442:   $result=~s/^__HASH_REF__//;
                   2443:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 2444:   return $result;
                   2445: }
                   2446: 
                   2447: sub hashref2str {
                   2448:   my ($hashref)=@_;
1.265     albertel 2449:   my $result='__HASH_REF__';
1.800     albertel 2450:   foreach my $key (sort(keys(%$hashref))) {
                   2451:     if (ref($key) eq 'ARRAY') {
                   2452:       $result.=&arrayref2str($key).'=';
                   2453:     } elsif (ref($key) eq 'HASH') {
                   2454:       $result.=&hashref2str($key).'=';
                   2455:     } elsif (ref($key)) {
1.265     albertel 2456:       $result.='=';
1.800     albertel 2457:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 2458:     } else {
1.800     albertel 2459: 	if ($key) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 2460:     }
                   2461: 
1.800     albertel 2462:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   2463:       $result.=&arrayref2str($hashref->{$key}).'&';
                   2464:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   2465:       $result.=&hashref2str($hashref->{$key}).'&';
                   2466:     } elsif(ref($hashref->{$key})) {
1.265     albertel 2467:        $result.='&';
1.800     albertel 2468:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 2469:     } else {
1.800     albertel 2470:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 2471:     }
                   2472:   }
1.168     albertel 2473:   $result=~s/\&$//;
1.265     albertel 2474:   $result .= '__END_HASH_REF__';
1.168     albertel 2475:   return $result;
                   2476: }
                   2477: 
                   2478: sub str2hash {
1.265     albertel 2479:     my ($string)=@_;
                   2480:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   2481:     return %$hash;
                   2482: }
                   2483: 
                   2484: sub str2hashref {
1.168     albertel 2485:   my ($string) = @_;
1.265     albertel 2486: 
                   2487:   my %hash;
                   2488: 
                   2489:   if($string !~ /^__HASH_REF__/) {
                   2490:       if (! ($string eq '' || !defined($string))) {
                   2491: 	  $hash{'error'}='Not hash reference';
                   2492:       }
                   2493:       return (\%hash, $string);
                   2494:   }
                   2495: 
                   2496:   $string =~ s/^__HASH_REF__//;
                   2497: 
                   2498:   while($string !~ /^__END_HASH_REF__/) {
                   2499:       #key
                   2500:       my $key='';
                   2501:       if($string =~ /^__HASH_REF__/) {
                   2502:           ($key, $string)=&str2hashref($string);
                   2503:           if(defined($key->{'error'})) {
                   2504:               $hash{'error'}='Bad data';
                   2505:               return (\%hash, $string);
                   2506:           }
                   2507:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2508:           ($key, $string)=&str2arrayref($string);
                   2509:           if($key->[0] eq 'Array reference error') {
                   2510:               $hash{'error'}='Bad data';
                   2511:               return (\%hash, $string);
                   2512:           }
                   2513:       } else {
                   2514:           $string =~ s/^(.*?)=//;
1.267     albertel 2515: 	  $key=&unescape($1);
1.265     albertel 2516:       }
                   2517:       $string =~ s/^=//;
                   2518: 
                   2519:       #value
                   2520:       my $value='';
                   2521:       if($string =~ /^__HASH_REF__/) {
                   2522:           ($value, $string)=&str2hashref($string);
                   2523:           if(defined($value->{'error'})) {
                   2524:               $hash{'error'}='Bad data';
                   2525:               return (\%hash, $string);
                   2526:           }
                   2527:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2528:           ($value, $string)=&str2arrayref($string);
                   2529:           if($value->[0] eq 'Array reference error') {
                   2530:               $hash{'error'}='Bad data';
                   2531:               return (\%hash, $string);
                   2532:           }
                   2533:       } else {
                   2534: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   2535:       }
                   2536:       $string =~ s/^&//;
                   2537: 
                   2538:       $hash{$key}=$value;
1.204     albertel 2539:   }
1.265     albertel 2540: 
                   2541:   $string =~ s/^__END_HASH_REF__//;
                   2542: 
                   2543:   return (\%hash, $string);
1.204     albertel 2544: }
                   2545: 
                   2546: sub str2array {
1.265     albertel 2547:     my ($string)=@_;
                   2548:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   2549:     return @$array;
                   2550: }
                   2551: 
                   2552: sub str2arrayref {
1.204     albertel 2553:   my ($string) = @_;
1.265     albertel 2554:   my @array;
                   2555: 
                   2556:   if($string !~ /^__ARRAY_REF__/) {
                   2557:       if (! ($string eq '' || !defined($string))) {
                   2558: 	  $array[0]='Array reference error';
                   2559:       }
                   2560:       return (\@array, $string);
                   2561:   }
                   2562: 
                   2563:   $string =~ s/^__ARRAY_REF__//;
                   2564: 
                   2565:   while($string !~ /^__END_ARRAY_REF__/) {
                   2566:       my $value='';
                   2567:       if($string =~ /^__HASH_REF__/) {
                   2568:           ($value, $string)=&str2hashref($string);
                   2569:           if(defined($value->{'error'})) {
                   2570:               $array[0] ='Array reference error';
                   2571:               return (\@array, $string);
                   2572:           }
                   2573:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2574:           ($value, $string)=&str2arrayref($string);
                   2575:           if($value->[0] eq 'Array reference error') {
                   2576:               $array[0] ='Array reference error';
                   2577:               return (\@array, $string);
                   2578:           }
                   2579:       } else {
                   2580: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   2581:       }
                   2582:       $string =~ s/^&//;
                   2583: 
                   2584:       push(@array, $value);
1.191     harris41 2585:   }
1.265     albertel 2586: 
                   2587:   $string =~ s/^__END_ARRAY_REF__//;
                   2588: 
                   2589:   return (\@array, $string);
1.168     albertel 2590: }
                   2591: 
1.167     albertel 2592: # -------------------------------------------------------------------Temp Store
                   2593: 
1.168     albertel 2594: sub tmpreset {
                   2595:   my ($symb,$namespace,$domain,$stuname) = @_;
                   2596:   if (!$symb) {
                   2597:     $symb=&symbread();
1.620     albertel 2598:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2599:   }
                   2600:   $symb=escape($symb);
                   2601: 
1.620     albertel 2602:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 2603:   $namespace=~s/\//\_/g;
                   2604:   $namespace=~s/\W//g;
                   2605: 
1.620     albertel 2606:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2607:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2608:   if ($domain eq 'public' && $stuname eq 'public') {
                   2609:       $stuname=$ENV{'REMOTE_ADDR'};
                   2610:   }
1.168     albertel 2611:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2612:   my %hash;
                   2613:   if (tie(%hash,'GDBM_File',
                   2614: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2615: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2616:     foreach my $key (keys %hash) {
1.180     albertel 2617:       if ($key=~ /:$symb/) {
1.168     albertel 2618: 	delete($hash{$key});
                   2619:       }
                   2620:     }
                   2621:   }
                   2622: }
                   2623: 
1.167     albertel 2624: sub tmpstore {
1.168     albertel 2625:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2626: 
                   2627:   if (!$symb) {
                   2628:     $symb=&symbread();
1.620     albertel 2629:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2630:   }
                   2631:   $symb=escape($symb);
                   2632: 
                   2633:   if (!$namespace) {
                   2634:     # I don't think we would ever want to store this for a course.
                   2635:     # it seems this will only be used if we don't have a course.
1.620     albertel 2636:     #$namespace=$env{'request.course.id'};
1.168     albertel 2637:     #if (!$namespace) {
1.620     albertel 2638:       $namespace=$env{'request.state'};
1.168     albertel 2639:     #}
                   2640:   }
                   2641:   $namespace=~s/\//\_/g;
                   2642:   $namespace=~s/\W//g;
1.620     albertel 2643:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2644:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2645:   if ($domain eq 'public' && $stuname eq 'public') {
                   2646:       $stuname=$ENV{'REMOTE_ADDR'};
                   2647:   }
1.168     albertel 2648:   my $now=time;
                   2649:   my %hash;
                   2650:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2651:   if (tie(%hash,'GDBM_File',
                   2652: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2653: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2654:     $hash{"version:$symb"}++;
                   2655:     my $version=$hash{"version:$symb"};
                   2656:     my $allkeys=''; 
                   2657:     foreach my $key (keys(%$storehash)) {
                   2658:       $allkeys.=$key.':';
1.591     albertel 2659:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 2660:     }
                   2661:     $hash{"$version:$symb:timestamp"}=$now;
                   2662:     $allkeys.='timestamp';
                   2663:     $hash{"$version:keys:$symb"}=$allkeys;
                   2664:     if (untie(%hash)) {
                   2665:       return 'ok';
                   2666:     } else {
                   2667:       return "error:$!";
                   2668:     }
                   2669:   } else {
                   2670:     return "error:$!";
                   2671:   }
                   2672: }
1.167     albertel 2673: 
1.168     albertel 2674: # -----------------------------------------------------------------Temp Restore
1.167     albertel 2675: 
1.168     albertel 2676: sub tmprestore {
                   2677:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 2678: 
1.168     albertel 2679:   if (!$symb) {
                   2680:     $symb=&symbread();
1.620     albertel 2681:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2682:   }
                   2683:   $symb=escape($symb);
                   2684: 
1.620     albertel 2685:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 2686: 
1.620     albertel 2687:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2688:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2689:   if ($domain eq 'public' && $stuname eq 'public') {
                   2690:       $stuname=$ENV{'REMOTE_ADDR'};
                   2691:   }
1.168     albertel 2692:   my %returnhash;
                   2693:   $namespace=~s/\//\_/g;
                   2694:   $namespace=~s/\W//g;
                   2695:   my %hash;
                   2696:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2697:   if (tie(%hash,'GDBM_File',
                   2698: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2699: 	  &GDBM_READER(),0640)) {
1.168     albertel 2700:     my $version=$hash{"version:$symb"};
                   2701:     $returnhash{'version'}=$version;
                   2702:     my $scope;
                   2703:     for ($scope=1;$scope<=$version;$scope++) {
                   2704:       my $vkeys=$hash{"$scope:keys:$symb"};
                   2705:       my @keys=split(/:/,$vkeys);
                   2706:       my $key;
                   2707:       $returnhash{"$scope:keys"}=$vkeys;
                   2708:       foreach $key (@keys) {
1.591     albertel 2709: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   2710: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 2711:       }
                   2712:     }
1.168     albertel 2713:     if (!(untie(%hash))) {
                   2714:       return "error:$!";
                   2715:     }
                   2716:   } else {
                   2717:     return "error:$!";
                   2718:   }
                   2719:   return %returnhash;
1.167     albertel 2720: }
                   2721: 
1.9       www      2722: # ----------------------------------------------------------------------- Store
                   2723: 
                   2724: sub store {
1.124     www      2725:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2726:     my $home='';
                   2727: 
1.168     albertel 2728:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2729: 
1.213     www      2730:     $symb=&symbclean($symb);
1.122     albertel 2731:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      2732: 
1.620     albertel 2733:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2734:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      2735: 
                   2736:     &devalidate($symb,$stuname,$domain);
1.109     www      2737: 
                   2738:     $symb=escape($symb);
1.187     www      2739:     if (!$namespace) { 
1.620     albertel 2740:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      2741:           return ''; 
                   2742:        } 
                   2743:     }
1.620     albertel 2744:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      2745: 
                   2746:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   2747:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   2748: 
1.12      www      2749:     my $namevalue='';
1.800     albertel 2750:     foreach my $key (keys(%$storehash)) {
                   2751:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 2752:     }
1.12      www      2753:     $namevalue=~s/\&$//;
1.187     www      2754:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      2755:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      2756: }
                   2757: 
1.47      www      2758: # -------------------------------------------------------------- Critical Store
                   2759: 
                   2760: sub cstore {
1.124     www      2761:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2762:     my $home='';
                   2763: 
1.168     albertel 2764:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2765: 
1.213     www      2766:     $symb=&symbclean($symb);
1.122     albertel 2767:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      2768: 
1.620     albertel 2769:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2770:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      2771: 
                   2772:     &devalidate($symb,$stuname,$domain);
1.109     www      2773: 
                   2774:     $symb=escape($symb);
1.187     www      2775:     if (!$namespace) { 
1.620     albertel 2776:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      2777:           return ''; 
                   2778:        } 
                   2779:     }
1.620     albertel 2780:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      2781: 
                   2782:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   2783:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 2784: 
1.47      www      2785:     my $namevalue='';
1.800     albertel 2786:     foreach my $key (keys(%$storehash)) {
                   2787:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 2788:     }
1.47      www      2789:     $namevalue=~s/\&$//;
1.187     www      2790:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      2791:     return critical
                   2792:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      2793: }
                   2794: 
1.9       www      2795: # --------------------------------------------------------------------- Restore
                   2796: 
                   2797: sub restore {
1.124     www      2798:     my ($symb,$namespace,$domain,$stuname) = @_;
                   2799:     my $home='';
                   2800: 
1.168     albertel 2801:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2802: 
1.122     albertel 2803:     if (!$symb) {
                   2804:       unless ($symb=escape(&symbread())) { return ''; }
                   2805:     } else {
1.213     www      2806:       $symb=&escape(&symbclean($symb));
1.122     albertel 2807:     }
1.188     www      2808:     if (!$namespace) { 
1.620     albertel 2809:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      2810:           return ''; 
                   2811:        } 
                   2812:     }
1.620     albertel 2813:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2814:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   2815:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 2816:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   2817: 
1.12      www      2818:     my %returnhash=();
1.800     albertel 2819:     foreach my $line (split(/\&/,$answer)) {
                   2820: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 2821:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 2822:     }
1.75      www      2823:     my $version;
                   2824:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 2825:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   2826:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 2827:        }
1.75      www      2828:     }
1.13      www      2829:     return %returnhash;
1.34      www      2830: }
                   2831: 
                   2832: # ---------------------------------------------------------- Course Description
                   2833: 
                   2834: sub coursedescription {
1.731     albertel 2835:     my ($courseid,$args)=@_;
1.34      www      2836:     $courseid=~s/^\///;
1.49      www      2837:     $courseid=~s/\_/\//g;
1.34      www      2838:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 2839:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 2840:     my $normalid=$cdomain.'_'.$cnum;
                   2841:     # need to always cache even if we get errors otherwise we keep 
                   2842:     # trying and trying and trying to get the course description.
                   2843:     my %envhash=();
                   2844:     my %returnhash=();
1.731     albertel 2845:     
                   2846:     my $expiretime=600;
                   2847:     if ($env{'request.course.id'} eq $normalid) {
                   2848: 	$expiretime=120;
                   2849:     }
                   2850: 
                   2851:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   2852:     if (!$args->{'freshen_cache'}
                   2853: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   2854: 	foreach my $key (keys(%env)) {
                   2855: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   2856: 	    my ($setting) = $1;
                   2857: 	    $returnhash{$setting} = $env{$key};
                   2858: 	}
                   2859: 	return %returnhash;
                   2860:     }
                   2861: 
                   2862:     # get the data agin
                   2863:     if (!$args->{'one_time'}) {
                   2864: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   2865:     }
1.811     albertel 2866: 
1.34      www      2867:     if ($chome ne 'no_host') {
1.302     albertel 2868:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 2869:        if (!exists($returnhash{'con_lost'})) {
                   2870:            $returnhash{'home'}= $chome;
                   2871: 	   $returnhash{'domain'} = $cdomain;
                   2872: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  2873:            if (!defined($returnhash{'type'})) {
                   2874:                $returnhash{'type'} = 'Course';
                   2875:            }
1.130     albertel 2876:            while (my ($name,$value) = each %returnhash) {
1.53      www      2877:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 2878:            }
1.270     www      2879:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      2880:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 2881: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      2882:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   2883:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   2884:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      2885:        }
                   2886:     }
1.731     albertel 2887:     if (!$args->{'one_time'}) {
                   2888: 	&appenv(%envhash);
                   2889:     }
1.302     albertel 2890:     return %returnhash;
1.461     www      2891: }
                   2892: 
                   2893: # -------------------------------------------------See if a user is privileged
                   2894: 
                   2895: sub privileged {
                   2896:     my ($username,$domain)=@_;
                   2897:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   2898: 			&homeserver($username,$domain));
                   2899:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
                   2900:     my $now=time;
                   2901:     if ($rolesdump ne '') {
1.800     albertel 2902:         foreach my $entry (split(/&/,$rolesdump)) {
                   2903: 	    if ($entry!~/^rolesdef_/) {
                   2904: 		my ($area,$role)=split(/=/,$entry);
1.461     www      2905: 		$area=~s/\_\w\w$//;
                   2906: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   2907: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   2908: 		    my $active=1;
                   2909: 		    if ($tend) {
                   2910: 			if ($tend<$now) { $active=0; }
                   2911: 		    }
                   2912: 		    if ($tstart) {
                   2913: 			if ($tstart>$now) { $active=0; }
                   2914: 		    }
                   2915: 		    if ($active) { return 1; }
                   2916: 		}
                   2917: 	    }
                   2918: 	}
                   2919:     }
                   2920:     return 0;
1.9       www      2921: }
1.1       albertel 2922: 
1.103     harris41 2923: # -------------------------------------------------------- Get user privileges
1.11      www      2924: 
                   2925: sub rolesinit {
                   2926:     my ($domain,$username,$authhost)=@_;
                   2927:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.12      www      2928:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
1.11      www      2929:     my %allroles=();
1.678     raeburn  2930:     my %allgroups=();   
1.11      www      2931:     my $now=time;
1.743     albertel 2932:     my %userroles = ('user.login.time' => $now);
1.678     raeburn  2933:     my $group_privs;
1.11      www      2934: 
                   2935:     if ($rolesdump ne '') {
1.800     albertel 2936:         foreach my $entry (split(/&/,$rolesdump)) {
                   2937: 	  if ($entry!~/^rolesdef_/) {
                   2938:             my ($area,$role)=split(/=/,$entry);
1.587     albertel 2939: 	    $area=~s/\_\w\w$//;
1.678     raeburn  2940:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 2941: 	    if ($role=~/^cr/) { 
1.807     albertel 2942: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   2943: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655     albertel 2944: 		    ($tend,$tstart)=split('_',$trest);
                   2945: 		} else {
                   2946: 		    $trole=$role;
                   2947: 		}
1.678     raeburn  2948:             } elsif ($role =~ m|^gr/|) {
                   2949:                 ($trole,$tend,$tstart) = split(/_/,$role);
                   2950:                 ($trole,$group_privs) = split(/\//,$trole);
                   2951:                 $group_privs = &unescape($group_privs);
1.587     albertel 2952: 	    } else {
                   2953: 		($trole,$tend,$tstart)=split(/_/,$role);
                   2954: 	    }
1.743     albertel 2955: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   2956: 					 $username);
                   2957: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  2958:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   2959:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      2960:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 2961: 		my $spec=$trole.'.'.$area;
                   2962: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   2963: 		if ($trole =~ /^cr\//) {
1.567     raeburn  2964:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  2965:                 } elsif ($trole eq 'gr') {
                   2966:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 2967: 		} else {
1.567     raeburn  2968:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 2969: 		}
1.12      www      2970:             }
1.662     raeburn  2971:           }
1.191     harris41 2972:         }
1.743     albertel 2973:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   2974:         $userroles{'user.adv'}    = $adv;
                   2975: 	$userroles{'user.author'} = $author;
1.620     albertel 2976:         $env{'user.adv'}=$adv;
1.11      www      2977:     }
1.743     albertel 2978:     return \%userroles;  
1.11      www      2979: }
                   2980: 
1.567     raeburn  2981: sub set_arearole {
                   2982:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   2983: # log the associated role with the area
                   2984:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 2985:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  2986: }
                   2987: 
                   2988: sub custom_roleprivs {
                   2989:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   2990:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   2991:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 2992:     if (&hostname($homsvr) ne '') {
1.567     raeburn  2993:         my ($rdummy,$roledef)=
                   2994:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   2995:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   2996:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   2997:             if (defined($syspriv)) {
                   2998:                 $$allroles{'cm./'}.=':'.$syspriv;
                   2999:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   3000:             }
                   3001:             if ($tdomain ne '') {
                   3002:                 if (defined($dompriv)) {
                   3003:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   3004:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   3005:                 }
                   3006:                 if (($trest ne '') && (defined($coursepriv))) {
                   3007:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   3008:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   3009:                 }
                   3010:             }
                   3011:         }
                   3012:     }
                   3013: }
                   3014: 
1.678     raeburn  3015: sub group_roleprivs {
                   3016:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   3017:     my $access = 1;
                   3018:     my $now = time;
                   3019:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   3020:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   3021:     if ($access) {
1.811     albertel 3022:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  3023:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   3024:     }
                   3025: }
1.567     raeburn  3026: 
                   3027: sub standard_roleprivs {
                   3028:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   3029:     if (defined($pr{$trole.':s'})) {
                   3030:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   3031:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   3032:     }
                   3033:     if ($tdomain ne '') {
                   3034:         if (defined($pr{$trole.':d'})) {
                   3035:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3036:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3037:         }
                   3038:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   3039:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   3040:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   3041:         }
                   3042:     }
                   3043: }
                   3044: 
                   3045: sub set_userprivs {
1.678     raeburn  3046:     my ($userroles,$allroles,$allgroups) = @_; 
1.567     raeburn  3047:     my $author=0;
                   3048:     my $adv=0;
1.678     raeburn  3049:     my %grouproles = ();
                   3050:     if (keys(%{$allgroups}) > 0) {
                   3051:         foreach my $role (keys %{$allroles}) {
1.681     raeburn  3052:             my ($trole,$area,$sec,$extendedarea);
1.811     albertel 3053:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)-) {
1.678     raeburn  3054:                 $trole = $1;
                   3055:                 $area = $2;
1.681     raeburn  3056:                 $sec = $3;
                   3057:                 $extendedarea = $area.$sec;
                   3058:                 if (exists($$allgroups{$area})) {
                   3059:                     foreach my $group (keys(%{$$allgroups{$area}})) {
                   3060:                         my $spec = $trole.'.'.$extendedarea;
                   3061:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
                   3062:                                                 $$allgroups{$area}{$group};
1.678     raeburn  3063:                     }
                   3064:                 }
                   3065:             }
                   3066:         }
                   3067:     }
1.800     albertel 3068:     foreach my $group (keys(%grouproles)) {
                   3069:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  3070:     }
1.800     albertel 3071:     foreach my $role (keys(%{$allroles})) {
                   3072:         my %thesepriv;
                   3073:         if (($role=~/^au/) || ($role=~/^ca/)) { $author=1; }
                   3074:         foreach my $item (split(/:/,$$allroles{$role})) {
                   3075:             if ($item ne '') {
                   3076:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  3077:                 if ($restrictions eq '') {
                   3078:                     $thesepriv{$privilege}='F';
                   3079:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   3080:                     $thesepriv{$privilege}.=$restrictions;
                   3081:                 }
                   3082:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   3083:             }
                   3084:         }
                   3085:         my $thesestr='';
1.800     albertel 3086:         foreach my $priv (keys(%thesepriv)) {
                   3087: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   3088: 	}
                   3089:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  3090:     }
                   3091:     return ($author,$adv);
                   3092: }
                   3093: 
1.12      www      3094: # --------------------------------------------------------------- get interface
                   3095: 
                   3096: sub get {
1.131     albertel 3097:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3098:    my $items='';
1.800     albertel 3099:    foreach my $item (@$storearr) {
                   3100:        $items.=&escape($item).'&';
1.191     harris41 3101:    }
1.12      www      3102:    $items=~s/\&$//;
1.620     albertel 3103:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3104:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 3105:    my $uhome=&homeserver($uname,$udomain);
                   3106: 
1.133     albertel 3107:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3108:    my @pairs=split(/\&/,$rep);
1.273     albertel 3109:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   3110:      return @pairs;
                   3111:    }
1.15      www      3112:    my %returnhash=();
1.42      www      3113:    my $i=0;
1.800     albertel 3114:    foreach my $item (@$storearr) {
                   3115:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      3116:       $i++;
1.191     harris41 3117:    }
1.15      www      3118:    return %returnhash;
1.27      www      3119: }
                   3120: 
                   3121: # --------------------------------------------------------------- del interface
                   3122: 
                   3123: sub del {
1.133     albertel 3124:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      3125:    my $items='';
1.800     albertel 3126:    foreach my $item (@$storearr) {
                   3127:        $items.=&escape($item).'&';
1.191     harris41 3128:    }
1.27      www      3129:    $items=~s/\&$//;
1.620     albertel 3130:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3131:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3132:    my $uhome=&homeserver($uname,$udomain);
                   3133: 
                   3134:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3135: }
                   3136: 
                   3137: # -------------------------------------------------------------- dump interface
                   3138: 
                   3139: sub dump {
1.755     albertel 3140:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   3141:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3142:     if (!$uname) { $uname=$env{'user.name'}; }
                   3143:     my $uhome=&homeserver($uname,$udomain);
                   3144:     if ($regexp) {
                   3145: 	$regexp=&escape($regexp);
                   3146:     } else {
                   3147: 	$regexp='.';
                   3148:     }
                   3149:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3150:     my @pairs=split(/\&/,$rep);
                   3151:     my %returnhash=();
                   3152:     foreach my $item (@pairs) {
                   3153: 	my ($key,$value)=split(/=/,$item,2);
                   3154: 	$key = &unescape($key);
                   3155: 	next if ($key =~ /^error: 2 /);
                   3156: 	$returnhash{$key}=&thaw_unescape($value);
                   3157:     }
                   3158:     return %returnhash;
1.407     www      3159: }
                   3160: 
1.717     albertel 3161: # --------------------------------------------------------- dumpstore interface
                   3162: 
                   3163: sub dumpstore {
                   3164:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822     albertel 3165:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3166:    if (!$uname) { $uname=$env{'user.name'}; }
                   3167:    my $uhome=&homeserver($uname,$udomain);
                   3168:    if ($regexp) {
                   3169:        $regexp=&escape($regexp);
                   3170:    } else {
                   3171:        $regexp='.';
                   3172:    }
                   3173:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3174:    my @pairs=split(/\&/,$rep);
                   3175:    my %returnhash=();
                   3176:    foreach my $item (@pairs) {
                   3177:        my ($key,$value)=split(/=/,$item,2);
                   3178:        next if ($key =~ /^error: 2 /);
                   3179:        $returnhash{$key}=&thaw_unescape($value);
                   3180:    }
                   3181:    return %returnhash;
1.717     albertel 3182: }
                   3183: 
1.407     www      3184: # -------------------------------------------------------------- keys interface
                   3185: 
                   3186: sub getkeys {
                   3187:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 3188:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3189:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      3190:    my $uhome=&homeserver($uname,$udomain);
                   3191:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   3192:    my @keyarray=();
1.800     albertel 3193:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  3194:       next if ($key =~ /^error: 2 /);
1.800     albertel 3195:       push(@keyarray,&unescape($key));
1.407     www      3196:    }
                   3197:    return @keyarray;
1.318     matthew  3198: }
                   3199: 
1.319     matthew  3200: # --------------------------------------------------------------- currentdump
                   3201: sub currentdump {
1.328     matthew  3202:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 3203:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   3204:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   3205:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  3206:    my $uhome = &homeserver($sname,$sdom);
                   3207:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  3208:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  3209:    #
1.318     matthew  3210:    my %returnhash=();
1.319     matthew  3211:    #
                   3212:    if ($rep eq "unknown_cmd") { 
                   3213:        # an old lond will not know currentdump
                   3214:        # Do a dump and make it look like a currentdump
1.822     albertel 3215:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  3216:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   3217:        my %hash = @tmp;
                   3218:        @tmp=();
1.424     matthew  3219:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  3220:    } else {
                   3221:        my @pairs=split(/\&/,$rep);
1.800     albertel 3222:        foreach my $pair (@pairs) {
                   3223:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  3224:            my ($symb,$param) = split(/:/,$key);
                   3225:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 3226:                                                         &thaw_unescape($value);
1.319     matthew  3227:        }
1.191     harris41 3228:    }
1.12      www      3229:    return %returnhash;
1.424     matthew  3230: }
                   3231: 
                   3232: sub convert_dump_to_currentdump{
                   3233:     my %hash = %{shift()};
                   3234:     my %returnhash;
                   3235:     # Code ripped from lond, essentially.  The only difference
                   3236:     # here is the unescaping done by lonnet::dump().  Conceivably
                   3237:     # we might run in to problems with parameter names =~ /^v\./
                   3238:     while (my ($key,$value) = each(%hash)) {
                   3239:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 3240: 	$symb  = &unescape($symb);
                   3241: 	$param = &unescape($param);
1.424     matthew  3242:         next if ($v eq 'version' || $symb eq 'keys');
                   3243:         next if (exists($returnhash{$symb}) &&
                   3244:                  exists($returnhash{$symb}->{$param}) &&
                   3245:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   3246:         $returnhash{$symb}->{$param}=$value;
                   3247:         $returnhash{$symb}->{'v.'.$param}=$v;
                   3248:     }
                   3249:     #
                   3250:     # Remove all of the keys in the hashes which keep track of
                   3251:     # the version of the parameter.
                   3252:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   3253:         # use a foreach because we are going to delete from the hash.
                   3254:         foreach my $key (keys(%$param_hash)) {
                   3255:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   3256:         }
                   3257:     }
                   3258:     return \%returnhash;
1.12      www      3259: }
                   3260: 
1.627     albertel 3261: # ------------------------------------------------------ critical inc interface
                   3262: 
                   3263: sub cinc {
                   3264:     return &inc(@_,'critical');
                   3265: }
                   3266: 
1.449     matthew  3267: # --------------------------------------------------------------- inc interface
                   3268: 
                   3269: sub inc {
1.627     albertel 3270:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 3271:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3272:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  3273:     my $uhome=&homeserver($uname,$udomain);
                   3274:     my $items='';
                   3275:     if (! ref($store)) {
                   3276:         # got a single value, so use that instead
                   3277:         $items = &escape($store).'=&';
                   3278:     } elsif (ref($store) eq 'SCALAR') {
                   3279:         $items = &escape($$store).'=&';        
                   3280:     } elsif (ref($store) eq 'ARRAY') {
                   3281:         $items = join('=&',map {&escape($_);} @{$store});
                   3282:     } elsif (ref($store) eq 'HASH') {
                   3283:         while (my($key,$value) = each(%{$store})) {
                   3284:             $items.= &escape($key).'='.&escape($value).'&';
                   3285:         }
                   3286:     }
                   3287:     $items=~s/\&$//;
1.627     albertel 3288:     if ($critical) {
                   3289: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3290:     } else {
                   3291: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3292:     }
1.449     matthew  3293: }
                   3294: 
1.12      www      3295: # --------------------------------------------------------------- put interface
                   3296: 
                   3297: sub put {
1.134     albertel 3298:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3299:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3300:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3301:    my $uhome=&homeserver($uname,$udomain);
1.12      www      3302:    my $items='';
1.800     albertel 3303:    foreach my $item (keys(%$storehash)) {
                   3304:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 3305:    }
1.12      www      3306:    $items=~s/\&$//;
1.134     albertel 3307:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      3308: }
                   3309: 
1.631     albertel 3310: # ------------------------------------------------------------ newput interface
                   3311: 
                   3312: sub newput {
                   3313:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   3314:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3315:    if (!$uname) { $uname=$env{'user.name'}; }
                   3316:    my $uhome=&homeserver($uname,$udomain);
                   3317:    my $items='';
                   3318:    foreach my $key (keys(%$storehash)) {
                   3319:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   3320:    }
                   3321:    $items=~s/\&$//;
                   3322:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   3323: }
                   3324: 
                   3325: # ---------------------------------------------------------  putstore interface
                   3326: 
1.524     raeburn  3327: sub putstore {
1.715     albertel 3328:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 3329:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3330:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  3331:    my $uhome=&homeserver($uname,$udomain);
                   3332:    my $items='';
1.715     albertel 3333:    foreach my $key (keys(%$storehash)) {
                   3334:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  3335:    }
1.715     albertel 3336:    $items=~s/\&$//;
1.716     albertel 3337:    my $esc_symb=&escape($symb);
                   3338:    my $esc_v=&escape($version);
1.715     albertel 3339:    my $reply =
1.716     albertel 3340:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 3341: 	      $uhome);
                   3342:    if ($reply eq 'unknown_cmd') {
1.716     albertel 3343:        # gfall back to way things use to be done
1.715     albertel 3344:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   3345: 			    $uname);
1.524     raeburn  3346:    }
1.715     albertel 3347:    return $reply;
                   3348: }
                   3349: 
                   3350: sub old_putstore {
1.716     albertel 3351:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   3352:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3353:     if (!$uname) { $uname=$env{'user.name'}; }
                   3354:     my $uhome=&homeserver($uname,$udomain);
                   3355:     my %newstorehash;
1.800     albertel 3356:     foreach my $item (keys(%$storehash)) {
                   3357: 	my $key = $version.':'.&escape($symb).':'.$item;
                   3358: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 3359:     }
                   3360:     my $items='';
                   3361:     my %allitems = ();
1.800     albertel 3362:     foreach my $item (keys(%newstorehash)) {
                   3363: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 3364: 	    my $key = $1.':keys:'.$2;
                   3365: 	    $allitems{$key} .= $3.':';
                   3366: 	}
1.800     albertel 3367: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 3368:     }
1.800     albertel 3369:     foreach my $item (keys(%allitems)) {
                   3370: 	$allitems{$item} =~ s/\:$//;
                   3371: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 3372:     }
                   3373:     $items=~s/\&$//;
                   3374:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  3375: }
                   3376: 
1.47      www      3377: # ------------------------------------------------------ critical put interface
                   3378: 
                   3379: sub cput {
1.134     albertel 3380:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3381:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3382:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3383:    my $uhome=&homeserver($uname,$udomain);
1.47      www      3384:    my $items='';
1.800     albertel 3385:    foreach my $item (keys(%$storehash)) {
                   3386:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 3387:    }
1.47      www      3388:    $items=~s/\&$//;
1.134     albertel 3389:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3390: }
                   3391: 
                   3392: # -------------------------------------------------------------- eget interface
                   3393: 
                   3394: sub eget {
1.133     albertel 3395:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3396:    my $items='';
1.800     albertel 3397:    foreach my $item (@$storearr) {
                   3398:        $items.=&escape($item).'&';
1.191     harris41 3399:    }
1.12      www      3400:    $items=~s/\&$//;
1.620     albertel 3401:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3402:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3403:    my $uhome=&homeserver($uname,$udomain);
                   3404:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3405:    my @pairs=split(/\&/,$rep);
                   3406:    my %returnhash=();
1.42      www      3407:    my $i=0;
1.800     albertel 3408:    foreach my $item (@$storearr) {
                   3409:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      3410:       $i++;
1.191     harris41 3411:    }
1.12      www      3412:    return %returnhash;
                   3413: }
                   3414: 
1.667     albertel 3415: # ------------------------------------------------------------ tmpput interface
                   3416: sub tmpput {
1.802     raeburn  3417:     my ($storehash,$server,$context)=@_;
1.667     albertel 3418:     my $items='';
1.800     albertel 3419:     foreach my $item (keys(%$storehash)) {
                   3420: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 3421:     }
                   3422:     $items=~s/\&$//;
1.802     raeburn  3423:     if (defined($context)) {
                   3424:         $items .= ':'.&escape($context);
                   3425:     }
1.667     albertel 3426:     return &reply("tmpput:$items",$server);
                   3427: }
                   3428: 
                   3429: # ------------------------------------------------------------ tmpget interface
                   3430: sub tmpget {
1.688     albertel 3431:     my ($token,$server)=@_;
                   3432:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3433:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 3434:     my %returnhash;
                   3435:     foreach my $item (split(/\&/,$rep)) {
                   3436: 	my ($key,$value)=split(/=/,$item);
                   3437: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   3438:     }
                   3439:     return %returnhash;
                   3440: }
                   3441: 
1.688     albertel 3442: # ------------------------------------------------------------ tmpget interface
                   3443: sub tmpdel {
                   3444:     my ($token,$server)=@_;
                   3445:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3446:     return &reply("tmpdel:$token",$server);
                   3447: }
                   3448: 
1.765     albertel 3449: # -------------------------------------------------- portfolio access checking
                   3450: 
                   3451: sub portfolio_access {
1.766     albertel 3452:     my ($requrl) = @_;
1.765     albertel 3453:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   3454:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  3455:     if ($result) {
                   3456:         my %setters;
                   3457:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   3458:             my ($startblock,$endblock) =
                   3459:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   3460:             if ($startblock && $endblock) {
                   3461:                 return 'B';
                   3462:             }
                   3463:         } else {
                   3464:             my ($startblock,$endblock) =
                   3465:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   3466:             if ($startblock && $endblock) {
                   3467:                 return 'B';
                   3468:             }
                   3469:         }
                   3470:     }
1.765     albertel 3471:     if ($result eq 'ok') {
1.766     albertel 3472:        return 'F';
1.765     albertel 3473:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 3474:        return 'A';
1.765     albertel 3475:     }
1.766     albertel 3476:     return '';
1.765     albertel 3477: }
                   3478: 
                   3479: sub get_portfolio_access {
1.767     albertel 3480:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   3481: 
                   3482:     if (!ref($access_hash)) {
                   3483: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   3484: 	my %access_controls = &get_access_controls($current_perms,$group,
                   3485: 						   $file_name);
                   3486: 	$access_hash = $access_controls{$file_name};
                   3487:     }
                   3488: 
1.765     albertel 3489:     my ($public,$guest,@domains,@users,@courses,@groups);
                   3490:     my $now = time;
                   3491:     if (ref($access_hash) eq 'HASH') {
                   3492:         foreach my $key (keys(%{$access_hash})) {
                   3493:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   3494:             if ($start > $now) {
                   3495:                 next;
                   3496:             }
                   3497:             if ($end && $end<$now) {
                   3498:                 next;
                   3499:             }
                   3500:             if ($scope eq 'public') {
                   3501:                 $public = $key;
                   3502:                 last;
                   3503:             } elsif ($scope eq 'guest') {
                   3504:                 $guest = $key;
                   3505:             } elsif ($scope eq 'domains') {
                   3506:                 push(@domains,$key);
                   3507:             } elsif ($scope eq 'users') {
                   3508:                 push(@users,$key);
                   3509:             } elsif ($scope eq 'course') {
                   3510:                 push(@courses,$key);
                   3511:             } elsif ($scope eq 'group') {
                   3512:                 push(@groups,$key);
                   3513:             }
                   3514:         }
                   3515:         if ($public) {
                   3516:             return 'ok';
                   3517:         }
                   3518:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   3519:             if ($guest) {
                   3520:                 return $guest;
                   3521:             }
                   3522:         } else {
                   3523:             if (@domains > 0) {
                   3524:                 foreach my $domkey (@domains) {
                   3525:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   3526:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   3527:                             return 'ok';
                   3528:                         }
                   3529:                     }
                   3530:                 }
                   3531:             }
                   3532:             if (@users > 0) {
                   3533:                 foreach my $userkey (@users) {
                   3534:                     if (exists($access_hash->{$userkey}{'users'}{$env{'user.name'}.':'.$env{'user.domain'}})) {
                   3535:                         return 'ok';
                   3536:                     }
                   3537:                 }
                   3538:             }
                   3539:             my %roleshash;
                   3540:             my @courses_and_groups = @courses;
                   3541:             push(@courses_and_groups,@groups); 
                   3542:             if (@courses_and_groups > 0) {
                   3543:                 my (%allgroups,%allroles); 
                   3544:                 my ($start,$end,$role,$sec,$group);
                   3545:                 foreach my $envkey (%env) {
1.811     albertel 3546:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 3547:                         my $cid = $2.'_'.$3; 
                   3548:                         if ($1 eq 'gr') {
                   3549:                             $group = $4;
                   3550:                             $allgroups{$cid}{$group} = $env{$envkey};
                   3551:                         } else {
                   3552:                             if ($4 eq '') {
                   3553:                                 $sec = 'none';
                   3554:                             } else {
                   3555:                                 $sec = $4;
                   3556:                             }
                   3557:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   3558:                         }
1.811     albertel 3559:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 3560:                         my $cid = $2.'_'.$3;
                   3561:                         if ($4 eq '') {
                   3562:                             $sec = 'none';
                   3563:                         } else {
                   3564:                             $sec = $4;
                   3565:                         }
                   3566:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   3567:                     }
                   3568:                 }
                   3569:                 if (keys(%allroles) == 0) {
                   3570:                     return;
                   3571:                 }
                   3572:                 foreach my $key (@courses_and_groups) {
                   3573:                     my %content = %{$$access_hash{$key}};
                   3574:                     my $cnum = $content{'number'};
                   3575:                     my $cdom = $content{'domain'};
                   3576:                     my $cid = $cdom.'_'.$cnum;
                   3577:                     if (!exists($allroles{$cid})) {
                   3578:                         next;
                   3579:                     }    
                   3580:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   3581:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   3582:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   3583:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   3584:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   3585:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   3586:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   3587:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   3588:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   3589:                                         if (grep/^all$/,@sections) {
                   3590:                                             return 'ok';
                   3591:                                         } else {
                   3592:                                             if (grep/^$sec$/,@sections) {
                   3593:                                                 return 'ok';
                   3594:                                             }
                   3595:                                         }
                   3596:                                     }
                   3597:                                 }
                   3598:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   3599:                                     if (grep/^none$/,@groups) {
                   3600:                                         return 'ok';
                   3601:                                     }
                   3602:                                 } else {
                   3603:                                     if (grep/^all$/,@groups) {
                   3604:                                         return 'ok';
                   3605:                                     } 
                   3606:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   3607:                                         if (grep/^$group$/,@groups) {
                   3608:                                             return 'ok';
                   3609:                                         }
                   3610:                                     }
                   3611:                                 } 
                   3612:                             }
                   3613:                         }
                   3614:                     }
                   3615:                 }
                   3616:             }
                   3617:             if ($guest) {
                   3618:                 return $guest;
                   3619:             }
                   3620:         }
                   3621:     }
                   3622:     return;
                   3623: }
                   3624: 
                   3625: sub course_group_datechecker {
                   3626:     my ($dates,$now,$status) = @_;
                   3627:     my ($start,$end) = split(/\./,$dates);
                   3628:     if (!$start && !$end) {
                   3629:         return 'ok';
                   3630:     }
                   3631:     if (grep/^active$/,@{$status}) {
                   3632:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   3633:             return 'ok';
                   3634:         }
                   3635:     }
                   3636:     if (grep/^previous$/,@{$status}) {
                   3637:         if ($end > $now ) {
                   3638:             return 'ok';
                   3639:         }
                   3640:     }
                   3641:     if (grep/^future$/,@{$status}) {
                   3642:         if ($start > $now) {
                   3643:             return 'ok';
                   3644:         }
                   3645:     }
                   3646:     return; 
                   3647: }
                   3648: 
                   3649: sub parse_portfolio_url {
                   3650:     my ($url) = @_;
                   3651: 
                   3652:     my ($type,$udom,$unum,$group,$file_name);
                   3653:     
1.823     albertel 3654:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 3655: 	$type = 1;
                   3656:         $udom = $1;
                   3657:         $unum = $2;
                   3658:         $file_name = $3;
1.823     albertel 3659:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 3660: 	$type = 2;
                   3661:         $udom = $1;
                   3662:         $unum = $2;
                   3663:         $group = $3;
                   3664:         $file_name = $3.'/'.$4;
                   3665:     }
                   3666:     if (wantarray) {
                   3667: 	return ($type,$udom,$unum,$file_name,$group);
                   3668:     }
                   3669:     return $type;
                   3670: }
                   3671: 
                   3672: sub is_portfolio_url {
                   3673:     my ($url) = @_;
                   3674:     return scalar(&parse_portfolio_url($url));
                   3675: }
                   3676: 
1.798     raeburn  3677: sub is_portfolio_file {
                   3678:     my ($file) = @_;
1.820     raeburn  3679:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  3680:         return 1;
                   3681:     }
                   3682:     return;
                   3683: }
                   3684: 
                   3685: 
1.341     www      3686: # ---------------------------------------------- Custom access rule evaluation
                   3687: 
                   3688: sub customaccess {
                   3689:     my ($priv,$uri)=@_;
1.807     albertel 3690:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      3691:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 3692:     $udom = &LONCAPA::clean_domain($udom);
                   3693:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      3694:     my $access=0;
1.800     albertel 3695:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
                   3696: 	my ($effect,$realm,$role)=split(/\:/,$right);
1.343     www      3697:         if ($role) {
                   3698: 	   if ($role ne $urole) { next; }
                   3699:         }
1.800     albertel 3700:         foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   3701:             my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
1.343     www      3702:             if ($tdom) {
                   3703: 		if ($tdom ne $udom) { next; }
                   3704:             }
                   3705:             if ($tcrs) {
                   3706: 		if ($tcrs ne $ucrs) { next; }
                   3707:             }
                   3708:             if ($tsec) {
                   3709: 		if ($tsec ne $usec) { next; }
                   3710:             }
                   3711:             $access=($effect eq 'allow');
                   3712:             last;
1.342     www      3713:         }
1.402     bowersj2 3714: 	if ($realm eq '' && $role eq '') {
                   3715:             $access=($effect eq 'allow');
                   3716: 	}
1.341     www      3717:     }
                   3718:     return $access;
                   3719: }
                   3720: 
1.103     harris41 3721: # ------------------------------------------------- Check for a user privilege
1.12      www      3722: 
                   3723: sub allowed {
1.810     raeburn  3724:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 3725:     my $ver_orguri=$uri;
1.439     www      3726:     $uri=&deversion($uri);
1.152     www      3727:     my $orguri=$uri;
1.52      www      3728:     $uri=&declutter($uri);
1.809     raeburn  3729: 
1.810     raeburn  3730:     if ($priv eq 'evb') {
                   3731: # Evade communication block restrictions for specified role in a course
                   3732:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   3733:             return $1;
                   3734:         } else {
                   3735:             return;
                   3736:         }
                   3737:     }
                   3738: 
1.620     albertel 3739:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      3740: # Free bre access to adm and meta resources
1.775     albertel 3741:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 3742: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   3743: 	&& ($priv eq 'bre')) {
1.14      www      3744: 	return 'F';
1.159     www      3745:     }
                   3746: 
1.545     banghart 3747: # Free bre access to user's own portfolio contents
1.714     raeburn  3748:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  3749:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  3750: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  3751:         my %setters;
                   3752:         my ($startblock,$endblock) = 
                   3753:             &Apache::loncommon::blockcheck(\%setters,'port');
                   3754:         if ($startblock && $endblock) {
                   3755:             return 'B';
                   3756:         } else {
                   3757:             return 'F';
                   3758:         }
1.545     banghart 3759:     }
                   3760: 
1.762     raeburn  3761: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  3762:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   3763:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   3764:         if (exists($env{'request.course.id'})) {
                   3765:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3766:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3767:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   3768:                 my $courseprivid=$env{'request.course.id'};
                   3769:                 $courseprivid=~s/\_/\//;
                   3770:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   3771:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   3772:                     return $1; 
1.762     raeburn  3773:                 } else {
                   3774:                     if ($env{'request.course.sec'}) {
                   3775:                         $courseprivid.='/'.$env{'request.course.sec'};
                   3776:                     }
                   3777:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   3778:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   3779:                         return $2;
                   3780:                     }
1.714     raeburn  3781:                 }
                   3782:             }
                   3783:         }
                   3784:     }
                   3785: 
1.159     www      3786: # Free bre to public access
                   3787: 
                   3788:     if ($priv eq 'bre') {
1.238     www      3789:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 3790: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      3791:            return 'F'; 
                   3792:         }
1.238     www      3793:         if ($copyright eq 'priv') {
                   3794:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 3795: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      3796: 		return '';
                   3797:             }
                   3798:         }
                   3799:         if ($copyright eq 'domain') {
                   3800:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 3801: 	    unless (($env{'user.domain'} eq $1) ||
                   3802:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      3803: 		return '';
                   3804:             }
1.262     matthew  3805:         }
1.620     albertel 3806:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  3807:             # Library role, so allow browsing of resources in this domain.
                   3808:             return 'F';
1.238     www      3809:         }
1.341     www      3810:         if ($copyright eq 'custom') {
                   3811: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   3812:         }
1.14      www      3813:     }
1.264     matthew  3814:     # Domain coordinator is trying to create a course
1.620     albertel 3815:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  3816:         # uri is the requested domain in this case.
                   3817:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  3818:         # a role of dc for the domain in question.
1.620     albertel 3819:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  3820:     }
1.29      www      3821: 
1.52      www      3822:     my $thisallowed='';
                   3823:     my $statecond=0;
                   3824:     my $courseprivid='';
                   3825: 
                   3826: # Course
                   3827: 
1.620     albertel 3828:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3829:        $thisallowed.=$1;
                   3830:     }
1.29      www      3831: 
1.52      www      3832: # Domain
                   3833: 
1.620     albertel 3834:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 3835:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      3836:        $thisallowed.=$1;
                   3837:     }
1.52      www      3838: 
                   3839: # Course: uri itself is a course
1.66      www      3840:     my $courseuri=$uri;
                   3841:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      3842:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      3843: 
1.620     albertel 3844:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 3845:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      3846:        $thisallowed.=$1;
                   3847:     }
1.29      www      3848: 
1.665     albertel 3849: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 3850: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 3851:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 3852: 	$thisallowed='';
1.671     raeburn  3853:         my ($match)=&is_on_map($uri);
                   3854:         if ($match) {
                   3855:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   3856:                   =~/\Q$priv\E\&([^\:]*)/) {
                   3857:                 $thisallowed.=$1;
                   3858:             }
                   3859:         } else {
1.705     albertel 3860:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  3861:             if ($refuri) {
                   3862:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  3863:                     $thisallowed='F';
1.671     raeburn  3864:                 } else {
                   3865:                     $refuri=&declutter($refuri);
                   3866:                     my ($match) = &is_on_map($refuri);
                   3867:                     if ($match) {
                   3868:                         $thisallowed='F';
                   3869:                     }
1.669     raeburn  3870:                 }
1.671     raeburn  3871:             }
                   3872:         }
1.314     www      3873:     }
1.492     albertel 3874: 
1.766     albertel 3875:     if ($priv eq 'bre'
                   3876: 	&& $thisallowed ne 'F' 
                   3877: 	&& $thisallowed ne '2'
                   3878: 	&& &is_portfolio_url($uri)) {
                   3879: 	$thisallowed = &portfolio_access($uri);
                   3880:     }
                   3881:     
1.52      www      3882: # Full access at system, domain or course-wide level? Exit.
1.29      www      3883: 
                   3884:     if ($thisallowed=~/F/) {
                   3885: 	return 'F';
                   3886:     }
                   3887: 
1.52      www      3888: # If this is generating or modifying users, exit with special codes
1.29      www      3889: 
1.643     www      3890:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   3891: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 3892: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      3893: # no author name given, so this just checks on the general right to make a co-author in this domain
                   3894: 	    unless ($auname) { return $thisallowed; }
                   3895: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 3896: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   3897: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   3898: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   3899: 	}
1.52      www      3900: 	return $thisallowed;
                   3901:     }
                   3902: #
1.103     harris41 3903: # Gathered so far: system, domain and course wide privileges
1.52      www      3904: #
                   3905: # Course: See if uri or referer is an individual resource that is part of 
                   3906: # the course
                   3907: 
1.620     albertel 3908:     if ($env{'request.course.id'}) {
1.232     www      3909: 
1.620     albertel 3910:        $courseprivid=$env{'request.course.id'};
                   3911:        if ($env{'request.course.sec'}) {
                   3912:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      3913:        }
                   3914:        $courseprivid=~s/\_/\//;
                   3915:        my $checkreferer=1;
1.232     www      3916:        my ($match,$cond)=&is_on_map($uri);
                   3917:        if ($match) {
                   3918:            $statecond=$cond;
1.620     albertel 3919:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 3920:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3921:                $thisallowed.=$1;
                   3922:                $checkreferer=0;
                   3923:            }
1.29      www      3924:        }
1.83      www      3925:        
1.148     www      3926:        if ($checkreferer) {
1.620     albertel 3927: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      3928:             unless ($refuri) {
1.800     albertel 3929:                 foreach my $key (keys(%env)) {
                   3930: 		    if ($key=~/^httpref\..*\*/) {
                   3931: 			my $pattern=$key;
1.156     www      3932:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      3933:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   3934:                         $pattern=~s/\//\\\//g;
1.152     www      3935:                         if ($orguri=~/$pattern/) {
1.800     albertel 3936: 			    $refuri=$env{$key};
1.148     www      3937:                         }
                   3938:                     }
1.191     harris41 3939:                 }
1.148     www      3940:             }
1.232     www      3941: 
1.148     www      3942:          if ($refuri) { 
1.152     www      3943: 	  $refuri=&declutter($refuri);
1.232     www      3944:           my ($match,$cond)=&is_on_map($refuri);
                   3945:             if ($match) {
                   3946:               my $refstatecond=$cond;
1.620     albertel 3947:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 3948:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3949:                   $thisallowed.=$1;
1.53      www      3950:                   $uri=$refuri;
                   3951:                   $statecond=$refstatecond;
1.52      www      3952:               }
                   3953:           }
1.148     www      3954:         }
1.29      www      3955:        }
1.52      www      3956:    }
1.29      www      3957: 
1.52      www      3958: #
1.103     harris41 3959: # Gathered now: all privileges that could apply, and condition number
1.52      www      3960: # 
                   3961: #
                   3962: # Full or no access?
                   3963: #
1.29      www      3964: 
1.52      www      3965:     if ($thisallowed=~/F/) {
                   3966: 	return 'F';
                   3967:     }
1.29      www      3968: 
1.52      www      3969:     unless ($thisallowed) {
                   3970:         return '';
                   3971:     }
1.29      www      3972: 
1.52      www      3973: # Restrictions exist, deal with them
                   3974: #
                   3975: #   C:according to course preferences
                   3976: #   R:according to resource settings
                   3977: #   L:unless locked
                   3978: #   X:according to user session state
                   3979: #
                   3980: 
                   3981: # Possibly locked functionality, check all courses
1.54      www      3982: # Locks might take effect only after 10 minutes cache expiration for other
                   3983: # courses, and 2 minutes for current course
1.52      www      3984: 
                   3985:     my $envkey;
                   3986:     if ($thisallowed=~/L/) {
1.620     albertel 3987:         foreach $envkey (keys %env) {
1.54      www      3988:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   3989:                my $courseid=$2;
                   3990:                my $roleid=$1.'.'.$2;
1.92      www      3991:                $courseid=~s/^\///;
1.54      www      3992:                my $expiretime=600;
1.620     albertel 3993:                if ($env{'request.role'} eq $roleid) {
1.54      www      3994: 		  $expiretime=120;
                   3995:                }
                   3996: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   3997:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 3998:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 3999: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      4000:                }
1.620     albertel 4001:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   4002:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   4003: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   4004:                        &log($env{'user.domain'},$env{'user.name'},
                   4005:                             $env{'user.home'},
1.57      www      4006:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      4007:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 4008:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      4009: 		       return '';
                   4010:                    }
                   4011:                }
1.620     albertel 4012:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   4013:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   4014: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   4015:                        &log($env{'user.domain'},$env{'user.name'},
                   4016:                             $env{'user.home'},
1.57      www      4017:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      4018:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 4019:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      4020: 		       return '';
                   4021:                    }
                   4022:                }
                   4023: 	   }
1.29      www      4024:        }
1.52      www      4025:     }
                   4026:    
                   4027: #
                   4028: # Rest of the restrictions depend on selected course
                   4029: #
                   4030: 
1.620     albertel 4031:     unless ($env{'request.course.id'}) {
1.766     albertel 4032: 	if ($thisallowed eq 'A') {
                   4033: 	    return 'A';
1.814     raeburn  4034:         } elsif ($thisallowed eq 'B') {
                   4035:             return 'B';
1.766     albertel 4036: 	} else {
                   4037: 	    return '1';
                   4038: 	}
1.52      www      4039:     }
1.29      www      4040: 
1.52      www      4041: #
                   4042: # Now user is definitely in a course
                   4043: #
1.53      www      4044: 
                   4045: 
                   4046: # Course preferences
                   4047: 
                   4048:    if ($thisallowed=~/C/) {
1.620     albertel 4049:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   4050:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   4051:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 4052: 	   =~/\Q$rolecode\E/) {
1.689     albertel 4053: 	   if ($priv ne 'pch') { 
                   4054: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   4055: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   4056: 			$env{'request.course.id'});
                   4057: 	   }
1.237     www      4058:            return '';
                   4059:        }
                   4060: 
1.620     albertel 4061:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 4062: 	   =~/\Q$unamedom\E/) {
1.689     albertel 4063: 	   if ($priv ne 'pch') { 
                   4064: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   4065: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   4066: 			$env{'request.course.id'});
                   4067: 	   }
1.54      www      4068:            return '';
                   4069:        }
1.53      www      4070:    }
                   4071: 
                   4072: # Resource preferences
                   4073: 
                   4074:    if ($thisallowed=~/R/) {
1.620     albertel 4075:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 4076:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689     albertel 4077: 	   if ($priv ne 'pch') { 
                   4078: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   4079: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   4080: 	   }
                   4081: 	   return '';
1.54      www      4082:        }
1.53      www      4083:    }
1.30      www      4084: 
1.246     www      4085: # Restricted by state or randomout?
1.30      www      4086: 
1.52      www      4087:    if ($thisallowed=~/X/) {
1.620     albertel 4088:       if ($env{'acc.randomout'}) {
1.579     albertel 4089: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 4090:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      4091:             return ''; 
                   4092:          }
1.247     www      4093:       }
                   4094:       if (&condval($statecond)) {
1.52      www      4095: 	 return '2';
                   4096:       } else {
                   4097:          return '';
                   4098:       }
                   4099:    }
1.30      www      4100: 
1.766     albertel 4101:     if ($thisallowed eq 'A') {
                   4102: 	return 'A';
1.814     raeburn  4103:     } elsif ($thisallowed eq 'B') {
                   4104:         return 'B';
1.766     albertel 4105:     }
1.52      www      4106:    return 'F';
1.232     www      4107: }
                   4108: 
1.710     albertel 4109: sub split_uri_for_cond {
                   4110:     my $uri=&deversion(&declutter(shift));
                   4111:     my @uriparts=split(/\//,$uri);
                   4112:     my $filename=pop(@uriparts);
                   4113:     my $pathname=join('/',@uriparts);
                   4114:     return ($pathname,$filename);
                   4115: }
1.232     www      4116: # --------------------------------------------------- Is a resource on the map?
                   4117: 
                   4118: sub is_on_map {
1.710     albertel 4119:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 4120:     #Trying to find the conditional for the file
1.620     albertel 4121:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 4122: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      4123:     if ($match) {
1.289     bowersj2 4124: 	return (1,$1);
                   4125:     } else {
1.434     www      4126: 	return (0,0);
1.289     bowersj2 4127:     }
1.12      www      4128: }
                   4129: 
1.427     www      4130: # --------------------------------------------------------- Get symb from alias
                   4131: 
                   4132: sub get_symb_from_alias {
                   4133:     my $symb=shift;
                   4134:     my ($map,$resid,$url)=&decode_symb($symb);
                   4135: # Already is a symb
                   4136:     if ($url) { return $symb; }
                   4137: # Must be an alias
                   4138:     my $aliassymb='';
                   4139:     my %bighash;
1.620     albertel 4140:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      4141:                             &GDBM_READER(),0640)) {
                   4142:         my $rid=$bighash{'mapalias_'.$symb};
                   4143: 	if ($rid) {
                   4144: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 4145: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   4146: 				    $resid,$bighash{'src_'.$rid});
1.427     www      4147: 	}
                   4148:         untie %bighash;
                   4149:     }
                   4150:     return $aliassymb;
                   4151: }
                   4152: 
1.12      www      4153: # ----------------------------------------------------------------- Define Role
                   4154: 
                   4155: sub definerole {
                   4156:   if (allowed('mcr','/')) {
                   4157:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 4158:     foreach my $role (split(':',$sysrole)) {
                   4159: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4160:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   4161:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   4162: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      4163:                return "refused:s:$crole&$cqual"; 
                   4164:             }
                   4165:         }
1.191     harris41 4166:     }
1.800     albertel 4167:     foreach my $role (split(':',$domrole)) {
                   4168: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4169:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   4170:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   4171: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      4172:                return "refused:d:$crole&$cqual"; 
                   4173:             }
                   4174:         }
1.191     harris41 4175:     }
1.800     albertel 4176:     foreach my $role (split(':',$courole)) {
                   4177: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4178:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   4179:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   4180: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      4181:                return "refused:c:$crole&$cqual"; 
                   4182:             }
                   4183:         }
1.191     harris41 4184:     }
1.620     albertel 4185:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   4186:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      4187: 	        "rolesdef_$rolename=".
                   4188:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 4189:     return reply($command,$env{'user.home'});
1.12      www      4190:   } else {
                   4191:     return 'refused';
                   4192:   }
1.105     harris41 4193: }
                   4194: 
                   4195: # ---------------- Make a metadata query against the network of library servers
                   4196: 
                   4197: sub metadata_query {
1.244     matthew  4198:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 4199:     my %rhash;
1.845     albertel 4200:     my %libserv = &all_library();
1.244     matthew  4201:     my @server_list = (defined($server_array) ? @$server_array
                   4202:                                               : keys(%libserv) );
                   4203:     for my $server (@server_list) {
1.118     harris41 4204: 	unless ($custom or $customshow) {
                   4205: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   4206: 	    $rhash{$server}=$reply;
                   4207: 	}
                   4208: 	else {
                   4209: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   4210: 			     &escape($custom).':'.&escape($customshow),
                   4211: 			     $server);
                   4212: 	    $rhash{$server}=$reply;
                   4213: 	}
1.112     harris41 4214:     }
1.118     harris41 4215:     return \%rhash;
1.240     www      4216: }
                   4217: 
                   4218: # ----------------------------------------- Send log queries and wait for reply
                   4219: 
                   4220: sub log_query {
                   4221:     my ($uname,$udom,$query,%filters)=@_;
                   4222:     my $uhome=&homeserver($uname,$udom);
                   4223:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 4224:     my $uhost=&hostname($uhome);
1.800     albertel 4225:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      4226:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   4227:                        $uhome);
1.479     albertel 4228:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      4229:     return get_query_reply($queryid);
                   4230: }
                   4231: 
1.818     raeburn  4232: # -------------------------- Update MySQL table for portfolio file
                   4233: 
                   4234: sub update_portfolio_table {
1.821     raeburn  4235:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.818     raeburn  4236:     my $homeserver = &homeserver($uname,$udom);
                   4237:     my $queryid=
1.821     raeburn  4238:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   4239:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  4240:     my $reply = &get_query_reply($queryid);
                   4241:     return $reply;
                   4242: }
                   4243: 
1.508     raeburn  4244: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  4245: 
                   4246: sub fetch_enrollment_query {
1.511     raeburn  4247:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  4248:     my $homeserver;
1.547     raeburn  4249:     my $maxtries = 1;
1.508     raeburn  4250:     if ($context eq 'automated') {
                   4251:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  4252:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  4253:     } else {
                   4254:         $homeserver = &homeserver($cnum,$dom);
                   4255:     }
1.838     albertel 4256:     my $host=&hostname($homeserver);
1.506     raeburn  4257:     my $cmd = '';
1.800     albertel 4258:     foreach my $affiliate (keys %{$affiliatesref}) {
                   4259:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  4260:     }
                   4261:     $cmd =~ s/%%$//;
                   4262:     $cmd = &escape($cmd);
                   4263:     my $query = 'fetchenrollment';
1.620     albertel 4264:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  4265:     unless ($queryid=~/^\Q$host\E\_/) { 
                   4266:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   4267:         return 'error: '.$queryid;
                   4268:     }
1.506     raeburn  4269:     my $reply = &get_query_reply($queryid);
1.547     raeburn  4270:     my $tries = 1;
                   4271:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   4272:         $reply = &get_query_reply($queryid);
                   4273:         $tries ++;
                   4274:     }
1.526     raeburn  4275:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 4276:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  4277:     } else {
1.515     raeburn  4278:         my @responses = split/:/,$reply;
                   4279:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 4280:             foreach my $line (@responses) {
                   4281:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  4282:                 $$replyref{$key} = $value;
                   4283:             }
                   4284:         } else {
1.506     raeburn  4285:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800     albertel 4286:             foreach my $line (@responses) {
                   4287:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  4288:                 $$replyref{$key} = $value;
                   4289:                 if ($value > 0) {
1.800     albertel 4290:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   4291:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  4292:                         my $destname = $pathname.'/'.$filename;
                   4293:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  4294:                         if ($xml_classlist =~ /^error/) {
                   4295:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   4296:                         } else {
1.506     raeburn  4297:                             if ( open(FILE,">$destname") ) {
                   4298:                                 print FILE &unescape($xml_classlist);
                   4299:                                 close(FILE);
1.526     raeburn  4300:                             } else {
                   4301:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  4302:                             }
                   4303:                         }
                   4304:                     }
                   4305:                 }
                   4306:             }
                   4307:         }
                   4308:         return 'ok';
                   4309:     }
                   4310:     return 'error';
                   4311: }
                   4312: 
1.242     www      4313: sub get_query_reply {
                   4314:     my $queryid=shift;
1.240     www      4315:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   4316:     my $reply='';
                   4317:     for (1..100) {
                   4318: 	sleep 2;
                   4319:         if (-e $replyfile.'.end') {
1.448     albertel 4320: 	    if (open(my $fh,$replyfile)) {
1.240     www      4321:                $reply.=<$fh>;
1.448     albertel 4322:                close($fh);
1.240     www      4323: 	   } else { return 'error: reply_file_error'; }
1.242     www      4324:            return &unescape($reply);
                   4325: 	}
1.240     www      4326:     }
1.242     www      4327:     return 'timeout:'.$queryid;
1.240     www      4328: }
                   4329: 
                   4330: sub courselog_query {
1.241     www      4331: #
                   4332: # possible filters:
                   4333: # url: url or symb
                   4334: # username
                   4335: # domain
                   4336: # action: view, submit, grade
                   4337: # start: timestamp
                   4338: # end: timestamp
                   4339: #
1.240     www      4340:     my (%filters)=@_;
1.620     albertel 4341:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      4342:     if ($filters{'url'}) {
                   4343: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   4344:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   4345:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   4346:     }
1.620     albertel 4347:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4348:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      4349:     return &log_query($cname,$cdom,'courselog',%filters);
                   4350: }
                   4351: 
                   4352: sub userlog_query {
                   4353:     my ($uname,$udom,%filters)=@_;
                   4354:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      4355: }
                   4356: 
1.506     raeburn  4357: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   4358: 
                   4359: sub auto_run {
1.508     raeburn  4360:     my ($cnum,$cdom) = @_;
                   4361:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  4362:     my $response = &reply('autorun:'.$cdom,$homeserver);
1.506     raeburn  4363:     return $response;
                   4364: }
1.776     albertel 4365: 
1.506     raeburn  4366: sub auto_get_sections {
1.508     raeburn  4367:     my ($cnum,$cdom,$inst_coursecode) = @_;
                   4368:     my $homeserver = &homeserver($cnum,$cdom);
1.506     raeburn  4369:     my @secs = ();
1.511     raeburn  4370:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506     raeburn  4371:     unless ($response eq 'refused') {
                   4372:         @secs = split/:/,$response;
                   4373:     }
                   4374:     return @secs;
                   4375: }
1.776     albertel 4376: 
1.506     raeburn  4377: sub auto_new_course {
1.508     raeburn  4378:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
                   4379:     my $homeserver = &homeserver($cnum,$cdom);
1.515     raeburn  4380:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506     raeburn  4381:     return $response;
                   4382: }
1.776     albertel 4383: 
1.506     raeburn  4384: sub auto_validate_courseID {
1.508     raeburn  4385:     my ($cnum,$cdom,$inst_course_id) = @_;
                   4386:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  4387:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  4388:     return $response;
                   4389: }
1.776     albertel 4390: 
1.506     raeburn  4391: sub auto_create_password {
1.508     raeburn  4392:     my ($cnum,$cdom,$authparam) = @_;
                   4393:     my $homeserver = &homeserver($cnum,$cdom); 
1.506     raeburn  4394:     my $create_passwd = 0;
                   4395:     my $authchk = '';
1.511     raeburn  4396:     my $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
1.506     raeburn  4397:     if ($response eq 'refused') {
                   4398:         $authchk = 'refused';
                   4399:     } else {
                   4400:         ($authparam,$create_passwd,$authchk) = split/:/,$response;
                   4401:     }
                   4402:     return ($authparam,$create_passwd,$authchk);
                   4403: }
                   4404: 
1.706     raeburn  4405: sub auto_photo_permission {
                   4406:     my ($cnum,$cdom,$students) = @_;
                   4407:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 4408:     my ($outcome,$perm_reqd,$conditions) = 
                   4409: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 4410:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4411: 	return (undef,undef);
                   4412:     }
1.706     raeburn  4413:     return ($outcome,$perm_reqd,$conditions);
                   4414: }
                   4415: 
                   4416: sub auto_checkphotos {
                   4417:     my ($uname,$udom,$pid) = @_;
                   4418:     my $homeserver = &homeserver($uname,$udom);
                   4419:     my ($result,$resulttype);
                   4420:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 4421: 				   &escape($uname).':'.&escape($pid),
                   4422: 				   $homeserver));
1.709     albertel 4423:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4424: 	return (undef,undef);
                   4425:     }
1.706     raeburn  4426:     if ($outcome) {
                   4427:         ($result,$resulttype) = split(/:/,$outcome);
                   4428:     } 
                   4429:     return ($result,$resulttype);
                   4430: }
                   4431: 
                   4432: sub auto_photochoice {
                   4433:     my ($cnum,$cdom) = @_;
                   4434:     my $homeserver = &homeserver($cnum,$cdom);
                   4435:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 4436: 						       &escape($cdom),
                   4437: 						       $homeserver)));
1.709     albertel 4438:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4439: 	return (undef,undef);
                   4440:     }
1.706     raeburn  4441:     return ($update,$comment);
                   4442: }
                   4443: 
                   4444: sub auto_photoupdate {
                   4445:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   4446:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 4447:     my $host=&hostname($homeserver);
1.706     raeburn  4448:     my $cmd = '';
                   4449:     my $maxtries = 1;
1.800     albertel 4450:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   4451:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  4452:     }
                   4453:     $cmd =~ s/%%$//;
                   4454:     $cmd = &escape($cmd);
                   4455:     my $query = 'institutionalphotos';
                   4456:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   4457:     unless ($queryid=~/^\Q$host\E\_/) {
                   4458:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   4459:         return 'error: '.$queryid;
                   4460:     }
                   4461:     my $reply = &get_query_reply($queryid);
                   4462:     my $tries = 1;
                   4463:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   4464:         $reply = &get_query_reply($queryid);
                   4465:         $tries ++;
                   4466:     }
                   4467:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   4468:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   4469:     } else {
                   4470:         my @responses = split(/:/,$reply);
                   4471:         my $outcome = shift(@responses); 
                   4472:         foreach my $item (@responses) {
                   4473:             my ($key,$value) = split(/=/,$item);
                   4474:             $$photo{$key} = $value;
                   4475:         }
                   4476:         return $outcome;
                   4477:     }
                   4478:     return 'error';
                   4479: }
                   4480: 
1.521     raeburn  4481: sub auto_instcode_format {
1.793     albertel 4482:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   4483: 	$cat_order) = @_;
1.521     raeburn  4484:     my $courses = '';
1.772     raeburn  4485:     my @homeservers;
1.521     raeburn  4486:     if ($caller eq 'global') {
1.841     albertel 4487: 	my %servers = &get_servers($codedom,'library');
                   4488: 	foreach my $tryserver (keys(%servers)) {
                   4489: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   4490: 		push(@homeservers,$tryserver);
                   4491: 	    }
1.584     raeburn  4492:         }
1.521     raeburn  4493:     } else {
1.772     raeburn  4494:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  4495:     }
1.793     albertel 4496:     foreach my $code (keys(%{$instcodes})) {
                   4497:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  4498:     }
                   4499:     chop($courses);
1.772     raeburn  4500:     my $ok_response = 0;
                   4501:     my $response;
                   4502:     while (@homeservers > 0 && $ok_response == 0) {
                   4503:         my $server = shift(@homeservers); 
                   4504:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   4505:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   4506:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.793     albertel 4507: 		split/:/,$response;
1.772     raeburn  4508:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   4509:             push(@{$codetitles},&str2array($codetitles_str));
                   4510:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   4511:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   4512:             $ok_response = 1;
                   4513:         }
                   4514:     }
                   4515:     if ($ok_response) {
1.521     raeburn  4516:         return 'ok';
1.772     raeburn  4517:     } else {
                   4518:         return $response;
1.521     raeburn  4519:     }
                   4520: }
                   4521: 
1.792     raeburn  4522: sub auto_instcode_defaults {
                   4523:     my ($domain,$returnhash,$code_order) = @_;
                   4524:     my @homeservers;
1.841     albertel 4525: 
                   4526:     my %servers = &get_servers($domain,'library');
                   4527:     foreach my $tryserver (keys(%servers)) {
                   4528: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   4529: 	    push(@homeservers,$tryserver);
                   4530: 	}
1.792     raeburn  4531:     }
1.841     albertel 4532: 
1.792     raeburn  4533:     my $response;
1.841     albertel 4534:     foreach my $server (@homeservers) {
1.792     raeburn  4535:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 4536:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   4537: 	
                   4538: 	foreach my $pair (split(/\&/,$response)) {
                   4539: 	    my ($name,$value)=split(/\=/,$pair);
                   4540: 	    if ($name eq 'code_order') {
                   4541: 		@{$code_order} = split(/\&/,&unescape($value));
                   4542: 	    } else {
                   4543: 		$returnhash->{&unescape($name)}=&unescape($value);
                   4544: 	    }
                   4545: 	}
                   4546: 	return 'ok';
1.792     raeburn  4547:     }
1.841     albertel 4548: 
                   4549:     return $response;
1.792     raeburn  4550: } 
                   4551: 
1.777     albertel 4552: sub auto_validate_class_sec {
1.773     raeburn  4553:     my ($cdom,$cnum,$owner,$inst_class) = @_;
                   4554:     my $homeserver = &homeserver($cnum,$cdom);
                   4555:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.774     banghart 4556:                         &escape($owner).':'.$cdom,$homeserver);
1.773     raeburn  4557:     return $response;
                   4558: }
                   4559: 
1.679     raeburn  4560: # ------------------------------------------------------- Course Group routines
                   4561: 
                   4562: sub get_coursegroups {
1.809     raeburn  4563:     my ($cdom,$cnum,$group,$namespace) = @_;
                   4564:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  4565: }
                   4566: 
1.679     raeburn  4567: sub modify_coursegroup {
                   4568:     my ($cdom,$cnum,$groupsettings) = @_;
                   4569:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   4570: }
                   4571: 
1.809     raeburn  4572: sub toggle_coursegroup_status {
                   4573:     my ($cdom,$cnum,$group,$action) = @_;
                   4574:     my ($from_namespace,$to_namespace);
                   4575:     if ($action eq 'delete') {
                   4576:         $from_namespace = 'coursegroups';
                   4577:         $to_namespace = 'deleted_groups';
                   4578:     } else {
                   4579:         $from_namespace = 'deleted_groups';
                   4580:         $to_namespace = 'coursegroups';
                   4581:     }
                   4582:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  4583:     if (my $tmp = &error(%curr_group)) {
                   4584:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   4585:         return ('read error',$tmp);
                   4586:     } else {
                   4587:         my %savedsettings = %curr_group; 
1.809     raeburn  4588:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  4589:         my $deloutcome;
                   4590:         if ($result eq 'ok') {
1.809     raeburn  4591:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  4592:         } else {
                   4593:             return ('write error',$result);
                   4594:         }
                   4595:         if ($deloutcome eq 'ok') {
                   4596:             return 'ok';
                   4597:         } else {
                   4598:             return ('delete error',$deloutcome);
                   4599:         }
                   4600:     }
                   4601: }
                   4602: 
1.679     raeburn  4603: sub modify_group_roles {
                   4604:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
                   4605:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   4606:     my $role = 'gr/'.&escape($userprivs);
                   4607:     my ($uname,$udom) = split(/:/,$user);
                   4608:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
1.684     raeburn  4609:     if ($result eq 'ok') {
                   4610:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   4611:     }
1.679     raeburn  4612:     return $result;
                   4613: }
                   4614: 
                   4615: sub modify_coursegroup_membership {
                   4616:     my ($cdom,$cnum,$membership) = @_;
                   4617:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   4618:     return $result;
                   4619: }
                   4620: 
1.682     raeburn  4621: sub get_active_groups {
                   4622:     my ($udom,$uname,$cdom,$cnum) = @_;
                   4623:     my $now = time;
                   4624:     my %groups = ();
                   4625:     foreach my $key (keys(%env)) {
1.811     albertel 4626:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  4627:             my ($start,$end) = split(/\./,$env{$key});
                   4628:             if (($end!=0) && ($end<$now)) { next; }
                   4629:             if (($start!=0) && ($start>$now)) { next; }
                   4630:             if ($1 eq $cdom && $2 eq $cnum) {
                   4631:                 $groups{$3} = $env{$key} ;
                   4632:             }
                   4633:         }
                   4634:     }
                   4635:     return %groups;
                   4636: }
                   4637: 
1.683     raeburn  4638: sub get_group_membership {
                   4639:     my ($cdom,$cnum,$group) = @_;
                   4640:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   4641: }
                   4642: 
                   4643: sub get_users_groups {
                   4644:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  4645:     my @usersgroups;
1.683     raeburn  4646:     my $cachetime=1800;
                   4647: 
                   4648:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  4649:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   4650:     if (defined($cached)) {
1.734     albertel 4651:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  4652:     } else {  
                   4653:         $grouplist = '';
1.816     raeburn  4654:         my $courseurl = &courseid_to_courseurl($courseid);
                   4655:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  4656:         my $access_end = $env{'course.'.$courseid.
                   4657:                               '.default_enrollment_end_date'};
                   4658:         my $now = time;
                   4659:         foreach my $key (keys(%roleshash)) {
                   4660:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   4661:                 my $group = $1;
                   4662:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   4663:                     my $start = $2;
                   4664:                     my $end = $1;
                   4665:                     if ($start == -1) { next; } # deleted from group
                   4666:                     if (($start!=0) && ($start>$now)) { next; }
                   4667:                     if (($end!=0) && ($end<$now)) {
                   4668:                         if ($access_end && $access_end < $now) {
                   4669:                             if ($access_end - $end < 86400) {
                   4670:                                 push(@usersgroups,$group);
1.733     raeburn  4671:                             }
                   4672:                         }
1.817     raeburn  4673:                         next;
1.733     raeburn  4674:                     }
1.817     raeburn  4675:                     push(@usersgroups,$group);
1.683     raeburn  4676:                 }
                   4677:             }
                   4678:         }
1.817     raeburn  4679:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   4680:         $grouplist = join(':',@usersgroups);
                   4681:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  4682:     }
1.733     raeburn  4683:     return @usersgroups;
1.683     raeburn  4684: }
                   4685: 
                   4686: sub devalidate_getgroups_cache {
                   4687:     my ($udom,$uname,$cdom,$cnum)=@_;
                   4688:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 4689: 
1.683     raeburn  4690:     my $hashid="$udom:$uname:$courseid";
                   4691:     &devalidate_cache_new('getgroups',$hashid);
                   4692: }
                   4693: 
1.12      www      4694: # ------------------------------------------------------------------ Plain Text
                   4695: 
                   4696: sub plaintext {
1.742     raeburn  4697:     my ($short,$type,$cid) = @_;
1.758     albertel 4698:     if ($short =~ /^cr/) {
                   4699: 	return (split('/',$short))[-1];
                   4700:     }
1.742     raeburn  4701:     if (!defined($cid)) {
                   4702:         $cid = $env{'request.course.id'};
                   4703:     }
                   4704:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
                   4705:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
                   4706:                                           '.plaintext'});
                   4707:     }
                   4708:     my %rolenames = (
                   4709:                       Course => 'std',
                   4710:                       Group => 'alt1',
                   4711:                     );
                   4712:     if (defined($type) && 
                   4713:          defined($rolenames{$type}) && 
                   4714:          defined($prp{$short}{$rolenames{$type}})) {
                   4715:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
                   4716:     } else {
                   4717:         return &Apache::lonlocal::mt($prp{$short}{'std'});
                   4718:     }
1.12      www      4719: }
                   4720: 
                   4721: # ----------------------------------------------------------------- Assign Role
                   4722: 
                   4723: sub assignrole {
1.357     www      4724:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
1.21      www      4725:     my $mrole;
                   4726:     if ($role =~ /^cr\//) {
1.393     www      4727:         my $cwosec=$url;
1.811     albertel 4728:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      4729: 	unless (&allowed('ccr',$cwosec)) {
1.104     www      4730:            &logthis('Refused custom assignrole: '.
                   4731:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 4732: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      4733:            return 'refused'; 
                   4734:         }
1.21      www      4735:         $mrole='cr';
1.678     raeburn  4736:     } elsif ($role =~ /^gr\//) {
                   4737:         my $cwogrp=$url;
1.811     albertel 4738:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  4739:         unless (&allowed('mdg',$cwogrp)) {
                   4740:             &logthis('Refused group assignrole: '.
                   4741:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   4742:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   4743:             return 'refused';
                   4744:         }
                   4745:         $mrole='gr';
1.21      www      4746:     } else {
1.82      www      4747:         my $cwosec=$url;
1.811     albertel 4748:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.373     www      4749:         unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) { 
1.104     www      4750:            &logthis('Refused assignrole: '.
                   4751:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 4752: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      4753:            return 'refused'; 
                   4754:         }
1.21      www      4755:         $mrole=$role;
                   4756:     }
1.620     albertel 4757:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      4758:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      4759:     if ($end) { $command.='_'.$end; }
1.21      www      4760:     if ($start) {
                   4761: 	if ($end) { 
1.81      www      4762:            $command.='_'.$start; 
1.21      www      4763:         } else {
1.81      www      4764:            $command.='_0_'.$start;
1.21      www      4765:         }
                   4766:     }
1.739     raeburn  4767:     my $origstart = $start;
                   4768:     my $origend = $end;
1.357     www      4769: # actually delete
                   4770:     if ($deleteflag) {
1.373     www      4771: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      4772: # modify command to delete the role
1.620     albertel 4773:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      4774:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 4775: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      4776: # set start and finish to negative values for userrolelog
                   4777:            $start=-1;
                   4778:            $end=-1;
                   4779:         }
                   4780:     }
                   4781: # send command
1.349     www      4782:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      4783: # log new user role if status is ok
1.349     www      4784:     if ($answer eq 'ok') {
1.663     raeburn  4785: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  4786: # for course roles, perform group memberships changes triggered by role change.
                   4787:         unless ($role =~ /^gr/) {
                   4788:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   4789:                                              $origstart);
                   4790:         }
1.349     www      4791:     }
                   4792:     return $answer;
1.169     harris41 4793: }
                   4794: 
                   4795: # -------------------------------------------------- Modify user authentication
1.197     www      4796: # Overrides without validation
                   4797: 
1.169     harris41 4798: sub modifyuserauth {
                   4799:     my ($udom,$uname,$umode,$upass)=@_;
                   4800:     my $uhome=&homeserver($uname,$udom);
1.197     www      4801:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   4802:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 4803:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   4804:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 4805:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   4806: 		     &escape($upass),$uhome);
1.620     albertel 4807:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      4808:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   4809:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   4810:     &log($udom,,$uname,$uhome,
1.620     albertel 4811:         'Authentication changed by '.$env{'user.domain'}.', '.
                   4812:                                      $env{'user.name'}.', '.$umode.
1.197     www      4813:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 4814:     unless ($reply eq 'ok') {
1.197     www      4815:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 4816: 	return 'error: '.$reply;
                   4817:     }   
1.170     harris41 4818:     return 'ok';
1.80      www      4819: }
                   4820: 
1.81      www      4821: # --------------------------------------------------------------- Modify a user
1.80      www      4822: 
1.81      www      4823: sub modifyuser {
1.206     matthew  4824:     my ($udom,    $uname, $uid,
                   4825:         $umode,   $upass, $first,
                   4826:         $middle,  $last,  $gene,
1.387     www      4827:         $forceid, $desiredhome, $email)=@_;
1.807     albertel 4828:     $udom= &LONCAPA::clean_domain($udom);
                   4829:     $uname=&LONCAPA::clean_username($uname);
1.81      www      4830:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      4831:              $umode.', '.$first.', '.$middle.', '.
1.206     matthew  4832: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
                   4833:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   4834:                                      ' desiredhome not specified'). 
1.620     albertel 4835:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   4836:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 4837:     my $uhome=&homeserver($uname,$udom,'true');
1.80      www      4838: # ----------------------------------------------------------------- Create User
1.406     albertel 4839:     if (($uhome eq 'no_host') && 
                   4840: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      4841:         my $unhome='';
1.844     albertel 4842:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  4843:             $unhome = $desiredhome;
1.620     albertel 4844: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   4845: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  4846:         } else { # load balancing routine for determining $unhome
1.81      www      4847:             my $loadm=10000000;
1.841     albertel 4848: 	    my %servers = &get_servers($udom,'library');
                   4849: 	    foreach my $tryserver (keys(%servers)) {
                   4850: 		my $answer=reply('load',$tryserver);
                   4851: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   4852: 		    $loadm=$answer;
                   4853: 		    $unhome=$tryserver;
                   4854: 		}
1.80      www      4855: 	    }
                   4856:         }
                   4857:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  4858: 	    return 'error: unable to find a home server for '.$uname.
                   4859:                    ' in domain '.$udom;
1.80      www      4860:         }
                   4861:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   4862:                          &escape($upass),$unhome);
                   4863: 	unless ($reply eq 'ok') {
                   4864:             return 'error: '.$reply;
                   4865:         }   
1.230     stredwic 4866:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      4867:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  4868: 	    return 'error: unable verify users home machine.';
1.80      www      4869:         }
1.209     matthew  4870:     }   # End of creation of new user
1.80      www      4871: # ---------------------------------------------------------------------- Add ID
                   4872:     if ($uid) {
                   4873:        $uid=~tr/A-Z/a-z/;
                   4874:        my %uidhash=&idrget($udom,$uname);
1.196     www      4875:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   4876:          && (!$forceid)) {
1.80      www      4877: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  4878: 	      return 'error: user id "'.$uid.'" does not match '.
                   4879:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      4880:           }
                   4881:        } else {
                   4882: 	  &idput($udom,($uname => $uid));
                   4883:        }
                   4884:     }
                   4885: # -------------------------------------------------------------- Add names, etc
1.313     matthew  4886:     my @tmp=&get('environment',
1.134     albertel 4887: 		   ['firstname','middlename','lastname','generation'],
                   4888: 		   $udom,$uname);
1.313     matthew  4889:     my %names;
                   4890:     if ($tmp[0] =~ m/^error:.*/) { 
                   4891:         %names=(); 
                   4892:     } else {
                   4893:         %names = @tmp;
                   4894:     }
1.388     www      4895: #
                   4896: # Make sure to not trash student environment if instructor does not bother
                   4897: # to supply name and email information
                   4898: #
                   4899:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  4900:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      4901:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  4902:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      4903:     if ($email) {
                   4904:        $email=~s/[^\w\@\.\-\,]//gs;
                   4905:        if ($email=~/\@/) { $names{'notification'} = $email;
                   4906: 			   $names{'critnotification'} = $email;
                   4907: 			   $names{'permanentemail'} = $email; }
                   4908:     }
1.134     albertel 4909:     my $reply = &put('environment', \%names, $udom,$uname);
                   4910:     if ($reply ne 'ok') { return 'error: '.$reply; }
1.680     www      4911:     &devalidate_cache_new('namescache',$uname.':'.$udom);
1.81      www      4912:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      4913:              $umode.', '.$first.', '.$middle.', '.
                   4914: 	     $last.', '.$gene.' by '.
1.620     albertel 4915:              $env{'user.name'}.' at '.$env{'user.domain'});
1.134     albertel 4916:     return 'ok';
1.80      www      4917: }
                   4918: 
1.81      www      4919: # -------------------------------------------------------------- Modify student
1.80      www      4920: 
1.81      www      4921: sub modifystudent {
                   4922:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.515     raeburn  4923:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
1.455     albertel 4924:     if (!$cid) {
1.620     albertel 4925: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 4926: 	    return 'not_in_class';
                   4927: 	}
1.80      www      4928:     }
                   4929: # --------------------------------------------------------------- Make the user
1.81      www      4930:     my $reply=&modifyuser
1.209     matthew  4931: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387     www      4932:          $desiredhome,$email);
1.80      www      4933:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  4934:     # This will cause &modify_student_enrollment to get the uid from the
                   4935:     # students environment
                   4936:     $uid = undef if (!$forceid);
1.455     albertel 4937:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.515     raeburn  4938: 					$gene,$usec,$end,$start,$type,$locktype,$cid);
1.297     matthew  4939:     return $reply;
                   4940: }
                   4941: 
                   4942: sub modify_student_enrollment {
1.515     raeburn  4943:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
1.455     albertel 4944:     my ($cdom,$cnum,$chome);
                   4945:     if (!$cid) {
1.620     albertel 4946: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 4947: 	    return 'not_in_class';
                   4948: 	}
1.620     albertel 4949: 	$cdom=$env{'course.'.$cid.'.domain'};
                   4950: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 4951:     } else {
                   4952: 	($cdom,$cnum)=split(/_/,$cid);
                   4953:     }
1.620     albertel 4954:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 4955:     if (!$chome) {
1.457     raeburn  4956: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  4957:     }
1.455     albertel 4958:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  4959:     # Make sure the user exists
1.81      www      4960:     my $uhome=&homeserver($uname,$udom);
                   4961:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   4962: 	return 'error: no such user';
                   4963:     }
1.297     matthew  4964:     # Get student data if we were not given enough information
                   4965:     if (!defined($first)  || $first  eq '' || 
                   4966:         !defined($last)   || $last   eq '' || 
                   4967:         !defined($uid)    || $uid    eq '' || 
                   4968:         !defined($middle) || $middle eq '' || 
                   4969:         !defined($gene)   || $gene   eq '') {
1.294     matthew  4970:         # They did not supply us with enough data to enroll the student, so
                   4971:         # we need to pick up more information.
1.297     matthew  4972:         my %tmp = &get('environment',
1.294     matthew  4973:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  4974:                        ,$udom,$uname);
                   4975: 
1.800     albertel 4976:         #foreach my $key (keys(%tmp)) {
                   4977:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 4978:         #}
1.294     matthew  4979:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   4980:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   4981:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  4982:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  4983:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   4984:     }
1.556     albertel 4985:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 4986:     my $reply=cput('classlist',
                   4987: 		   {"$uname:$udom" => 
1.515     raeburn  4988: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 4989: 		   $cdom,$cnum);
1.81      www      4990:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   4991: 	return 'error: '.$reply;
1.652     albertel 4992:     } else {
                   4993: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      4994:     }
1.297     matthew  4995:     # Add student role to user
1.83      www      4996:     my $uurl='/'.$cid;
1.81      www      4997:     $uurl=~s/\_/\//g;
                   4998:     if ($usec) {
                   4999: 	$uurl.='/'.$usec;
                   5000:     }
                   5001:     return &assignrole($udom,$uname,$uurl,'st',$end,$start);
1.21      www      5002: }
                   5003: 
1.556     albertel 5004: sub format_name {
                   5005:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   5006:     my $name;
                   5007:     if ($first ne 'lastname') {
                   5008: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   5009:     } else {
                   5010: 	if ($lastname=~/\S/) {
                   5011: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   5012: 	    $name=~s/\s+,/,/;
                   5013: 	} else {
                   5014: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   5015: 	}
                   5016:     }
                   5017:     $name=~s/^\s+//;
                   5018:     $name=~s/\s+$//;
                   5019:     $name=~s/\s+/ /g;
                   5020:     return $name;
                   5021: }
                   5022: 
1.84      www      5023: # ------------------------------------------------- Write to course preferences
                   5024: 
                   5025: sub writecoursepref {
                   5026:     my ($courseid,%prefs)=@_;
                   5027:     $courseid=~s/^\///;
                   5028:     $courseid=~s/\_/\//g;
                   5029:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   5030:     my $chome=homeserver($cnum,$cdomain);
                   5031:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   5032: 	return 'error: no such course';
                   5033:     }
                   5034:     my $cstring='';
1.800     albertel 5035:     foreach my $pref (keys(%prefs)) {
                   5036: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 5037:     }
1.84      www      5038:     $cstring=~s/\&$//;
                   5039:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   5040: }
                   5041: 
                   5042: # ---------------------------------------------------------- Make/modify course
                   5043: 
                   5044: sub createcourse {
1.741     raeburn  5045:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
                   5046:         $course_owner,$crstype)=@_;
1.84      www      5047:     $url=&declutter($url);
                   5048:     my $cid='';
1.264     matthew  5049:     unless (&allowed('ccc',$udom)) {
1.84      www      5050:         return 'refused';
                   5051:     }
                   5052: # ------------------------------------------------------------------- Create ID
1.674     www      5053:    my $uname=int(1+rand(9)).
                   5054:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   5055:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
1.84      www      5056:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   5057: # ----------------------------------------------- Make sure that does not exist
1.230     stredwic 5058:    my $uhome=&homeserver($uname,$udom,'true');
1.84      www      5059:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   5060:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   5061:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230     stredwic 5062:        $uhome=&homeserver($uname,$udom,'true');       
1.84      www      5063:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   5064:            return 'error: unable to generate unique course-ID';
                   5065:        } 
                   5066:    }
1.264     matthew  5067: # ------------------------------------------------ Check supplied server name
1.620     albertel 5068:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.845     albertel 5069:     if (! &is_library($course_server)) {
1.264     matthew  5070:         return 'error:bad server name '.$course_server;
                   5071:     }
1.84      www      5072: # ------------------------------------------------------------- Make the course
                   5073:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  5074:                       $course_server);
1.84      www      5075:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230     stredwic 5076:     $uhome=&homeserver($uname,$udom,'true');
1.84      www      5077:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   5078: 	return 'error: no such course';
                   5079:     }
1.271     www      5080: # ----------------------------------------------------------------- Course made
1.516     raeburn  5081: # log existence
                   5082:     &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description).
1.741     raeburn  5083:                  ':'.&escape($inst_code).':'.&escape($course_owner).':'.
                   5084:                   &escape($crstype),$uhome);
1.358     www      5085:     &flushcourselogs();
                   5086: # set toplevel url
1.271     www      5087:     my $topurl=$url;
                   5088:     unless ($nonstandard) {
                   5089: # ------------------------------------------ For standard courses, make top url
                   5090:         my $mapurl=&clutter($url);
1.278     www      5091:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 5092:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      5093: <map>
                   5094: <resource id="1" type="start"></resource>
                   5095: <resource id="2" src="$mapurl"></resource>
                   5096: <resource id="3" type="finish"></resource>
                   5097: <link index="1" from="1" to="2"></link>
                   5098: <link index="2" from="2" to="3"></link>
                   5099: </map>
                   5100: ENDINITMAP
                   5101:         $topurl=&declutter(
1.638     albertel 5102:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      5103:                           );
                   5104:     }
                   5105: # ----------------------------------------------------------- Write preferences
1.84      www      5106:     &writecoursepref($udom.'_'.$uname,
                   5107:                      ('description' => $description,
1.271     www      5108:                       'url'         => $topurl));
1.84      www      5109:     return '/'.$udom.'/'.$uname;
                   5110: }
                   5111: 
1.813     albertel 5112: sub is_course {
                   5113:     my ($cdom,$cnum) = @_;
                   5114:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
                   5115: 				undef,'.');
                   5116:     if (exists($courses{$cdom.'_'.$cnum})) {
                   5117:         return 1;
                   5118:     }
                   5119:     return 0;
                   5120: }
                   5121: 
1.21      www      5122: # ---------------------------------------------------------- Assign Custom Role
                   5123: 
                   5124: sub assigncustomrole {
1.357     www      5125:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
1.21      www      5126:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.357     www      5127:                        $end,$start,$deleteflag);
1.21      www      5128: }
                   5129: 
                   5130: # ----------------------------------------------------------------- Revoke Role
                   5131: 
                   5132: sub revokerole {
1.357     www      5133:     my ($udom,$uname,$url,$role,$deleteflag)=@_;
1.21      www      5134:     my $now=time;
1.357     www      5135:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
1.21      www      5136: }
                   5137: 
                   5138: # ---------------------------------------------------------- Revoke Custom Role
                   5139: 
                   5140: sub revokecustomrole {
1.357     www      5141:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
1.21      www      5142:     my $now=time;
1.357     www      5143:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
                   5144:            $deleteflag);
1.17      www      5145: }
                   5146: 
1.533     banghart 5147: # ------------------------------------------------------------ Disk usage
1.535     albertel 5148: sub diskusage {
1.533     banghart 5149:     my ($udom,$uname,$directoryRoot)=@_;
                   5150:     $directoryRoot =~ s/\/$//;
1.535     albertel 5151:     my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
1.514     albertel 5152:     return $listing;
1.512     banghart 5153: }
                   5154: 
1.566     banghart 5155: sub is_locked {
                   5156:     my ($file_name, $domain, $user) = @_;
                   5157:     my @check;
                   5158:     my $is_locked;
                   5159:     push @check, $file_name;
1.613     albertel 5160:     my %locked = &get('file_permissions',\@check,
1.620     albertel 5161: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 5162:     my ($tmp)=keys(%locked);
                   5163:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  5164:     
1.566     banghart 5165:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  5166:         $is_locked = 'false';
                   5167:         foreach my $entry (@{$locked{$file_name}}) {
                   5168:            if (ref($entry) eq 'ARRAY') { 
1.746     raeburn  5169:                $is_locked = 'true';
                   5170:                last;
1.745     raeburn  5171:            }
                   5172:        }
1.566     banghart 5173:     } else {
                   5174:         $is_locked = 'false';
                   5175:     }
                   5176: }
                   5177: 
1.759     albertel 5178: sub declutter_portfile {
                   5179:     my ($file) = @_;
1.833     albertel 5180:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 5181:     return $file;
                   5182: }
                   5183: 
1.559     banghart 5184: # ------------------------------------------------------------- Mark as Read Only
                   5185: 
                   5186: sub mark_as_readonly {
                   5187:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 5188:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 5189:     my ($tmp)=keys(%current_permissions);
                   5190:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 5191:     foreach my $file (@{$files}) {
1.759     albertel 5192: 	$file = &declutter_portfile($file);
1.561     banghart 5193:         push(@{$current_permissions{$file}},$what);
1.559     banghart 5194:     }
1.613     albertel 5195:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 5196:     return;
                   5197: }
                   5198: 
1.572     banghart 5199: # ------------------------------------------------------------Save Selected Files
                   5200: 
                   5201: sub save_selected_files {
                   5202:     my ($user, $path, @files) = @_;
                   5203:     my $filename = $user."savedfiles";
1.573     banghart 5204:     my @other_files = &files_not_in_path($user, $path);
1.574     banghart 5205:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 5206:     foreach my $file (@files) {
1.620     albertel 5207:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 5208:     }
                   5209:     foreach my $file (@other_files) {
1.574     banghart 5210:         print (OUT $file."\n");
1.572     banghart 5211:     }
1.574     banghart 5212:     close (OUT);
1.572     banghart 5213:     return 'ok';
                   5214: }
                   5215: 
1.574     banghart 5216: sub clear_selected_files {
                   5217:     my ($user) = @_;
                   5218:     my $filename = $user."savedfiles";
                   5219:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   5220:     print (OUT undef);
                   5221:     close (OUT);
                   5222:     return ("ok");    
                   5223: }
                   5224: 
1.572     banghart 5225: sub files_in_path {
                   5226:     my ($user, $path) = @_;
                   5227:     my $filename = $user."savedfiles";
                   5228:     my %return_files;
1.574     banghart 5229:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 5230:     while (my $line_in = <IN>) {
1.574     banghart 5231:         chomp ($line_in);
                   5232:         my @paths_and_file = split (m!/!, $line_in);
                   5233:         my $file_part = pop (@paths_and_file);
                   5234:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 5235:         $path_part.='/';
                   5236:         my $path_and_file = $path_part.$file_part;
                   5237:         if ($path_part eq $path) {
                   5238:             $return_files{$file_part}= 'selected';
                   5239:         }
                   5240:     }
1.574     banghart 5241:     close (IN);
                   5242:     return (\%return_files);
1.572     banghart 5243: }
                   5244: 
                   5245: # called in portfolio select mode, to show files selected NOT in current directory
                   5246: sub files_not_in_path {
                   5247:     my ($user, $path) = @_;
                   5248:     my $filename = $user."savedfiles";
                   5249:     my @return_files;
                   5250:     my $path_part;
1.800     albertel 5251:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   5252:     while (my $line = <IN>) {
1.572     banghart 5253:         #ok, I know it's clunky, but I want it to work
1.800     albertel 5254:         my @paths_and_file = split(m|/|, $line);
                   5255:         my $file_part = pop(@paths_and_file);
                   5256:         chomp($file_part);
                   5257:         my $path_part = join('/', @paths_and_file);
1.572     banghart 5258:         $path_part .= '/';
                   5259:         my $path_and_file = $path_part.$file_part;
                   5260:         if ($path_part ne $path) {
1.800     albertel 5261:             push(@return_files, ($path_and_file));
1.572     banghart 5262:         }
                   5263:     }
1.800     albertel 5264:     close(OUT);
1.574     banghart 5265:     return (@return_files);
1.572     banghart 5266: }
                   5267: 
1.745     raeburn  5268: #----------------------------------------------Get portfolio file permissions
1.629     banghart 5269: 
1.745     raeburn  5270: sub get_portfile_permissions {
                   5271:     my ($domain,$user) = @_;
1.613     albertel 5272:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 5273:     my ($tmp)=keys(%current_permissions);
                   5274:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  5275:     return \%current_permissions;
                   5276: }
                   5277: 
                   5278: #---------------------------------------------Get portfolio file access controls
                   5279: 
1.749     raeburn  5280: sub get_access_controls {
1.745     raeburn  5281:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 5282:     my %access;
                   5283:     my $real_file = $file;
                   5284:     $file =~ s/\.meta$//;
1.745     raeburn  5285:     if (defined($file)) {
1.749     raeburn  5286:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   5287:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 5288:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  5289:             }
                   5290:         }
1.745     raeburn  5291:     } else {
1.749     raeburn  5292:         foreach my $key (keys(%{$current_permissions})) {
                   5293:             if ($key =~ /\0accesscontrol$/) {
                   5294:                 if (defined($group)) {
                   5295:                     if ($key !~ m-^\Q$group\E/-) {
                   5296:                         next;
                   5297:                     }
                   5298:                 }
                   5299:                 my ($fullpath) = split(/\0/,$key);
                   5300:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   5301:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   5302:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   5303:                     }
                   5304:                 }
                   5305:             }
                   5306:         }
                   5307:     }
                   5308:     return %access;
                   5309: }
                   5310: 
                   5311: sub modify_access_controls {
                   5312:     my ($file_name,$changes,$domain,$user)=@_;
                   5313:     my ($outcome,$deloutcome);
                   5314:     my %store_permissions;
                   5315:     my %new_values;
                   5316:     my %new_control;
                   5317:     my %translation;
                   5318:     my @deletions = ();
                   5319:     my $now = time;
                   5320:     if (exists($$changes{'activate'})) {
                   5321:         if (ref($$changes{'activate'}) eq 'HASH') {
                   5322:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   5323:             my $numnew = scalar(@newitems);
                   5324:             for (my $i=0; $i<$numnew; $i++) {
                   5325:                 my $newkey = $newitems[$i];
                   5326:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  5327:                 if ($newkey =~ /^\d+:/) { 
                   5328:                     $newkey =~ s/^(\d+)/$newid/;
                   5329:                     $translation{$1} = $newid;
                   5330:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   5331:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   5332:                     $translation{$1} = $newid;
                   5333:                 }
1.749     raeburn  5334:                 $new_values{$file_name."\0".$newkey} = 
                   5335:                                           $$changes{'activate'}{$newitems[$i]};
                   5336:                 $new_control{$newkey} = $now;
                   5337:             }
                   5338:         }
                   5339:     }
                   5340:     my %todelete;
                   5341:     my %changed_items;
                   5342:     foreach my $action ('delete','update') {
                   5343:         if (exists($$changes{$action})) {
                   5344:             if (ref($$changes{$action}) eq 'HASH') {
                   5345:                 foreach my $key (keys(%{$$changes{$action}})) {
                   5346:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   5347:                     if ($action eq 'delete') { 
                   5348:                         $todelete{$itemnum} = 1;
                   5349:                     } else {
                   5350:                         $changed_items{$itemnum} = $key;
                   5351:                     }
                   5352:                 }
1.745     raeburn  5353:             }
                   5354:         }
1.749     raeburn  5355:     }
                   5356:     # get lock on access controls for file.
                   5357:     my $lockhash = {
                   5358:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   5359:                                                        ':'.$env{'user.domain'},
                   5360:                    }; 
                   5361:     my $tries = 0;
                   5362:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   5363:    
                   5364:     while (($gotlock ne 'ok') && $tries <3) {
                   5365:         $tries ++;
                   5366:         sleep 1;
                   5367:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   5368:     }
                   5369:     if ($gotlock eq 'ok') {
                   5370:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   5371:         my ($tmp)=keys(%curr_permissions);
                   5372:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   5373:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   5374:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   5375:             if (ref($curr_controls) eq 'HASH') {
                   5376:                 foreach my $control_item (keys(%{$curr_controls})) {
                   5377:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   5378:                     if (defined($todelete{$itemnum})) {
                   5379:                         push(@deletions,$file_name."\0".$control_item);
                   5380:                     } else {
                   5381:                         if (defined($changed_items{$itemnum})) {
                   5382:                             $new_control{$changed_items{$itemnum}} = $now;
                   5383:                             push(@deletions,$file_name."\0".$control_item);
                   5384:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   5385:                         } else {
                   5386:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   5387:                         }
                   5388:                     }
1.745     raeburn  5389:                 }
                   5390:             }
                   5391:         }
1.749     raeburn  5392:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   5393:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   5394:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   5395:         #  remove lock
                   5396:         my @del_lock = ($file_name."\0".'locked_access_records');
                   5397:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  5398:         my ($file,$group);
                   5399:         if (&is_course($domain,$user)) {
                   5400:             ($group,$file) = split(/\//,$file_name,2);
                   5401:         } else {
                   5402:             $file = $file_name;
                   5403:         }
                   5404:         my $sqlresult =
                   5405:             &update_portfolio_table($user,$domain,$file,'portfolio_access',
                   5406:                                     $group);
1.749     raeburn  5407:     } else {
                   5408:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  5409:     }
1.749     raeburn  5410:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  5411: }
                   5412: 
1.827     raeburn  5413: sub make_public_indefinitely {
                   5414:     my ($requrl) = @_;
                   5415:     my $now = time;
                   5416:     my $action = 'activate';
                   5417:     my $aclnum = 0;
                   5418:     if (&is_portfolio_url($requrl)) {
                   5419:         my (undef,$udom,$unum,$file_name,$group) =
                   5420:             &parse_portfolio_url($requrl);
                   5421:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   5422:         my %access_controls = &get_access_controls($current_perms,
                   5423:                                                    $group,$file_name);
                   5424:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   5425:             my ($num,$scope,$end,$start) = 
                   5426:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   5427:             if ($scope eq 'public') {
                   5428:                 if ($start <= $now && $end == 0) {
                   5429:                     $action = 'none';
                   5430:                 } else {
                   5431:                     $action = 'update';
                   5432:                     $aclnum = $num;
                   5433:                 }
                   5434:                 last;
                   5435:             }
                   5436:         }
                   5437:         if ($action eq 'none') {
                   5438:              return 'ok';
                   5439:         } else {
                   5440:             my %changes;
                   5441:             my $newend = 0;
                   5442:             my $newstart = $now;
                   5443:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   5444:             $changes{$action}{$newkey} = {
                   5445:                 type => 'public',
                   5446:                 time => {
                   5447:                     start => $newstart,
                   5448:                     end   => $newend,
                   5449:                 },
                   5450:             };
                   5451:             my ($outcome,$deloutcome,$new_values,$translation) =
                   5452:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   5453:             return $outcome;
                   5454:         }
                   5455:     } else {
                   5456:         return 'invalid';
                   5457:     }
                   5458: }
                   5459: 
1.745     raeburn  5460: #------------------------------------------------------Get Marked as Read Only
                   5461: 
                   5462: sub get_marked_as_readonly {
                   5463:     my ($domain,$user,$what,$group) = @_;
                   5464:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 5465:     my @readonly_files;
1.629     banghart 5466:     my $cmp1=$what;
                   5467:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  5468:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   5469:         if (defined($group)) {
                   5470:             if ($file_name !~ m-^\Q$group\E/-) {
                   5471:                 next;
                   5472:             }
                   5473:         }
1.561     banghart 5474:         if (ref($value) eq "ARRAY"){
                   5475:             foreach my $stored_what (@{$value}) {
1.629     banghart 5476:                 my $cmp2=$stored_what;
1.759     albertel 5477:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  5478:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  5479:                 }
1.629     banghart 5480:                 if ($cmp1 eq $cmp2) {
1.561     banghart 5481:                     push(@readonly_files, $file_name);
1.745     raeburn  5482:                     last;
1.563     banghart 5483:                 } elsif (!defined($what)) {
                   5484:                     push(@readonly_files, $file_name);
1.745     raeburn  5485:                     last;
1.561     banghart 5486:                 }
                   5487:             }
1.745     raeburn  5488:         }
1.561     banghart 5489:     }
                   5490:     return @readonly_files;
                   5491: }
1.577     banghart 5492: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 5493: 
1.577     banghart 5494: sub get_marked_as_readonly_hash {
1.745     raeburn  5495:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 5496:     my %readonly_files;
1.745     raeburn  5497:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   5498:         if (defined($group)) {
                   5499:             if ($file_name !~ m-^\Q$group\E/-) {
                   5500:                 next;
                   5501:             }
                   5502:         }
1.577     banghart 5503:         if (ref($value) eq "ARRAY"){
                   5504:             foreach my $stored_what (@{$value}) {
1.745     raeburn  5505:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 5506:                     foreach my $lock_descriptor(@{$stored_what}) {
                   5507:                         if ($lock_descriptor eq 'graded') {
                   5508:                             $readonly_files{$file_name} = 'graded';
                   5509:                         } elsif ($lock_descriptor eq 'handback') {
                   5510:                             $readonly_files{$file_name} = 'handback';
                   5511:                         } else {
                   5512:                             if (!exists($readonly_files{$file_name})) {
                   5513:                                 $readonly_files{$file_name} = 'locked';
                   5514:                             }
                   5515:                         }
1.745     raeburn  5516:                     }
1.750     banghart 5517:                 } 
1.577     banghart 5518:             }
                   5519:         } 
                   5520:     }
                   5521:     return %readonly_files;
                   5522: }
1.559     banghart 5523: # ------------------------------------------------------------ Unmark as Read Only
                   5524: 
                   5525: sub unmark_as_readonly {
1.629     banghart 5526:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   5527:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  5528:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 5529:     $file_name = &declutter_portfile($file_name);
1.634     albertel 5530:     my $symb_crs = $what;
                   5531:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  5532:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 5533:     my ($tmp)=keys(%current_permissions);
                   5534:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  5535:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 5536:     foreach my $file (@readonly_files) {
1.759     albertel 5537: 	my $clean_file = &declutter_portfile($file);
                   5538: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 5539: 	my $current_locks = $current_permissions{$file};
1.563     banghart 5540:         my @new_locks;
                   5541:         my @del_keys;
                   5542:         if (ref($current_locks) eq "ARRAY"){
                   5543:             foreach my $locker (@{$current_locks}) {
1.632     albertel 5544:                 my $compare=$locker;
1.749     raeburn  5545:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  5546:                     $compare=join('',@{$locker});
1.746     raeburn  5547:                     if ($compare ne $symb_crs) {
                   5548:                         push(@new_locks, $locker);
                   5549:                     }
1.563     banghart 5550:                 }
                   5551:             }
1.650     albertel 5552:             if (scalar(@new_locks) > 0) {
1.563     banghart 5553:                 $current_permissions{$file} = \@new_locks;
                   5554:             } else {
                   5555:                 push(@del_keys, $file);
1.613     albertel 5556:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 5557:                 delete($current_permissions{$file});
1.563     banghart 5558:             }
                   5559:         }
1.561     banghart 5560:     }
1.613     albertel 5561:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 5562:     return;
                   5563: }
1.512     banghart 5564: 
1.17      www      5565: # ------------------------------------------------------------ Directory lister
                   5566: 
                   5567: sub dirlist {
1.253     stredwic 5568:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
                   5569: 
1.18      www      5570:     $uri=~s/^\///;
                   5571:     $uri=~s/\/$//;
1.253     stredwic 5572:     my ($udom, $uname);
                   5573:     (undef,$udom,$uname)=split(/\//,$uri);
                   5574:     if(defined($userdomain)) {
                   5575:         $udom = $userdomain;
                   5576:     }
                   5577:     if(defined($username)) {
                   5578:         $uname = $username;
                   5579:     }
                   5580: 
                   5581:     my $dirRoot = $perlvar{'lonDocRoot'};
                   5582:     if(defined($alternateDirectoryRoot)) {
                   5583:         $dirRoot = $alternateDirectoryRoot;
                   5584:         $dirRoot =~ s/\/$//;
1.751     banghart 5585:     }
1.253     stredwic 5586: 
                   5587:     if($udom) {
                   5588:         if($uname) {
1.800     albertel 5589:             my $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
                   5590: 				 &homeserver($uname,$udom));
1.605     matthew  5591:             my @listing_results;
                   5592:             if ($listing eq 'unknown_cmd') {
1.800     albertel 5593:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
                   5594: 				  &homeserver($uname,$udom));
1.605     matthew  5595:                 @listing_results = split(/:/,$listing);
                   5596:             } else {
                   5597:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   5598:             }
                   5599:             return @listing_results;
1.253     stredwic 5600:         } elsif(!defined($alternateDirectoryRoot)) {
1.800     albertel 5601:             my %allusers;
1.841     albertel 5602: 	    my %servers = &get_servers($udom,'library');
                   5603: 	    foreach my $tryserver (keys(%servers)) {
                   5604: 		my $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   5605: 				     $udom, $tryserver);
                   5606: 		my @listing_results;
                   5607: 		if ($listing eq 'unknown_cmd') {
                   5608: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   5609: 				      $udom, $tryserver);
                   5610: 		    @listing_results = split(/:/,$listing);
                   5611: 		} else {
                   5612: 		    @listing_results =
                   5613: 			map { &unescape($_); } split(/:/,$listing);
                   5614: 		}
                   5615: 		if ($listing_results[0] ne 'no_such_dir' && 
                   5616: 		    $listing_results[0] ne 'empty'       &&
                   5617: 		    $listing_results[0] ne 'con_lost') {
                   5618: 		    foreach my $line (@listing_results) {
                   5619: 			my ($entry) = split(/&/,$line,2);
                   5620: 			$allusers{$entry} = 1;
                   5621: 		    }
                   5622: 		}
1.253     stredwic 5623:             }
                   5624:             my $alluserstr='';
1.800     albertel 5625:             foreach my $user (sort(keys(%allusers))) {
                   5626:                 $alluserstr.=$user.'&user:';
1.253     stredwic 5627:             }
                   5628:             $alluserstr=~s/:$//;
                   5629:             return split(/:/,$alluserstr);
                   5630:         } else {
1.800     albertel 5631:             return ('missing user name');
1.253     stredwic 5632:         }
                   5633:     } elsif(!defined($alternateDirectoryRoot)) {
1.841     albertel 5634:         my @all_domains = sort(&all_domains());
                   5635:          foreach my $domain (@all_domains) {
                   5636:              $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
                   5637:          }
                   5638:          return @all_domains;
                   5639:      } else {
1.800     albertel 5640:         return ('missing domain');
1.275     stredwic 5641:     }
                   5642: }
                   5643: 
                   5644: # --------------------------------------------- GetFileTimestamp
                   5645: # This function utilizes dirlist and returns the date stamp for
                   5646: # when it was last modified.  It will also return an error of -1
                   5647: # if an error occurs
                   5648: 
1.410     matthew  5649: ##
                   5650: ## FIXME: This subroutine assumes its caller knows something about the
                   5651: ## directory structure of the home server for the student ($root).
                   5652: ## Not a good assumption to make.  Since this is for looking up files
                   5653: ## in user directories, the full path should be constructed by lond, not
                   5654: ## whatever machine we request data from.
                   5655: ##
1.275     stredwic 5656: sub GetFileTimestamp {
                   5657:     my ($studentDomain,$studentName,$filename,$root)=@_;
1.807     albertel 5658:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   5659:     $studentName   = &LONCAPA::clean_username($studentName);
1.275     stredwic 5660:     my $subdir=$studentName.'__';
                   5661:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   5662:     my $proname="$studentDomain/$subdir/$studentName";
                   5663:     $proname .= '/'.$filename;
1.375     matthew  5664:     my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain, 
                   5665:                                               $studentName, $root);
1.275     stredwic 5666:     my @stats = split('&', $fileStat);
                   5667:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  5668:         # @stats contains first the filename, then the stat output
                   5669:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 5670:     } else {
                   5671:         return -1;
1.253     stredwic 5672:     }
1.26      www      5673: }
                   5674: 
1.712     albertel 5675: sub stat_file {
                   5676:     my ($uri) = @_;
1.787     albertel 5677:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 5678: 
1.712     albertel 5679:     my ($udom,$uname,$file,$dir);
                   5680:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   5681: 	($udom,$uname,$file) =
1.811     albertel 5682: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 5683: 	$file = 'userfiles/'.$file;
1.740     www      5684: 	$dir = &propath($udom,$uname);
1.712     albertel 5685:     }
                   5686:     if ($uri =~ m-^/res/-) {
                   5687: 	($udom,$uname) = 
1.807     albertel 5688: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 5689: 	$file = $uri;
                   5690:     }
                   5691: 
                   5692:     if (!$udom || !$uname || !$file) {
                   5693: 	# unable to handle the uri
                   5694: 	return ();
                   5695:     }
                   5696: 
                   5697:     my ($result) = &dirlist($file,$udom,$uname,$dir);
                   5698:     my @stats = split('&', $result);
1.721     banghart 5699:     
1.712     albertel 5700:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   5701: 	shift(@stats); #filename is first
                   5702: 	return @stats;
                   5703:     }
                   5704:     return ();
                   5705: }
                   5706: 
1.26      www      5707: # -------------------------------------------------------- Value of a Condition
                   5708: 
1.713     albertel 5709: # gets the value of a specific preevaluated condition
                   5710: #    stored in the string  $env{user.state.<cid>}
                   5711: # or looks up a condition reference in the bighash and if if hasn't
                   5712: # already been evaluated recurses into docondval to get the value of
                   5713: # the condition, then memoizing it to 
                   5714: #   $env{user.state.<cid>.<condition>}
1.40      www      5715: sub directcondval {
                   5716:     my $number=shift;
1.620     albertel 5717:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 5718: 	&Apache::lonuserstate::evalstate();
                   5719:     }
1.713     albertel 5720:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   5721: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   5722:     } elsif ($number =~ /^_/) {
                   5723: 	my $sub_condition;
                   5724: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   5725: 		&GDBM_READER(),0640)) {
                   5726: 	    $sub_condition=$bighash{'conditions'.$number};
                   5727: 	    untie(%bighash);
                   5728: 	}
                   5729: 	my $value = &docondval($sub_condition);
                   5730: 	&appenv('user.state.'.$env{'request.course.id'}.".$number" => $value);
                   5731: 	return $value;
                   5732:     }
1.620     albertel 5733:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   5734:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      5735:     } else {
                   5736:        return 2;
                   5737:     }
                   5738: }
                   5739: 
1.713     albertel 5740: # get the collection of conditions for this resource
1.26      www      5741: sub condval {
                   5742:     my $condidx=shift;
1.54      www      5743:     my $allpathcond='';
1.713     albertel 5744:     foreach my $cond (split(/\|/,$condidx)) {
                   5745: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   5746: 	    $allpathcond.=
                   5747: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   5748: 	}
1.191     harris41 5749:     }
1.54      www      5750:     $allpathcond=~s/\|$//;
1.713     albertel 5751:     return &docondval($allpathcond);
                   5752: }
                   5753: 
                   5754: #evaluates an expression of conditions
                   5755: sub docondval {
                   5756:     my ($allpathcond) = @_;
                   5757:     my $result=0;
                   5758:     if ($env{'request.course.id'}
                   5759: 	&& defined($allpathcond)) {
                   5760: 	my $operand='|';
                   5761: 	my @stack;
                   5762: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   5763: 	    if ($chunk eq '(') {
                   5764: 		push @stack,($operand,$result);
                   5765: 	    } elsif ($chunk eq ')') {
                   5766: 		my $before=pop @stack;
                   5767: 		if (pop @stack eq '&') {
                   5768: 		    $result=$result>$before?$before:$result;
                   5769: 		} else {
                   5770: 		    $result=$result>$before?$result:$before;
                   5771: 		}
                   5772: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   5773: 		$operand=$chunk;
                   5774: 	    } else {
                   5775: 		my $new=directcondval($chunk);
                   5776: 		if ($operand eq '&') {
                   5777: 		    $result=$result>$new?$new:$result;
                   5778: 		} else {
                   5779: 		    $result=$result>$new?$result:$new;
                   5780: 		}
                   5781: 	    }
                   5782: 	}
1.26      www      5783:     }
                   5784:     return $result;
1.421     albertel 5785: }
                   5786: 
                   5787: # ---------------------------------------------------- Devalidate courseresdata
                   5788: 
                   5789: sub devalidatecourseresdata {
                   5790:     my ($coursenum,$coursedomain)=@_;
                   5791:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 5792:     &devalidate_cache_new('courseres',$hashid);
1.28      www      5793: }
                   5794: 
1.763     www      5795: 
1.200     www      5796: # --------------------------------------------------- Course Resourcedata Query
                   5797: 
1.624     albertel 5798: sub get_courseresdata {
                   5799:     my ($coursenum,$coursedomain)=@_;
1.200     www      5800:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   5801:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 5802:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 5803:     my %dumpreply;
1.417     albertel 5804:     unless (defined($cached)) {
1.624     albertel 5805: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 5806: 	$result=\%dumpreply;
1.251     albertel 5807: 	my ($tmp) = keys(%dumpreply);
                   5808: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 5809: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 5810: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   5811: 	    return $tmp;
1.416     albertel 5812: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 5813: 	    $result=undef;
1.599     albertel 5814: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 5815: 	}
                   5816:     }
1.624     albertel 5817:     return $result;
                   5818: }
                   5819: 
1.633     albertel 5820: sub devalidateuserresdata {
                   5821:     my ($uname,$udom)=@_;
                   5822:     my $hashid="$udom:$uname";
                   5823:     &devalidate_cache_new('userres',$hashid);
                   5824: }
                   5825: 
1.624     albertel 5826: sub get_userresdata {
                   5827:     my ($uname,$udom)=@_;
                   5828:     #most student don\'t have any data set, check if there is some data
                   5829:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   5830: 
                   5831:     my $hashid="$udom:$uname";
                   5832:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   5833:     if (!defined($cached)) {
                   5834: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   5835: 	$result=\%resourcedata;
                   5836: 	&do_cache_new('userres',$hashid,$result,600);
                   5837:     }
                   5838:     my ($tmp)=keys(%$result);
                   5839:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   5840: 	return $result;
                   5841:     }
                   5842:     #error 2 occurs when the .db doesn't exist
                   5843:     if ($tmp!~/error: 2 /) {
1.672     albertel 5844: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 5845: 		 " Trying to get resource data for ".
                   5846: 		 $uname." at ".$udom.": ".
                   5847: 		 $tmp."</font>");
                   5848:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 5849: 	#&EXT_cache_set($udom,$uname);
                   5850: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 5851: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 5852:     }
                   5853:     return $tmp;
                   5854: }
                   5855: 
                   5856: sub resdata {
                   5857:     my ($name,$domain,$type,@which)=@_;
                   5858:     my $result;
                   5859:     if ($type eq 'course') {
                   5860: 	$result=&get_courseresdata($name,$domain);
                   5861:     } elsif ($type eq 'user') {
                   5862: 	$result=&get_userresdata($name,$domain);
                   5863:     }
                   5864:     if (!ref($result)) { return $result; }    
1.251     albertel 5865:     foreach my $item (@which) {
1.417     albertel 5866: 	if (defined($result->{$item})) {
                   5867: 	    return $result->{$item};
1.251     albertel 5868: 	}
1.250     albertel 5869:     }
1.291     albertel 5870:     return undef;
1.200     www      5871: }
                   5872: 
1.379     matthew  5873: #
                   5874: # EXT resource caching routines
                   5875: #
                   5876: 
                   5877: sub clear_EXT_cache_status {
1.383     albertel 5878:     &delenv('cache.EXT.');
1.379     matthew  5879: }
                   5880: 
                   5881: sub EXT_cache_status {
                   5882:     my ($target_domain,$target_user) = @_;
1.383     albertel 5883:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 5884:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  5885:         # We know already the user has no data
                   5886:         return 1;
                   5887:     } else {
                   5888:         return 0;
                   5889:     }
                   5890: }
                   5891: 
                   5892: sub EXT_cache_set {
                   5893:     my ($target_domain,$target_user) = @_;
1.383     albertel 5894:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.633     albertel 5895:     #&appenv($cachename => time);
1.379     matthew  5896: }
                   5897: 
1.28      www      5898: # --------------------------------------------------------- Value of a Variable
1.58      www      5899: sub EXT {
1.715     albertel 5900: 
1.395     albertel 5901:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      5902:     unless ($varname) { return ''; }
1.218     albertel 5903:     #get real user name/domain, courseid and symb
                   5904:     my $courseid;
1.359     albertel 5905:     my $publicuser;
1.427     www      5906:     if ($symbparm) {
                   5907: 	$symbparm=&get_symb_from_alias($symbparm);
                   5908:     }
1.218     albertel 5909:     if (!($uname && $udom)) {
1.790     albertel 5910:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 5911:       if (!$symbparm) {	$symbparm=$cursymb; }
                   5912:     } else {
1.620     albertel 5913: 	$courseid=$env{'request.course.id'};
1.218     albertel 5914:     }
1.48      www      5915:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   5916:     my $rest;
1.320     albertel 5917:     if (defined($therest[0])) {
1.48      www      5918:        $rest=join('.',@therest);
                   5919:     } else {
                   5920:        $rest='';
                   5921:     }
1.320     albertel 5922: 
1.57      www      5923:     my $qualifierrest=$qualifier;
                   5924:     if ($rest) { $qualifierrest.='.'.$rest; }
                   5925:     my $spacequalifierrest=$space;
                   5926:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      5927:     if ($realm eq 'user') {
1.48      www      5928: # --------------------------------------------------------------- user.resource
                   5929: 	if ($space eq 'resource') {
1.651     albertel 5930: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   5931: 		  || defined($Apache::lonhomework::parsing_a_task))
                   5932: 		 &&
1.744     albertel 5933: 		 ($symbparm eq &symbread()) ) {	
                   5934: 		# if we are in the middle of processing the resource the
                   5935: 		# get the value we are planning on committing
                   5936:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   5937:                     return $Apache::lonhomework::results{$qualifierrest};
                   5938:                 } else {
                   5939:                     return $Apache::lonhomework::history{$qualifierrest};
                   5940:                 }
1.335     albertel 5941: 	    } else {
1.359     albertel 5942: 		my %restored;
1.620     albertel 5943: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 5944: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   5945: 		} else {
                   5946: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   5947: 		}
1.335     albertel 5948: 		return $restored{$qualifierrest};
                   5949: 	    }
1.48      www      5950: # ----------------------------------------------------------------- user.access
                   5951:         } elsif ($space eq 'access') {
1.218     albertel 5952: 	    # FIXME - not supporting calls for a specific user
1.48      www      5953:             return &allowed($qualifier,$rest);
                   5954: # ------------------------------------------ user.preferences, user.environment
                   5955:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 5956: 	    if (($uname eq $env{'user.name'}) &&
                   5957: 		($udom eq $env{'user.domain'})) {
                   5958: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 5959: 	    } else {
1.359     albertel 5960: 		my %returnhash;
                   5961: 		if (!$publicuser) {
                   5962: 		    %returnhash=&userenvironment($udom,$uname,
                   5963: 						 $qualifierrest);
                   5964: 		}
1.218     albertel 5965: 		return $returnhash{$qualifierrest};
                   5966: 	    }
1.48      www      5967: # ----------------------------------------------------------------- user.course
                   5968:         } elsif ($space eq 'course') {
1.218     albertel 5969: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 5970:             return $env{join('.',('request.course',$qualifier))};
1.48      www      5971: # ------------------------------------------------------------------- user.role
                   5972:         } elsif ($space eq 'role') {
1.218     albertel 5973: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 5974:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      5975:             if ($qualifier eq 'value') {
                   5976: 		return $role;
                   5977:             } elsif ($qualifier eq 'extent') {
                   5978:                 return $where;
                   5979:             }
                   5980: # ----------------------------------------------------------------- user.domain
                   5981:         } elsif ($space eq 'domain') {
1.218     albertel 5982:             return $udom;
1.48      www      5983: # ------------------------------------------------------------------- user.name
                   5984:         } elsif ($space eq 'name') {
1.218     albertel 5985:             return $uname;
1.48      www      5986: # ---------------------------------------------------- Any other user namespace
1.29      www      5987:         } else {
1.359     albertel 5988: 	    my %reply;
                   5989: 	    if (!$publicuser) {
                   5990: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   5991: 	    }
                   5992: 	    return $reply{$qualifierrest};
1.48      www      5993:         }
1.236     www      5994:     } elsif ($realm eq 'query') {
                   5995: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 5996:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   5997: 						[$spacequalifierrest]);
1.620     albertel 5998: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      5999:    } elsif ($realm eq 'request') {
1.48      www      6000: # ------------------------------------------------------------- request.browser
                   6001:         if ($space eq 'browser') {
1.430     www      6002: 	    if ($qualifier eq 'textremote') {
1.676     albertel 6003: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      6004: 		    return 1;
                   6005: 		} else {
                   6006: 		    return 0;
                   6007: 		}
                   6008: 	    } else {
1.620     albertel 6009: 		return $env{'browser.'.$qualifier};
1.430     www      6010: 	    }
1.57      www      6011: # ------------------------------------------------------------ request.filename
                   6012:         } else {
1.620     albertel 6013:             return $env{'request.'.$spacequalifierrest};
1.29      www      6014:         }
1.28      www      6015:     } elsif ($realm eq 'course') {
1.48      www      6016: # ---------------------------------------------------------- course.description
1.620     albertel 6017:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      6018:     } elsif ($realm eq 'resource') {
1.165     www      6019: 
1.620     albertel 6020: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 6021: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   6022: 	}
1.693     albertel 6023: 
                   6024: 	if ($space eq 'title') {
                   6025: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   6026: 	    return &gettitle($symbparm);
                   6027: 	}
                   6028: 	
                   6029: 	if ($space eq 'map') {
                   6030: 	    my ($map) = &decode_symb($symbparm);
                   6031: 	    return &symbread($map);
                   6032: 	}
                   6033: 
                   6034: 	my ($section, $group, @groups);
1.593     albertel 6035: 	my ($courselevelm,$courselevel);
1.539     albertel 6036: 	if ($symbparm && defined($courseid) && 
1.620     albertel 6037: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      6038: 
1.218     albertel 6039: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      6040: 
1.60      www      6041: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 6042: 	    my $symbp=$symbparm;
1.735     albertel 6043: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 6044: 
                   6045: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   6046: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   6047: 
1.620     albertel 6048: 	    if (($env{'user.name'} eq $uname) &&
                   6049: 		($env{'user.domain'} eq $udom)) {
                   6050: 		$section=$env{'request.course.sec'};
1.733     raeburn  6051:                 @groups = split(/:/,$env{'request.course.groups'});  
                   6052:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 6053: 	    } else {
1.539     albertel 6054: 		if (! defined($usection)) {
1.551     albertel 6055: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 6056: 		} else {
                   6057: 		    $section = $usection;
                   6058: 		}
1.733     raeburn  6059:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 6060: 	    }
                   6061: 
                   6062: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   6063: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   6064: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   6065: 
1.593     albertel 6066: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 6067: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 6068: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      6069: 
1.60      www      6070: # ----------------------------------------------------------- first, check user
1.624     albertel 6071: 
                   6072: 	    my $userreply=&resdata($uname,$udom,'user',
                   6073: 				       ($courselevelr,$courselevelm,
                   6074: 					$courselevel));
                   6075: 	    if (defined($userreply)) { return $userreply; }
1.95      www      6076: 
1.594     albertel 6077: # ------------------------------------------------ second, check some of course
1.684     raeburn  6078:             my $coursereply;
1.691     raeburn  6079:             if (@groups > 0) {
                   6080:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   6081:                                        $mapparm,$spacequalifierrest);
1.684     raeburn  6082:                 if (defined($coursereply)) { return $coursereply; }
                   6083:             }
1.96      www      6084: 
1.684     raeburn  6085: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.624     albertel 6086: 				     $env{'course.'.$courseid.'.domain'},
                   6087: 				     'course',
                   6088: 				     ($seclevelr,$seclevelm,$seclevel,
                   6089: 				      $courselevelr));
1.287     albertel 6090: 	    if (defined($coursereply)) { return $coursereply; }
1.200     www      6091: 
1.60      www      6092: # ------------------------------------------------------ third, check map parms
1.218     albertel 6093: 	    my %parmhash=();
                   6094: 	    my $thisparm='';
                   6095: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 6096: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 6097: 		    &GDBM_READER(),0640)) {
1.218     albertel 6098: 		$thisparm=$parmhash{$symbparm};
                   6099: 		untie(%parmhash);
                   6100: 	    }
                   6101: 	    if ($thisparm) { return $thisparm; }
                   6102: 	}
1.594     albertel 6103: # ------------------------------------------ fourth, look in resource metadata
1.71      www      6104: 
1.218     albertel 6105: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 6106: 	my $filename;
                   6107: 	if (!$symbparm) { $symbparm=&symbread(); }
                   6108: 	if ($symbparm) {
1.409     www      6109: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 6110: 	} else {
1.620     albertel 6111: 	    $filename=$env{'request.filename'};
1.282     albertel 6112: 	}
                   6113: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.288     albertel 6114: 	if (defined($metadata)) { return $metadata; }
1.282     albertel 6115: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.288     albertel 6116: 	if (defined($metadata)) { return $metadata; }
1.142     www      6117: 
1.594     albertel 6118: # ---------------------------------------------- fourth, look in rest pf course
1.593     albertel 6119: 	if ($symbparm && defined($courseid) && 
1.620     albertel 6120: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 6121: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   6122: 				     $env{'course.'.$courseid.'.domain'},
                   6123: 				     'course',
                   6124: 				     ($courselevelm,$courselevel));
1.593     albertel 6125: 	    if (defined($coursereply)) { return $coursereply; }
                   6126: 	}
1.145     www      6127: # ------------------------------------------------------------------ Cascade up
1.218     albertel 6128: 	unless ($space eq '0') {
1.336     albertel 6129: 	    my @parts=split(/_/,$space);
                   6130: 	    my $id=pop(@parts);
                   6131: 	    my $part=join('_',@parts);
                   6132: 	    if ($part eq '') { $part='0'; }
                   6133: 	    my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 6134: 				 $symbparm,$udom,$uname,$section,1);
1.337     albertel 6135: 	    if (defined($partgeneral)) { return $partgeneral; }
1.218     albertel 6136: 	}
1.395     albertel 6137: 	if ($recurse) { return undef; }
                   6138: 	my $pack_def=&packages_tab_default($filename,$varname);
                   6139: 	if (defined($pack_def)) { return $pack_def; }
1.71      www      6140: 
1.48      www      6141: # ---------------------------------------------------- Any other user namespace
                   6142:     } elsif ($realm eq 'environment') {
                   6143: # ----------------------------------------------------------------- environment
1.620     albertel 6144: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   6145: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 6146: 	} else {
1.770     albertel 6147: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   6148: 		return '';
                   6149: 	    }
1.219     albertel 6150: 	    my %returnhash=&userenvironment($udom,$uname,
                   6151: 					    $spacequalifierrest);
                   6152: 	    return $returnhash{$spacequalifierrest};
                   6153: 	}
1.28      www      6154:     } elsif ($realm eq 'system') {
1.48      www      6155: # ----------------------------------------------------------------- system.time
                   6156: 	if ($space eq 'time') {
                   6157: 	    return time;
                   6158:         }
1.696     albertel 6159:     } elsif ($realm eq 'server') {
                   6160: # ----------------------------------------------------------------- system.time
                   6161: 	if ($space eq 'name') {
                   6162: 	    return $ENV{'SERVER_NAME'};
                   6163:         }
1.28      www      6164:     }
1.48      www      6165:     return '';
1.61      www      6166: }
                   6167: 
1.691     raeburn  6168: sub check_group_parms {
                   6169:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   6170:     my @groupitems = ();
                   6171:     my $resultitem;
                   6172:     my @levels = ($symbparm,$mapparm,$what);
                   6173:     foreach my $group (@{$groups}) {
                   6174:         foreach my $level (@levels) {
                   6175:              my $item = $courseid.'.['.$group.'].'.$level;
                   6176:              push(@groupitems,$item);
                   6177:         }
                   6178:     }
                   6179:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   6180:                             $env{'course.'.$courseid.'.domain'},
                   6181:                                      'course',@groupitems);
                   6182:     return $coursereply;
                   6183: }
                   6184: 
                   6185: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  6186:     my ($courseid,@groups) = @_;
                   6187:     @groups = sort(@groups);
1.691     raeburn  6188:     return @groups;
                   6189: }
                   6190: 
1.395     albertel 6191: sub packages_tab_default {
                   6192:     my ($uri,$varname)=@_;
                   6193:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 6194: 
                   6195:     my (@extension,@specifics,$do_default);
                   6196:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 6197: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 6198: 	if ($pack_type eq 'default') {
                   6199: 	    $do_default=1;
                   6200: 	} elsif ($pack_type eq 'extension') {
                   6201: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.848     albertel 6202: 	} elsif ($pack_part eq $part) {
                   6203: 	    # only look at packages defaults for packages that this id is
1.738     albertel 6204: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   6205: 	}
                   6206:     }
                   6207:     # first look for a package that matches the requested part id
                   6208:     foreach my $package (@specifics) {
                   6209: 	my (undef,$pack_type,$pack_part)=@{$package};
                   6210: 	next if ($pack_part ne $part);
                   6211: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6212: 	    return $packagetab{"$pack_type&$name&default"};
                   6213: 	}
                   6214:     }
                   6215:     # look for any possible matching non extension_ package
                   6216:     foreach my $package (@specifics) {
                   6217: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 6218: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6219: 	    return $packagetab{"$pack_type&$name&default"};
                   6220: 	}
1.585     albertel 6221: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 6222: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   6223: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 6224: 	}
                   6225:     }
1.738     albertel 6226:     # look for any posible extension_ match
                   6227:     foreach my $package (@extension) {
                   6228: 	my ($package,$pack_type)=@{$package};
                   6229: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6230: 	    return $packagetab{"$pack_type&$name&default"};
                   6231: 	}
                   6232: 	if (defined($packagetab{$package."&$name&default"})) {
                   6233: 	    return $packagetab{$package."&$name&default"};
                   6234: 	}
                   6235:     }
                   6236:     # look for a global default setting
                   6237:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   6238: 	return $packagetab{"default&$name&default"};
                   6239:     }
1.395     albertel 6240:     return undef;
                   6241: }
                   6242: 
1.334     albertel 6243: sub add_prefix_and_part {
                   6244:     my ($prefix,$part)=@_;
                   6245:     my $keyroot;
                   6246:     if (defined($prefix) && $prefix !~ /^__/) {
                   6247: 	# prefix that has a part already
                   6248: 	$keyroot=$prefix;
                   6249:     } elsif (defined($prefix)) {
                   6250: 	# prefix that is missing a part
                   6251: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   6252:     } else {
                   6253: 	# no prefix at all
                   6254: 	if (defined($part)) { $keyroot='_'.$part; }
                   6255:     }
                   6256:     return $keyroot;
                   6257: }
                   6258: 
1.71      www      6259: # ---------------------------------------------------------------- Get metadata
                   6260: 
1.599     albertel 6261: my %metaentry;
1.71      www      6262: sub metadata {
1.176     www      6263:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      6264:     $uri=&declutter($uri);
1.288     albertel 6265:     # if it is a non metadata possible uri return quickly
1.529     albertel 6266:     if (($uri eq '') || 
                   6267: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 6268: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.423     albertel 6269:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) ||
1.807     albertel 6270: 	($uri =~ m|home/$match_username/public_html/|)) {
1.468     albertel 6271: 	return undef;
1.288     albertel 6272:     }
1.73      www      6273:     my $filename=$uri;
                   6274:     $uri=~s/\.meta$//;
1.172     www      6275: #
                   6276: # Is the metadata already cached?
1.177     www      6277: # Look at timestamp of caching
1.172     www      6278: # Everything is cached by the main uri, libraries are never directly cached
                   6279: #
1.428     albertel 6280:     if (!defined($liburi)) {
1.599     albertel 6281: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 6282: 	if (defined($cached)) { return $result->{':'.$what}; }
                   6283:     }
                   6284:     {
1.172     www      6285: #
                   6286: # Is this a recursive call for a library?
                   6287: #
1.599     albertel 6288: #	if (! exists($metacache{$uri})) {
                   6289: #	    $metacache{$uri}={};
                   6290: #	}
1.171     www      6291:         if ($liburi) {
                   6292: 	    $liburi=&declutter($liburi);
                   6293:             $filename=$liburi;
1.401     bowersj2 6294:         } else {
1.599     albertel 6295: 	    &devalidate_cache_new('meta',$uri);
                   6296: 	    undef(%metaentry);
1.401     bowersj2 6297: 	}
1.140     www      6298:         my %metathesekeys=();
1.73      www      6299:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 6300: 	my $metastring;
1.768     albertel 6301: 	if ($uri !~ m -^(editupload)/-) {
1.543     albertel 6302: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 6303: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 6304: 	    $metastring=&getfile($file);
1.489     albertel 6305: 	}
1.208     albertel 6306:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      6307:         my $token;
1.140     www      6308:         undef %metathesekeys;
1.71      www      6309:         while ($token=$parser->get_token) {
1.339     albertel 6310: 	    if ($token->[0] eq 'S') {
                   6311: 		if (defined($token->[2]->{'package'})) {
1.172     www      6312: #
                   6313: # This is a package - get package info
                   6314: #
1.339     albertel 6315: 		    my $package=$token->[2]->{'package'};
                   6316: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   6317: 		    if (defined($token->[2]->{'id'})) { 
                   6318: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   6319: 		    }
1.599     albertel 6320: 		    if ($metaentry{':packages'}) {
                   6321: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 6322: 		    } else {
1.599     albertel 6323: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 6324: 		    }
1.736     albertel 6325: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 6326: 			my $part=$keyroot;
                   6327: 			$part=~s/^\_//;
1.736     albertel 6328: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   6329: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   6330: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 6331: 			    # ignore package.tab specified default values
                   6332:                             # here &package_tab_default() will fetch those
                   6333: 			    if ($subp eq 'default') { next; }
1.736     albertel 6334: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 6335: 			    my $unikey;
                   6336: 			    if ($pack =~ /_0$/) {
                   6337: 				$unikey='parameter_0_'.$name;
                   6338: 				$part=0;
                   6339: 			    } else {
                   6340: 				$unikey='parameter'.$keyroot.'_'.$name;
                   6341: 			    }
1.339     albertel 6342: 			    if ($subp eq 'display') {
                   6343: 				$value.=' [Part: '.$part.']';
                   6344: 			    }
1.599     albertel 6345: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 6346: 			    $metathesekeys{$unikey}=1;
1.599     albertel 6347: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   6348: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 6349: 			    }
1.599     albertel 6350: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   6351: 				$metaentry{':'.$unikey}=
                   6352: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 6353: 			    }
1.339     albertel 6354: 			}
                   6355: 		    }
                   6356: 		} else {
1.172     www      6357: #
                   6358: # This is not a package - some other kind of start tag
1.339     albertel 6359: #
                   6360: 		    my $entry=$token->[1];
                   6361: 		    my $unikey;
                   6362: 		    if ($entry eq 'import') {
                   6363: 			$unikey='';
                   6364: 		    } else {
                   6365: 			$unikey=$entry;
                   6366: 		    }
                   6367: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   6368: 
                   6369: 		    if (defined($token->[2]->{'id'})) { 
                   6370: 			$unikey.='_'.$token->[2]->{'id'}; 
                   6371: 		    }
1.175     www      6372: 
1.339     albertel 6373: 		    if ($entry eq 'import') {
1.175     www      6374: #
                   6375: # Importing a library here
1.339     albertel 6376: #
                   6377: 			if ($depthcount<20) {
                   6378: 			    my $location=$parser->get_text('/import');
                   6379: 			    my $dir=$filename;
                   6380: 			    $dir=~s|[^/]*$||;
                   6381: 			    $location=&filelocation($dir,$location);
1.736     albertel 6382: 			    my $metadata = 
                   6383: 				&metadata($uri,'keys', $location,$unikey,
                   6384: 					  $depthcount+1);
                   6385: 			    foreach my $meta (split(',',$metadata)) {
                   6386: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   6387: 				$metathesekeys{$meta}=1;
1.339     albertel 6388: 			    }
                   6389: 			}
                   6390: 		    } else { 
                   6391: 			
                   6392: 			if (defined($token->[2]->{'name'})) { 
                   6393: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   6394: 			}
                   6395: 			$metathesekeys{$unikey}=1;
1.736     albertel 6396: 			foreach my $param (@{$token->[3]}) {
                   6397: 			    $metaentry{':'.$unikey.'.'.$param} =
                   6398: 				$token->[2]->{$param};
1.339     albertel 6399: 			}
                   6400: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 6401: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 6402: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   6403: 		 # only ws inside the tag, and not in default, so use default
                   6404: 		 # as value
1.599     albertel 6405: 			    $metaentry{':'.$unikey}=$default;
1.339     albertel 6406: 			} else {
1.321     albertel 6407: 		  # either something interesting inside the tag or default
                   6408:                   # uninteresting
1.599     albertel 6409: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 6410: 			}
1.172     www      6411: # end of not-a-package not-a-library import
1.339     albertel 6412: 		    }
1.172     www      6413: # end of not-a-package start tag
1.339     albertel 6414: 		}
1.172     www      6415: # the next is the end of "start tag"
1.339     albertel 6416: 	    }
                   6417: 	}
1.483     albertel 6418: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.737     albertel 6419: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 6420: 	    #no specific packages #how's our extension
                   6421: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 6422: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 6423: 					 \%metathesekeys);
                   6424: 	}
1.599     albertel 6425: 	if (!exists($metaentry{':packages'})) {
1.737     albertel 6426: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 6427: 		#no specific packages well let's get default then
                   6428: 		if ($key!~/^default&/) { next; }
1.488     albertel 6429: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 6430: 					     \%metathesekeys);
                   6431: 	    }
                   6432: 	}
1.338     www      6433: # are there custom rights to evaluate
1.599     albertel 6434: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 6435: 
1.338     www      6436:     #
                   6437:     # Importing a rights file here
1.339     albertel 6438:     #
                   6439: 	    unless ($depthcount) {
1.599     albertel 6440: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 6441: 		my $dir=$filename;
                   6442: 		$dir=~s|[^/]*$||;
                   6443: 		$location=&filelocation($dir,$location);
1.736     albertel 6444: 		my $rights_metadata =
                   6445: 		    &metadata($uri,'keys',$location,'_rights',
                   6446: 			      $depthcount+1);
                   6447: 		foreach my $rights (split(',',$rights_metadata)) {
                   6448: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   6449: 		    $metathesekeys{$rights}=1;
1.339     albertel 6450: 		}
                   6451: 	    }
                   6452: 	}
1.737     albertel 6453: 	# uniqifiy package listing
                   6454: 	my %seen;
                   6455: 	my @uniq_packages =
                   6456: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   6457: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   6458: 
                   6459: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 6460: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   6461: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.699     albertel 6462: 	&do_cache_new('meta',$uri,\%metaentry,60*60);
1.177     www      6463: # this is the end of "was not already recently cached
1.71      www      6464:     }
1.599     albertel 6465:     return $metaentry{':'.$what};
1.261     albertel 6466: }
                   6467: 
1.488     albertel 6468: sub metadata_create_package_def {
1.483     albertel 6469:     my ($uri,$key,$package,$metathesekeys)=@_;
                   6470:     my ($pack,$name,$subp)=split(/\&/,$key);
                   6471:     if ($subp eq 'default') { next; }
                   6472:     
1.599     albertel 6473:     if (defined($metaentry{':packages'})) {
                   6474: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 6475:     } else {
1.599     albertel 6476: 	$metaentry{':packages'}=$package;
1.483     albertel 6477:     }
                   6478:     my $value=$packagetab{$key};
                   6479:     my $unikey;
                   6480:     $unikey='parameter_0_'.$name;
1.599     albertel 6481:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 6482:     $$metathesekeys{$unikey}=1;
1.599     albertel 6483:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   6484: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 6485:     }
1.599     albertel 6486:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   6487: 	$metaentry{':'.$unikey}=
                   6488: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 6489:     }
                   6490: }
                   6491: 
1.261     albertel 6492: sub metadata_generate_part0 {
                   6493:     my ($metadata,$metacache,$uri) = @_;
                   6494:     my %allnames;
1.737     albertel 6495:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 6496: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 6497: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   6498: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 6499: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 6500: 	    $allnames{$name}=$part;
                   6501: 	  }
                   6502: 	}
                   6503:     }
                   6504:     foreach my $name (keys(%allnames)) {
                   6505:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 6506:       my $key=":parameter_0_$name";
1.261     albertel 6507:       $$metacache{"$key.part"}='0';
                   6508:       $$metacache{"$key.name"}=$name;
1.428     albertel 6509:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 6510: 					   $allnames{$name}.'_'.$name.
                   6511: 					   '.type'};
1.428     albertel 6512:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 6513: 			     '.display'};
1.644     www      6514:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 6515:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 6516:       $$metacache{"$key.display"}=$olddis;
                   6517:     }
1.71      www      6518: }
                   6519: 
1.764     albertel 6520: # ------------------------------------------------------ Devalidate title cache
                   6521: 
                   6522: sub devalidate_title_cache {
                   6523:     my ($url)=@_;
                   6524:     if (!$env{'request.course.id'}) { return; }
                   6525:     my $symb=&symbread($url);
                   6526:     if (!$symb) { return; }
                   6527:     my $key=$env{'request.course.id'}."\0".$symb;
                   6528:     &devalidate_cache_new('title',$key);
                   6529: }
                   6530: 
1.301     www      6531: # ------------------------------------------------- Get the title of a resource
                   6532: 
                   6533: sub gettitle {
                   6534:     my $urlsymb=shift;
                   6535:     my $symb=&symbread($urlsymb);
1.534     albertel 6536:     if ($symb) {
1.620     albertel 6537: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 6538: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 6539: 	if (defined($cached)) { 
                   6540: 	    return $result;
                   6541: 	}
1.534     albertel 6542: 	my ($map,$resid,$url)=&decode_symb($symb);
                   6543: 	my $title='';
                   6544: 	my %bighash;
1.620     albertel 6545: 	if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.534     albertel 6546: 		&GDBM_READER(),0640)) {
                   6547: 	    my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   6548: 	    $title=$bighash{'title_'.$mapid.'.'.$resid};
                   6549: 	    untie %bighash;
                   6550: 	}
                   6551: 	$title=~s/\&colon\;/\:/gs;
                   6552: 	if ($title) {
1.599     albertel 6553: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 6554: 	}
                   6555: 	$urlsymb=$url;
                   6556:     }
                   6557:     my $title=&metadata($urlsymb,'title');
                   6558:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   6559:     return $title;
1.301     www      6560: }
1.613     albertel 6561: 
1.614     albertel 6562: sub get_slot {
                   6563:     my ($which,$cnum,$cdom)=@_;
                   6564:     if (!$cnum || !$cdom) {
1.790     albertel 6565: 	(undef,my $courseid)=&whichuser();
1.620     albertel 6566: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   6567: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 6568:     }
1.703     albertel 6569:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   6570:     my %slotinfo;
                   6571:     if (exists($remembered{$key})) {
                   6572: 	$slotinfo{$which} = $remembered{$key};
                   6573:     } else {
                   6574: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   6575: 	&Apache::lonhomework::showhash(%slotinfo);
                   6576: 	my ($tmp)=keys(%slotinfo);
                   6577: 	if ($tmp=~/^error:/) { return (); }
                   6578: 	$remembered{$key} = $slotinfo{$which};
                   6579:     }
1.616     albertel 6580:     if (ref($slotinfo{$which}) eq 'HASH') {
                   6581: 	return %{$slotinfo{$which}};
                   6582:     }
                   6583:     return $slotinfo{$which};
1.614     albertel 6584: }
1.31      www      6585: # ------------------------------------------------- Update symbolic store links
                   6586: 
                   6587: sub symblist {
                   6588:     my ($mapname,%newhash)=@_;
1.438     www      6589:     $mapname=&deversion(&declutter($mapname));
1.31      www      6590:     my %hash;
1.620     albertel 6591:     if (($env{'request.course.fn'}) && (%newhash)) {
                   6592:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 6593:                       &GDBM_WRCREAT(),0640)) {
1.711     albertel 6594: 	    foreach my $url (keys %newhash) {
                   6595: 		next if ($url eq 'last_known'
                   6596: 			 && $env{'form.no_update_last_known'});
                   6597: 		$hash{declutter($url)}=&encode_symb($mapname,
                   6598: 						    $newhash{$url}->[1],
                   6599: 						    $newhash{$url}->[0]);
1.191     harris41 6600:             }
1.31      www      6601:             if (untie(%hash)) {
                   6602: 		return 'ok';
                   6603:             }
                   6604:         }
                   6605:     }
                   6606:     return 'error';
1.212     www      6607: }
                   6608: 
                   6609: # --------------------------------------------------------------- Verify a symb
                   6610: 
                   6611: sub symbverify {
1.510     www      6612:     my ($symb,$thisurl)=@_;
                   6613:     my $thisfn=$thisurl;
1.439     www      6614:     $thisfn=&declutter($thisfn);
1.215     www      6615: # direct jump to resource in page or to a sequence - will construct own symbs
                   6616:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   6617: # check URL part
1.409     www      6618:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      6619: 
1.431     www      6620:     unless ($url eq $thisfn) { return 0; }
1.213     www      6621: 
1.216     www      6622:     $symb=&symbclean($symb);
1.510     www      6623:     $thisurl=&deversion($thisurl);
1.439     www      6624:     $thisfn=&deversion($thisfn);
1.213     www      6625: 
                   6626:     my %bighash;
                   6627:     my $okay=0;
1.431     www      6628: 
1.620     albertel 6629:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 6630:                             &GDBM_READER(),0640)) {
1.510     www      6631:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      6632:         unless ($ids) { 
1.510     www      6633:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      6634:         }
                   6635:         if ($ids) {
                   6636: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 6637: 	    foreach my $id (split(/\,/,$ids)) {
                   6638: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      6639:                if (
                   6640:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   6641:    eq $symb) { 
1.620     albertel 6642: 		   if (($env{'request.role.adv'}) ||
1.800     albertel 6643: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582     albertel 6644: 		       $okay=1; 
                   6645: 		   }
                   6646: 	       }
1.216     www      6647: 	   }
                   6648:         }
1.213     www      6649: 	untie(%bighash);
                   6650:     }
                   6651:     return $okay;
1.31      www      6652: }
                   6653: 
1.210     www      6654: # --------------------------------------------------------------- Clean-up symb
                   6655: 
                   6656: sub symbclean {
                   6657:     my $symb=shift;
1.568     albertel 6658:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      6659: # remove version from map
                   6660:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      6661: 
1.210     www      6662: # remove version from URL
                   6663:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      6664: 
1.507     www      6665: # remove wrapper
                   6666: 
1.510     www      6667:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 6668:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      6669:     return $symb;
1.409     www      6670: }
                   6671: 
                   6672: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 6673: 
                   6674: sub encode_symb {
                   6675:     my ($map,$resid,$url)=@_;
                   6676:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   6677: }
1.409     www      6678: 
                   6679: sub decode_symb {
1.568     albertel 6680:     my $symb=shift;
                   6681:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   6682:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      6683:     return (&fixversion($map),$resid,&fixversion($url));
                   6684: }
                   6685: 
                   6686: sub fixversion {
                   6687:     my $fn=shift;
1.609     banghart 6688:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      6689:     my %bighash;
                   6690:     my $uri=&clutter($fn);
1.620     albertel 6691:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      6692: # is this cached?
1.599     albertel 6693:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      6694:     if (defined($cached)) { return $result; }
                   6695: # unfortunately not cached, or expired
1.620     albertel 6696:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      6697: 	    &GDBM_READER(),0640)) {
                   6698:  	if ($bighash{'version_'.$uri}) {
                   6699:  	    my $version=$bighash{'version_'.$uri};
1.444     www      6700:  	    unless (($version eq 'mostrecent') || 
                   6701: 		    ($version==&getversion($uri))) {
1.440     www      6702:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   6703:  	    }
                   6704:  	}
                   6705:  	untie %bighash;
1.413     www      6706:     }
1.599     albertel 6707:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      6708: }
                   6709: 
                   6710: sub deversion {
                   6711:     my $url=shift;
                   6712:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   6713:     return $url;
1.210     www      6714: }
                   6715: 
1.31      www      6716: # ------------------------------------------------------ Return symb list entry
                   6717: 
                   6718: sub symbread {
1.249     www      6719:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 6720:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 6721:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      6722: # no filename provided? try from environment
1.44      www      6723:     unless ($thisfn) {
1.620     albertel 6724:         if ($env{'request.symb'}) {
                   6725: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 6726: 	}
1.620     albertel 6727: 	$thisfn=$env{'request.filename'};
1.44      www      6728:     }
1.569     albertel 6729:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      6730: # is that filename actually a symb? Verify, clean, and return
                   6731:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 6732: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 6733: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 6734: 	}
1.242     www      6735:     }
1.44      www      6736:     $thisfn=declutter($thisfn);
1.31      www      6737:     my %hash;
1.37      www      6738:     my %bighash;
                   6739:     my $syval='';
1.620     albertel 6740:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  6741:         my $targetfn = $thisfn;
1.609     banghart 6742:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  6743:             $targetfn = 'adm/wrapper/'.$thisfn;
                   6744:         }
1.687     albertel 6745: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   6746: 	    $targetfn=$1;
                   6747: 	}
1.620     albertel 6748:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 6749:                       &GDBM_READER(),0640)) {
1.481     raeburn  6750: 	    $syval=$hash{$targetfn};
1.37      www      6751:             untie(%hash);
                   6752:         }
                   6753: # ---------------------------------------------------------- There was an entry
                   6754:         if ($syval) {
1.601     albertel 6755: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 6756: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.601     albertel 6757: 		    #&appenv('request.ambiguous' => $thisfn);
1.620     albertel 6758: 		    #return $env{$cache_str}='';
1.601     albertel 6759: 		#}    
                   6760: 		#$syval.=$1;
                   6761: 	    #}
1.37      www      6762:         } else {
                   6763: # ------------------------------------------------------- Was not in symb table
1.620     albertel 6764:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 6765:                             &GDBM_READER(),0640)) {
1.37      www      6766: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      6767:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      6768:               unless ($ids) { 
                   6769:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      6770:               }
                   6771:               unless ($ids) {
                   6772: # alias?
                   6773: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      6774:               }
1.37      www      6775:               if ($ids) {
                   6776: # ------------------------------------------------------------------- Has ID(s)
                   6777:                  my @possibilities=split(/\,/,$ids);
1.39      www      6778:                  if ($#possibilities==0) {
                   6779: # ----------------------------------------------- There is only one possibility
1.37      www      6780: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 6781: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   6782: 						    $resid,$thisfn);
1.249     www      6783:                  } elsif (!$donotrecurse) {
1.39      www      6784: # ------------------------------------------ There is more than one possibility
                   6785:                      my $realpossible=0;
1.800     albertel 6786:                      foreach my $id (@possibilities) {
                   6787: 			 my $file=$bighash{'src_'.$id};
1.39      www      6788:                          if (&allowed('bre',$file)) {
1.800     albertel 6789:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      6790:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   6791: 				$realpossible++;
1.626     albertel 6792:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   6793: 						    $resid,$thisfn);
1.39      www      6794:                             }
                   6795: 			 }
1.191     harris41 6796:                      }
1.39      www      6797: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      6798:                  } else {
                   6799:                      $syval='';
1.37      www      6800:                  }
                   6801: 	      }
                   6802:               untie(%bighash)
1.481     raeburn  6803:            }
1.31      www      6804:         }
1.62      www      6805:         if ($syval) {
1.620     albertel 6806: 	    return $env{$cache_str}=$syval;
1.62      www      6807:         }
1.31      www      6808:     }
1.44      www      6809:     &appenv('request.ambiguous' => $thisfn);
1.620     albertel 6810:     return $env{$cache_str}='';
1.31      www      6811: }
                   6812: 
                   6813: # ---------------------------------------------------------- Return random seed
                   6814: 
1.32      www      6815: sub numval {
                   6816:     my $txt=shift;
                   6817:     $txt=~tr/A-J/0-9/;
                   6818:     $txt=~tr/a-j/0-9/;
                   6819:     $txt=~tr/K-T/0-9/;
                   6820:     $txt=~tr/k-t/0-9/;
                   6821:     $txt=~tr/U-Z/0-5/;
                   6822:     $txt=~tr/u-z/0-5/;
                   6823:     $txt=~s/\D//g;
1.564     albertel 6824:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      6825:     return int($txt);
1.368     albertel 6826: }
                   6827: 
1.484     albertel 6828: sub numval2 {
                   6829:     my $txt=shift;
                   6830:     $txt=~tr/A-J/0-9/;
                   6831:     $txt=~tr/a-j/0-9/;
                   6832:     $txt=~tr/K-T/0-9/;
                   6833:     $txt=~tr/k-t/0-9/;
                   6834:     $txt=~tr/U-Z/0-5/;
                   6835:     $txt=~tr/u-z/0-5/;
                   6836:     $txt=~s/\D//g;
                   6837:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   6838:     my $total;
                   6839:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 6840:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 6841:     return int($total);
                   6842: }
                   6843: 
1.575     albertel 6844: sub numval3 {
                   6845:     use integer;
                   6846:     my $txt=shift;
                   6847:     $txt=~tr/A-J/0-9/;
                   6848:     $txt=~tr/a-j/0-9/;
                   6849:     $txt=~tr/K-T/0-9/;
                   6850:     $txt=~tr/k-t/0-9/;
                   6851:     $txt=~tr/U-Z/0-5/;
                   6852:     $txt=~tr/u-z/0-5/;
                   6853:     $txt=~s/\D//g;
                   6854:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   6855:     my $total;
                   6856:     foreach my $val (@txts) { $total+=$val; }
                   6857:     if ($_64bit) { $total=(($total<<32)>>32); }
                   6858:     return $total;
                   6859: }
                   6860: 
1.675     albertel 6861: sub digest {
                   6862:     my ($data)=@_;
                   6863:     my $digest=&Digest::MD5::md5($data);
                   6864:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   6865:     my ($e,$f);
                   6866:     {
                   6867:         use integer;
                   6868:         $e=($a+$b);
                   6869:         $f=($c+$d);
                   6870:         if ($_64bit) {
                   6871:             $e=(($e<<32)>>32);
                   6872:             $f=(($f<<32)>>32);
                   6873:         }
                   6874:     }
                   6875:     if (wantarray) {
                   6876: 	return ($e,$f);
                   6877:     } else {
                   6878: 	my $g;
                   6879: 	{
                   6880: 	    use integer;
                   6881: 	    $g=($e+$f);
                   6882: 	    if ($_64bit) {
                   6883: 		$g=(($g<<32)>>32);
                   6884: 	    }
                   6885: 	}
                   6886: 	return $g;
                   6887:     }
                   6888: }
                   6889: 
1.368     albertel 6890: sub latest_rnd_algorithm_id {
1.675     albertel 6891:     return '64bit5';
1.366     albertel 6892: }
1.32      www      6893: 
1.503     albertel 6894: sub get_rand_alg {
                   6895:     my ($courseid)=@_;
1.790     albertel 6896:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 6897:     if ($courseid) {
1.620     albertel 6898: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 6899:     }
                   6900:     return &latest_rnd_algorithm_id();
                   6901: }
                   6902: 
1.562     albertel 6903: sub validCODE {
                   6904:     my ($CODE)=@_;
                   6905:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   6906:     return 0;
                   6907: }
                   6908: 
1.491     albertel 6909: sub getCODE {
1.620     albertel 6910:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 6911:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   6912: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   6913: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 6914: 	return $Apache::lonhomework::history{'resource.CODE'};
                   6915:     }
                   6916:     return undef;
                   6917: }
                   6918: 
1.31      www      6919: sub rndseed {
1.155     albertel 6920:     my ($symb,$courseid,$domain,$username)=@_;
1.366     albertel 6921: 
1.790     albertel 6922:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.155     albertel 6923:     if (!$symb) {
1.366     albertel 6924: 	unless ($symb=$wsymb) { return time; }
                   6925:     }
                   6926:     if (!$courseid) { $courseid=$wcourseid; }
                   6927:     if (!$domain) { $domain=$wdomain; }
                   6928:     if (!$username) { $username=$wusername }
1.503     albertel 6929:     my $which=&get_rand_alg();
1.803     albertel 6930: 
1.491     albertel 6931:     if (defined(&getCODE())) {
1.675     albertel 6932: 	if ($which eq '64bit5') {
                   6933: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   6934: 	} elsif ($which eq '64bit4') {
1.575     albertel 6935: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   6936: 	} else {
                   6937: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   6938: 	}
1.675     albertel 6939:     } elsif ($which eq '64bit5') {
                   6940: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 6941:     } elsif ($which eq '64bit4') {
                   6942: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 6943:     } elsif ($which eq '64bit3') {
                   6944: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 6945:     } elsif ($which eq '64bit2') {
                   6946: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 6947:     } elsif ($which eq '64bit') {
                   6948: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   6949:     }
                   6950:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   6951: }
                   6952: 
                   6953: sub rndseed_32bit {
                   6954:     my ($symb,$courseid,$domain,$username)=@_;
                   6955:     {
                   6956: 	use integer;
                   6957: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   6958: 	my $symbseed=numval($symb) << 22;
                   6959: 	my $namechck=unpack("%32C*",$username) << 17;
                   6960: 	my $nameseed=numval($username) << 12;
                   6961: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   6962: 	my $courseseed=unpack("%32C*",$courseid);
                   6963: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 6964: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6965: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 6966: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 6967: 	return $num;
                   6968:     }
                   6969: }
                   6970: 
                   6971: sub rndseed_64bit {
                   6972:     my ($symb,$courseid,$domain,$username)=@_;
                   6973:     {
                   6974: 	use integer;
                   6975: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   6976: 	my $symbseed=numval($symb) << 10;
                   6977: 	my $namechck=unpack("%32S*",$username);
                   6978: 	
                   6979: 	my $nameseed=numval($username) << 21;
                   6980: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   6981: 	my $courseseed=unpack("%32S*",$courseid);
                   6982: 	
                   6983: 	my $num1=$symbchck+$symbseed+$namechck;
                   6984: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 6985: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6986: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 6987: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 6988: 	return "$num1,$num2";
1.155     albertel 6989:     }
1.366     albertel 6990: }
                   6991: 
1.443     albertel 6992: sub rndseed_64bit2 {
                   6993:     my ($symb,$courseid,$domain,$username)=@_;
                   6994:     {
                   6995: 	use integer;
                   6996: 	# strings need to be an even # of cahracters long, it it is odd the
                   6997:         # last characters gets thrown away
                   6998: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6999: 	my $symbseed=numval($symb) << 10;
                   7000: 	my $namechck=unpack("%32S*",$username.' ');
                   7001: 	
                   7002: 	my $nameseed=numval($username) << 21;
1.501     albertel 7003: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7004: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7005: 	
                   7006: 	my $num1=$symbchck+$symbseed+$namechck;
                   7007: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7008: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7009: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 7010: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 7011: 	return "$num1,$num2";
                   7012:     }
                   7013: }
                   7014: 
                   7015: sub rndseed_64bit3 {
                   7016:     my ($symb,$courseid,$domain,$username)=@_;
                   7017:     {
                   7018: 	use integer;
                   7019: 	# strings need to be an even # of cahracters long, it it is odd the
                   7020:         # last characters gets thrown away
                   7021: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   7022: 	my $symbseed=numval2($symb) << 10;
                   7023: 	my $namechck=unpack("%32S*",$username.' ');
                   7024: 	
                   7025: 	my $nameseed=numval2($username) << 21;
1.443     albertel 7026: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7027: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7028: 	
                   7029: 	my $num1=$symbchck+$symbseed+$namechck;
                   7030: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7031: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7032: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 7033: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   7034: 	
1.503     albertel 7035: 	return "$num1:$num2";
1.443     albertel 7036:     }
                   7037: }
                   7038: 
1.575     albertel 7039: sub rndseed_64bit4 {
                   7040:     my ($symb,$courseid,$domain,$username)=@_;
                   7041:     {
                   7042: 	use integer;
                   7043: 	# strings need to be an even # of cahracters long, it it is odd the
                   7044:         # last characters gets thrown away
                   7045: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   7046: 	my $symbseed=numval3($symb) << 10;
                   7047: 	my $namechck=unpack("%32S*",$username.' ');
                   7048: 	
                   7049: 	my $nameseed=numval3($username) << 21;
                   7050: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7051: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7052: 	
                   7053: 	my $num1=$symbchck+$symbseed+$namechck;
                   7054: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7055: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7056: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 7057: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   7058: 	
                   7059: 	return "$num1:$num2";
                   7060:     }
                   7061: }
                   7062: 
1.675     albertel 7063: sub rndseed_64bit5 {
                   7064:     my ($symb,$courseid,$domain,$username)=@_;
                   7065:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   7066:     return "$num1:$num2";
                   7067: }
                   7068: 
1.366     albertel 7069: sub rndseed_CODE_64bit {
                   7070:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 7071:     {
1.366     albertel 7072: 	use integer;
1.443     albertel 7073: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 7074: 	my $symbseed=numval2($symb);
1.491     albertel 7075: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   7076: 	my $CODEseed=numval(&getCODE());
1.443     albertel 7077: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 7078: 	my $num1=$symbseed+$CODEchck;
                   7079: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 7080: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   7081: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 7082: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   7083: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 7084: 	return "$num1:$num2";
1.366     albertel 7085:     }
                   7086: }
                   7087: 
1.575     albertel 7088: sub rndseed_CODE_64bit4 {
                   7089:     my ($symb,$courseid,$domain,$username)=@_;
                   7090:     {
                   7091: 	use integer;
                   7092: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   7093: 	my $symbseed=numval3($symb);
                   7094: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   7095: 	my $CODEseed=numval3(&getCODE());
                   7096: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7097: 	my $num1=$symbseed+$CODEchck;
                   7098: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 7099: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   7100: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 7101: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   7102: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   7103: 	return "$num1:$num2";
                   7104:     }
                   7105: }
                   7106: 
1.675     albertel 7107: sub rndseed_CODE_64bit5 {
                   7108:     my ($symb,$courseid,$domain,$username)=@_;
                   7109:     my $code = &getCODE();
                   7110:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   7111:     return "$num1:$num2";
                   7112: }
                   7113: 
1.366     albertel 7114: sub setup_random_from_rndseed {
                   7115:     my ($rndseed)=@_;
1.503     albertel 7116:     if ($rndseed =~/([,:])/) {
                   7117: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 7118: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   7119:     } else {
                   7120: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 7121:     }
1.36      albertel 7122: }
                   7123: 
1.474     albertel 7124: sub latest_receipt_algorithm_id {
1.835     albertel 7125:     return 'receipt3';
1.474     albertel 7126: }
                   7127: 
1.480     www      7128: sub recunique {
                   7129:     my $fucourseid=shift;
                   7130:     my $unique;
1.835     albertel 7131:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   7132: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 7133: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      7134:     } else {
                   7135: 	$unique=$perlvar{'lonReceipt'};
                   7136:     }
                   7137:     return unpack("%32C*",$unique);
                   7138: }
                   7139: 
                   7140: sub recprefix {
                   7141:     my $fucourseid=shift;
                   7142:     my $prefix;
1.835     albertel 7143:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   7144: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 7145: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      7146:     } else {
                   7147: 	$prefix=$perlvar{'lonHostID'};
                   7148:     }
                   7149:     return unpack("%32C*",$prefix);
                   7150: }
                   7151: 
1.76      www      7152: sub ireceipt {
1.474     albertel 7153:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 7154: 
                   7155:     my $return =&recprefix($fucourseid).'-';
                   7156: 
                   7157:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   7158: 	$env{'request.state'} eq 'construct') {
                   7159: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   7160: 	return $return;
                   7161:     }
                   7162: 
1.76      www      7163:     my $cuname=unpack("%32C*",$funame);
                   7164:     my $cudom=unpack("%32C*",$fudom);
                   7165:     my $cucourseid=unpack("%32C*",$fucourseid);
                   7166:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      7167:     my $cunique=&recunique($fucourseid);
1.474     albertel 7168:     my $cpart=unpack("%32S*",$part);
1.835     albertel 7169:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   7170: 
1.790     albertel 7171: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 7172: 			       
                   7173: 	$return.= ($cunique%$cuname+
                   7174: 		   $cunique%$cudom+
                   7175: 		   $cusymb%$cuname+
                   7176: 		   $cusymb%$cudom+
                   7177: 		   $cucourseid%$cuname+
                   7178: 		   $cucourseid%$cudom+
                   7179: 		   $cpart%$cuname+
                   7180: 		   $cpart%$cudom);
                   7181:     } else {
                   7182: 	$return.= ($cunique%$cuname+
                   7183: 		   $cunique%$cudom+
                   7184: 		   $cusymb%$cuname+
                   7185: 		   $cusymb%$cudom+
                   7186: 		   $cucourseid%$cuname+
                   7187: 		   $cucourseid%$cudom);
                   7188:     }
                   7189:     return $return;
1.76      www      7190: }
                   7191: 
                   7192: sub receipt {
1.474     albertel 7193:     my ($part)=@_;
1.790     albertel 7194:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 7195:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      7196: }
1.260     ng       7197: 
1.790     albertel 7198: sub whichuser {
                   7199:     my ($passedsymb)=@_;
                   7200:     my ($symb,$courseid,$domain,$name,$publicuser);
                   7201:     if (defined($env{'form.grade_symb'})) {
                   7202: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   7203: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   7204: 	if (!$allowed &&
                   7205: 	    exists($env{'request.course.sec'}) &&
                   7206: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   7207: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   7208: 			      '/'.$env{'request.course.sec'});
                   7209: 	}
                   7210: 	if ($allowed) {
                   7211: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   7212: 	    $courseid=$tmp_courseid;
                   7213: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   7214: 	    ($name)=&get_env_multiple('form.grade_username');
                   7215: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   7216: 	}
                   7217:     }
                   7218:     if (!$passedsymb) {
                   7219: 	$symb=&symbread();
                   7220:     } else {
                   7221: 	$symb=$passedsymb;
                   7222:     }
                   7223:     $courseid=$env{'request.course.id'};
                   7224:     $domain=$env{'user.domain'};
                   7225:     $name=$env{'user.name'};
                   7226:     if ($name eq 'public' && $domain eq 'public') {
                   7227: 	if (!defined($env{'form.username'})) {
                   7228: 	    $env{'form.username'}.=time.rand(10000000);
                   7229: 	}
                   7230: 	$name.=$env{'form.username'};
                   7231:     }
                   7232:     return ($symb,$courseid,$domain,$name,$publicuser);
                   7233: 
                   7234: }
                   7235: 
1.36      albertel 7236: # ------------------------------------------------------------ Serves up a file
1.472     albertel 7237: # returns either the contents of the file or 
                   7238: # -1 if the file doesn't exist
1.481     raeburn  7239: #
                   7240: # if the target is a file that was uploaded via DOCS, 
                   7241: # a check will be made to see if a current copy exists on the local server,
                   7242: # if it does this will be served, otherwise a copy will be retrieved from
                   7243: # the home server for the course and stored in /home/httpd/html/userfiles on
                   7244: # the local server.   
1.472     albertel 7245: 
1.36      albertel 7246: sub getfile {
1.538     albertel 7247:     my ($file) = @_;
1.609     banghart 7248:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 7249:     &repcopy($file);
                   7250:     return &readfile($file);
                   7251: }
                   7252: 
                   7253: sub repcopy_userfile {
                   7254:     my ($file)=@_;
1.609     banghart 7255:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 7256:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 7257:     my ($cdom,$cnum,$filename) = 
1.811     albertel 7258: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 7259:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   7260:     if (-e "$file") {
1.828     www      7261: # we already have a local copy, check it out
1.538     albertel 7262: 	my @fileinfo = stat($file);
1.828     www      7263: 	my $rtncode;
                   7264: 	my $info;
1.538     albertel 7265: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 7266: 	if ($lwpresp ne 'ok') {
1.828     www      7267: # there is no such file anymore, even though we had a local copy
1.482     albertel 7268: 	    if ($rtncode eq '404') {
1.538     albertel 7269: 		unlink($file);
1.482     albertel 7270: 	    }
                   7271: 	    return -1;
                   7272: 	}
                   7273: 	if ($info < $fileinfo[9]) {
1.828     www      7274: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  7275: 	    return 'ok';
1.828     www      7276: 	} else {
                   7277: # the file is outdated, get rid of it
                   7278: 	    unlink($file);
1.482     albertel 7279: 	}
1.828     www      7280:     }
                   7281: # one way or the other, at this point, we don't have the file
                   7282: # construct the correct path for the file
                   7283:     my @parts = ($cdom,$cnum); 
                   7284:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   7285: 	push @parts, split(/\//,$1);
                   7286:     }
                   7287:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   7288:     foreach my $part (@parts) {
                   7289: 	$path .= '/'.$part;
                   7290: 	if (!-e $path) {
                   7291: 	    mkdir($path,0770);
1.482     albertel 7292: 	}
                   7293:     }
1.828     www      7294: # now the path exists for sure
                   7295: # get a user agent
                   7296:     my $ua=new LWP::UserAgent;
                   7297:     my $transferfile=$file.'.in.transfer';
                   7298: # FIXME: this should flock
                   7299:     if (-e $transferfile) { return 'ok'; }
                   7300:     my $request;
                   7301:     $uri=~s/^\///;
1.838     albertel 7302:     $request=new HTTP::Request('GET','http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri);
1.828     www      7303:     my $response=$ua->request($request,$transferfile);
                   7304: # did it work?
                   7305:     if ($response->is_error()) {
                   7306: 	unlink($transferfile);
                   7307: 	&logthis("Userfile repcopy failed for $uri");
                   7308: 	return -1;
                   7309:     }
                   7310: # worked, rename the transfer file
                   7311:     rename($transferfile,$file);
1.607     raeburn  7312:     return 'ok';
1.481     raeburn  7313: }
                   7314: 
1.517     albertel 7315: sub tokenwrapper {
                   7316:     my $uri=shift;
1.552     albertel 7317:     $uri=~s|^http\://([^/]+)||;
                   7318:     $uri=~s|^/||;
1.620     albertel 7319:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 7320:     my $token=$1;
1.552     albertel 7321:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   7322:     if ($udom && $uname && $file) {
                   7323: 	$file=~s|(\?\.*)*$||;
1.620     albertel 7324:         &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
1.838     albertel 7325:         return 'http://'.&hostname(&homeserver($uname,$udom)).'/'.$uri.
1.517     albertel 7326:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   7327:                                '&tokenissued='.$perlvar{'lonHostID'};
                   7328:     } else {
                   7329:         return '/adm/notfound.html';
                   7330:     }
                   7331: }
                   7332: 
1.828     www      7333: # call with reqtype HEAD: get last modification time
                   7334: # call with reqtype GET: get the file contents
                   7335: # Do not call this with reqtype GET for large files! It loads everything into memory
                   7336: #
1.481     raeburn  7337: sub getuploaded {
                   7338:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   7339:     $uri=~s/^\///;
1.838     albertel 7340:     $uri = 'http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri;
1.481     raeburn  7341:     my $ua=new LWP::UserAgent;
                   7342:     my $request=new HTTP::Request($reqtype,$uri);
                   7343:     my $response=$ua->request($request);
                   7344:     $$rtncode = $response->code;
1.482     albertel 7345:     if (! $response->is_success()) {
                   7346: 	return 'failed';
                   7347:     }      
                   7348:     if ($reqtype eq 'HEAD') {
1.486     www      7349: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 7350:     } elsif ($reqtype eq 'GET') {
                   7351: 	$$info = $response->content;
1.472     albertel 7352:     }
1.482     albertel 7353:     return 'ok';
1.36      albertel 7354: }
                   7355: 
1.481     raeburn  7356: sub readfile {
                   7357:     my $file = shift;
                   7358:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   7359:     my $fh;
                   7360:     open($fh,"<$file");
                   7361:     my $a='';
1.800     albertel 7362:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  7363:     return $a;
                   7364: }
                   7365: 
1.36      albertel 7366: sub filelocation {
1.590     banghart 7367:     my ($dir,$file) = @_;
                   7368:     my $location;
                   7369:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 7370: 
                   7371:     if ($file =~ m-^/adm/-) {
                   7372: 	$file=~s-^/adm/wrapper/-/-;
                   7373: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   7374:     }
1.590     banghart 7375:     if ($file=~m:^/~:) { # is a contruction space reference
                   7376:         $location = $file;
                   7377:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807     albertel 7378:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649     albertel 7379: 	# is a correct contruction space reference
                   7380:         $location = $file;
1.609     banghart 7381:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 7382:         my ($udom,$uname,$filename)=
1.811     albertel 7383:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 7384:         my $home=&homeserver($uname,$udom);
                   7385:         my $is_me=0;
                   7386:         my @ids=&current_machine_ids();
                   7387:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   7388:         if ($is_me) {
1.740     www      7389:   	    $location=&propath($udom,$uname).
1.590     banghart 7390:   	      '/userfiles/'.$filename;
                   7391:         } else {
                   7392:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   7393:   	      $udom.'/'.$uname.'/'.$filename;
                   7394:         }
                   7395:     } else {
                   7396:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   7397:         $file=~s:^/res/:/:;
                   7398:         if ( !( $file =~ m:^/:) ) {
                   7399:             $location = $dir. '/'.$file;
                   7400:         } else {
                   7401:             $location = '/home/httpd/html/res'.$file;
                   7402:         }
1.59      albertel 7403:     }
1.590     banghart 7404:     $location=~s://+:/:g; # remove duplicate /
                   7405:     while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
                   7406:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   7407:     return $location;
1.46      www      7408: }
1.36      albertel 7409: 
1.46      www      7410: sub hreflocation {
                   7411:     my ($dir,$file)=@_;
1.460     albertel 7412:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
1.666     albertel 7413: 	$file=filelocation($dir,$file);
1.700     albertel 7414:     } elsif ($file=~m-^/adm/-) {
                   7415: 	$file=~s-^/adm/wrapper/-/-;
                   7416: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 7417:     }
                   7418:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   7419: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807     albertel 7420:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
                   7421: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666     albertel 7422:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811     albertel 7423: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666     albertel 7424: 	    -/uploaded/$1/$2/-x;
1.46      www      7425:     }
1.462     albertel 7426:     return $file;
1.465     albertel 7427: }
                   7428: 
                   7429: sub current_machine_domains {
1.853     albertel 7430:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   7431: }
                   7432: 
                   7433: sub machine_domains {
                   7434:     my ($hostname) = @_;
1.465     albertel 7435:     my @domains;
1.838     albertel 7436:     my %hostname = &all_hostnames();
1.465     albertel 7437:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  7438: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 7439: 	if ($hostname eq $name) {
1.844     albertel 7440: 	    push(@domains,&host_domain($id));
1.465     albertel 7441: 	}
                   7442:     }
                   7443:     return @domains;
                   7444: }
                   7445: 
                   7446: sub current_machine_ids {
1.853     albertel 7447:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   7448: }
                   7449: 
                   7450: sub machine_ids {
                   7451:     my ($hostname) = @_;
                   7452:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 7453:     my @ids;
1.838     albertel 7454:     my %hostname = &all_hostnames();
1.465     albertel 7455:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  7456: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 7457: 	if ($hostname eq $name) {
                   7458: 	    push(@ids,$id);
                   7459: 	}
                   7460:     }
                   7461:     return @ids;
1.31      www      7462: }
                   7463: 
1.824     raeburn  7464: sub additional_machine_domains {
                   7465:     my @domains;
                   7466:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   7467:     while( my $line = <$fh>) {
                   7468:         $line =~ s/\s//g;
                   7469:         push(@domains,$line);
                   7470:     }
                   7471:     return @domains;
                   7472: }
                   7473: 
                   7474: sub default_login_domain {
                   7475:     my $domain = $perlvar{'lonDefDomain'};
                   7476:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   7477:     foreach my $posdom (&current_machine_domains(),
                   7478:                         &additional_machine_domains()) {
                   7479:         if (lc($posdom) eq lc($testdomain)) {
                   7480:             $domain=$posdom;
                   7481:             last;
                   7482:         }
                   7483:     }
                   7484:     return $domain;
                   7485: }
                   7486: 
1.31      www      7487: # ------------------------------------------------------------- Declutters URLs
                   7488: 
                   7489: sub declutter {
                   7490:     my $thisfn=shift;
1.569     albertel 7491:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 7492:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      7493:     $thisfn=~s/^\///;
1.697     albertel 7494:     $thisfn=~s|^adm/wrapper/||;
                   7495:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      7496:     $thisfn=~s/^res\///;
1.235     www      7497:     $thisfn=~s/\?.+$//;
1.268     www      7498:     return $thisfn;
                   7499: }
                   7500: 
                   7501: # ------------------------------------------------------------- Clutter up URLs
                   7502: 
                   7503: sub clutter {
                   7504:     my $thisfn='/'.&declutter(shift);
1.609     banghart 7505:     unless ($thisfn=~/^\/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)\//) { 
1.270     www      7506:        $thisfn='/res'.$thisfn; 
                   7507:     }
1.694     albertel 7508:     if ($thisfn !~m|/adm|) {
1.695     albertel 7509: 	if ($thisfn =~ m|/ext/|) {
1.694     albertel 7510: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 7511: 	} else {
                   7512: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   7513: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 7514: 	    if ($embstyle eq 'ssi'
                   7515: 		|| ($embstyle eq 'hdn')
                   7516: 		|| ($embstyle eq 'rat')
                   7517: 		|| ($embstyle eq 'prv')
                   7518: 		|| ($embstyle eq 'ign')) {
                   7519: 		#do nothing with these
                   7520: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 7521: 		|| ($embstyle eq 'emb')
                   7522: 		|| ($embstyle eq 'wrp')) {
                   7523: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 7524: 	    } elsif ($embstyle eq 'unk'
                   7525: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 7526: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 7527: 	    } else {
1.718     www      7528: #		&logthis("Got a blank emb style");
1.695     albertel 7529: 	    }
1.694     albertel 7530: 	}
                   7531:     }
1.31      www      7532:     return $thisfn;
1.12      www      7533: }
                   7534: 
1.787     albertel 7535: sub clutter_with_no_wrapper {
                   7536:     my $uri = &clutter(shift);
                   7537:     if ($uri =~ m-^/adm/-) {
                   7538: 	$uri =~ s-^/adm/wrapper/-/-;
                   7539: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   7540:     }
                   7541:     return $uri;
                   7542: }
                   7543: 
1.557     albertel 7544: sub freeze_escape {
                   7545:     my ($value)=@_;
                   7546:     if (ref($value)) {
                   7547: 	$value=&nfreeze($value);
                   7548: 	return '__FROZEN__'.&escape($value);
                   7549:     }
                   7550:     return &escape($value);
                   7551: }
                   7552: 
1.11      www      7553: 
1.557     albertel 7554: sub thaw_unescape {
                   7555:     my ($value)=@_;
                   7556:     if ($value =~ /^__FROZEN__/) {
                   7557: 	substr($value,0,10,undef);
                   7558: 	$value=&unescape($value);
                   7559: 	return &thaw($value);
                   7560:     }
                   7561:     return &unescape($value);
                   7562: }
                   7563: 
1.436     albertel 7564: sub correct_line_ends {
                   7565:     my ($result)=@_;
                   7566:     $$result =~s/\r\n/\n/mg;
                   7567:     $$result =~s/\r/\n/mg;
1.415     albertel 7568: }
1.1       albertel 7569: # ================================================================ Main Program
                   7570: 
1.184     www      7571: sub goodbye {
1.204     albertel 7572:    &logthis("Starting Shut down");
1.443     albertel 7573: #not converted to using infrastruture and probably shouldn't be
1.599     albertel 7574:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&freeze(\%badServerCache))));
1.443     albertel 7575: #converted
1.599     albertel 7576: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
                   7577:    &logthis(sprintf("%-20s is %s",'%homecache',length(&freeze(\%homecache))));
                   7578: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&freeze(\%titlecache))));
                   7579: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&freeze(\%courseresdatacache))));
1.425     albertel 7580: #1.1 only
1.599     albertel 7581: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&freeze(\%userresdatacache))));
                   7582: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&freeze(\%getsectioncache))));
                   7583: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&freeze(\%courseresversioncache))));
                   7584: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&freeze(\%resversioncache))));
                   7585:    &logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
                   7586:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   7587:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      7588:    &flushcourselogs();
                   7589:    &logthis("Shutting down");
                   7590: }
                   7591: 
1.179     www      7592: BEGIN {
1.228     harris41 7593: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
1.195     www      7594:     unless ($readit) {
1.217     harris41 7595: {
1.781     raeburn  7596:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   7597:     %perlvar = (%perlvar,%{$configvars});
1.227     harris41 7598: }
1.1       albertel 7599: 
1.852     albertel 7600: sub get_dns {
                   7601:     my ($url,$func) = @_;
                   7602:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   7603:     foreach my $dns (<$config>) {
                   7604: 	next if ($dns !~ /^\^(\S*)/x);
                   7605: 	$dns = $1;
                   7606: 	my $ua=new LWP::UserAgent;
                   7607: 	my $request=new HTTP::Request('GET',"http://$dns$url");
                   7608: 	my $response=$ua->request($request);
                   7609: 	next if ($response->is_error());
                   7610: 	my @content = split("\n",$response->content);
                   7611: 	&$func(\@content);
                   7612:     }
                   7613:     close($config);
                   7614: }
1.327     albertel 7615: # ------------------------------------------------------------ Read domain file
                   7616: {
1.852     albertel 7617:     my $loaded;
1.846     albertel 7618:     my %domain;
                   7619: 
1.852     albertel 7620:     sub parse_domain_tab {
                   7621: 	my ($lines) = @_;
                   7622: 	foreach my $line (@$lines) {
                   7623: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      7624: 
1.846     albertel 7625: 	    chomp($line);
1.852     albertel 7626: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 7627: 	    my %this_domain;
                   7628: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   7629: 			       'lang_def', 'city', 'longi', 'lati',
                   7630: 			       'primary') {
                   7631: 		$this_domain{$field} = shift(@elements);
                   7632: 	    }
                   7633: 	    $domain{$name} = \%this_domain;
1.852     albertel 7634: 	    &logthis("Domain.tab: $name ".$domain{$name}{'description'} );
                   7635: 	}
                   7636:     }
                   7637:     
                   7638:     sub load_domain_tab {
                   7639: 	&get_dns('/adm/dns/domain',\&parse_domain_tab);
                   7640: 	my $fh;
                   7641: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   7642: 	    my @lines = <$fh>;
                   7643: 	    &parse_domain_tab(\@lines);
1.448     albertel 7644: 	}
1.852     albertel 7645: 	close($fh);
                   7646: 	$loaded = 1;
1.327     albertel 7647:     }
1.846     albertel 7648: 
                   7649:     sub domain {
1.852     albertel 7650: 	&load_domain_tab() if (!$loaded);
                   7651: 
1.846     albertel 7652: 	my ($name,$what) = @_;
                   7653: 	return if ( !exists($domain{$name}) );
                   7654: 
                   7655: 	if (!$what) {
                   7656: 	    return $domain{$name}{'description'};
                   7657: 	}
                   7658: 	return $domain{$name}{$what};
                   7659:     }
1.327     albertel 7660: }
                   7661: 
                   7662: 
1.1       albertel 7663: # ------------------------------------------------------------- Read hosts file
                   7664: {
1.838     albertel 7665:     my %hostname;
1.844     albertel 7666:     my %hostdom;
1.845     albertel 7667:     my %libserv;
1.852     albertel 7668:     my $loaded;
                   7669: 
                   7670:     sub parse_hosts_tab {
                   7671: 	my ($file) = @_;
                   7672: 	foreach my $configline (@$file) {
                   7673: 	    next if ($configline =~ /^(\#|\s*$ )/x);
                   7674: 	    next if ($configline =~ /^\^/);
                   7675: 	    chomp($configline);
                   7676: 	    my ($id,$domain,$role,$name)=split(/:/,$configline);
                   7677: 	    $name=~s/\s//g;
                   7678: 	    if ($id && $domain && $role && $name) {
                   7679: 		$hostname{$id}=$name;
                   7680: 		$hostdom{$id}=$domain;
                   7681: 		if ($role eq 'library') { $libserv{$id}=$name; }
                   7682: 	    }
                   7683: 	    &logthis("Hosts.tab: $name ".$id );
                   7684: 	}
                   7685:     }
1.1       albertel 7686: 
1.852     albertel 7687:     sub load_hosts_tab {
                   7688: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab);
                   7689: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   7690: 	my @config = <$config>;
                   7691: 	&parse_hosts_tab(\@config);
                   7692: 	close($config);
                   7693: 	$loaded=1;
1.1       albertel 7694:     }
1.852     albertel 7695: 
1.619     albertel 7696:     # FIXME: dev server don't want this, production servers _do_ want this
1.654     albertel 7697:     #&get_iphost();
1.838     albertel 7698: 
                   7699:     sub hostname {
1.852     albertel 7700: 	&load_hosts_tab() if (!$loaded);
                   7701: 
1.838     albertel 7702: 	my ($lonid) = @_;
                   7703: 	return $hostname{$lonid};
                   7704:     }
1.845     albertel 7705: 
1.838     albertel 7706:     sub all_hostnames {
1.852     albertel 7707: 	&load_hosts_tab() if (!$loaded);
                   7708: 
1.838     albertel 7709: 	return %hostname;
                   7710:     }
1.845     albertel 7711: 
                   7712:     sub is_library {
1.852     albertel 7713: 	&load_hosts_tab() if (!$loaded);
                   7714: 
1.845     albertel 7715: 	return exists($libserv{$_[0]});
                   7716:     }
                   7717: 
                   7718:     sub all_library {
1.852     albertel 7719: 	&load_hosts_tab() if (!$loaded);
                   7720: 
1.845     albertel 7721: 	return %libserv;
                   7722:     }
                   7723: 
1.841     albertel 7724:     sub get_servers {
1.852     albertel 7725: 	&load_hosts_tab() if (!$loaded);
                   7726: 
1.841     albertel 7727: 	my ($domain,$type) = @_;
                   7728: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   7729: 	                                          : %hostname;
                   7730: 	my %result;
1.842     albertel 7731: 	if (ref($domain) eq 'ARRAY') {
                   7732: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 7733: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 7734: 		    $result{$host} = $hostname;
                   7735: 		}
                   7736: 	    }
                   7737: 	} else {
                   7738: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   7739: 		if ($hostdom{$host} eq $domain) {
                   7740: 		    $result{$host} = $hostname;
                   7741: 		}
1.841     albertel 7742: 	    }
                   7743: 	}
                   7744: 	return %result;
                   7745:     }
1.845     albertel 7746: 
1.844     albertel 7747:     sub host_domain {
1.852     albertel 7748: 	&load_hosts_tab() if (!$loaded);
                   7749: 
1.844     albertel 7750: 	my ($lonid) = @_;
                   7751: 	return $hostdom{$lonid};
                   7752:     }
                   7753: 
1.841     albertel 7754:     sub all_domains {
1.852     albertel 7755: 	&load_hosts_tab() if (!$loaded);
                   7756: 
1.841     albertel 7757: 	my %seen;
                   7758: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   7759: 	return @uniq;
                   7760:     }
1.1       albertel 7761: }
                   7762: 
1.847     albertel 7763: { 
                   7764:     my %iphost;
                   7765:     sub get_hosts_from_ip {
                   7766: 	my ($ip) = @_;
                   7767: 	my %iphosts = &get_iphost();
                   7768: 	if (ref($iphosts{$ip})) {
                   7769: 	    return @{$iphosts{$ip}};
                   7770: 	}
                   7771: 	return;
1.839     albertel 7772:     }
1.847     albertel 7773:     
                   7774:     sub get_iphost {
                   7775: 	if (%iphost) { return %iphost; }
                   7776: 	my %name_to_ip;
                   7777: 	my %hostname = &all_hostnames();
                   7778: 	foreach my $id (keys(%hostname)) {
                   7779: 	    my $name=$hostname{$id};
                   7780: 	    my $ip;
                   7781: 	    if (!exists($name_to_ip{$name})) {
                   7782: 		$ip = gethostbyname($name);
                   7783: 		if (!$ip || length($ip) ne 4) {
                   7784: 		    &logthis("Skipping host $id name $name no IP found");
                   7785: 		    next;
                   7786: 		}
                   7787: 		$ip=inet_ntoa($ip);
                   7788: 		$name_to_ip{$name} = $ip;
                   7789: 	    } else {
                   7790: 		$ip = $name_to_ip{$name};
1.653     albertel 7791: 	    }
1.847     albertel 7792: 	    push(@{$iphost{$ip}},$id);
1.598     albertel 7793: 	}
1.847     albertel 7794: 	return %iphost;
1.598     albertel 7795:     }
                   7796: }
                   7797: 
1.1       albertel 7798: # ------------------------------------------------------ Read spare server file
                   7799: {
1.448     albertel 7800:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 7801: 
                   7802:     while (my $configline=<$config>) {
                   7803:        chomp($configline);
1.284     matthew  7804:        if ($configline) {
1.784     albertel 7805: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 7806: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 7807: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 7808:        }
                   7809:     }
1.448     albertel 7810:     close($config);
1.1       albertel 7811: }
1.11      www      7812: # ------------------------------------------------------------ Read permissions
                   7813: {
1.448     albertel 7814:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      7815: 
                   7816:     while (my $configline=<$config>) {
1.448     albertel 7817: 	chomp($configline);
                   7818: 	if ($configline) {
                   7819: 	    my ($role,$perm)=split(/ /,$configline);
                   7820: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   7821: 	}
1.11      www      7822:     }
1.448     albertel 7823:     close($config);
1.11      www      7824: }
                   7825: 
                   7826: # -------------------------------------------- Read plain texts for permissions
                   7827: {
1.448     albertel 7828:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      7829: 
                   7830:     while (my $configline=<$config>) {
1.448     albertel 7831: 	chomp($configline);
                   7832: 	if ($configline) {
1.742     raeburn  7833: 	    my ($short,@plain)=split(/:/,$configline);
                   7834:             %{$prp{$short}} = ();
                   7835: 	    if (@plain > 0) {
                   7836:                 $prp{$short}{'std'} = $plain[0];
                   7837:                 for (my $i=1; $i<@plain; $i++) {
                   7838:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   7839:                 }
                   7840:             }
1.448     albertel 7841: 	}
1.135     www      7842:     }
1.448     albertel 7843:     close($config);
1.135     www      7844: }
                   7845: 
                   7846: # ---------------------------------------------------------- Read package table
                   7847: {
1.448     albertel 7848:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      7849: 
                   7850:     while (my $configline=<$config>) {
1.483     albertel 7851: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 7852: 	chomp($configline);
                   7853: 	my ($short,$plain)=split(/:/,$configline);
                   7854: 	my ($pack,$name)=split(/\&/,$short);
                   7855: 	if ($plain ne '') {
                   7856: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   7857: 	    $packagetab{$short}=$plain; 
                   7858: 	}
1.11      www      7859:     }
1.448     albertel 7860:     close($config);
1.329     matthew  7861: }
                   7862: 
                   7863: # ------------- set up temporary directory
                   7864: {
                   7865:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   7866: 
1.11      www      7867: }
                   7868: 
1.794     albertel 7869: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   7870: 				'compress_threshold'=> 20_000,
                   7871:  			        });
1.185     www      7872: 
1.281     www      7873: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      7874: $dumpcount=0;
1.22      www      7875: 
1.163     harris41 7876: &logtouch();
1.672     albertel 7877: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      7878: $readit=1;
1.564     albertel 7879:     {
                   7880: 	use integer;
                   7881: 	my $test=(2**32)+1;
1.568     albertel 7882: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 7883: 	&logthis(" Detected 64bit platform ($_64bit)");
                   7884:     }
1.195     www      7885: }
1.1       albertel 7886: }
1.179     www      7887: 
1.1       albertel 7888: 1;
1.191     harris41 7889: __END__
                   7890: 
1.243     albertel 7891: =pod
                   7892: 
1.191     harris41 7893: =head1 NAME
                   7894: 
1.243     albertel 7895: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 7896: 
                   7897: =head1 SYNOPSIS
                   7898: 
1.243     albertel 7899: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 7900: 
                   7901:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   7902: 
1.243     albertel 7903: Common parameters:
                   7904: 
                   7905: =over 4
                   7906: 
                   7907: =item *
                   7908: 
                   7909: $uname : an internal username (if $cname expecting a course Id specifically)
                   7910: 
                   7911: =item *
                   7912: 
                   7913: $udom : a domain (if $cdom expecting a course's domain specifically)
                   7914: 
                   7915: =item *
                   7916: 
                   7917: $symb : a resource instance identifier
                   7918: 
                   7919: =item *
                   7920: 
                   7921: $namespace : the name of a .db file that contains the data needed or
                   7922: being set.
                   7923: 
                   7924: =back
                   7925: 
1.394     bowersj2 7926: =head1 OVERVIEW
1.191     harris41 7927: 
1.394     bowersj2 7928: lonnet provides subroutines which interact with the
                   7929: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   7930: about classes, users, and resources.
1.243     albertel 7931: 
                   7932: For many of these objects you can also use this to store data about
                   7933: them or modify them in various ways.
1.191     harris41 7934: 
1.394     bowersj2 7935: =head2 Symbs
1.191     harris41 7936: 
1.394     bowersj2 7937: To identify a specific instance of a resource, LON-CAPA uses symbols
                   7938: or "symbs"X<symb>. These identifiers are built from the URL of the
                   7939: map, the resource number of the resource in the map, and the URL of
                   7940: the resource itself. The latter is somewhat redundant, but might help
                   7941: if maps change.
                   7942: 
                   7943: An example is
                   7944: 
                   7945:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   7946: 
                   7947: The respective map entry is
                   7948: 
                   7949:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   7950:   title="Problem 2">
                   7951:  </resource>
                   7952: 
                   7953: Symbs are used by the random number generator, as well as to store and
                   7954: restore data specific to a certain instance of for example a problem.
                   7955: 
                   7956: =head2 Storing And Retrieving Data
                   7957: 
                   7958: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   7959: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   7960: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   7961: is is the non-critical message twin of cstore. These functions are for
                   7962: handlers to store a perl hash to a user's permanent data space in an
                   7963: easy manner, and to retrieve it again on another call. It is expected
                   7964: that a handler would use this once at the beginning to retrieve data,
                   7965: and then again once at the end to send only the new data back.
                   7966: 
                   7967: The data is stored in the user's data directory on the user's
                   7968: homeserver under the ID of the course.
                   7969: 
                   7970: The hash that is returned by restore will have all of the previous
                   7971: value for all of the elements of the hash.
                   7972: 
                   7973: Example:
                   7974: 
                   7975:  #creating a hash
                   7976:  my %hash;
                   7977:  $hash{'foo'}='bar';
                   7978: 
                   7979:  #storing it
                   7980:  &Apache::lonnet::cstore(\%hash);
                   7981: 
                   7982:  #changing a value
                   7983:  $hash{'foo'}='notbar';
                   7984: 
                   7985:  #adding a new value
                   7986:  $hash{'bar'}='foo';
                   7987:  &Apache::lonnet::cstore(\%hash);
                   7988: 
                   7989:  #retrieving the hash
                   7990:  my %history=&Apache::lonnet::restore();
                   7991: 
                   7992:  #print the hash
                   7993:  foreach my $key (sort(keys(%history))) {
                   7994:    print("\%history{$key} = $history{$key}");
                   7995:  }
                   7996: 
                   7997: Will print out:
1.191     harris41 7998: 
1.394     bowersj2 7999:  %history{1:foo} = bar
                   8000:  %history{1:keys} = foo:timestamp
                   8001:  %history{1:timestamp} = 990455579
                   8002:  %history{2:bar} = foo
                   8003:  %history{2:foo} = notbar
                   8004:  %history{2:keys} = foo:bar:timestamp
                   8005:  %history{2:timestamp} = 990455580
                   8006:  %history{bar} = foo
                   8007:  %history{foo} = notbar
                   8008:  %history{timestamp} = 990455580
                   8009:  %history{version} = 2
                   8010: 
                   8011: Note that the special hash entries C<keys>, C<version> and
                   8012: C<timestamp> were added to the hash. C<version> will be equal to the
                   8013: total number of versions of the data that have been stored. The
                   8014: C<timestamp> attribute will be the UNIX time the hash was
                   8015: stored. C<keys> is available in every historical section to list which
                   8016: keys were added or changed at a specific historical revision of a
                   8017: hash.
                   8018: 
                   8019: B<Warning>: do not store the hash that restore returns directly. This
                   8020: will cause a mess since it will restore the historical keys as if the
                   8021: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 8022: 
1.394     bowersj2 8023: Calling convention:
1.191     harris41 8024: 
1.394     bowersj2 8025:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   8026:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 8027: 
1.394     bowersj2 8028: For more detailed information, see lonnet specific documentation.
1.191     harris41 8029: 
1.394     bowersj2 8030: =head1 RETURN MESSAGES
1.191     harris41 8031: 
1.394     bowersj2 8032: =over 4
1.191     harris41 8033: 
1.394     bowersj2 8034: =item * B<con_lost>: unable to contact remote host
1.191     harris41 8035: 
1.394     bowersj2 8036: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   8037: when the connection is brought back up
1.191     harris41 8038: 
1.394     bowersj2 8039: =item * B<con_failed>: unable to contact remote host and unable to save message
                   8040: for later delivery
1.191     harris41 8041: 
1.394     bowersj2 8042: =item * B<error:>: an error a occured, a description of the error follows the :
1.191     harris41 8043: 
1.394     bowersj2 8044: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 8045: that was requested
1.191     harris41 8046: 
1.243     albertel 8047: =back
1.191     harris41 8048: 
1.243     albertel 8049: =head1 PUBLIC SUBROUTINES
1.191     harris41 8050: 
1.243     albertel 8051: =head2 Session Environment Functions
1.191     harris41 8052: 
1.243     albertel 8053: =over 4
1.191     harris41 8054: 
1.394     bowersj2 8055: =item * 
                   8056: X<appenv()>
                   8057: B<appenv(%hash)>: the value of %hash is written to
                   8058: the user envirnoment file, and will be restored for each access this
1.620     albertel 8059: user makes during this session, also modifies the %env for the current
1.394     bowersj2 8060: process
1.191     harris41 8061: 
                   8062: =item *
1.394     bowersj2 8063: X<delenv()>
                   8064: B<delenv($regexp)>: removes all items from the session
                   8065: environment file that matches the regular expression in $regexp. The
1.620     albertel 8066: values are also delted from the current processes %env.
1.191     harris41 8067: 
1.795     albertel 8068: =item * get_env_multiple($name) 
                   8069: 
                   8070: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   8071: values may be defined and end up as an array ref.
                   8072: 
                   8073: returns an array of values
                   8074: 
1.243     albertel 8075: =back
                   8076: 
                   8077: =head2 User Information
1.191     harris41 8078: 
1.243     albertel 8079: =over 4
1.191     harris41 8080: 
                   8081: =item *
1.394     bowersj2 8082: X<queryauthenticate()>
                   8083: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 8084: authentication scheme
                   8085: 
                   8086: =item *
1.394     bowersj2 8087: X<authenticate()>
                   8088: B<authenticate($uname,$upass,$udom)>: try to
                   8089: authenticate user from domain's lib servers (first use the current
                   8090: one). C<$upass> should be the users password.
1.191     harris41 8091: 
                   8092: =item *
1.394     bowersj2 8093: X<homeserver()>
                   8094: B<homeserver($uname,$udom)>: find the server which has
                   8095: the user's directory and files (there must be only one), this caches
                   8096: the answer, and also caches if there is a borken connection.
1.191     harris41 8097: 
                   8098: =item *
1.394     bowersj2 8099: X<idget()>
                   8100: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   8101: (IDs are a unique resource in a domain, there must be only 1 ID per
                   8102: username, and only 1 username per ID in a specific domain) (returns
                   8103: hash: id=>name,id=>name)
1.191     harris41 8104: 
                   8105: =item *
1.394     bowersj2 8106: X<idrget()>
                   8107: B<idrget($udom,@unames)>: find the IDs behind a list of
                   8108: usernames (returns hash: name=>id,name=>id)
1.191     harris41 8109: 
                   8110: =item *
1.394     bowersj2 8111: X<idput()>
                   8112: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 8113: 
                   8114: =item *
1.394     bowersj2 8115: X<rolesinit()>
                   8116: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 8117: 
                   8118: =item *
1.551     albertel 8119: X<getsection()>
                   8120: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 8121: course $cname, return section name/number or '' for "not in course"
                   8122: and '-1' for "no section"
                   8123: 
                   8124: =item *
1.394     bowersj2 8125: X<userenvironment()>
                   8126: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 8127: passed in @what from the requested user's environment, returns a hash
                   8128: 
                   8129: =back
                   8130: 
                   8131: =head2 User Roles
                   8132: 
                   8133: =over 4
                   8134: 
                   8135: =item *
                   8136: 
1.810     raeburn  8137: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 8138:  F: full access
                   8139:  U,I,K: authentication modes (cxx only)
                   8140:  '': forbidden
                   8141:  1: user needs to choose course
                   8142:  2: browse allowed
1.766     albertel 8143:  A: passphrase authentication needed
1.243     albertel 8144: 
                   8145: =item *
                   8146: 
                   8147: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   8148: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   8149: and course level
                   8150: 
                   8151: =item *
                   8152: 
                   8153: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
                   8154: explanation of a user role term
                   8155: 
1.832     raeburn  8156: =item *
                   8157: 
1.834     albertel 8158: get_my_roles($uname,$udom,$types,$roles,$roledoms) : All arguments are
                   8159: optional.  Returns a hash of a user's roles, with keys set to
                   8160: colon-sparated $uname,$udom,and $role, and value set to
                   8161: colon-separated start and end times for the role. If no username and
                   8162: domain are specified, will default to current user/domain. Types,
                   8163: roles, and roledoms are references to arrays, of role statuses
                   8164: (active, future or previous), roles (e.g., cc,in, st etc.) and domains
                   8165: of the roles which can be used to restrict the list if roles
                   8166: reported. If no array ref is provided for types, will default to
                   8167: return only active roles.
                   8168: 
1.243     albertel 8169: =back
                   8170: 
                   8171: =head2 User Modification
                   8172: 
                   8173: =over 4
                   8174: 
                   8175: =item *
                   8176: 
                   8177: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
                   8178: user for the level given by URL.  Optional start and end dates (leave empty
                   8179: string or zero for "no date")
1.191     harris41 8180: 
                   8181: =item *
                   8182: 
1.243     albertel 8183: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   8184: change a users, password, possible return values are: ok,
                   8185: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   8186: refused
1.191     harris41 8187: 
                   8188: =item *
                   8189: 
1.243     albertel 8190: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 8191: 
                   8192: =item *
                   8193: 
1.243     albertel 8194: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
                   8195: modify user
1.191     harris41 8196: 
                   8197: =item *
                   8198: 
1.286     matthew  8199: modifystudent
                   8200: 
                   8201: modify a students enrollment and identification information.
                   8202: The course id is resolved based on the current users environment.  
                   8203: This means the envoking user must be a course coordinator or otherwise
                   8204: associated with a course.
                   8205: 
1.297     matthew  8206: This call is essentially a wrapper for lonnet::modifyuser and
                   8207: lonnet::modify_student_enrollment
1.286     matthew  8208: 
                   8209: Inputs: 
                   8210: 
                   8211: =over 4
                   8212: 
                   8213: =item B<$udom> Students loncapa domain
                   8214: 
                   8215: =item B<$uname> Students loncapa login name
                   8216: 
                   8217: =item B<$uid> Students id/student number
                   8218: 
                   8219: =item B<$umode> Students authentication mode
                   8220: 
                   8221: =item B<$upass> Students password
                   8222: 
                   8223: =item B<$first> Students first name
                   8224: 
                   8225: =item B<$middle> Students middle name
                   8226: 
                   8227: =item B<$last> Students last name
                   8228: 
                   8229: =item B<$gene> Students generation
                   8230: 
                   8231: =item B<$usec> Students section in course
                   8232: 
                   8233: =item B<$end> Unix time of the roles expiration
                   8234: 
                   8235: =item B<$start> Unix time of the roles start date
                   8236: 
                   8237: =item B<$forceid> If defined, allow $uid to be changed
                   8238: 
                   8239: =item B<$desiredhome> server to use as home server for student
                   8240: 
                   8241: =back
1.297     matthew  8242: 
                   8243: =item *
                   8244: 
                   8245: modify_student_enrollment
                   8246: 
                   8247: Change a students enrollment status in a class.  The environment variable
                   8248: 'role.request.course' must be defined for this function to proceed.
                   8249: 
                   8250: Inputs:
                   8251: 
                   8252: =over 4
                   8253: 
                   8254: =item $udom, students domain
                   8255: 
                   8256: =item $uname, students name
                   8257: 
                   8258: =item $uid, students user id
                   8259: 
                   8260: =item $first, students first name
                   8261: 
                   8262: =item $middle
                   8263: 
                   8264: =item $last
                   8265: 
                   8266: =item $gene
                   8267: 
                   8268: =item $usec
                   8269: 
                   8270: =item $end
                   8271: 
                   8272: =item $start
                   8273: 
                   8274: =back
                   8275: 
1.191     harris41 8276: 
                   8277: =item *
                   8278: 
1.243     albertel 8279: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   8280: custom role; give a custom role to a user for the level given by URL.  Specify
                   8281: name and domain of role author, and role name
1.191     harris41 8282: 
                   8283: =item *
                   8284: 
1.243     albertel 8285: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 8286: 
                   8287: =item *
                   8288: 
1.243     albertel 8289: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   8290: 
                   8291: =back
                   8292: 
                   8293: =head2 Course Infomation
                   8294: 
                   8295: =over 4
1.191     harris41 8296: 
                   8297: =item *
                   8298: 
1.631     albertel 8299: coursedescription($courseid) : returns a hash of information about the
                   8300: specified course id, including all environment settings for the
                   8301: course, the description of the course will be in the hash under the
                   8302: key 'description'
1.191     harris41 8303: 
                   8304: =item *
                   8305: 
1.624     albertel 8306: resdata($name,$domain,$type,@which) : request for current parameter
                   8307: setting for a specific $type, where $type is either 'course' or 'user',
                   8308: @what should be a list of parameters to ask about. This routine caches
                   8309: answers for 5 minutes.
1.243     albertel 8310: 
                   8311: =back
                   8312: 
                   8313: =head2 Course Modification
                   8314: 
                   8315: =over 4
1.191     harris41 8316: 
                   8317: =item *
                   8318: 
1.243     albertel 8319: writecoursepref($courseid,%prefs) : write preferences (environment
                   8320: database) for a course
1.191     harris41 8321: 
                   8322: =item *
                   8323: 
1.243     albertel 8324: createcourse($udom,$description,$url) : make/modify course
                   8325: 
                   8326: =back
                   8327: 
                   8328: =head2 Resource Subroutines
                   8329: 
                   8330: =over 4
1.191     harris41 8331: 
                   8332: =item *
                   8333: 
1.243     albertel 8334: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 8335: 
                   8336: =item *
                   8337: 
1.243     albertel 8338: repcopy($filename) : subscribes to the requested file, and attempts to
                   8339: replicate from the owning library server, Might return
1.607     raeburn  8340: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   8341: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 8342: resource. Expects the local filesystem pathname
                   8343: (/home/httpd/html/res/....)
                   8344: 
                   8345: =back
                   8346: 
                   8347: =head2 Resource Information
                   8348: 
                   8349: =over 4
1.191     harris41 8350: 
                   8351: =item *
                   8352: 
1.243     albertel 8353: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   8354: a vairety of different possible values, $varname should be a request
                   8355: string, and the other parameters can be used to specify who and what
                   8356: one is asking about.
                   8357: 
                   8358: Possible values for $varname are environment.lastname (or other item
                   8359: from the envirnment hash), user.name (or someother aspect about the
                   8360: user), resource.0.maxtries (or some other part and parameter of a
                   8361: resource)
1.204     albertel 8362: 
                   8363: =item *
                   8364: 
1.243     albertel 8365: directcondval($number) : get current value of a condition; reads from a state
                   8366: string
1.204     albertel 8367: 
                   8368: =item *
                   8369: 
1.243     albertel 8370: condval($condidx) : value of condition index based on state
1.204     albertel 8371: 
                   8372: =item *
                   8373: 
1.243     albertel 8374: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   8375: resource's metadata, $what should be either a specific key, or either
                   8376: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   8377: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   8378: 
                   8379: this function automatically caches all requests
1.191     harris41 8380: 
                   8381: =item *
                   8382: 
1.243     albertel 8383: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   8384: network of library servers; returns file handle of where SQL and regex results
                   8385: will be stored for query
1.191     harris41 8386: 
                   8387: =item *
                   8388: 
1.243     albertel 8389: symbread($filename) : return symbolic list entry (filename argument optional);
                   8390: returns the data handle
1.191     harris41 8391: 
                   8392: =item *
                   8393: 
1.243     albertel 8394: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 8395: a possible symb for the URL in $thisfn, and if is an encryypted
                   8396: resource that the user accessed using /enc/ returns a 1 on success, 0
                   8397: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 8398: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 8399: 
1.191     harris41 8400: 
                   8401: =item *
                   8402: 
1.243     albertel 8403: symbclean($symb) : removes versions numbers from a symb, returns the
                   8404: cleaned symb
1.191     harris41 8405: 
                   8406: =item *
                   8407: 
1.243     albertel 8408: is_on_map($uri) : checks if the $uri is somewhere on the current
                   8409: course map, user must be in a course for it to work.
1.191     harris41 8410: 
                   8411: =item *
                   8412: 
1.243     albertel 8413: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 8414: 
                   8415: =item *
                   8416: 
1.243     albertel 8417: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   8418: a random seed, all arguments are optional, if they aren't sent it uses the
                   8419: environment to derive them. Note: if symb isn't sent and it can't get one
                   8420: from &symbread it will use the current time as its return value
1.191     harris41 8421: 
                   8422: =item *
                   8423: 
1.243     albertel 8424: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   8425: unfakeable, receipt
1.191     harris41 8426: 
                   8427: =item *
                   8428: 
1.620     albertel 8429: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 8430: 
                   8431: =item *
                   8432: 
1.243     albertel 8433: countacc($url) : count the number of accesses to a given URL
1.191     harris41 8434: 
                   8435: =item *
                   8436: 
1.243     albertel 8437: 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 8438: 
                   8439: =item *
                   8440: 
1.243     albertel 8441: 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 8442: 
                   8443: =item *
                   8444: 
1.243     albertel 8445: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 8446: 
                   8447: =item *
                   8448: 
1.243     albertel 8449: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   8450: forcing spreadsheet to reevaluate the resource scores next time.
                   8451: 
                   8452: =back
                   8453: 
                   8454: =head2 Storing/Retreiving Data
                   8455: 
                   8456: =over 4
1.191     harris41 8457: 
                   8458: =item *
                   8459: 
1.243     albertel 8460: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   8461: for this url; hashref needs to be given and should be a \%hashname; the
                   8462: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 8463: be derived from the env
1.191     harris41 8464: 
                   8465: =item *
                   8466: 
1.243     albertel 8467: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   8468: uses critical subroutine
1.191     harris41 8469: 
                   8470: =item *
                   8471: 
1.243     albertel 8472: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   8473: all args are optional
1.191     harris41 8474: 
                   8475: =item *
                   8476: 
1.717     albertel 8477: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   8478: dumps the complete (or key matching regexp) namespace into a hash
                   8479: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   8480: normally &store()ed into
                   8481: 
                   8482: $range should be either an integer '100' (give me the first 100
                   8483:                                            matching records)
                   8484:               or be  two integers sperated by a - with no spaces
                   8485:                  '30-50' (give me the 30th through the 50th matching
                   8486:                           records)
                   8487: 
                   8488: 
                   8489: =item *
                   8490: 
                   8491: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   8492: replaces a &store() version of data with a replacement set of data
                   8493: for a particular resource in a namespace passed in the $storehash hash 
                   8494: reference
                   8495: 
                   8496: =item *
                   8497: 
1.243     albertel 8498: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   8499: works very similar to store/cstore, but all data is stored in a
                   8500: temporary location and can be reset using tmpreset, $storehash should
                   8501: be a hash reference, returns nothing on success
1.191     harris41 8502: 
                   8503: =item *
                   8504: 
1.243     albertel 8505: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   8506: similar to restore, but all data is stored in a temporary location and
                   8507: can be reset using tmpreset. Returns a hash of values on success,
                   8508: error string otherwise.
1.191     harris41 8509: 
                   8510: =item *
                   8511: 
1.243     albertel 8512: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   8513: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 8514: 
                   8515: =item *
                   8516: 
1.243     albertel 8517: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   8518: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 8519: 
                   8520: =item *
                   8521: 
1.243     albertel 8522: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   8523: namesp ($udom and $uname are optional)
1.191     harris41 8524: 
                   8525: =item *
                   8526: 
1.702     albertel 8527: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 8528: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 8529: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  8530: 
1.702     albertel 8531: $range should be either an integer '100' (give me the first 100
                   8532:                                            matching records)
                   8533:               or be  two integers sperated by a - with no spaces
                   8534:                  '30-50' (give me the 30th through the 50th matching
                   8535:                           records)
1.449     matthew  8536: =item *
                   8537: 
                   8538: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   8539: $store can be a scalar, an array reference, or if the amount to be 
                   8540: incremented is > 1, a hash reference.
                   8541: 
                   8542: ($udom and $uname are optional)
1.191     harris41 8543: 
                   8544: =item *
                   8545: 
1.243     albertel 8546: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   8547: ($udom and $uname are optional)
1.191     harris41 8548: 
                   8549: =item *
                   8550: 
1.243     albertel 8551: cput($namespace,$storehash,$udom,$uname) : critical put
                   8552: ($udom and $uname are optional)
1.191     harris41 8553: 
                   8554: =item *
                   8555: 
1.748     albertel 8556: newput($namespace,$storehash,$udom,$uname) :
                   8557: 
                   8558: Attempts to store the items in the $storehash, but only if they don't
                   8559: currently exist, if this succeeds you can be certain that you have 
                   8560: successfully created a new key value pair in the $namespace db.
                   8561: 
                   8562: 
                   8563: Args:
                   8564:  $namespace: name of database to store values to
                   8565:  $storehash: hashref to store to the db
                   8566:  $udom: (optional) domain of user containing the db
                   8567:  $uname: (optional) name of user caontaining the db
                   8568: 
                   8569: Returns:
                   8570:  'ok' -> succeeded in storing all keys of $storehash
                   8571:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   8572:                         least <key> already existed in the db (other
                   8573:                         requested keys may also already exist)
                   8574:  'error: <msg>' -> unable to tie the DB or other erorr occured
                   8575:  'con_lost' -> unable to contact request server
                   8576:  'refused' -> action was not allowed by remote machine
                   8577: 
                   8578: 
                   8579: =item *
                   8580: 
1.243     albertel 8581: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   8582: reference filled in from namesp (encrypts the return communication)
                   8583: ($udom and $uname are optional)
1.191     harris41 8584: 
                   8585: =item *
                   8586: 
1.243     albertel 8587: log($udom,$name,$home,$message) : write to permanent log for user; use
                   8588: critical subroutine
                   8589: 
1.806     raeburn  8590: =item *
                   8591: 
                   8592: get_dom($namespace,$storearr,$udomain) : returns hash with keys from array
                   8593: reference filled in from namespace found in domain level on primary domain server ($udomain is optional)
                   8594: 
                   8595: =item *
                   8596: 
                   8597: put_dom($namespace,$storehash,$udomain) :  stores hash in namespace at domain level on primary domain server ($udomain is optional)
                   8598: 
1.243     albertel 8599: =back
                   8600: 
                   8601: =head2 Network Status Functions
                   8602: 
                   8603: =over 4
1.191     harris41 8604: 
                   8605: =item *
                   8606: 
                   8607: dirlist($uri) : return directory list based on URI
                   8608: 
                   8609: =item *
                   8610: 
1.243     albertel 8611: spareserver() : find server with least workload from spare.tab
                   8612: 
                   8613: =back
                   8614: 
                   8615: =head2 Apache Request
                   8616: 
                   8617: =over 4
1.191     harris41 8618: 
                   8619: =item *
                   8620: 
1.243     albertel 8621: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   8622: localhost, posts hash
                   8623: 
                   8624: =back
                   8625: 
                   8626: =head2 Data to String to Data
                   8627: 
                   8628: =over 4
1.191     harris41 8629: 
                   8630: =item *
                   8631: 
1.243     albertel 8632: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   8633: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 8634: 
                   8635: =item *
                   8636: 
1.243     albertel 8637: hashref2str($hashref) : convert a hashref into a string complete with
                   8638: escaping and '=' and '&' separators, supports elements that are
                   8639: arrayrefs and hashrefs
1.191     harris41 8640: 
                   8641: =item *
                   8642: 
1.243     albertel 8643: arrayref2str($arrayref) : convert an arrayref into a string complete
                   8644: with escaping and '&' separators, supports elements that are arrayrefs
                   8645: and hashrefs
1.191     harris41 8646: 
                   8647: =item *
                   8648: 
1.243     albertel 8649: str2hash($string) : convert string to hash using unescaping and
                   8650: splitting on '=' and '&', supports elements that are arrayrefs and
                   8651: hashrefs
1.191     harris41 8652: 
                   8653: =item *
                   8654: 
1.243     albertel 8655: str2array($string) : convert string to hash using unescaping and
                   8656: splitting on '&', supports elements that are arrayrefs and hashrefs
                   8657: 
                   8658: =back
                   8659: 
                   8660: =head2 Logging Routines
                   8661: 
                   8662: =over 4
                   8663: 
                   8664: These routines allow one to make log messages in the lonnet.log and
                   8665: lonnet.perm logfiles.
1.191     harris41 8666: 
                   8667: =item *
                   8668: 
1.243     albertel 8669: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 8670: 
                   8671: =item *
                   8672: 
1.243     albertel 8673: logthis() : append message to the normal lonnet.log file, it gets
                   8674: preiodically rolled over and deleted.
1.191     harris41 8675: 
                   8676: =item *
                   8677: 
1.243     albertel 8678: logperm() : append a permanent message to lonnet.perm.log, this log
                   8679: file never gets deleted by any automated portion of the system, only
                   8680: messages of critical importance should go in here.
                   8681: 
                   8682: =back
                   8683: 
                   8684: =head2 General File Helper Routines
                   8685: 
                   8686: =over 4
1.191     harris41 8687: 
                   8688: =item *
                   8689: 
1.481     raeburn  8690: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   8691: (a) files in /uploaded
                   8692:   (i) If a local copy of the file exists - 
                   8693:       compares modification date of local copy with last-modified date for 
                   8694:       definitive version stored on home server for course. If local copy is 
                   8695:       stale, requests a new version from the home server and stores it. 
                   8696:       If the original has been removed from the home server, then local copy 
                   8697:       is unlinked.
                   8698:   (ii) If local copy does not exist -
                   8699:       requests the file from the home server and stores it. 
                   8700:   
                   8701:   If $caller is 'uploadrep':  
                   8702:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   8703:     for request for files originally uploaded via DOCS. 
                   8704:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   8705:   
                   8706:   Otherwise:
                   8707:      This indicates a call from the content generation phase of the request.
                   8708:      -  returns the entire contents of the file or -1.
                   8709:      
                   8710: (b) files in /res
                   8711:    - returns the entire contents of a file or -1; 
                   8712:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 8713: 
1.712     albertel 8714: 
                   8715: =item *
                   8716: 
                   8717: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   8718:                   reference
                   8719: 
                   8720: returns either a stat() list of data about the file or an empty list
                   8721: if the file doesn't exist or couldn't find out about it (connection
                   8722: problems or user unknown)
                   8723: 
1.191     harris41 8724: =item *
                   8725: 
1.243     albertel 8726: filelocation($dir,$file) : returns file system location of a file
                   8727: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   8728: directory that relative $file lookups are to looked in ($dir of /a/dir
                   8729: and a file of ../bob will become /a/bob)
1.191     harris41 8730: 
                   8731: =item *
                   8732: 
                   8733: hreflocation($dir,$file) : returns file system location or a URL; same as
                   8734: filelocation except for hrefs
                   8735: 
                   8736: =item *
                   8737: 
                   8738: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   8739: 
1.243     albertel 8740: =back
                   8741: 
1.608     albertel 8742: =head2 Usererfile file routines (/uploaded*)
                   8743: 
                   8744: =over 4
                   8745: 
                   8746: =item *
                   8747: 
                   8748: userfileupload(): main rotine for putting a file in a user or course's
                   8749:                   filespace, arguments are,
                   8750: 
1.620     albertel 8751:  formname - required - this is the name of the element in $env where the
1.608     albertel 8752:            filename, and the contents of the file to create/modifed exist
1.620     albertel 8753:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   8754:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 8755:  coursedoc - if true, store the file in the course of the active role
                   8756:              of the current user
                   8757:  subdir - required - subdirectory to put the file in under ../userfiles/
                   8758:          if undefined, it will be placed in "unknown"
                   8759: 
                   8760:  (This routine calls clean_filename() to remove any dangerous
                   8761:  characters from the filename, and then calls finuserfileupload() to
                   8762:  complete the transaction)
                   8763: 
                   8764:  returns either the url of the uploaded file (/uploaded/....) if successful
                   8765:  and /adm/notfound.html if unsuccessful
                   8766: 
                   8767: =item *
                   8768: 
                   8769: clean_filename(): routine for cleaing a filename up for storage in
                   8770:                  userfile space, argument is:
                   8771: 
                   8772:  filename - proposed filename
                   8773: 
                   8774: returns: the new clean filename
                   8775: 
                   8776: =item *
                   8777: 
                   8778: finishuserfileupload(): routine that creaes and sends the file to
                   8779: userspace, probably shouldn't be called directly
                   8780: 
                   8781:   docuname: username or courseid of destination for the file
                   8782:   docudom: domain of user/course of destination for the file
                   8783:   formname: same as for userfileupload()
                   8784:   fname: filename (inculding subdirectories) for the file
                   8785: 
                   8786:  returns either the url of the uploaded file (/uploaded/....) if successful
                   8787:  and /adm/notfound.html if unsuccessful
                   8788: 
                   8789: =item *
                   8790: 
                   8791: renameuserfile(): renames an existing userfile to a new name
                   8792: 
                   8793:   Args:
                   8794:    docuname: username or courseid of destination for the file
                   8795:    docudom: domain of user/course of destination for the file
                   8796:    old: current file name (including any subdirs under userfiles)
                   8797:    new: desired file name (including any subdirs under userfiles)
                   8798: 
                   8799: =item *
                   8800: 
                   8801: mkdiruserfile(): creates a directory is a userfiles dir
                   8802: 
                   8803:   Args:
                   8804:    docuname: username or courseid of destination for the file
                   8805:    docudom: domain of user/course of destination for the file
                   8806:    dir: dir to create (including any subdirs under userfiles)
                   8807: 
                   8808: =item *
                   8809: 
                   8810: removeuserfile(): removes a file that exists in userfiles
                   8811: 
                   8812:   Args:
                   8813:    docuname: username or courseid of destination for the file
                   8814:    docudom: domain of user/course of destination for the file
                   8815:    fname: filname to delete (including any subdirs under userfiles)
                   8816: 
                   8817: =item *
                   8818: 
                   8819: removeuploadedurl(): convience function for removeuserfile()
                   8820: 
                   8821:   Args:
                   8822:    url:  a full /uploaded/... url to delete
                   8823: 
1.747     albertel 8824: =item * 
                   8825: 
                   8826: get_portfile_permissions():
                   8827:   Args:
                   8828:     domain: domain of user or course contain the portfolio files
                   8829:     user: name of user or num of course contain the portfolio files
                   8830:   Returns:
                   8831:     hashref of a dump of the proper file_permissions.db
                   8832:    
                   8833: 
                   8834: =item * 
                   8835: 
                   8836: get_access_controls():
                   8837: 
                   8838: Args:
                   8839:   current_permissions: the hash ref returned from get_portfile_permissions()
                   8840:   group: (optional) the group you want the files associated with
                   8841:   file: (optional) the file you want access info on
                   8842: 
                   8843: Returns:
1.749     raeburn  8844:     a hash (keys are file names) of hashes containing
                   8845:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   8846:         values are XML containing access control settings (see below) 
1.747     albertel 8847: 
                   8848: Internal notes:
                   8849: 
1.749     raeburn  8850:  access controls are stored in file_permissions.db as key=value pairs.
                   8851:     key -> path to file/file_name\0uniqueID:scope_end_start
                   8852:         where scope -> public,guest,course,group,domains or users.
                   8853:               end -> UNIX time for end of access (0 -> no end date)
                   8854:               start -> UNIX time for start of access
                   8855: 
                   8856:     value -> XML description of access control
                   8857:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   8858:             <start></start>
                   8859:             <end></end>
                   8860: 
                   8861:             <password></password>  for scope type = guest
                   8862: 
                   8863:             <domain></domain>     for scope type = course or group
                   8864:             <number></number>
                   8865:             <roles id="">
                   8866:              <role></role>
                   8867:              <access></access>
                   8868:              <section></section>
                   8869:              <group></group>
                   8870:             </roles>
                   8871: 
                   8872:             <dom></dom>         for scope type = domains
                   8873: 
                   8874:             <users>             for scope type = users
                   8875:              <user>
                   8876:               <uname></uname>
                   8877:               <udom></udom>
                   8878:              </user>
                   8879:             </users>
                   8880:            </scope> 
                   8881:               
                   8882:  Access data is also aggregated for each file in an additional key=value pair:
                   8883:  key -> path to file/file_name\0accesscontrol 
                   8884:  value -> reference to hash
                   8885:           hash contains key = value pairs
                   8886:           where key = uniqueID:scope_end_start
                   8887:                 value = UNIX time record was last updated
                   8888: 
                   8889:           Used to improve speed of look-ups of access controls for each file.  
                   8890:  
                   8891:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   8892: 
                   8893: modify_access_controls():
                   8894: 
                   8895: Modifies access controls for a portfolio file
                   8896: Args
                   8897: 1. file name
                   8898: 2. reference to hash of required changes,
                   8899: 3. domain
                   8900: 4. username
                   8901:   where domain,username are the domain of the portfolio owner 
                   8902:   (either a user or a course) 
                   8903: 
                   8904: Returns:
                   8905: 1. result of additions or updates ('ok' or 'error', with error message). 
                   8906: 2. result of deletions ('ok' or 'error', with error message).
                   8907: 3. reference to hash of any new or updated access controls.
                   8908: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   8909:    key = integer (inbound ID)
                   8910:    value = uniqueID  
1.747     albertel 8911: 
1.608     albertel 8912: =back
                   8913: 
1.243     albertel 8914: =head2 HTTP Helper Routines
                   8915: 
                   8916: =over 4
                   8917: 
1.191     harris41 8918: =item *
                   8919: 
                   8920: escape() : unpack non-word characters into CGI-compatible hex codes
                   8921: 
                   8922: =item *
                   8923: 
                   8924: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   8925: 
1.243     albertel 8926: =back
                   8927: 
                   8928: =head1 PRIVATE SUBROUTINES
                   8929: 
                   8930: =head2 Underlying communication routines (Shouldn't call)
                   8931: 
                   8932: =over 4
                   8933: 
                   8934: =item *
                   8935: 
                   8936: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   8937: 
                   8938: =item *
                   8939: 
                   8940: reply() : uses subreply to send a message to remote machine, logs all failures
                   8941: 
                   8942: =item *
                   8943: 
                   8944: critical() : passes a critical message to another server; if cannot
                   8945: get through then place message in connection buffer directory and
                   8946: returns con_delayed, if incapable of saving message, returns
                   8947: con_failed
                   8948: 
                   8949: =item *
                   8950: 
                   8951: reconlonc() : tries to reconnect lonc client processes.
                   8952: 
                   8953: =back
                   8954: 
                   8955: =head2 Resource Access Logging
                   8956: 
                   8957: =over 4
                   8958: 
                   8959: =item *
                   8960: 
                   8961: flushcourselogs() : flush (save) buffer logs and access logs
                   8962: 
                   8963: =item *
                   8964: 
                   8965: courselog($what) : save message for course in hash
                   8966: 
                   8967: =item *
                   8968: 
                   8969: courseacclog($what) : save message for course using &courselog().  Perform
                   8970: special processing for specific resource types (problems, exams, quizzes, etc).
                   8971: 
1.191     harris41 8972: =item *
                   8973: 
                   8974: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   8975: as a PerlChildExitHandler
1.243     albertel 8976: 
                   8977: =back
                   8978: 
                   8979: =head2 Other
                   8980: 
                   8981: =over 4
                   8982: 
                   8983: =item *
                   8984: 
                   8985: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 8986: 
                   8987: =back
                   8988: 
                   8989: =cut

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