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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.976   ! raeburn     4: # $Id: lonnet.pm,v 1.975 2008/11/29 10:34:29 raeburn 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.971     jms        30: =pod
                     31: 
1.972     jms        32: =head1 NAME
                     33: 
                     34: Apache::lonnet.pm
                     35: 
                     36: =head1 SYNOPSIS
                     37: 
                     38: This file is an interface to the lonc processes of
                     39: the LON-CAPA network as well as set of elaborated functions for handling information
                     40: necessary for navigating through a given cluster of LON-CAPA machines within a
                     41: domain. There are over 40 specialized functions in this module which handle the
                     42: reading and transmission of metadata, user information (ids, names, environments, roles,
                     43: logs), file information (storage, reading, directories, extensions, replication, embedded
                     44: styles and descriptors), educational resources (course descriptions, section names and
                     45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
                     46: and from more descriptive phrases or explanations.
                     47: 
                     48: This is part of the LearningOnline Network with CAPA project
                     49: described at http://www.lon-capa.org.
                     50: 
1.971     jms        51: =head1 Package Variables
                     52: 
                     53: These are largely undocumented, so if you decipher one please note it here.
                     54: 
                     55: =over 4
                     56: 
                     57: =item $processmarker
                     58: 
                     59: Contains the time this process was started and this servers host id.
                     60: 
                     61: =item $dumpcount
                     62: 
                     63: Counts the number of times a message log flush has been attempted (regardless
                     64: of success) by this process.  Used as part of the filename when messages are
                     65: delayed.
                     66: 
                     67: =back
                     68: 
                     69: =cut
                     70: 
1.1       albertel   71: package Apache::lonnet;
                     72: 
                     73: use strict;
1.8       www        74: use LWP::UserAgent();
1.486     www        75: use HTTP::Date;
                     76: # use Date::Parse;
1.871     albertel   77: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
1.968     raeburn    78:             $_64bit %env %protocol);
1.871     albertel   79: 
                     80: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
                     81:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
                     82:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958     www        83:     %courseownerbuf, %coursetypebuf,$locknum);
1.403     www        84: 
1.1       albertel   85: use IO::Socket;
1.31      www        86: use GDBM_File;
1.208     albertel   87: use HTML::LCParser;
1.88      www        88: use Fcntl qw(:flock);
1.870     albertel   89: use Storable qw(thaw nfreeze);
1.539     albertel   90: use Time::HiRes qw( gettimeofday tv_interval );
1.599     albertel   91: use Cache::Memcached;
1.676     albertel   92: use Digest::MD5;
1.790     albertel   93: use Math::Random;
1.807     albertel   94: use LONCAPA qw(:DEFAULT :match);
1.740     www        95: use LONCAPA::Configuration;
1.676     albertel   96: 
1.195     www        97: my $readit;
1.550     foxr       98: my $max_connection_retries = 10;     # Or some such value.
1.1       albertel   99: 
1.619     albertel  100: require Exporter;
                    101: 
                    102: our @ISA = qw (Exporter);
                    103: our @EXPORT = qw(%env);
                    104: 
1.449     matthew   105: 
1.1       albertel  106: # --------------------------------------------------------------------- Logging
1.729     www       107: {
                    108:     my $logid;
                    109:     sub instructor_log {
1.957     raeburn   110: 	my ($hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
                    111:         if (($cnum eq '') || ($cdom eq '')) {
                    112:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                    113:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                    114:         }
1.729     www       115: 	$logid++;
1.957     raeburn   116:         my $now = time();
                    117: 	my $id=$now.'00000'.$$.'00000'.$logid;
1.729     www       118: 	return &Apache::lonnet::put('nohist_'.$hash_name,
1.730     www       119: 				    { $id => {
                    120: 					'exe_uname' => $env{'user.name'},
                    121: 					'exe_udom'  => $env{'user.domain'},
1.957     raeburn   122: 					'exe_time'  => $now,
1.730     www       123: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    124: 					'delflag'   => $delflag,
                    125: 					'logentry'  => $storehash,
                    126: 					'uname'     => $uname,
                    127: 					'udom'      => $udom,
                    128: 				    }
1.957     raeburn   129: 				  },$cdom,$cnum);
1.729     www       130:     }
                    131: }
1.1       albertel  132: 
1.163     harris41  133: sub logtouch {
                    134:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  135:     unless (-e "$execdir/logs/lonnet.log") {	
                    136: 	open(my $fh,">>$execdir/logs/lonnet.log");
1.163     harris41  137: 	close $fh;
                    138:     }
                    139:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    140:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    141: }
                    142: 
1.1       albertel  143: sub logthis {
                    144:     my $message=shift;
                    145:     my $execdir=$perlvar{'lonDaemons'};
                    146:     my $now=time;
                    147:     my $local=localtime($now);
1.448     albertel  148:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
                    149: 	print $fh "$local ($$): $message\n";
                    150: 	close($fh);
                    151:     }
1.1       albertel  152:     return 1;
                    153: }
                    154: 
                    155: sub logperm {
                    156:     my $message=shift;
                    157:     my $execdir=$perlvar{'lonDaemons'};
                    158:     my $now=time;
                    159:     my $local=localtime($now);
1.448     albertel  160:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
                    161: 	print $fh "$now:$message:$local\n";
                    162: 	close($fh);
                    163:     }
1.1       albertel  164:     return 1;
                    165: }
                    166: 
1.850     albertel  167: sub create_connection {
1.853     albertel  168:     my ($hostname,$lonid) = @_;
1.851     albertel  169:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
1.850     albertel  170: 				     Type    => SOCK_STREAM,
                    171: 				     Timeout => 10);
                    172:     return 0 if (!$client);
1.890     albertel  173:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850     albertel  174:     my $result = <$client>;
                    175:     chomp($result);
                    176:     return 1 if ($result eq 'done');
                    177:     return 0;
                    178: }
                    179: 
                    180: 
1.1       albertel  181: # -------------------------------------------------- Non-critical communication
                    182: sub subreply {
                    183:     my ($cmd,$server)=@_;
1.838     albertel  184:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      185:     #
                    186:     #  With loncnew process trimming, there's a timing hole between lonc server
                    187:     #  process exit and the master server picking up the listen on the AF_UNIX
                    188:     #  socket.  In that time interval, a lock file will exist:
                    189: 
                    190:     my $lockfile=$peerfile.".lock";
                    191:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
                    192: 	sleep(1);
                    193:     }
                    194:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      195:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      196:     #
1.550     foxr      197:     #   We'll give the connection a few tries before abandoning it.  If
                    198:     #   connection is not possible, we'll con_lost back to the client.
                    199:     #   
                    200:     my $client;
                    201:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    202: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    203: 				      Type    => SOCK_STREAM,
                    204: 				      Timeout => 10);
1.869     albertel  205: 	if ($client) {
1.550     foxr      206: 	    last;		# Connected!
1.850     albertel  207: 	} else {
1.853     albertel  208: 	    &create_connection(&hostname($server),$server);
1.550     foxr      209: 	}
1.850     albertel  210:         sleep(1);		# Try again later if failed connection.
1.550     foxr      211:     }
                    212:     my $answer;
                    213:     if ($client) {
1.704     albertel  214: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      215: 	$answer=<$client>;
                    216: 	if (!$answer) { $answer="con_lost"; }
                    217: 	chomp($answer);
                    218:     } else {
                    219: 	$answer = 'con_lost';	# Failed connection.
                    220:     }
1.1       albertel  221:     return $answer;
                    222: }
                    223: 
                    224: sub reply {
                    225:     my ($cmd,$server)=@_;
1.838     albertel  226:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  227:     my $answer=subreply($cmd,$server);
1.65      www       228:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  229:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       230:                 " $cmd to $server returned $answer</font>");
                    231:     }
1.1       albertel  232:     return $answer;
                    233: }
                    234: 
                    235: # ----------------------------------------------------------- Send USR1 to lonc
                    236: 
                    237: sub reconlonc {
1.891     albertel  238:     my ($lonid) = @_;
                    239:     my $hostname = &hostname($lonid);
                    240:     if ($lonid) {
                    241: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    242: 	if ($hostname && -e $peerfile) {
                    243: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    244: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    245: 					     Type    => SOCK_STREAM,
                    246: 					     Timeout => 10);
                    247: 	    if ($client) {
                    248: 		print $client ("reset_retries\n");
                    249: 		my $answer=<$client>;
                    250: 		#reset just this one.
                    251: 	    }
                    252: 	}
                    253: 	return;
                    254:     }
                    255: 
1.836     www       256:     &logthis("Trying to reconnect lonc");
1.1       albertel  257:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  258:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  259: 	my $loncpid=<$fh>;
                    260:         chomp($loncpid);
                    261:         if (kill 0 => $loncpid) {
                    262: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    263:             kill USR1 => $loncpid;
                    264:             sleep 1;
1.836     www       265:          } else {
1.12      www       266: 	    &logthis(
1.672     albertel  267:                "<font color=\"blue\">WARNING:".
1.12      www       268:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  269:         }
                    270:     } else {
1.836     www       271: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  272:     }
                    273: }
                    274: 
                    275: # ------------------------------------------------------ Critical communication
1.12      www       276: 
1.1       albertel  277: sub critical {
                    278:     my ($cmd,$server)=@_;
1.838     albertel  279:     unless (&hostname($server)) {
1.672     albertel  280:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       281:                " Critical message to unknown server ($server)</font>");
                    282:         return 'no_such_host';
                    283:     }
1.1       albertel  284:     my $answer=reply($cmd,$server);
                    285:     if ($answer eq 'con_lost') {
                    286: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
1.589     albertel  287: 	my $answer=reply($cmd,$server);
1.1       albertel  288:         if ($answer eq 'con_lost') {
                    289:             my $now=time;
                    290:             my $middlename=$cmd;
1.5       www       291:             $middlename=substr($middlename,0,16);
1.1       albertel  292:             $middlename=~s/\W//g;
                    293:             my $dfilename=
1.305     www       294:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    295:             $dumpcount++;
1.1       albertel  296:             {
1.448     albertel  297: 		my $dfh;
                    298: 		if (open($dfh,">$dfilename")) {
                    299: 		    print $dfh "$cmd\n"; 
                    300: 		    close($dfh);
                    301: 		}
1.1       albertel  302:             }
                    303:             sleep 2;
                    304:             my $wcmd='';
                    305:             {
1.448     albertel  306: 		my $dfh;
                    307: 		if (open($dfh,"<$dfilename")) {
                    308: 		    $wcmd=<$dfh>; 
                    309: 		    close($dfh);
                    310: 		}
1.1       albertel  311:             }
                    312:             chomp($wcmd);
1.7       www       313:             if ($wcmd eq $cmd) {
1.672     albertel  314: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       315:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  316:                 &logperm("D:$server:$cmd");
                    317: 	        return 'con_delayed';
                    318:             } else {
1.672     albertel  319:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       320:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  321:                 &logperm("F:$server:$cmd");
                    322:                 return 'con_failed';
                    323:             }
                    324:         }
                    325:     }
                    326:     return $answer;
1.405     albertel  327: }
                    328: 
1.755     albertel  329: # ------------------------------------------- check if return value is an error
                    330: 
                    331: sub error {
                    332:     my ($result) = @_;
1.756     albertel  333:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  334: 	if ($2 == 2) { return undef; }
                    335: 	return $1;
                    336:     }
                    337:     return undef;
                    338: }
                    339: 
1.783     albertel  340: sub convert_and_load_session_env {
                    341:     my ($lonidsdir,$handle)=@_;
                    342:     my @profile;
                    343:     {
1.917     albertel  344: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    345: 	if (!$opened) {
1.915     albertel  346: 	    return 0;
                    347: 	}
1.783     albertel  348: 	flock($idf,LOCK_SH);
                    349: 	@profile=<$idf>;
                    350: 	close($idf);
                    351:     }
                    352:     my %temp_env;
                    353:     foreach my $line (@profile) {
1.786     albertel  354: 	if ($line !~ m/=/) {
                    355: 	    return 0;
                    356: 	}
1.783     albertel  357: 	chomp($line);
                    358: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    359: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    360:     }
                    361:     unlink("$lonidsdir/$handle.id");
                    362:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    363: 	    0640)) {
                    364: 	%disk_env = %temp_env;
                    365: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    366: 	untie(%disk_env);
                    367:     }
1.786     albertel  368:     return 1;
1.783     albertel  369: }
                    370: 
1.374     www       371: # ------------------------------------------- Transfer profile into environment
1.780     albertel  372: my $env_loaded;
                    373: sub transfer_profile_to_env {
1.788     albertel  374:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    375:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       376: 
1.720     albertel  377:     if (!defined($lonidsdir)) {
                    378: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    379:     }
                    380:     if (!defined($handle)) {
                    381:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    382:     }
                    383: 
1.786     albertel  384:     my $convert;
                    385:     {
1.917     albertel  386:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    387: 	if (!$opened) {
1.915     albertel  388: 	    return;
                    389: 	}
1.786     albertel  390: 	flock($idf,LOCK_SH);
                    391: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    392: 		&GDBM_READER(),0640)) {
                    393: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    394: 	    untie(%disk_env);
                    395: 	} else {
                    396: 	    $convert = 1;
                    397: 	}
                    398:     }
                    399:     if ($convert) {
                    400: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    401: 	    &logthis("Failed to load session, or convert session.");
                    402: 	}
1.374     www       403:     }
1.783     albertel  404: 
1.786     albertel  405:     my %remove;
1.783     albertel  406:     while ( my $envname = each(%env) ) {
1.433     matthew   407:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    408:             if ($time < time-300) {
1.783     albertel  409:                 $remove{$key}++;
1.433     matthew   410:             }
                    411:         }
                    412:     }
1.783     albertel  413: 
1.619     albertel  414:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  415:     $env_loaded=1;
1.783     albertel  416:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   417:         &delenv($expired_key);
1.374     www       418:     }
1.1       albertel  419: }
                    420: 
1.916     albertel  421: # ---------------------------------------------------- Check for valid session 
                    422: sub check_for_valid_session {
                    423:     my ($r) = @_;
                    424:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
                    425:     my $lonid=$cookies{'lonID'};
                    426:     return undef if (!$lonid);
                    427: 
                    428:     my $handle=&LONCAPA::clean_handle($lonid->value);
                    429:     my $lonidsdir=$r->dir_config('lonIDsDir');
                    430:     return undef if (!-e "$lonidsdir/$handle.id");
                    431: 
1.917     albertel  432:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    433:     return undef if (!$opened);
1.916     albertel  434: 
                    435:     flock($idf,LOCK_SH);
                    436:     my %disk_env;
                    437:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    438: 	    &GDBM_READER(),0640)) {
                    439: 	return undef;	
                    440:     }
                    441: 
                    442:     if (!defined($disk_env{'user.name'})
                    443: 	|| !defined($disk_env{'user.domain'})) {
                    444: 	return undef;
                    445:     }
                    446:     return $handle;
                    447: }
                    448: 
1.830     albertel  449: sub timed_flock {
                    450:     my ($file,$lock_type) = @_;
                    451:     my $failed=0;
                    452:     eval {
                    453: 	local $SIG{__DIE__}='DEFAULT';
                    454: 	local $SIG{ALRM}=sub {
                    455: 	    $failed=1;
                    456: 	    die("failed lock");
                    457: 	};
                    458: 	alarm(13);
                    459: 	flock($file,$lock_type);
                    460: 	alarm(0);
                    461:     };
                    462:     if ($failed) {
                    463: 	return undef;
                    464:     } else {
                    465: 	return 1;
                    466:     }
                    467: }
                    468: 
1.5       www       469: # ---------------------------------------------------------- Append Environment
                    470: 
                    471: sub appenv {
1.949     raeburn   472:     my ($newenv,$roles) = @_;
                    473:     if (ref($newenv) eq 'HASH') {
                    474:         foreach my $key (keys(%{$newenv})) {
                    475:             my $refused = 0;
                    476: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    477:                 $refused = 1;
                    478:                 if (ref($roles) eq 'ARRAY') {
                    479:                     my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
                    480:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    481:                         $refused = 0;
                    482:                     }
                    483:                 }
                    484:             }
                    485:             if ($refused) {
                    486:                 &logthis("<font color=\"blue\">WARNING: ".
                    487:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    488:                          .'</font>');
                    489: 	        delete($newenv->{$key});
                    490:             } else {
                    491:                 $env{$key}=$newenv->{$key};
                    492:             }
                    493:         }
                    494:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    495:         if ($opened
                    496: 	    && &timed_flock($env_file,LOCK_EX)
                    497: 	    &&
                    498: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    499: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    500: 	    while (my ($key,$value) = each(%{$newenv})) {
                    501: 	        $disk_env{$key} = $value;
                    502: 	    }
                    503: 	    untie(%disk_env);
1.35      www       504:         }
1.191     harris41  505:     }
1.56      www       506:     return 'ok';
                    507: }
                    508: # ----------------------------------------------------- Delete from Environment
                    509: 
                    510: sub delenv {
                    511:     my $delthis=shift;
                    512:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
1.672     albertel  513:         &logthis("<font color=\"blue\">WARNING: ".
1.56      www       514:                 "Attempt to delete from environment ".$delthis);
                    515:         return 'error';
                    516:     }
1.917     albertel  517:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    518:     if ($opened
1.915     albertel  519: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  520: 	&&
                    521: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    522: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  523: 	foreach my $key (keys(%disk_env)) {
                    524: 	    if ($key=~/^$delthis/) { 
1.915     albertel  525: 		delete($env{$key});
                    526: 		delete($disk_env{$key});
                    527: 	    }
1.448     albertel  528: 	}
1.783     albertel  529: 	untie(%disk_env);
1.5       www       530:     }
                    531:     return 'ok';
1.369     albertel  532: }
                    533: 
1.790     albertel  534: sub get_env_multiple {
                    535:     my ($name) = @_;
                    536:     my @values;
                    537:     if (defined($env{$name})) {
                    538:         # exists is it an array
                    539:         if (ref($env{$name})) {
                    540:             @values=@{ $env{$name} };
                    541:         } else {
                    542:             $values[0]=$env{$name};
                    543:         }
                    544:     }
                    545:     return(@values);
                    546: }
                    547: 
1.958     www       548: # ------------------------------------------------------------------- Locking
                    549: 
                    550: sub set_lock {
                    551:     my ($text)=@_;
                    552:     $locknum++;
                    553:     my $id=$$.'-'.$locknum;
                    554:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    555:              'session.lock.'.$id => $text});
                    556:     return $id;
                    557: }
                    558: 
                    559: sub get_locks {
                    560:     my $num=0;
                    561:     my %texts=();
                    562:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    563:        if ($lock=~/\w/) {
                    564:           $num++;
                    565:           $texts{$lock}=$env{'session.lock.'.$lock};
                    566:        }
                    567:    }
                    568:    return ($num,%texts);
                    569: }
                    570: 
                    571: sub remove_lock {
                    572:     my ($id)=@_;
                    573:     my $newlocks='';
                    574:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    575:        if (($lock=~/\w/) && ($lock ne $id)) {
                    576:           $newlocks.=','.$lock;
                    577:        }
                    578:     }
                    579:     &appenv({'session.locks' => $newlocks});
                    580:     &delenv('session.lock.'.$id);
                    581: }
                    582: 
                    583: sub remove_all_locks {
                    584:     my $activelocks=$env{'session.locks'};
                    585:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    586:        if ($lock=~/\w/) {
                    587:           &remove_lock($lock);
                    588:        }
                    589:     }
                    590: }
                    591: 
                    592: 
1.369     albertel  593: # ------------------------------------------ Find out current server userload
                    594: sub userload {
                    595:     my $numusers=0;
                    596:     {
                    597: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    598: 	my $filename;
                    599: 	my $curtime=time;
                    600: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  601: 	    next if ($filename eq '.' || $filename eq '..');
                    602: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.404     albertel  603: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  604: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  605: 	}
                    606: 	closedir(LONIDS);
                    607:     }
                    608:     my $userloadpercent=0;
                    609:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    610:     if ($maxuserload) {
1.371     albertel  611: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  612:     }
1.372     albertel  613:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  614:     return $userloadpercent;
1.283     www       615: }
                    616: 
                    617: # ------------------------------------------ Fight off request when overloaded
                    618: 
                    619: sub overloaderror {
                    620:     my ($r,$checkserver)=@_;
                    621:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
                    622:     my $loadavg;
                    623:     if ($checkserver eq $perlvar{'lonHostID'}) {
1.448     albertel  624:        open(my $loadfile,'/proc/loadavg');
1.283     www       625:        $loadavg=<$loadfile>;
                    626:        $loadavg =~ s/\s.*//g;
1.285     matthew   627:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
1.448     albertel  628:        close($loadfile);
1.283     www       629:     } else {
                    630:        $loadavg=&reply('load',$checkserver);
                    631:     }
1.285     matthew   632:     my $overload=$loadavg-100;
1.283     www       633:     if ($overload>0) {
1.285     matthew   634: 	$r->err_headers_out->{'Retry-After'}=$overload;
1.283     www       635:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
1.554     www       636:         return 413;
1.283     www       637:     }    
                    638:     return '';
1.5       www       639: }
1.1       albertel  640: 
                    641: # ------------------------------ Find server with least workload from spare.tab
1.11      www       642: 
1.1       albertel  643: sub spareserver {
1.670     albertel  644:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
1.784     albertel  645:     my $spare_server;
1.370     albertel  646:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  647:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    648:                                                      :  $userloadpercent;
                    649:     
                    650:     foreach my $try_server (@{ $spareid{'primary'} }) {
                    651: 	($spare_server, $lowest_load) =
                    652: 	    &compare_server_load($try_server, $spare_server, $lowest_load);
                    653:     }
                    654: 
                    655:     my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    656: 
                    657:     if (!$found_server) {
                    658: 	foreach my $try_server (@{ $spareid{'default'} }) {
                    659: 	    ($spare_server, $lowest_load) =
                    660: 		&compare_server_load($try_server, $spare_server, $lowest_load);
                    661: 	}
                    662:     }
                    663: 
                    664:     if (!$want_server_name) {
1.968     raeburn   665:         my $protocol = 'http';
                    666:         if ($protocol{$spare_server} eq 'https') {
                    667:             $protocol = $protocol{$spare_server};
                    668:         }
                    669: 	$spare_server = $protocol.'://'.&hostname($spare_server);
1.784     albertel  670:     }
                    671:     return $spare_server;
                    672: }
                    673: 
                    674: sub compare_server_load {
                    675:     my ($try_server, $spare_server, $lowest_load) = @_;
                    676: 
                    677:     my $loadans     = &reply('load',    $try_server);
                    678:     my $userloadans = &reply('userload',$try_server);
                    679: 
                    680:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
                    681: 	next; #didn't get a number from the server
                    682:     }
                    683: 
                    684:     my $load;
                    685:     if ($loadans =~ /\d/) {
                    686: 	if ($userloadans =~ /\d/) {
                    687: 	    #both are numbers, pick the bigger one
                    688: 	    $load = ($loadans > $userloadans) ? $loadans 
                    689: 		                              : $userloadans;
1.411     albertel  690: 	} else {
1.784     albertel  691: 	    $load = $loadans;
1.411     albertel  692: 	}
1.784     albertel  693:     } else {
                    694: 	$load = $userloadans;
                    695:     }
                    696: 
                    697:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    698: 	$spare_server = $try_server;
                    699: 	$lowest_load  = $load;
1.370     albertel  700:     }
1.784     albertel  701:     return ($spare_server,$lowest_load);
1.202     matthew   702: }
1.914     albertel  703: 
                    704: # --------------------------- ask offload servers if user already has a session
                    705: sub find_existing_session {
                    706:     my ($udom,$uname) = @_;
                    707:     foreach my $try_server (@{ $spareid{'primary'} },
                    708: 			    @{ $spareid{'default'} }) {
                    709: 	return $try_server if (&has_user_session($try_server, $udom, $uname));
                    710:     }
                    711:     return;
                    712: }
                    713: 
                    714: # -------------------------------- ask if server already has a session for user
                    715: sub has_user_session {
                    716:     my ($lonid,$udom,$uname) = @_;
                    717:     my $result = &reply(join(':','userhassession',
                    718: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                    719:     return 1 if ($result eq 'ok');
                    720: 
                    721:     return 0;
                    722: }
                    723: 
1.202     matthew   724: # --------------------------------------------- Try to change a user's password
                    725: 
                    726: sub changepass {
1.799     raeburn   727:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew   728:     $currentpass = &escape($currentpass);
                    729:     $newpass     = &escape($newpass);
1.799     raeburn   730:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context",
1.202     matthew   731: 		       $server);
                    732:     if (! $answer) {
                    733: 	&logthis("No reply on password change request to $server ".
                    734: 		 "by $uname in domain $udom.");
                    735:     } elsif ($answer =~ "^ok") {
                    736:         &logthis("$uname in $udom successfully changed their password ".
                    737: 		 "on $server.");
                    738:     } elsif ($answer =~ "^pwchange_failure") {
                    739: 	&logthis("$uname in $udom was unable to change their password ".
                    740: 		 "on $server.  The action was blocked by either lcpasswd ".
                    741: 		 "or pwchange");
                    742:     } elsif ($answer =~ "^non_authorized") {
                    743:         &logthis("$uname in $udom did not get their password correct when ".
                    744: 		 "attempting to change it on $server.");
                    745:     } elsif ($answer =~ "^auth_mode_error") {
                    746:         &logthis("$uname in $udom attempted to change their password despite ".
                    747: 		 "not being locally or internally authenticated on $server.");
                    748:     } elsif ($answer =~ "^unknown_user") {
                    749:         &logthis("$uname in $udom attempted to change their password ".
                    750: 		 "on $server but were unable to because $server is not ".
                    751: 		 "their home server.");
                    752:     } elsif ($answer =~ "^refused") {
                    753: 	&logthis("$server refused to change $uname in $udom password because ".
                    754: 		 "it was sent an unencrypted request to change the password.");
                    755:     }
                    756:     return $answer;
1.1       albertel  757: }
                    758: 
1.169     harris41  759: # ----------------------- Try to determine user's current authentication scheme
                    760: 
                    761: sub queryauthenticate {
                    762:     my ($uname,$udom)=@_;
1.456     albertel  763:     my $uhome=&homeserver($uname,$udom);
                    764:     if (!$uhome) {
                    765: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                    766: 	return 'no_host';
                    767:     }
                    768:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                    769:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                    770: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41  771:     }
1.456     albertel  772:     return $answer;
1.169     harris41  773: }
                    774: 
1.1       albertel  775: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www       776: 
1.1       albertel  777: sub authenticate {
1.952     raeburn   778:     my ($uname,$upass,$udom,$checkdefauth)=@_;
1.807     albertel  779:     $upass=&escape($upass);
                    780:     $uname= &LONCAPA::clean_username($uname);
1.836     www       781:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn   782:     my $newhome;
1.836     www       783:     if ((!$uhome) || ($uhome eq 'no_host')) {
                    784: # Maybe the machine was offline and only re-appeared again recently?
                    785:         &reconlonc();
                    786: # One more
1.952     raeburn   787: 	$uhome=&homeserver($uname,$udom,1);
                    788:         if (($uhome eq 'no_host') && $checkdefauth) {
                    789:             if (defined(&domain($udom,'primary'))) {
                    790:                 $newhome=&domain($udom,'primary');
                    791:             }
                    792:             if ($newhome ne '') {
                    793:                 $uhome = $newhome;
                    794:             }
                    795:         }
1.836     www       796: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                    797: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn   798: 	    return 'no_host';
                    799:         }
1.1       albertel  800:     }
1.952     raeburn   801:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth",$uhome);
1.471     albertel  802:     if ($answer eq 'authorized') {
1.952     raeburn   803:         if ($newhome) {
                    804:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                    805:             return 'no_account_on_host'; 
                    806:         } else {
                    807:             &logthis("User $uname at $udom authorized by $uhome");
                    808:             return $uhome;
                    809:         }
1.471     albertel  810:     }
                    811:     if ($answer eq 'non_authorized') {
                    812: 	&logthis("User $uname at $udom rejected by $uhome");
                    813: 	return 'no_host'; 
1.9       www       814:     }
1.471     albertel  815:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel  816:     return 'no_host';
                    817: }
                    818: 
                    819: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www       820: 
1.599     albertel  821: my %homecache;
1.1       albertel  822: sub homeserver {
1.230     stredwic  823:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel  824:     my $index="$uname:$udom";
1.426     albertel  825: 
1.599     albertel  826:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel  827: 
                    828:     my %servers = &get_servers($udom,'library');
                    829:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic  830:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic  831: 		 exists($badServerCache{$tryserver}));
1.841     albertel  832: 
                    833: 	my $answer=reply("home:$udom:$uname",$tryserver);
                    834: 	if ($answer eq 'found') {
                    835: 	    delete($badServerCache{$tryserver}); 
                    836: 	    return $homecache{$index}=$tryserver;
                    837: 	} elsif ($answer eq 'no_host') {
                    838: 	    $badServerCache{$tryserver}=1;
                    839: 	}
1.1       albertel  840:     }    
                    841:     return 'no_host';
1.70      www       842: }
                    843: 
                    844: # ------------------------------------- Find the usernames behind a list of IDs
                    845: 
                    846: sub idget {
                    847:     my ($udom,@ids)=@_;
                    848:     my %returnhash=();
                    849:     
1.841     albertel  850:     my %servers = &get_servers($udom,'library');
                    851:     foreach my $tryserver (keys(%servers)) {
                    852: 	my $idlist=join('&',@ids);
                    853: 	$idlist=~tr/A-Z/a-z/; 
                    854: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                    855: 	my @answer=();
                    856: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                    857: 	    @answer=split(/\&/,$reply);
                    858: 	}                    ;
                    859: 	my $i;
                    860: 	for ($i=0;$i<=$#ids;$i++) {
                    861: 	    if ($answer[$i]) {
                    862: 		$returnhash{$ids[$i]}=$answer[$i];
                    863: 	    } 
                    864: 	}
                    865:     } 
1.70      www       866:     return %returnhash;
                    867: }
                    868: 
                    869: # ------------------------------------- Find the IDs behind a list of usernames
                    870: 
                    871: sub idrget {
                    872:     my ($udom,@unames)=@_;
                    873:     my %returnhash=();
1.800     albertel  874:     foreach my $uname (@unames) {
                    875:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41  876:     }
1.70      www       877:     return %returnhash;
                    878: }
                    879: 
                    880: # ------------------------------- Store away a list of names and associated IDs
                    881: 
                    882: sub idput {
                    883:     my ($udom,%ids)=@_;
                    884:     my %servers=();
1.800     albertel  885:     foreach my $uname (keys(%ids)) {
                    886: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                    887:         my $uhom=&homeserver($uname,$udom);
1.70      www       888:         if ($uhom ne 'no_host') {
1.800     albertel  889:             my $id=&escape($ids{$uname});
1.70      www       890:             $id=~tr/A-Z/a-z/;
1.800     albertel  891:             my $esc_unam=&escape($uname);
1.70      www       892: 	    if ($servers{$uhom}) {
1.800     albertel  893: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www       894:             } else {
1.800     albertel  895:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www       896:             }
                    897:         }
1.191     harris41  898:     }
1.800     albertel  899:     foreach my $server (keys(%servers)) {
                    900:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41  901:     }
1.344     www       902: }
                    903: 
1.806     raeburn   904: # ------------------------------------------- get items from domain db files   
                    905: 
                    906: sub get_dom {
1.860     raeburn   907:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.806     raeburn   908:     my $items='';
                    909:     foreach my $item (@$storearr) {
                    910:         $items.=&escape($item).'&';
                    911:     }
                    912:     $items=~s/\&$//;
1.860     raeburn   913:     if (!$udom) {
                    914:         $udom=$env{'user.domain'};
                    915:         if (defined(&domain($udom,'primary'))) {
                    916:             $uhome=&domain($udom,'primary');
                    917:         } else {
1.874     albertel  918:             undef($uhome);
1.860     raeburn   919:         }
                    920:     } else {
                    921:         if (!$uhome) {
                    922:             if (defined(&domain($udom,'primary'))) {
                    923:                 $uhome=&domain($udom,'primary');
                    924:             }
                    925:         }
                    926:     }
                    927:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn   928:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn   929:         my %returnhash;
1.875     albertel  930:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn   931:             return %returnhash;
                    932:         }
1.806     raeburn   933:         my @pairs=split(/\&/,$rep);
                    934:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                    935:             return @pairs;
                    936:         }
                    937:         my $i=0;
                    938:         foreach my $item (@$storearr) {
                    939:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                    940:             $i++;
                    941:         }
                    942:         return %returnhash;
                    943:     } else {
1.880     banghart  944:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn   945:     }
                    946: }
                    947: 
                    948: # -------------------------------------------- put items in domain db files 
                    949: 
                    950: sub put_dom {
1.860     raeburn   951:     my ($namespace,$storehash,$udom,$uhome)=@_;
                    952:     if (!$udom) {
                    953:         $udom=$env{'user.domain'};
                    954:         if (defined(&domain($udom,'primary'))) {
                    955:             $uhome=&domain($udom,'primary');
                    956:         } else {
1.874     albertel  957:             undef($uhome);
1.860     raeburn   958:         }
                    959:     } else {
                    960:         if (!$uhome) {
                    961:             if (defined(&domain($udom,'primary'))) {
                    962:                 $uhome=&domain($udom,'primary');
                    963:             }
                    964:         }
                    965:     } 
                    966:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn   967:         my $items='';
                    968:         foreach my $item (keys(%$storehash)) {
                    969:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                    970:         }
                    971:         $items=~s/\&$//;
                    972:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                    973:     } else {
1.860     raeburn   974:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn   975:     }
                    976: }
                    977: 
1.837     raeburn   978: sub retrieve_inst_usertypes {
                    979:     my ($udom) = @_;
                    980:     my (%returnhash,@order);
1.846     albertel  981:     if (defined(&domain($udom,'primary'))) {
                    982:         my $uhome=&domain($udom,'primary');
1.837     raeburn   983:         my $rep=&reply("inst_usertypes:$udom",$uhome);
1.960     raeburn   984:         if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
                    985:             &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
                    986:             return (\%returnhash,\@order);
                    987:         }
1.837     raeburn   988:         my ($hashitems,$orderitems) = split(/:/,$rep); 
                    989:         my @pairs=split(/\&/,$hashitems);
                    990:         foreach my $item (@pairs) {
                    991:             my ($key,$value)=split(/=/,$item,2);
                    992:             $key = &unescape($key);
                    993:             next if ($key =~ /^error: 2 /);
                    994:             $returnhash{$key}=&thaw_unescape($value);
                    995:         }
                    996:         my @esc_order = split(/\&/,$orderitems);
                    997:         foreach my $item (@esc_order) {
                    998:             push(@order,&unescape($item));
                    999:         }
                   1000:     } else {
                   1001:         &logthis("get_dom failed - no primary domain server for $udom");
                   1002:     }
                   1003:     return (\%returnhash,\@order);
                   1004: }
                   1005: 
1.868     raeburn  1006: sub is_domainimage {
                   1007:     my ($url) = @_;
                   1008:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
                   1009:         if (&domain($1) ne '') {
                   1010:             return '1';
                   1011:         }
                   1012:     }
                   1013:     return;
                   1014: }
                   1015: 
1.899     raeburn  1016: sub inst_directory_query {
                   1017:     my ($srch) = @_;
                   1018:     my $udom = $srch->{'srchdomain'};
                   1019:     my %results;
                   1020:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  1021:     my $outcome;
1.899     raeburn  1022:     if ($homeserver ne '') {
1.904     albertel 1023: 	my $queryid=&reply("querysend:instdirsearch:".
                   1024: 			   &escape($srch->{'srchby'}).':'.
                   1025: 			   &escape($srch->{'srchterm'}).':'.
                   1026: 			   &escape($srch->{'srchtype'}),$homeserver);
                   1027: 	my $host=&hostname($homeserver);
                   1028: 	if ($queryid !~/^\Q$host\E\_/) {
                   1029: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1030: 	    return;
                   1031: 	}
                   1032: 	my $response = &get_query_reply($queryid);
                   1033: 	my $maxtries = 5;
                   1034: 	my $tries = 1;
                   1035: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1036: 	    $response = &get_query_reply($queryid);
                   1037: 	    $tries ++;
                   1038: 	}
                   1039: 
                   1040:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  1041:             if ($response eq 'unavailable') {
                   1042:                 $outcome = $response;
                   1043:             } else {
                   1044:                 $outcome = 'ok';
                   1045:                 my @matches = split(/\n/,$response);
                   1046:                 foreach my $match (@matches) {
                   1047:                     my ($key,$value) = split(/=/,$match);
                   1048:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   1049:                 }
1.899     raeburn  1050:             }
                   1051:         }
                   1052:     }
1.909     raeburn  1053:     return ($outcome,%results);
1.899     raeburn  1054: }
                   1055: 
                   1056: sub usersearch {
                   1057:     my ($srch) = @_;
                   1058:     my $dom = $srch->{'srchdomain'};
                   1059:     my %results;
                   1060:     my %libserv = &all_library();
                   1061:     my $query = 'usersearch';
                   1062:     foreach my $tryserver (keys(%libserv)) {
                   1063:         if (&host_domain($tryserver) eq $dom) {
                   1064:             my $host=&hostname($tryserver);
                   1065:             my $queryid=
1.911     raeburn  1066:                 &reply("querysend:".&escape($query).':'.
                   1067:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  1068:                        &escape($srch->{'srchtype'}).':'.
                   1069:                        &escape($srch->{'srchterm'}),$tryserver);
                   1070:             if ($queryid !~/^\Q$host\E\_/) {
                   1071:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  1072:                 next;
1.899     raeburn  1073:             }
                   1074:             my $reply = &get_query_reply($queryid);
                   1075:             my $maxtries = 1;
                   1076:             my $tries = 1;
                   1077:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   1078:                 $reply = &get_query_reply($queryid);
                   1079:                 $tries ++;
                   1080:             }
                   1081:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   1082:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   1083:             } else {
1.911     raeburn  1084:                 my @matches;
                   1085:                 if ($reply =~ /\n/) {
                   1086:                     @matches = split(/\n/,$reply);
                   1087:                 } else {
                   1088:                     @matches = split(/\&/,$reply);
                   1089:                 }
1.899     raeburn  1090:                 foreach my $match (@matches) {
                   1091:                     my ($uname,$udom,%userhash);
1.911     raeburn  1092:                     foreach my $entry (split(/:/,$match)) {
                   1093:                         my ($key,$value) =
                   1094:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  1095:                         $userhash{$key} = $value;
                   1096:                         if ($key eq 'username') {
                   1097:                             $uname = $value;
                   1098:                         } elsif ($key eq 'domain') {
                   1099:                             $udom = $value;
1.911     raeburn  1100:                         }
1.899     raeburn  1101:                     }
                   1102:                     $results{$uname.':'.$udom} = \%userhash;
                   1103:                 }
                   1104:             }
                   1105:         }
                   1106:     }
                   1107:     return %results;
                   1108: }
                   1109: 
1.912     raeburn  1110: sub get_instuser {
                   1111:     my ($udom,$uname,$id) = @_;
                   1112:     my $homeserver = &domain($udom,'primary');
                   1113:     my ($outcome,%results);
                   1114:     if ($homeserver ne '') {
                   1115:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   1116:                            &escape($id).':'.&escape($udom),$homeserver);
                   1117:         my $host=&hostname($homeserver);
                   1118:         if ($queryid !~/^\Q$host\E\_/) {
                   1119:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1120:             return;
                   1121:         }
                   1122:         my $response = &get_query_reply($queryid);
                   1123:         my $maxtries = 5;
                   1124:         my $tries = 1;
                   1125:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1126:             $response = &get_query_reply($queryid);
                   1127:             $tries ++;
                   1128:         }
                   1129:         if (!&error($response) && $response ne 'refused') {
                   1130:             if ($response eq 'unavailable') {
                   1131:                 $outcome = $response;
                   1132:             } else {
                   1133:                 $outcome = 'ok';
                   1134:                 my @matches = split(/\n/,$response);
                   1135:                 foreach my $match (@matches) {
                   1136:                     my ($key,$value) = split(/=/,$match);
                   1137:                     $results{&unescape($key)} = &thaw_unescape($value);
                   1138:                 }
                   1139:             }
                   1140:         }
                   1141:     }
                   1142:     my %userinfo;
                   1143:     if (ref($results{$uname}) eq 'HASH') {
                   1144:         %userinfo = %{$results{$uname}};
                   1145:     } 
                   1146:     return ($outcome,%userinfo);
                   1147: }
                   1148: 
                   1149: sub inst_rulecheck {
1.923     raeburn  1150:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  1151:     my %returnhash;
                   1152:     if ($udom ne '') {
                   1153:         if (ref($rules) eq 'ARRAY') {
                   1154:             @{$rules} = map {&escape($_);} (@{$rules});
                   1155:             my $rulestr = join(':',@{$rules});
                   1156:             my $homeserver=&domain($udom,'primary');
                   1157:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1158:                 my $response;
                   1159:                 if ($item eq 'username') {                
                   1160:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   1161:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  1162:                                               $homeserver));
1.923     raeburn  1163:                 } elsif ($item eq 'id') {
                   1164:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   1165:                                               ':'.&escape($id).':'.$rulestr,
                   1166:                                               $homeserver));
1.945     raeburn  1167:                 } elsif ($item eq 'selfcreate') {
                   1168:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  1169:                                                &escape($udom).':'.&escape($uname).
                   1170:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  1171:                 }
1.912     raeburn  1172:                 if ($response ne 'refused') {
                   1173:                     my @pairs=split(/\&/,$response);
                   1174:                     foreach my $item (@pairs) {
                   1175:                         my ($key,$value)=split(/=/,$item,2);
                   1176:                         $key = &unescape($key);
                   1177:                         next if ($key =~ /^error: 2 /);
                   1178:                         $returnhash{$key}=&thaw_unescape($value);
                   1179:                     }
                   1180:                 }
                   1181:             }
                   1182:         }
                   1183:     }
                   1184:     return %returnhash;
                   1185: }
                   1186: 
                   1187: sub inst_userrules {
1.923     raeburn  1188:     my ($udom,$check) = @_;
1.912     raeburn  1189:     my (%ruleshash,@ruleorder);
                   1190:     if ($udom ne '') {
                   1191:         my $homeserver=&domain($udom,'primary');
                   1192:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1193:             my $response;
                   1194:             if ($check eq 'id') {
                   1195:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  1196:                                  $homeserver);
1.943     raeburn  1197:             } elsif ($check eq 'email') {
                   1198:                 $response=&reply('instemailrules:'.&escape($udom),
                   1199:                                  $homeserver);
1.923     raeburn  1200:             } else {
                   1201:                 $response=&reply('instuserrules:'.&escape($udom),
                   1202:                                  $homeserver);
                   1203:             }
1.912     raeburn  1204:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  1205:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  1206:                 ($response ne 'no_such_host')) {
                   1207:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   1208:                 my @pairs=split(/\&/,$hashitems);
                   1209:                 foreach my $item (@pairs) {
                   1210:                     my ($key,$value)=split(/=/,$item,2);
                   1211:                     $key = &unescape($key);
                   1212:                     next if ($key =~ /^error: 2 /);
                   1213:                     $ruleshash{$key}=&thaw_unescape($value);
                   1214:                 }
                   1215:                 my @esc_order = split(/\&/,$orderitems);
                   1216:                 foreach my $item (@esc_order) {
                   1217:                     push(@ruleorder,&unescape($item));
                   1218:                 }
                   1219:             }
                   1220:         }
                   1221:     }
                   1222:     return (\%ruleshash,\@ruleorder);
                   1223: }
                   1224: 
1.976   ! raeburn  1225: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  1226: 
                   1227: sub get_domain_defaults {
                   1228:     my ($domain) = @_;
                   1229:     my $cachetime = 60*60*24;
1.976   ! raeburn  1230:     my ($defauthtype,$defautharg,$deflang,%deftools);
1.943     raeburn  1231:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   1232:     if (defined($cached)) {
                   1233:         if (ref($result) eq 'HASH') {
                   1234:             return %{$result};
                   1235:         }
                   1236:     }
                   1237:     my %domdefaults;
                   1238:     my %domconfig =
1.976   ! raeburn  1239:          &Apache::lonnet::get_dom('configuration',['defaults','quotas'],$domain);
1.943     raeburn  1240:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   1241:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   1242:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   1243:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
                   1244:     } else {
                   1245:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   1246:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   1247:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   1248:     }
1.976   ! raeburn  1249:     if (ref($domconfig{'quotas'}) eq 'HASH') {
        !          1250:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
        !          1251:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
        !          1252:         } else {
        !          1253:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
        !          1254:         } 
        !          1255:         my @usertools = ('aboutme','blog','portfolio');
        !          1256:         foreach my $item (@usertools) {
        !          1257:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
        !          1258:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
        !          1259:             }
        !          1260:         }
        !          1261:     }
1.943     raeburn  1262:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
                   1263:                                   $cachetime);
                   1264:     return %domdefaults;
                   1265: }
                   1266: 
1.344     www      1267: # --------------------------------------------------- Assign a key to a student
                   1268: 
                   1269: sub assign_access_key {
1.364     www      1270: #
                   1271: # a valid key looks like uname:udom#comments
                   1272: # comments are being appended
                   1273: #
1.498     www      1274:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   1275:     $kdom=
1.620     albertel 1276:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      1277:     $knum=
1.620     albertel 1278:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      1279:     $cdom=
1.620     albertel 1280:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1281:     $cnum=
1.620     albertel 1282:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1283:     $udom=$env{'user.name'} unless (defined($udom));
                   1284:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      1285:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      1286:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 1287:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      1288:                                                   # assigned to this person
                   1289:                                                   # - this should not happen,
1.345     www      1290:                                                   # unless something went wrong
                   1291:                                                   # the first time around
                   1292: # ready to assign
1.364     www      1293:         $logentry=$1.'; '.$logentry;
1.496     www      1294:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      1295:                                                  $kdom,$knum) eq 'ok') {
1.345     www      1296: # key now belongs to user
1.346     www      1297: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      1298:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  1299:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      1300:                 return 'ok';
                   1301:             } else {
                   1302:                 return 
                   1303:   'error: Count not permanently assign key, will need to be re-entered later.';
                   1304: 	    }
                   1305:         } else {
                   1306:             return 'error: Could not assign key, try again later.';
                   1307:         }
1.364     www      1308:     } elsif (!$existing{$ckey}) {
1.345     www      1309: # the key does not exist
                   1310: 	return 'error: The key does not exist';
                   1311:     } else {
                   1312: # the key is somebody else's
                   1313: 	return 'error: The key is already in use';
                   1314:     }
1.344     www      1315: }
                   1316: 
1.364     www      1317: # ------------------------------------------ put an additional comment on a key
                   1318: 
                   1319: sub comment_access_key {
                   1320: #
                   1321: # a valid key looks like uname:udom#comments
                   1322: # comments are being appended
                   1323: #
                   1324:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   1325:     $cdom=
1.620     albertel 1326:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      1327:     $cnum=
1.620     albertel 1328:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      1329:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   1330:     if ($existing{$ckey}) {
                   1331:         $existing{$ckey}.='; '.$logentry;
                   1332: # ready to assign
1.367     www      1333:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      1334:                                                  $cdom,$cnum) eq 'ok') {
                   1335: 	    return 'ok';
                   1336:         } else {
                   1337: 	    return 'error: Count not store comment.';
                   1338:         }
                   1339:     } else {
                   1340: # the key does not exist
                   1341: 	return 'error: The key does not exist';
                   1342:     }
                   1343: }
                   1344: 
1.344     www      1345: # ------------------------------------------------------ Generate a set of keys
                   1346: 
                   1347: sub generate_access_keys {
1.364     www      1348:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      1349:     $cdom=
1.620     albertel 1350:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1351:     $cnum=
1.620     albertel 1352:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      1353:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      1354:     unless (($cdom) && ($cnum)) { return 0; }
                   1355:     if ($number>10000) { return 0; }
                   1356:     sleep(2); # make sure don't get same seed twice
                   1357:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   1358:     my $total=0;
                   1359:     for (my $i=1;$i<=$number;$i++) {
                   1360:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   1361:                   sprintf("%lx",int(100000*rand)).'-'.
                   1362:                   sprintf("%lx",int(100000*rand));
                   1363:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   1364:        $newkey=~s/0/h/g; # and also 0 and O
                   1365:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   1366:        if ($existing{$newkey}) {
                   1367:            $i--;
                   1368:        } else {
1.364     www      1369: 	  if (&put('accesskeys',
                   1370:               { $newkey => '# generated '.localtime().
1.620     albertel 1371:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      1372:                            '; '.$logentry },
                   1373: 		   $cdom,$cnum) eq 'ok') {
1.344     www      1374:               $total++;
                   1375: 	  }
                   1376:        }
                   1377:     }
1.620     albertel 1378:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      1379:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   1380:     return $total;
                   1381: }
                   1382: 
                   1383: # ------------------------------------------------------- Validate an accesskey
                   1384: 
                   1385: sub validate_access_key {
                   1386:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   1387:     $cdom=
1.620     albertel 1388:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1389:     $cnum=
1.620     albertel 1390:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1391:     $udom=$env{'user.domain'} unless (defined($udom));
                   1392:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      1393:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 1394:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      1395: }
                   1396: 
                   1397: # ------------------------------------- Find the section of student in a course
1.652     albertel 1398: sub devalidate_getsection_cache {
                   1399:     my ($udom,$unam,$courseid)=@_;
                   1400:     my $hashid="$udom:$unam:$courseid";
                   1401:     &devalidate_cache_new('getsection',$hashid);
                   1402: }
1.298     matthew  1403: 
1.815     albertel 1404: sub courseid_to_courseurl {
                   1405:     my ($courseid) = @_;
                   1406:     #already url style courseid
                   1407:     return $courseid if ($courseid =~ m{^/});
                   1408: 
                   1409:     if (exists($env{'course.'.$courseid.'.num'})) {
                   1410: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   1411: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   1412: 	return "/$cdom/$cnum";
                   1413:     }
                   1414: 
                   1415:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   1416:     if (exists($courseinfo{'num'})) {
                   1417: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   1418:     }
                   1419: 
                   1420:     return undef;
                   1421: }
                   1422: 
1.298     matthew  1423: sub getsection {
                   1424:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 1425:     my $cachetime=1800;
1.551     albertel 1426: 
                   1427:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 1428:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 1429:     if (defined($cached)) { return $result; }
                   1430: 
1.298     matthew  1431:     my %Pending; 
                   1432:     my %Expired;
                   1433:     #
                   1434:     # Each role can either have not started yet (pending), be active, 
                   1435:     #    or have expired.
                   1436:     #
                   1437:     # If there is an active role, we are done.
                   1438:     #
                   1439:     # If there is more than one role which has not started yet, 
                   1440:     #     choose the one which will start sooner
                   1441:     # If there is one role which has not started yet, return it.
                   1442:     #
                   1443:     # If there is more than one expired role, choose the one which ended last.
                   1444:     # If there is a role which has expired, return it.
                   1445:     #
1.815     albertel 1446:     $courseid = &courseid_to_courseurl($courseid);
1.817     raeburn  1447:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
                   1448:     foreach my $key (keys(%roleshash)) {
1.479     albertel 1449:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  1450:         my $section=$1;
                   1451:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  1452:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  1453:         my $now=time;
1.548     albertel 1454:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  1455:             $Expired{$end}=$section;
                   1456:             next;
                   1457:         }
1.548     albertel 1458:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  1459:             $Pending{$start}=$section;
                   1460:             next;
                   1461:         }
1.599     albertel 1462:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  1463:     }
                   1464:     #
                   1465:     # Presumedly there will be few matching roles from the above
                   1466:     # loop and the sorting time will be negligible.
                   1467:     if (scalar(keys(%Pending))) {
                   1468:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 1469:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  1470:     } 
                   1471:     if (scalar(keys(%Expired))) {
                   1472:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   1473:         my $time = pop(@sorted);
1.599     albertel 1474:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  1475:     }
1.599     albertel 1476:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  1477: }
1.70      www      1478: 
1.599     albertel 1479: sub save_cache {
                   1480:     &purge_remembered();
1.722     albertel 1481:     #&Apache::loncommon::validate_page();
1.620     albertel 1482:     undef(%env);
1.780     albertel 1483:     undef($env_loaded);
1.599     albertel 1484: }
1.452     albertel 1485: 
1.599     albertel 1486: my $to_remember=-1;
                   1487: my %remembered;
                   1488: my %accessed;
                   1489: my $kicks=0;
                   1490: my $hits=0;
1.849     albertel 1491: sub make_key {
                   1492:     my ($name,$id) = @_;
1.872     albertel 1493:     if (length($id) > 65 
                   1494: 	&& length(&escape($id)) > 200) {
                   1495: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   1496:     }
1.849     albertel 1497:     return &escape($name.':'.$id);
                   1498: }
                   1499: 
1.599     albertel 1500: sub devalidate_cache_new {
                   1501:     my ($name,$id,$debug) = @_;
                   1502:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 1503:     $id=&make_key($name,$id);
1.599     albertel 1504:     $memcache->delete($id);
                   1505:     delete($remembered{$id});
                   1506:     delete($accessed{$id});
                   1507: }
                   1508: 
                   1509: sub is_cached_new {
                   1510:     my ($name,$id,$debug) = @_;
1.849     albertel 1511:     $id=&make_key($name,$id);
1.599     albertel 1512:     if (exists($remembered{$id})) {
                   1513: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                   1514: 	$accessed{$id}=[&gettimeofday()];
                   1515: 	$hits++;
                   1516: 	return ($remembered{$id},1);
                   1517:     }
                   1518:     my $value = $memcache->get($id);
                   1519:     if (!(defined($value))) {
                   1520: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 1521: 	return (undef,undef);
1.416     albertel 1522:     }
1.599     albertel 1523:     if ($value eq '__undef__') {
                   1524: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   1525: 	$value=undef;
                   1526:     }
                   1527:     &make_room($id,$value,$debug);
                   1528:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   1529:     return ($value,1);
                   1530: }
                   1531: 
                   1532: sub do_cache_new {
                   1533:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 1534:     $id=&make_key($name,$id);
1.599     albertel 1535:     my $setvalue=$value;
                   1536:     if (!defined($setvalue)) {
                   1537: 	$setvalue='__undef__';
                   1538:     }
1.623     albertel 1539:     if (!defined($time) ) {
                   1540: 	$time=600;
                   1541:     }
1.599     albertel 1542:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 1543:     my $result = $memcache->set($id,$setvalue,$time);
                   1544:     if (! $result) {
1.872     albertel 1545: 	&logthis("caching of id -> $id  failed");
1.910     albertel 1546: 	$memcache->disconnect_all();
1.872     albertel 1547:     }
1.600     albertel 1548:     # need to make a copy of $value
1.919     albertel 1549:     &make_room($id,$value,$debug);
1.599     albertel 1550:     return $value;
                   1551: }
                   1552: 
                   1553: sub make_room {
                   1554:     my ($id,$value,$debug)=@_;
1.919     albertel 1555: 
                   1556:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
                   1557:                                     : $value;
1.599     albertel 1558:     if ($to_remember<0) { return; }
                   1559:     $accessed{$id}=[&gettimeofday()];
                   1560:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   1561:     my $to_kick;
                   1562:     my $max_time=0;
                   1563:     foreach my $other (keys(%accessed)) {
                   1564: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   1565: 	    $to_kick=$other;
                   1566: 	    $max_time=&tv_interval($accessed{$other});
                   1567: 	}
                   1568:     }
                   1569:     delete($remembered{$to_kick});
                   1570:     delete($accessed{$to_kick});
                   1571:     $kicks++;
                   1572:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 1573:     return;
                   1574: }
                   1575: 
1.599     albertel 1576: sub purge_remembered {
1.604     albertel 1577:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   1578:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 1579:     undef(%remembered);
                   1580:     undef(%accessed);
1.428     albertel 1581: }
1.70      www      1582: # ------------------------------------- Read an entry from a user's environment
                   1583: 
                   1584: sub userenvironment {
                   1585:     my ($udom,$unam,@what)=@_;
1.976   ! raeburn  1586:     my $items;
        !          1587:     foreach my $item (@what) {
        !          1588:         $items.=&escape($item).'&';
        !          1589:     }
        !          1590:     $items=~s/\&$//;
1.70      www      1591:     my %returnhash=();
                   1592:     my @answer=split(/\&/,
1.976   ! raeburn  1593:                 &reply('get:'.$udom.':'.$unam.':environment:'.$items,
1.70      www      1594:                       &homeserver($unam,$udom)));
                   1595:     my $i;
                   1596:     for ($i=0;$i<=$#what;$i++) {
                   1597: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
                   1598:     }
                   1599:     return %returnhash;
1.1       albertel 1600: }
                   1601: 
1.617     albertel 1602: # ---------------------------------------------------------- Get a studentphoto
                   1603: sub studentphoto {
                   1604:     my ($udom,$unam,$ext) = @_;
                   1605:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  1606:     if (defined($env{'request.course.id'})) {
1.708     raeburn  1607:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  1608:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   1609:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   1610:             } else {
                   1611:                 my ($result,$perm_reqd)=
1.707     albertel 1612: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1613:                 if ($result eq 'ok') {
                   1614:                     if (!($perm_reqd eq 'yes')) {
                   1615:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   1616:                     }
                   1617:                 }
                   1618:             }
                   1619:         }
                   1620:     } else {
                   1621:         my ($result,$perm_reqd) = 
1.707     albertel 1622: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1623:         if ($result eq 'ok') {
                   1624:             if (!($perm_reqd eq 'yes')) {
                   1625:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   1626:             }
                   1627:         }
                   1628:     }
                   1629:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   1630: }
                   1631: 
                   1632: sub retrievestudentphoto {
                   1633:     my ($udom,$unam,$ext,$type) = @_;
                   1634:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   1635:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   1636:     if ($ret eq 'ok') {
                   1637:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   1638:         if ($type eq 'thumbnail') {
                   1639:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   1640:         }
                   1641:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   1642:         return $tokenurl;
                   1643:     } else {
                   1644:         if ($type eq 'thumbnail') {
                   1645:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   1646:         } else { 
                   1647:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   1648:         }
1.617     albertel 1649:     }
                   1650: }
                   1651: 
1.263     www      1652: # -------------------------------------------------------------------- New chat
                   1653: 
                   1654: sub chatsend {
1.724     raeburn  1655:     my ($newentry,$anon,$group)=@_;
1.620     albertel 1656:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1657:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1658:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      1659:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 1660: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  1661: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      1662: }
                   1663: 
                   1664: # ------------------------------------------ Find current version of a resource
                   1665: 
                   1666: sub getversion {
                   1667:     my $fname=&clutter(shift);
                   1668:     unless ($fname=~/^\/res\//) { return -1; }
                   1669:     return &currentversion(&filelocation('',$fname));
                   1670: }
                   1671: 
                   1672: sub currentversion {
                   1673:     my $fname=shift;
1.599     albertel 1674:     my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440     www      1675:     if (defined($cached)) { return $result; }
1.292     www      1676:     my $author=$fname;
                   1677:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1678:     my ($udom,$uname)=split(/\//,$author);
                   1679:     my $home=homeserver($uname,$udom);
                   1680:     if ($home eq 'no_host') { 
                   1681:         return -1; 
                   1682:     }
                   1683:     my $answer=reply("currentversion:$fname",$home);
                   1684:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1685: 	return -1;
                   1686:     }
1.599     albertel 1687:     return &do_cache_new('resversion',$fname,$answer,600);
1.263     www      1688: }
                   1689: 
1.1       albertel 1690: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      1691: 
1.1       albertel 1692: sub subscribe {
                   1693:     my $fname=shift;
1.761     raeburn  1694:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 1695:     $fname=~s/[\n\r]//g;
1.1       albertel 1696:     my $author=$fname;
                   1697:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1698:     my ($udom,$uname)=split(/\//,$author);
                   1699:     my $home=homeserver($uname,$udom);
1.335     albertel 1700:     if ($home eq 'no_host') {
                   1701:         return 'not_found';
1.1       albertel 1702:     }
                   1703:     my $answer=reply("sub:$fname",$home);
1.64      www      1704:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1705: 	$answer.=' by '.$home;
                   1706:     }
1.1       albertel 1707:     return $answer;
                   1708: }
                   1709:     
1.8       www      1710: # -------------------------------------------------------------- Replicate file
                   1711: 
                   1712: sub repcopy {
                   1713:     my $filename=shift;
1.23      www      1714:     $filename=~s/\/+/\//g;
1.607     raeburn  1715:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   1716:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 1717:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 1718: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 1719: 	return &repcopy_userfile($filename);
                   1720:     }
1.532     albertel 1721:     $filename=~s/[\n\r]//g;
1.8       www      1722:     my $transname="$filename.in.transfer";
1.828     www      1723: # FIXME: this should flock
1.607     raeburn  1724:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      1725:     my $remoteurl=subscribe($filename);
1.64      www      1726:     if ($remoteurl =~ /^con_lost by/) {
                   1727: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1728:            return 'unavailable';
1.8       www      1729:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 1730: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  1731: 	   return 'not_found';
1.64      www      1732:     } elsif ($remoteurl =~ /^rejected by/) {
                   1733: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1734:            return 'forbidden';
1.20      www      1735:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  1736:            return 'ok';
1.8       www      1737:     } else {
1.290     www      1738:         my $author=$filename;
                   1739:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1740:         my ($udom,$uname)=split(/\//,$author);
                   1741:         my $home=homeserver($uname,$udom);
                   1742:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      1743:            my @parts=split(/\//,$filename);
                   1744:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   1745:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   1746:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  1747: 	       return 'bad_request';
1.8       www      1748:            }
                   1749:            my $count;
                   1750:            for ($count=5;$count<$#parts;$count++) {
                   1751:                $path.="/$parts[$count]";
                   1752:                if ((-e $path)!=1) {
                   1753: 		   mkdir($path,0777);
                   1754:                }
                   1755:            }
                   1756:            my $ua=new LWP::UserAgent;
                   1757:            my $request=new HTTP::Request('GET',"$remoteurl");
                   1758:            my $response=$ua->request($request,$transname);
                   1759:            if ($response->is_error()) {
                   1760: 	       unlink($transname);
                   1761:                my $message=$response->status_line;
1.672     albertel 1762:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      1763:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  1764:                return 'unavailable';
1.8       www      1765:            } else {
1.16      www      1766: 	       if ($remoteurl!~/\.meta$/) {
                   1767:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   1768:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   1769:                   if ($mresponse->is_error()) {
                   1770: 		      unlink($filename.'.meta');
                   1771:                       &logthis(
1.672     albertel 1772:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      1773:                   }
                   1774: 	       }
1.8       www      1775:                rename($transname,$filename);
1.607     raeburn  1776:                return 'ok';
1.8       www      1777:            }
1.290     www      1778:        }
1.8       www      1779:     }
1.330     www      1780: }
                   1781: 
                   1782: # ------------------------------------------------ Get server side include body
                   1783: sub ssi_body {
1.381     albertel 1784:     my ($filelink,%form)=@_;
1.606     matthew  1785:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   1786:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   1787:     }
1.953     www      1788:     my $output='';
                   1789:     my $response;
                   1790:     if ($filelink=~/^http\:/) {
1.954     raeburn  1791:        ($output,$response)=&externalssi($filelink);
1.953     www      1792:     } else {
                   1793:        ($output,$response)=&ssi($filelink,%form);
                   1794:     }
1.778     albertel 1795:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 1796:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 1797:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      1798:     if (wantarray) {
                   1799:         return ($output, $response);
                   1800:     } else {
                   1801:         return $output;
                   1802:     }
1.8       www      1803: }
                   1804: 
1.15      www      1805: # --------------------------------------------------------- Server Side Include
                   1806: 
1.782     albertel 1807: sub absolute_url {
                   1808:     my ($host_name) = @_;
                   1809:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   1810:     if ($host_name eq '') {
                   1811: 	$host_name = $ENV{'SERVER_NAME'};
                   1812:     }
                   1813:     return $protocol.$host_name;
                   1814: }
                   1815: 
1.942     foxr     1816: #
                   1817: #   Server side include.
                   1818: # Parameters:
                   1819: #  fn     Possibly encrypted resource name/id.
                   1820: #  form   Hash that describes how the rendering should be done
                   1821: #         and other things.
1.944     foxr     1822: # Returns:
1.950     raeburn  1823: #   Scalar context: The content of the response.
                   1824: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     1825: #     
1.15      www      1826: sub ssi {
                   1827: 
1.944     foxr     1828:     my ($fn,%form)=@_;
1.15      www      1829:     my $ua=new LWP::UserAgent;
1.23      www      1830:     my $request;
1.711     albertel 1831: 
                   1832:     $form{'no_update_last_known'}=1;
1.895     albertel 1833:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      1834:     if (%form) {
1.782     albertel 1835:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.201     albertel 1836:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1.23      www      1837:     } else {
1.782     albertel 1838:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      1839:     }
                   1840: 
1.15      www      1841:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   1842:     my $response=$ua->request($request);
                   1843: 
1.944     foxr     1844:     if (wantarray) {
                   1845: 	return ($response->content, $response);
                   1846:     } else {
                   1847: 	return $response->content;
1.942     foxr     1848:     }
1.324     www      1849: }
                   1850: 
                   1851: sub externalssi {
                   1852:     my ($url)=@_;
                   1853:     my $ua=new LWP::UserAgent;
                   1854:     my $request=new HTTP::Request('GET',$url);
                   1855:     my $response=$ua->request($request);
1.954     raeburn  1856:     if (wantarray) {
                   1857:         return ($response->content, $response);
                   1858:     } else {
                   1859:         return $response->content;
                   1860:     }
1.15      www      1861: }
1.254     www      1862: 
1.492     albertel 1863: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   1864: 
                   1865: sub allowuploaded {
                   1866:     my ($srcurl,$url)=@_;
                   1867:     $url=&clutter(&declutter($url));
                   1868:     my $dir=$url;
                   1869:     $dir=~s/\/[^\/]+$//;
                   1870:     my %httpref=();
                   1871:     my $httpurl=&hreflocation('',$url);
                   1872:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  1873:     &Apache::lonnet::appenv(\%httpref);
1.254     www      1874: }
1.477     raeburn  1875: 
1.478     albertel 1876: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 1877: # input: action, courseID, current domain, intended
1.637     raeburn  1878: #        path to file, source of file, instruction to parse file for objects,
                   1879: #        ref to hash for embedded objects,
                   1880: #        ref to hash for codebase of java objects.
                   1881: #
1.485     raeburn  1882: # output: url to file (if action was uploaddoc), 
                   1883: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  1884: #
1.478     albertel 1885: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   1886: # course.
1.477     raeburn  1887: #
1.478     albertel 1888: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1889: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   1890: #          course's home server.
1.477     raeburn  1891: #
1.478     albertel 1892: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   1893: #          be copied from $source (current location) to 
                   1894: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1895: #         and will then be copied to
                   1896: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   1897: #         course's home server.
1.485     raeburn  1898: #
1.481     raeburn  1899: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 1900: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  1901: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1902: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   1903: #         in course's home server.
1.637     raeburn  1904: #
1.477     raeburn  1905: 
                   1906: sub process_coursefile {
1.638     albertel 1907:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477     raeburn  1908:     my $fetchresult;
1.638     albertel 1909:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  1910:     if ($action eq 'propagate') {
1.638     albertel 1911:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   1912: 			     $home);
1.481     raeburn  1913:     } else {
1.477     raeburn  1914:         my $fpath = '';
                   1915:         my $fname = $file;
1.478     albertel 1916:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  1917:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  1918:         my $filepath = &build_filepath($fpath);
1.481     raeburn  1919:         if ($action eq 'copy') {
                   1920:             if ($source eq '') {
                   1921:                 $fetchresult = 'no source file';
                   1922:                 return $fetchresult;
                   1923:             } else {
                   1924:                 my $destination = $filepath.'/'.$fname;
                   1925:                 rename($source,$destination);
                   1926:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1927:                                  $home);
1.481     raeburn  1928:             }
                   1929:         } elsif ($action eq 'uploaddoc') {
                   1930:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 1931:             print $fh $env{'form.'.$source};
1.481     raeburn  1932:             close($fh);
1.637     raeburn  1933:             if ($parser eq 'parse') {
1.961     raeburn  1934:                 my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
1.637     raeburn  1935:                 unless ($parse_result eq 'ok') {
                   1936:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   1937:                 }
                   1938:             }
1.477     raeburn  1939:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1940:                                  $home);
1.481     raeburn  1941:             if ($fetchresult eq 'ok') {
                   1942:                 return '/uploaded/'.$fpath.'/'.$fname;
                   1943:             } else {
                   1944:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1945:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  1946:                 return '/adm/notfound.html';
                   1947:             }
1.477     raeburn  1948:         }
                   1949:     }
1.485     raeburn  1950:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  1951:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1952:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  1953:     }
                   1954:     return $fetchresult;
                   1955: }
                   1956: 
1.637     raeburn  1957: sub build_filepath {
                   1958:     my ($fpath) = @_;
                   1959:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   1960:     unless ($fpath eq '') {
                   1961:         my @parts=split('/',$fpath);
                   1962:         foreach my $part (@parts) {
                   1963:             $filepath.= '/'.$part;
                   1964:             if ((-e $filepath)!=1) {
                   1965:                 mkdir($filepath,0777);
                   1966:             }
                   1967:         }
                   1968:     }
                   1969:     return $filepath;
                   1970: }
                   1971: 
                   1972: sub store_edited_file {
1.638     albertel 1973:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  1974:     my $file = $primary_url;
                   1975:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   1976:     my $fpath = '';
                   1977:     my $fname = $file;
                   1978:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   1979:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   1980:     my $filepath = &build_filepath($fpath);
                   1981:     open(my $fh,'>'.$filepath.'/'.$fname);
                   1982:     print $fh $content;
                   1983:     close($fh);
1.638     albertel 1984:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  1985:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1986: 			  $home);
1.637     raeburn  1987:     if ($$fetchresult eq 'ok') {
                   1988:         return '/uploaded/'.$fpath.'/'.$fname;
                   1989:     } else {
1.638     albertel 1990:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   1991: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  1992:         return '/adm/notfound.html';
                   1993:     }
                   1994: }
                   1995: 
1.531     albertel 1996: sub clean_filename {
1.831     albertel 1997:     my ($fname,$args)=@_;
1.315     www      1998: # Replace Windows backslashes by forward slashes
1.257     www      1999:     $fname=~s/\\/\//g;
1.831     albertel 2000:     if (!$args->{'keep_path'}) {
                   2001:         # Get rid of everything but the actual filename
                   2002: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   2003:     }
1.315     www      2004: # Replace spaces by underscores
                   2005:     $fname=~s/\s+/\_/g;
                   2006: # Replace all other weird characters by nothing
1.831     albertel 2007:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 2008: # Replace all .\d. sequences with _\d. so they no longer look like version
                   2009: # numbers
                   2010:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 2011:     return $fname;
                   2012: }
                   2013: 
1.608     albertel 2014: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 2015: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719     banghart 2016: #                    the desired filenam is in $env{"form.$formname.filename"}
1.686     albertel 2017: #        $coursedoc - if true up to the current course
                   2018: #                     if false
                   2019: #        $subdir - directory in userfile to store the file into
1.858     raeburn  2020: #        $parser - instruction to parse file for objects ($parser = parse)    
                   2021: #        $allfiles - reference to hash for embedded objects
                   2022: #        $codebase - reference to hash for codebase of java objects
                   2023: #        $desuname - username for permanent storage of uploaded file
                   2024: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  2025: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   2026: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.858     raeburn  2027: # 
1.686     albertel 2028: # output: url of file in userspace, or error: <message> 
                   2029: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 2030: 
                   2031: 
1.531     albertel 2032: sub userfileupload {
1.860     raeburn  2033:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
                   2034:         $destudom,$thumbwidth,$thumbheight)=@_;
1.531     albertel 2035:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 2036:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 2037:     $fname=&clean_filename($fname);
1.315     www      2038: # See if there is anything left
1.257     www      2039:     unless ($fname) { return 'error: no uploaded file'; }
1.620     albertel 2040:     chop($env{'form.'.$formname});
1.523     raeburn  2041:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
                   2042:         my $now = time;
                   2043:         my $filepath = 'tmp/helprequests/'.$now;
                   2044:         my @parts=split(/\//,$filepath);
                   2045:         my $fullpath = $perlvar{'lonDaemons'};
                   2046:         for (my $i=0;$i<@parts;$i++) {
                   2047:             $fullpath .= '/'.$parts[$i];
                   2048:             if ((-e $fullpath)!=1) {
                   2049:                 mkdir($fullpath,0777);
                   2050:             }
                   2051:         }
                   2052:         open(my $fh,'>'.$fullpath.'/'.$fname);
1.620     albertel 2053:         print $fh $env{'form.'.$formname};
1.523     raeburn  2054:         close($fh);
1.741     raeburn  2055:         return $fullpath.'/'.$fname;
                   2056:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
                   2057:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   2058:                        '_'.$env{'user.domain'}.'/pending';
                   2059:         my @parts=split(/\//,$filepath);
                   2060:         my $fullpath = $perlvar{'lonDaemons'};
                   2061:         for (my $i=0;$i<@parts;$i++) {
                   2062:             $fullpath .= '/'.$parts[$i];
                   2063:             if ((-e $fullpath)!=1) {
                   2064:                 mkdir($fullpath,0777);
                   2065:             }
                   2066:         }
                   2067:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   2068:         print $fh $env{'form.'.$formname};
                   2069:         close($fh);
                   2070:         return $fullpath.'/'.$fname;
1.523     raeburn  2071:     }
1.719     banghart 2072:     
1.258     www      2073: # Create the directory if not present
1.493     albertel 2074:     $fname="$subdir/$fname";
1.259     www      2075:     if ($coursedoc) {
1.638     albertel 2076: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2077: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  2078:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 2079:             return &finishuserfileupload($docuname,$docudom,
                   2080: 					 $formname,$fname,$parser,$allfiles,
1.860     raeburn  2081: 					 $codebase,$thumbwidth,$thumbheight);
1.481     raeburn  2082:         } else {
1.620     albertel 2083:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 2084:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   2085: 				       $fname,$formname,$parser,
                   2086: 				       $allfiles,$codebase);
1.481     raeburn  2087:         }
1.719     banghart 2088:     } elsif (defined($destuname)) {
                   2089:         my $docuname=$destuname;
                   2090:         my $docudom=$destudom;
1.860     raeburn  2091: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2092: 				     $parser,$allfiles,$codebase,
                   2093:                                      $thumbwidth,$thumbheight);
1.719     banghart 2094:         
1.259     www      2095:     } else {
1.638     albertel 2096:         my $docuname=$env{'user.name'};
                   2097:         my $docudom=$env{'user.domain'};
1.714     raeburn  2098:         if (exists($env{'form.group'})) {
                   2099:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2100:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2101:         }
1.860     raeburn  2102: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2103: 				     $parser,$allfiles,$codebase,
                   2104:                                      $thumbwidth,$thumbheight);
1.259     www      2105:     }
1.271     www      2106: }
                   2107: 
                   2108: sub finishuserfileupload {
1.860     raeburn  2109:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
                   2110:         $thumbwidth,$thumbheight) = @_;
1.477     raeburn  2111:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      2112:     my $filepath=$perlvar{'lonDocRoot'};
1.860     raeburn  2113:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 2114:     $file=$fname;
                   2115:     if ($fname=~m|/|) {
                   2116:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   2117: 	$path.=$fnamepath.'/';
                   2118:     }
1.259     www      2119:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      2120:     my $count;
                   2121:     for ($count=4;$count<=$#parts;$count++) {
                   2122:         $filepath.="/$parts[$count]";
                   2123:         if ((-e $filepath)!=1) {
                   2124: 	    mkdir($filepath,0777);
                   2125:         }
                   2126:     }
                   2127: # Save the file
                   2128:     {
1.701     albertel 2129: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   2130: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   2131: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   2132: 	    return '/adm/notfound.html';
                   2133: 	}
                   2134: 	if (!print FH ($env{'form.'.$formname})) {
                   2135: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   2136: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   2137: 	    return '/adm/notfound.html';
                   2138: 	}
1.570     albertel 2139: 	close(FH);
1.258     www      2140:     }
1.637     raeburn  2141:     if ($parser eq 'parse') {
1.961     raeburn  2142:         my $parse_result = &extract_embedded_items($filepath.'/'.$file,$allfiles,
1.638     albertel 2143: 						   $codebase);
1.637     raeburn  2144:         unless ($parse_result eq 'ok') {
1.638     albertel 2145:             &logthis('Failed to parse '.$filepath.$file.
                   2146: 		     ' for embedded media: '.$parse_result); 
1.637     raeburn  2147:         }
                   2148:     }
1.860     raeburn  2149:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   2150:         my $input = $filepath.'/'.$file;
                   2151:         my $output = $filepath.'/'.'tn-'.$file;
                   2152:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   2153:         system("convert -sample $thumbsize $input $output");
                   2154:         if (-e $filepath.'/'.'tn-'.$file) {
                   2155:             $fetchthumb  = 1; 
                   2156:         }
                   2157:     }
1.858     raeburn  2158:  
1.259     www      2159: # Notify homeserver to grep it
                   2160: #
1.638     albertel 2161:     my $docuhome=&homeserver($docuname,$docudom);
1.494     albertel 2162:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      2163:     if ($fetchresult eq 'ok') {
1.860     raeburn  2164:         if ($fetchthumb) {
                   2165:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   2166:             if ($thumbresult ne 'ok') {
                   2167:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   2168:                          $docuhome.': '.$thumbresult);
                   2169:             }
                   2170:         }
1.259     www      2171: #
1.258     www      2172: # Return the URL to it
1.494     albertel 2173:         return '/uploaded/'.$path.$file;
1.263     www      2174:     } else {
1.494     albertel 2175:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   2176: 		 ': '.$fetchresult);
1.263     www      2177:         return '/adm/notfound.html';
1.858     raeburn  2178:     }
1.493     albertel 2179: }
                   2180: 
1.637     raeburn  2181: sub extract_embedded_items {
1.961     raeburn  2182:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  2183:     my @state = ();
                   2184:     my %javafiles = (
                   2185:                       codebase => '',
                   2186:                       code => '',
                   2187:                       archive => ''
                   2188:                     );
                   2189:     my %mediafiles = (
                   2190:                       src => '',
                   2191:                       movie => '',
                   2192:                      );
1.648     raeburn  2193:     my $p;
                   2194:     if ($content) {
                   2195:         $p = HTML::LCParser->new($content);
                   2196:     } else {
1.961     raeburn  2197:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  2198:     }
1.641     albertel 2199:     while (my $t=$p->get_token()) {
1.640     albertel 2200: 	if ($t->[0] eq 'S') {
                   2201: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 2202: 	    push(@state, $tagname);
1.648     raeburn  2203:             if (lc($tagname) eq 'allow') {
                   2204:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   2205:             }
1.640     albertel 2206: 	    if (lc($tagname) eq 'img') {
                   2207: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   2208: 	    }
1.886     albertel 2209: 	    if (lc($tagname) eq 'a') {
                   2210: 		&add_filetype($allfiles,$attr->{'href'},'href');
                   2211: 	    }
1.645     raeburn  2212:             if (lc($tagname) eq 'script') {
                   2213:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   2214:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   2215:                 } else {
                   2216:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   2217:                 }
                   2218:             }
                   2219:             if (lc($tagname) eq 'link') {
                   2220:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   2221:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   2222:                 }
                   2223:             }
1.640     albertel 2224: 	    if (lc($tagname) eq 'object' ||
                   2225: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   2226: 		foreach my $item (keys(%javafiles)) {
                   2227: 		    $javafiles{$item} = '';
                   2228: 		}
                   2229: 	    }
                   2230: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   2231: 		my $name = lc($attr->{'name'});
                   2232: 		foreach my $item (keys(%javafiles)) {
                   2233: 		    if ($name eq $item) {
                   2234: 			$javafiles{$item} = $attr->{'value'};
                   2235: 			last;
                   2236: 		    }
                   2237: 		}
                   2238: 		foreach my $item (keys(%mediafiles)) {
                   2239: 		    if ($name eq $item) {
                   2240: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   2241: 			last;
                   2242: 		    }
                   2243: 		}
                   2244: 	    }
                   2245: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   2246: 		foreach my $item (keys(%javafiles)) {
                   2247: 		    if ($attr->{$item}) {
                   2248: 			$javafiles{$item} = $attr->{$item};
                   2249: 			last;
                   2250: 		    }
                   2251: 		}
                   2252: 		foreach my $item (keys(%mediafiles)) {
                   2253: 		    if ($attr->{$item}) {
                   2254: 			&add_filetype($allfiles,$attr->{$item},$item);
                   2255: 			last;
                   2256: 		    }
                   2257: 		}
                   2258: 	    }
                   2259: 	} elsif ($t->[0] eq 'E') {
                   2260: 	    my ($tagname) = ($t->[1]);
                   2261: 	    if ($javafiles{'codebase'} ne '') {
                   2262: 		$javafiles{'codebase'} .= '/';
                   2263: 	    }  
                   2264: 	    if (lc($tagname) eq 'applet' ||
                   2265: 		lc($tagname) eq 'object' ||
                   2266: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   2267: 		) {
                   2268: 		foreach my $item (keys(%javafiles)) {
                   2269: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   2270: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   2271: 			&add_filetype($allfiles,$file,$item);
                   2272: 		    }
                   2273: 		}
                   2274: 	    } 
                   2275: 	    pop @state;
                   2276: 	}
                   2277:     }
1.637     raeburn  2278:     return 'ok';
                   2279: }
                   2280: 
1.639     albertel 2281: sub add_filetype {
                   2282:     my ($allfiles,$file,$type)=@_;
                   2283:     if (exists($allfiles->{$file})) {
                   2284: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   2285: 	    push(@{$allfiles->{$file}}, &escape($type));
                   2286: 	}
                   2287:     } else {
                   2288: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  2289:     }
                   2290: }
                   2291: 
1.493     albertel 2292: sub removeuploadedurl {
                   2293:     my ($url)=@_;
                   2294:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613     albertel 2295:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 2296: }
                   2297: 
                   2298: sub removeuserfile {
                   2299:     my ($docuname,$docudom,$fname)=@_;
                   2300:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  2301:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
                   2302:     if ($result eq 'ok') {
                   2303:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   2304:             my $metafile = $fname.'.meta';
                   2305:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 2306: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
                   2307:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  2308:             my $sqlresult = 
1.823     albertel 2309:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2310:                                         'portfolio_metadata',$group,
                   2311:                                         'delete');
1.798     raeburn  2312:         }
                   2313:     }
                   2314:     return $result;
1.257     www      2315: }
1.15      www      2316: 
1.530     albertel 2317: sub mkdiruserfile {
                   2318:     my ($docuname,$docudom,$dir)=@_;
                   2319:     my $home=&homeserver($docuname,$docudom);
                   2320:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   2321: }
                   2322: 
1.531     albertel 2323: sub renameuserfile {
                   2324:     my ($docuname,$docudom,$old,$new)=@_;
                   2325:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  2326:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   2327:                         &escape("$old").':'.&escape("$new"),$home);
                   2328:     if ($result eq 'ok') {
                   2329:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   2330:             my $oldmeta = $old.'.meta';
                   2331:             my $newmeta = $new.'.meta';
                   2332:             my $metaresult = 
                   2333:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 2334: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   2335:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  2336:             my $sqlresult = 
1.823     albertel 2337:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2338:                                         'portfolio_metadata',$group,
                   2339:                                         'delete');
1.798     raeburn  2340:         }
                   2341:     }
                   2342:     return $result;
1.531     albertel 2343: }
                   2344: 
1.14      www      2345: # ------------------------------------------------------------------------- Log
                   2346: 
                   2347: sub log {
                   2348:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      2349:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      2350: }
                   2351: 
                   2352: # ------------------------------------------------------------------ Course Log
1.352     www      2353: #
                   2354: # This routine flushes several buffers of non-mission-critical nature
                   2355: #
1.157     www      2356: 
                   2357: sub flushcourselogs {
1.352     www      2358:     &logthis('Flushing log buffers');
                   2359: #
                   2360: # course logs
                   2361: # This is a log of all transactions in a course, which can be used
                   2362: # for data mining purposes
                   2363: #
                   2364: # It also collects the courseid database, which lists last transaction
                   2365: # times and course titles for all courseids
                   2366: #
                   2367:     my %courseidbuffer=();
1.921     raeburn  2368:     foreach my $crsid (keys(%courselogs)) {
1.352     www      2369:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      2370: 		          &escape($courselogs{$crsid}),
                   2371: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      2372: 	    delete $courselogs{$crsid};
                   2373:         } else {
                   2374:             &logthis('Failed to flush log buffer for '.$crsid);
                   2375:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 2376:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      2377:                         " exceeded maximum size, deleting.</font>");
                   2378:                delete $courselogs{$crsid};
                   2379:             }
1.352     www      2380:         }
1.920     raeburn  2381:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  2382:             'description' => $coursedescrbuf{$crsid},
                   2383:             'inst_code'    => $courseinstcodebuf{$crsid},
                   2384:             'type'        => $coursetypebuf{$crsid},
                   2385:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  2386:         };
1.191     harris41 2387:     }
1.352     www      2388: #
                   2389: # Write course id database (reverse lookup) to homeserver of courses 
                   2390: # Is used in pickcourse
                   2391: #
1.840     albertel 2392:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  2393:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  2394:                                     $courseidbuffer{$crs_home},
                   2395:                                     $crs_home,'timeonly');
1.352     www      2396:     }
                   2397: #
                   2398: # File accesses
                   2399: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   2400: #
1.449     matthew  2401:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  2402:         if ($entry =~ /___count$/) {
                   2403:             my ($dom,$name);
1.807     albertel 2404:             ($dom,$name,undef)=
1.811     albertel 2405: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  2406:             if (! defined($dom) || $dom eq '' || 
                   2407:                 ! defined($name) || $name eq '') {
1.620     albertel 2408:                 my $cid = $env{'request.course.id'};
                   2409:                 $dom  = $env{'request.'.$cid.'.domain'};
                   2410:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  2411:             }
1.450     matthew  2412:             my $value = $accesshash{$entry};
                   2413:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   2414:             my %temphash=($url => $value);
1.449     matthew  2415:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   2416:             if ($result eq 'ok') {
                   2417:                 delete $accesshash{$entry};
                   2418:             } elsif ($result eq 'unknown_cmd') {
                   2419:                 # Target server has old code running on it.
1.450     matthew  2420:                 my %temphash=($entry => $value);
1.449     matthew  2421:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2422:                     delete $accesshash{$entry};
                   2423:                 }
                   2424:             }
                   2425:         } else {
1.811     albertel 2426:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450     matthew  2427:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  2428:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2429:                 delete $accesshash{$entry};
                   2430:             }
1.185     www      2431:         }
1.191     harris41 2432:     }
1.352     www      2433: #
                   2434: # Roles
                   2435: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   2436: #
1.800     albertel 2437:     foreach my $entry (keys(%userrolehash)) {
1.351     www      2438:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      2439: 	    split(/\:/,$entry);
                   2440:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      2441:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      2442:                 $rudom,$runame) eq 'ok') {
                   2443: 	    delete $userrolehash{$entry};
                   2444:         }
                   2445:     }
1.662     raeburn  2446: #
                   2447: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   2448: #
                   2449:     my %domrolebuffer = ();
                   2450:     foreach my $entry (keys %domainrolehash) {
1.901     albertel 2451:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  2452:         if ($domrolebuffer{$rudom}) {
                   2453:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   2454:                       '='.&escape($domainrolehash{$entry});
                   2455:         } else {
                   2456:             $domrolebuffer{$rudom}.=&escape($entry).
                   2457:                       '='.&escape($domainrolehash{$entry});
                   2458:         }
                   2459:         delete $domainrolehash{$entry};
                   2460:     }
                   2461:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 2462: 	my %servers = &get_servers($dom,'library');
                   2463: 	foreach my $tryserver (keys(%servers)) {
                   2464: 	    unless (&reply('domroleput:'.$dom.':'.
                   2465: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   2466: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   2467: 	    }
1.662     raeburn  2468:         }
                   2469:     }
1.186     www      2470:     $dumpcount++;
1.157     www      2471: }
                   2472: 
                   2473: sub courselog {
                   2474:     my $what=shift;
1.158     www      2475:     $what=time.':'.$what;
1.620     albertel 2476:     unless ($env{'request.course.id'}) { return ''; }
                   2477:     $coursedombuf{$env{'request.course.id'}}=
                   2478:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2479:     $coursenumbuf{$env{'request.course.id'}}=
                   2480:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   2481:     $coursehombuf{$env{'request.course.id'}}=
                   2482:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   2483:     $coursedescrbuf{$env{'request.course.id'}}=
                   2484:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   2485:     $courseinstcodebuf{$env{'request.course.id'}}=
                   2486:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   2487:     $courseownerbuf{$env{'request.course.id'}}=
                   2488:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  2489:     $coursetypebuf{$env{'request.course.id'}}=
                   2490:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 2491:     if (defined $courselogs{$env{'request.course.id'}}) {
                   2492: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      2493:     } else {
1.620     albertel 2494: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      2495:     }
1.620     albertel 2496:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      2497: 	&flushcourselogs();
                   2498:     }
1.158     www      2499: }
                   2500: 
                   2501: sub courseacclog {
                   2502:     my $fnsymb=shift;
1.620     albertel 2503:     unless ($env{'request.course.id'}) { return ''; }
                   2504:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 2505:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      2506:         $what.=':POST';
1.583     matthew  2507:         # FIXME: Probably ought to escape things....
1.800     albertel 2508: 	foreach my $key (keys(%env)) {
                   2509:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  2510:                 my $formitem = $1;
                   2511:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   2512:                     $what.=':'.$formitem.'='.$env{$key};
                   2513:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   2514:                     $what.=':'.$formitem.'='.$env{$key};
                   2515:                 }
1.158     www      2516:             }
1.191     harris41 2517:         }
1.583     matthew  2518:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   2519:         # FIXME: We should not be depending on a form parameter that someone
                   2520:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 2521:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  2522:             $what.= ':POST';
                   2523:             # FIXME: Probably ought to escape things....
                   2524:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   2525:                                  'crsdiscuss') {
1.620     albertel 2526:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  2527:             }
                   2528:         }
1.158     www      2529:     }
                   2530:     &courselog($what);
1.149     www      2531: }
                   2532: 
1.185     www      2533: sub countacc {
                   2534:     my $url=&declutter(shift);
1.458     matthew  2535:     return if (! defined($url) || $url eq '');
1.620     albertel 2536:     unless ($env{'request.course.id'}) { return ''; }
                   2537:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      2538:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  2539:     $accesshash{$key}++;
1.185     www      2540: }
1.349     www      2541: 
1.361     www      2542: sub linklog {
                   2543:     my ($from,$to)=@_;
                   2544:     $from=&declutter($from);
                   2545:     $to=&declutter($to);
                   2546:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   2547:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   2548: }
                   2549:   
1.349     www      2550: sub userrolelog {
                   2551:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  2552:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  2553:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  2554:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
                   2555:         ($trole=~/^ta/)) {
1.350     www      2556:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2557:        $userrolehash
                   2558:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      2559:                     =$tend.':'.$tstart;
1.662     raeburn  2560:     }
1.898     albertel 2561:     if (($env{'request.role'} =~ /dc\./) &&
                   2562: 	(($trole=~/^au/) || ($trole=~/^in/) ||
                   2563: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
                   2564: 	 ($trole=~/^cr/) || ($trole=~/^ta/))) {
                   2565:        $userrolehash
                   2566:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   2567:                     =$tend.':'.$tstart;
                   2568:     }
1.662     raeburn  2569:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   2570:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   2571:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   2572:         ($trole=~/^sc/)) {
                   2573:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2574:        $domainrolehash
                   2575:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   2576:                     = $tend.':'.$tstart;
                   2577:     }
1.351     www      2578: }
                   2579: 
1.957     raeburn  2580: sub courserolelog {
                   2581:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
                   2582:     if (($trole eq 'cc') || ($trole eq 'in') ||
                   2583:         ($trole eq 'ep') || ($trole eq 'ad') ||
                   2584:         ($trole eq 'ta') || ($trole eq 'st') ||
                   2585:         ($trole=~/^cr/) || ($trole eq 'gr')) {
                   2586:         if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   2587:             my $cdom = $1;
                   2588:             my $cnum = $2;
                   2589:             my $sec = $3;
                   2590:             my $namespace = 'rolelog';
                   2591:             my %storehash = (
                   2592:                                role    => $trole,
                   2593:                                start   => $tstart,
                   2594:                                end     => $tend,
                   2595:                                selfenroll => $selfenroll,
                   2596:                                context    => $context,
                   2597:                             );
                   2598:             if ($trole eq 'gr') {
                   2599:                 $namespace = 'groupslog';
                   2600:                 $storehash{'group'} = $sec;
                   2601:             } else {
                   2602:                 $storehash{'section'} = $sec;
                   2603:             }
                   2604:             &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
                   2605:         }
                   2606:     }
                   2607:     return;
                   2608: }
                   2609: 
1.351     www      2610: sub get_course_adv_roles {
1.948     raeburn  2611:     my ($cid,$codes) = @_;
1.620     albertel 2612:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      2613:     my %coursehash=&coursedescription($cid);
1.470     www      2614:     my %nothide=();
1.800     albertel 2615:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  2616:         if ($user !~ /:/) {
                   2617: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   2618:         } else {
                   2619:             $nothide{$user}=1;
                   2620:         }
1.470     www      2621:     }
1.351     www      2622:     my %returnhash=();
                   2623:     my %dumphash=
                   2624:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   2625:     my $now=time;
1.800     albertel 2626:     foreach my $entry (keys %dumphash) {
                   2627: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      2628:         if (($tstart) && ($tstart<0)) { next; }
                   2629:         if (($tend) && ($tend<$now)) { next; }
                   2630:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 2631:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 2632: 	if ($username eq '' || $domain eq '') { next; }
1.470     www      2633: 	if ((&privileged($username,$domain)) && 
                   2634: 	    (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 2635: 	if ($role eq 'cr') { next; }
1.948     raeburn  2636:         if ($codes) {
                   2637:             if ($section) { $role .= ':'.$section; }
                   2638:             if ($returnhash{$role}) {
                   2639:                 $returnhash{$role}.=','.$username.':'.$domain;
                   2640:             } else {
                   2641:                 $returnhash{$role}=$username.':'.$domain;
                   2642:             }
1.351     www      2643:         } else {
1.948     raeburn  2644:             my $key=&plaintext($role);
1.973     bisitz   2645:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  2646:             if ($returnhash{$key}) {
                   2647: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   2648:             } else {
                   2649:                 $returnhash{$key}=$username.':'.$domain;
                   2650:             }
1.351     www      2651:         }
1.948     raeburn  2652:     }
1.400     www      2653:     return %returnhash;
                   2654: }
                   2655: 
                   2656: sub get_my_roles {
1.937     raeburn  2657:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 2658:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   2659:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  2660:     my (%dumphash,%nothide);
1.858     raeburn  2661:     if ($context eq 'userroles') { 
                   2662:         %dumphash = &dump('roles',$udom,$uname);
                   2663:     } else {
                   2664:         %dumphash=
1.400     www      2665:             &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  2666:         if ($hidepriv) {
                   2667:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   2668:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   2669:                 if ($user !~ /:/) {
                   2670:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   2671:                 } else {
                   2672:                     $nothide{$user} = 1;
                   2673:                 }
                   2674:             }
                   2675:         }
1.858     raeburn  2676:     }
1.400     www      2677:     my %returnhash=();
                   2678:     my $now=time;
1.800     albertel 2679:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  2680:         my ($role,$tend,$tstart);
                   2681:         if ($context eq 'userroles') {
                   2682: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   2683:         } else {
                   2684:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   2685:         }
1.400     www      2686:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  2687:         my $status = 'active';
1.939     raeburn  2688:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  2689:             $status = 'previous';
                   2690:         } 
                   2691:         if (($tstart) && ($now<$tstart)) {
                   2692:             $status = 'future';
                   2693:         }
                   2694:         if (ref($types) eq 'ARRAY') {
                   2695:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   2696:                 next;
                   2697:             } 
                   2698:         } else {
                   2699:             if ($status ne 'active') {
                   2700:                 next;
                   2701:             }
                   2702:         }
1.867     raeburn  2703:         my ($rolecode,$username,$domain,$section,$area);
                   2704:         if ($context eq 'userroles') {
                   2705:             ($area,$rolecode) = split(/_/,$entry);
                   2706:             (undef,$domain,$username,$section) = split(/\//,$area);
                   2707:         } else {
                   2708:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   2709:         }
1.832     raeburn  2710:         if (ref($roledoms) eq 'ARRAY') {
                   2711:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   2712:                 next;
                   2713:             }
                   2714:         }
                   2715:         if (ref($roles) eq 'ARRAY') {
                   2716:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  2717:                 if ($role =~ /^cr\//) {
                   2718:                     if (!grep(/^cr$/,@{$roles})) {
                   2719:                         next;
                   2720:                     }
                   2721:                 } else {
                   2722:                     next;
                   2723:                 }
1.832     raeburn  2724:             }
1.867     raeburn  2725:         }
1.937     raeburn  2726:         if ($hidepriv) {
                   2727:             if ((&privileged($username,$domain)) &&
                   2728:                 (!$nothide{$username.':'.$domain})) { 
                   2729:                 next;
                   2730:             }
                   2731:         }
1.933     raeburn  2732:         if ($withsec) {
                   2733:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   2734:                 $tstart.':'.$tend;
                   2735:         } else {
                   2736:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   2737:         }
1.832     raeburn  2738:     }
1.373     www      2739:     return %returnhash;
1.399     www      2740: }
                   2741: 
                   2742: # ----------------------------------------------------- Frontpage Announcements
                   2743: #
                   2744: #
                   2745: 
                   2746: sub postannounce {
                   2747:     my ($server,$text)=@_;
1.844     albertel 2748:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      2749:     unless ($text=~/\w/) { $text=''; }
                   2750:     return &reply('setannounce:'.&escape($text),$server);
                   2751: }
                   2752: 
                   2753: sub getannounce {
1.448     albertel 2754: 
                   2755:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      2756: 	my $announcement='';
1.800     albertel 2757: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 2758: 	close($fh);
1.399     www      2759: 	if ($announcement=~/\w/) { 
                   2760: 	    return 
                   2761:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 2762:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      2763: 	} else {
                   2764: 	    return '';
                   2765: 	}
                   2766:     } else {
                   2767: 	return '';
                   2768:     }
1.351     www      2769: }
1.353     www      2770: 
                   2771: # ---------------------------------------------------------- Course ID routines
                   2772: # Deal with domain's nohist_courseid.db files
                   2773: #
                   2774: 
                   2775: sub courseidput {
1.921     raeburn  2776:     my ($domain,$storehash,$coursehome,$caller) = @_;
                   2777:     my $outcome;
                   2778:     if ($caller eq 'timeonly') {
                   2779:         my $cids = '';
                   2780:         foreach my $item (keys(%$storehash)) {
                   2781:             $cids.=&escape($item).'&';
                   2782:         }
                   2783:         $cids=~s/\&$//;
                   2784:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   2785:                           $coursehome);       
                   2786:     } else {
                   2787:         my $items = '';
                   2788:         foreach my $item (keys(%$storehash)) {
                   2789:             $items.= &escape($item).'='.
                   2790:                      &freeze_escape($$storehash{$item}).'&';
                   2791:         }
                   2792:         $items=~s/\&$//;
                   2793:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   2794:                           $coursehome);
1.918     raeburn  2795:     }
                   2796:     if ($outcome eq 'unknown_cmd') {
                   2797:         my $what;
                   2798:         foreach my $cid (keys(%$storehash)) {
                   2799:             $what .= &escape($cid).'=';
1.921     raeburn  2800:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  2801:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  2802:             }
                   2803:             $what =~ s/\:$/&/;
                   2804:         }
                   2805:         $what =~ s/\&$//;  
                   2806:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   2807:     } else {
                   2808:         return $outcome;
                   2809:     }
1.353     www      2810: }
                   2811: 
                   2812: sub courseiddump {
1.921     raeburn  2813:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  2814:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.962     raeburn  2815:         $selfenrollonly,$catfilter,$showhidden,$caller)=@_;
1.918     raeburn  2816:     my $as_hash = 1;
                   2817:     my %returnhash;
                   2818:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 2819:     my %libserv = &all_library();
                   2820:     foreach my $tryserver (keys(%libserv)) {
                   2821:         if ( (  $hostidflag == 1 
                   2822: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   2823: 	     || (!defined($hostidflag)) ) {
                   2824: 
1.918     raeburn  2825: 	    if (($domfilter eq '') ||
                   2826: 		(&host_domain($tryserver) eq $domfilter)) {
                   2827:                 my $rep = 
                   2828:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
                   2829:                          $sincefilter.':'.&escape($descfilter).':'.
                   2830:                          &escape($instcodefilter).':'.&escape($ownerfilter).
                   2831:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947     raeburn  2832:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962     raeburn  2833:                          &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   2834:                          $showhidden.':'.$caller,$tryserver);
1.918     raeburn  2835:                 my @pairs=split(/\&/,$rep);
                   2836:                 foreach my $item (@pairs) {
                   2837:                     my ($key,$value)=split(/\=/,$item,2);
                   2838:                     $key = &unescape($key);
                   2839:                     next if ($key =~ /^error: 2 /);
                   2840:                     my $result = &thaw_unescape($value);
                   2841:                     if (ref($result) eq 'HASH') {
                   2842:                         $returnhash{$key}=$result;
                   2843:                     } else {
1.921     raeburn  2844:                         my @responses = split(/:/,$value);
                   2845:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  2846:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  2847:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  2848:                         }
                   2849:                     } 
1.353     www      2850:                 }
                   2851:             }
                   2852:         }
                   2853:     }
                   2854:     return %returnhash;
                   2855: }
                   2856: 
1.658     raeburn  2857: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  2858: 
                   2859: sub dcmailput {
1.685     raeburn  2860:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  2861:     my $status = &Apache::lonnet::critical(
1.740     www      2862:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   2863:        &escape($message),$server);
1.662     raeburn  2864:     return $status;
                   2865: }
                   2866: 
1.658     raeburn  2867: sub dcmaildump {
                   2868:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  2869:     my %returnhash=();
1.846     albertel 2870: 
                   2871:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  2872:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   2873:                                                          &escape($enddate).':';
                   2874: 	my @esc_senders=map { &escape($_)} @$senders;
                   2875: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 2876: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 2877:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  2878:             if (($key) && ($value)) {
                   2879:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  2880:             }
                   2881:         }
                   2882:     }
                   2883:     return %returnhash;
                   2884: }
1.662     raeburn  2885: # ---------------------------------------------------------- Domain roles
                   2886: 
                   2887: sub get_domain_roles {
                   2888:     my ($dom,$roles,$startdate,$enddate)=@_;
                   2889:     if (undef($startdate) || $startdate eq '') {
                   2890:         $startdate = '.';
                   2891:     }
                   2892:     if (undef($enddate) || $enddate eq '') {
                   2893:         $enddate = '.';
                   2894:     }
1.922     raeburn  2895:     my $rolelist;
                   2896:     if (ref($roles) eq 'ARRAY') {
                   2897:         $rolelist = join(':',@{$roles});
                   2898:     }
1.662     raeburn  2899:     my %personnel = ();
1.841     albertel 2900: 
                   2901:     my %servers = &get_servers($dom,'library');
                   2902:     foreach my $tryserver (keys(%servers)) {
                   2903: 	%{$personnel{$tryserver}}=();
                   2904: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   2905: 					    &escape($startdate).':'.
                   2906: 					    &escape($enddate).':'.
                   2907: 					    &escape($rolelist), $tryserver))) {
                   2908: 	    my ($key,$value) = split(/\=/,$line,2);
                   2909: 	    if (($key) && ($value)) {
                   2910: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   2911: 	    }
                   2912: 	}
1.662     raeburn  2913:     }
                   2914:     return %personnel;
                   2915: }
1.658     raeburn  2916: 
1.149     www      2917: # ----------------------------------------------------------- Check out an item
                   2918: 
1.504     albertel 2919: sub get_first_access {
                   2920:     my ($type,$argsymb)=@_;
1.790     albertel 2921:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2922:     if ($argsymb) { $symb=$argsymb; }
                   2923:     my ($map,$id,$res)=&decode_symb($symb);
1.926     albertel 2924:     if ($type eq 'course') {
                   2925: 	$res='course';
                   2926:     } elsif ($type eq 'map') {
1.588     albertel 2927: 	$res=&symbread($map);
                   2928:     } else {
                   2929: 	$res=$symb;
                   2930:     }
                   2931:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   2932:     return $times{"$courseid\0$res"};
1.504     albertel 2933: }
                   2934: 
                   2935: sub set_first_access {
                   2936:     my ($type)=@_;
1.790     albertel 2937:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2938:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 2939:     if ($type eq 'course') {
                   2940: 	$res='course';
                   2941:     } elsif ($type eq 'map') {
1.588     albertel 2942: 	$res=&symbread($map);
                   2943:     } else {
                   2944: 	$res=$symb;
                   2945:     }
                   2946:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 2947:     if (!$firstaccess) {
1.588     albertel 2948: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 2949:     }
                   2950:     return 'already_set';
1.504     albertel 2951: }
                   2952: 
1.149     www      2953: sub checkout {
                   2954:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   2955:     my $now=time;
                   2956:     my $lonhost=$perlvar{'lonHostID'};
                   2957:     my $infostr=&escape(
1.234     www      2958:                  'CHECKOUTTOKEN&'.
1.149     www      2959:                  $tuname.'&'.
                   2960:                  $tudom.'&'.
                   2961:                  $tcrsid.'&'.
                   2962:                  $symb.'&'.
                   2963: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                   2964:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www      2965:     if ($token=~/^error\:/) { 
1.672     albertel 2966:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2967:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2968:                  "</font>");
                   2969:         return ''; 
                   2970:     }
                   2971: 
1.149     www      2972:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   2973:     $token=~tr/a-z/A-Z/;
                   2974: 
1.153     www      2975:     my %infohash=('resource.0.outtoken' => $token,
                   2976:                   'resource.0.checkouttime' => $now,
                   2977:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www      2978: 
                   2979:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2980:        return '';
1.151     www      2981:     } else {
1.672     albertel 2982:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2983:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2984:                  "</font>");
1.149     www      2985:     }    
                   2986: 
                   2987:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2988:                          &escape('Checkout '.$infostr.' - '.
                   2989:                                                  $token)) ne 'ok') {
                   2990: 	return '';
1.151     www      2991:     } else {
1.672     albertel 2992:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2993:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2994:                  "</font>");
1.149     www      2995:     }
1.151     www      2996:     return $token;
1.149     www      2997: }
                   2998: 
                   2999: # ------------------------------------------------------------ Check in an item
                   3000: 
                   3001: sub checkin {
                   3002:     my $token=shift;
1.150     www      3003:     my $now=time;
                   3004:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   3005:     $lonhost=~tr/A-Z/a-z/;
1.838     albertel 3006:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
1.150     www      3007:     $dtoken=~s/\W/\_/g;
1.234     www      3008:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www      3009:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   3010: 
1.154     www      3011:     unless (($tuname) && ($tudom)) {
                   3012:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   3013:         return '';
                   3014:     }
                   3015:     
                   3016:     unless (&allowed('mgr',$tcrsid)) {
                   3017:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620     albertel 3018:                  $env{'user.name'}.' - '.$env{'user.domain'});
1.154     www      3019:         return '';
                   3020:     }
                   3021: 
1.153     www      3022:     my %infohash=('resource.0.intoken' => $token,
                   3023:                   'resource.0.checkintime' => $now,
                   3024:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      3025: 
                   3026:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   3027:        return '';
                   3028:     }    
                   3029: 
                   3030:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   3031:                          &escape('Checkin - '.$token)) ne 'ok') {
                   3032: 	return '';
                   3033:     }
                   3034: 
                   3035:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      3036: }
                   3037: 
                   3038: # --------------------------------------------- Set Expire Date for Spreadsheet
                   3039: 
                   3040: sub expirespread {
                   3041:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 3042:     my $cid=$env{'request.course.id'}; 
1.110     www      3043:     if ($cid) {
                   3044:        my $now=time;
                   3045:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 3046:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   3047:                             $env{'course.'.$cid.'.num'}.
1.110     www      3048: 	        	    ':nohist_expirationdates:'.
                   3049:                             &escape($key).'='.$now,
1.620     albertel 3050:                             $env{'course.'.$cid.'.home'})
1.110     www      3051:     }
                   3052:     return 'ok';
1.14      www      3053: }
                   3054: 
1.109     www      3055: # ----------------------------------------------------- Devalidate Spreadsheets
                   3056: 
                   3057: sub devalidate {
1.325     www      3058:     my ($symb,$uname,$udom)=@_;
1.620     albertel 3059:     my $cid=$env{'request.course.id'}; 
1.109     www      3060:     if ($cid) {
1.391     matthew  3061:         # delete the stored spreadsheets for
                   3062:         # - the student level sheet of this user in course's homespace
                   3063:         # - the assessment level sheet for this resource 
                   3064:         #   for this user in user's homespace
1.553     albertel 3065: 	# - current conditional state info
1.325     www      3066: 	my $key=$uname.':'.$udom.':';
1.109     www      3067:         my $status=
1.299     matthew  3068: 	    &del('nohist_calculatedsheets',
1.391     matthew  3069: 		 [$key.'studentcalc:'],
1.620     albertel 3070: 		 $env{'course.'.$cid.'.domain'},
                   3071: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 3072: 		.' '.
                   3073: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  3074: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      3075:         unless ($status eq 'ok ok') {
                   3076:            &logthis('Could not devalidate spreadsheet '.
1.325     www      3077:                     $uname.' at '.$udom.' for '.
1.109     www      3078: 		    $symb.': '.$status);
1.133     albertel 3079:         }
1.553     albertel 3080: 	&delenv('user.state.'.$cid);
1.109     www      3081:     }
                   3082: }
                   3083: 
1.265     albertel 3084: sub get_scalar {
                   3085:     my ($string,$end) = @_;
                   3086:     my $value;
                   3087:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   3088: 	$value = $1;
                   3089:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   3090: 	$value = $1;
                   3091:     }
                   3092:     return &unescape($value);
                   3093: }
                   3094: 
                   3095: sub array2str {
                   3096:   my (@array) = @_;
                   3097:   my $result=&arrayref2str(\@array);
                   3098:   $result=~s/^__ARRAY_REF__//;
                   3099:   $result=~s/__END_ARRAY_REF__$//;
                   3100:   return $result;
                   3101: }
                   3102: 
1.204     albertel 3103: sub arrayref2str {
                   3104:   my ($arrayref) = @_;
1.265     albertel 3105:   my $result='__ARRAY_REF__';
1.204     albertel 3106:   foreach my $elem (@$arrayref) {
1.265     albertel 3107:     if(ref($elem) eq 'ARRAY') {
                   3108:       $result.=&arrayref2str($elem).'&';
                   3109:     } elsif(ref($elem) eq 'HASH') {
                   3110:       $result.=&hashref2str($elem).'&';
                   3111:     } elsif(ref($elem)) {
                   3112:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 3113:     } else {
                   3114:       $result.=&escape($elem).'&';
                   3115:     }
                   3116:   }
                   3117:   $result=~s/\&$//;
1.265     albertel 3118:   $result .= '__END_ARRAY_REF__';
1.204     albertel 3119:   return $result;
                   3120: }
                   3121: 
1.168     albertel 3122: sub hash2str {
1.204     albertel 3123:   my (%hash) = @_;
                   3124:   my $result=&hashref2str(\%hash);
1.265     albertel 3125:   $result=~s/^__HASH_REF__//;
                   3126:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 3127:   return $result;
                   3128: }
                   3129: 
                   3130: sub hashref2str {
                   3131:   my ($hashref)=@_;
1.265     albertel 3132:   my $result='__HASH_REF__';
1.800     albertel 3133:   foreach my $key (sort(keys(%$hashref))) {
                   3134:     if (ref($key) eq 'ARRAY') {
                   3135:       $result.=&arrayref2str($key).'=';
                   3136:     } elsif (ref($key) eq 'HASH') {
                   3137:       $result.=&hashref2str($key).'=';
                   3138:     } elsif (ref($key)) {
1.265     albertel 3139:       $result.='=';
1.800     albertel 3140:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 3141:     } else {
1.800     albertel 3142: 	if ($key) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 3143:     }
                   3144: 
1.800     albertel 3145:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   3146:       $result.=&arrayref2str($hashref->{$key}).'&';
                   3147:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   3148:       $result.=&hashref2str($hashref->{$key}).'&';
                   3149:     } elsif(ref($hashref->{$key})) {
1.265     albertel 3150:        $result.='&';
1.800     albertel 3151:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 3152:     } else {
1.800     albertel 3153:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 3154:     }
                   3155:   }
1.168     albertel 3156:   $result=~s/\&$//;
1.265     albertel 3157:   $result .= '__END_HASH_REF__';
1.168     albertel 3158:   return $result;
                   3159: }
                   3160: 
                   3161: sub str2hash {
1.265     albertel 3162:     my ($string)=@_;
                   3163:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   3164:     return %$hash;
                   3165: }
                   3166: 
                   3167: sub str2hashref {
1.168     albertel 3168:   my ($string) = @_;
1.265     albertel 3169: 
                   3170:   my %hash;
                   3171: 
                   3172:   if($string !~ /^__HASH_REF__/) {
                   3173:       if (! ($string eq '' || !defined($string))) {
                   3174: 	  $hash{'error'}='Not hash reference';
                   3175:       }
                   3176:       return (\%hash, $string);
                   3177:   }
                   3178: 
                   3179:   $string =~ s/^__HASH_REF__//;
                   3180: 
                   3181:   while($string !~ /^__END_HASH_REF__/) {
                   3182:       #key
                   3183:       my $key='';
                   3184:       if($string =~ /^__HASH_REF__/) {
                   3185:           ($key, $string)=&str2hashref($string);
                   3186:           if(defined($key->{'error'})) {
                   3187:               $hash{'error'}='Bad data';
                   3188:               return (\%hash, $string);
                   3189:           }
                   3190:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3191:           ($key, $string)=&str2arrayref($string);
                   3192:           if($key->[0] eq 'Array reference error') {
                   3193:               $hash{'error'}='Bad data';
                   3194:               return (\%hash, $string);
                   3195:           }
                   3196:       } else {
                   3197:           $string =~ s/^(.*?)=//;
1.267     albertel 3198: 	  $key=&unescape($1);
1.265     albertel 3199:       }
                   3200:       $string =~ s/^=//;
                   3201: 
                   3202:       #value
                   3203:       my $value='';
                   3204:       if($string =~ /^__HASH_REF__/) {
                   3205:           ($value, $string)=&str2hashref($string);
                   3206:           if(defined($value->{'error'})) {
                   3207:               $hash{'error'}='Bad data';
                   3208:               return (\%hash, $string);
                   3209:           }
                   3210:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3211:           ($value, $string)=&str2arrayref($string);
                   3212:           if($value->[0] eq 'Array reference error') {
                   3213:               $hash{'error'}='Bad data';
                   3214:               return (\%hash, $string);
                   3215:           }
                   3216:       } else {
                   3217: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   3218:       }
                   3219:       $string =~ s/^&//;
                   3220: 
                   3221:       $hash{$key}=$value;
1.204     albertel 3222:   }
1.265     albertel 3223: 
                   3224:   $string =~ s/^__END_HASH_REF__//;
                   3225: 
                   3226:   return (\%hash, $string);
1.204     albertel 3227: }
                   3228: 
                   3229: sub str2array {
1.265     albertel 3230:     my ($string)=@_;
                   3231:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   3232:     return @$array;
                   3233: }
                   3234: 
                   3235: sub str2arrayref {
1.204     albertel 3236:   my ($string) = @_;
1.265     albertel 3237:   my @array;
                   3238: 
                   3239:   if($string !~ /^__ARRAY_REF__/) {
                   3240:       if (! ($string eq '' || !defined($string))) {
                   3241: 	  $array[0]='Array reference error';
                   3242:       }
                   3243:       return (\@array, $string);
                   3244:   }
                   3245: 
                   3246:   $string =~ s/^__ARRAY_REF__//;
                   3247: 
                   3248:   while($string !~ /^__END_ARRAY_REF__/) {
                   3249:       my $value='';
                   3250:       if($string =~ /^__HASH_REF__/) {
                   3251:           ($value, $string)=&str2hashref($string);
                   3252:           if(defined($value->{'error'})) {
                   3253:               $array[0] ='Array reference error';
                   3254:               return (\@array, $string);
                   3255:           }
                   3256:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3257:           ($value, $string)=&str2arrayref($string);
                   3258:           if($value->[0] eq 'Array reference error') {
                   3259:               $array[0] ='Array reference error';
                   3260:               return (\@array, $string);
                   3261:           }
                   3262:       } else {
                   3263: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   3264:       }
                   3265:       $string =~ s/^&//;
                   3266: 
                   3267:       push(@array, $value);
1.191     harris41 3268:   }
1.265     albertel 3269: 
                   3270:   $string =~ s/^__END_ARRAY_REF__//;
                   3271: 
                   3272:   return (\@array, $string);
1.168     albertel 3273: }
                   3274: 
1.167     albertel 3275: # -------------------------------------------------------------------Temp Store
                   3276: 
1.168     albertel 3277: sub tmpreset {
                   3278:   my ($symb,$namespace,$domain,$stuname) = @_;
                   3279:   if (!$symb) {
                   3280:     $symb=&symbread();
1.620     albertel 3281:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3282:   }
                   3283:   $symb=escape($symb);
                   3284: 
1.620     albertel 3285:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 3286:   $namespace=~s/\//\_/g;
                   3287:   $namespace=~s/\W//g;
                   3288: 
1.620     albertel 3289:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3290:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3291:   if ($domain eq 'public' && $stuname eq 'public') {
                   3292:       $stuname=$ENV{'REMOTE_ADDR'};
                   3293:   }
1.168     albertel 3294:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3295:   my %hash;
                   3296:   if (tie(%hash,'GDBM_File',
                   3297: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3298: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 3299:     foreach my $key (keys %hash) {
1.180     albertel 3300:       if ($key=~ /:$symb/) {
1.168     albertel 3301: 	delete($hash{$key});
                   3302:       }
                   3303:     }
                   3304:   }
                   3305: }
                   3306: 
1.167     albertel 3307: sub tmpstore {
1.168     albertel 3308:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3309: 
                   3310:   if (!$symb) {
                   3311:     $symb=&symbread();
1.620     albertel 3312:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3313:   }
                   3314:   $symb=escape($symb);
                   3315: 
                   3316:   if (!$namespace) {
                   3317:     # I don't think we would ever want to store this for a course.
                   3318:     # it seems this will only be used if we don't have a course.
1.620     albertel 3319:     #$namespace=$env{'request.course.id'};
1.168     albertel 3320:     #if (!$namespace) {
1.620     albertel 3321:       $namespace=$env{'request.state'};
1.168     albertel 3322:     #}
                   3323:   }
                   3324:   $namespace=~s/\//\_/g;
                   3325:   $namespace=~s/\W//g;
1.620     albertel 3326:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3327:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3328:   if ($domain eq 'public' && $stuname eq 'public') {
                   3329:       $stuname=$ENV{'REMOTE_ADDR'};
                   3330:   }
1.168     albertel 3331:   my $now=time;
                   3332:   my %hash;
                   3333:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3334:   if (tie(%hash,'GDBM_File',
                   3335: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3336: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 3337:     $hash{"version:$symb"}++;
                   3338:     my $version=$hash{"version:$symb"};
                   3339:     my $allkeys=''; 
                   3340:     foreach my $key (keys(%$storehash)) {
                   3341:       $allkeys.=$key.':';
1.591     albertel 3342:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 3343:     }
                   3344:     $hash{"$version:$symb:timestamp"}=$now;
                   3345:     $allkeys.='timestamp';
                   3346:     $hash{"$version:keys:$symb"}=$allkeys;
                   3347:     if (untie(%hash)) {
                   3348:       return 'ok';
                   3349:     } else {
                   3350:       return "error:$!";
                   3351:     }
                   3352:   } else {
                   3353:     return "error:$!";
                   3354:   }
                   3355: }
1.167     albertel 3356: 
1.168     albertel 3357: # -----------------------------------------------------------------Temp Restore
1.167     albertel 3358: 
1.168     albertel 3359: sub tmprestore {
                   3360:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 3361: 
1.168     albertel 3362:   if (!$symb) {
                   3363:     $symb=&symbread();
1.620     albertel 3364:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3365:   }
                   3366:   $symb=escape($symb);
                   3367: 
1.620     albertel 3368:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 3369: 
1.620     albertel 3370:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3371:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3372:   if ($domain eq 'public' && $stuname eq 'public') {
                   3373:       $stuname=$ENV{'REMOTE_ADDR'};
                   3374:   }
1.168     albertel 3375:   my %returnhash;
                   3376:   $namespace=~s/\//\_/g;
                   3377:   $namespace=~s/\W//g;
                   3378:   my %hash;
                   3379:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3380:   if (tie(%hash,'GDBM_File',
                   3381: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3382: 	  &GDBM_READER(),0640)) {
1.168     albertel 3383:     my $version=$hash{"version:$symb"};
                   3384:     $returnhash{'version'}=$version;
                   3385:     my $scope;
                   3386:     for ($scope=1;$scope<=$version;$scope++) {
                   3387:       my $vkeys=$hash{"$scope:keys:$symb"};
                   3388:       my @keys=split(/:/,$vkeys);
                   3389:       my $key;
                   3390:       $returnhash{"$scope:keys"}=$vkeys;
                   3391:       foreach $key (@keys) {
1.591     albertel 3392: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   3393: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 3394:       }
                   3395:     }
1.168     albertel 3396:     if (!(untie(%hash))) {
                   3397:       return "error:$!";
                   3398:     }
                   3399:   } else {
                   3400:     return "error:$!";
                   3401:   }
                   3402:   return %returnhash;
1.167     albertel 3403: }
                   3404: 
1.9       www      3405: # ----------------------------------------------------------------------- Store
                   3406: 
                   3407: sub store {
1.124     www      3408:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3409:     my $home='';
                   3410: 
1.168     albertel 3411:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3412: 
1.213     www      3413:     $symb=&symbclean($symb);
1.122     albertel 3414:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3415: 
1.620     albertel 3416:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3417:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3418: 
                   3419:     &devalidate($symb,$stuname,$domain);
1.109     www      3420: 
                   3421:     $symb=escape($symb);
1.187     www      3422:     if (!$namespace) { 
1.620     albertel 3423:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3424:           return ''; 
                   3425:        } 
                   3426:     }
1.620     albertel 3427:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3428: 
                   3429:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3430:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   3431: 
1.12      www      3432:     my $namevalue='';
1.800     albertel 3433:     foreach my $key (keys(%$storehash)) {
                   3434:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3435:     }
1.12      www      3436:     $namevalue=~s/\&$//;
1.187     www      3437:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      3438:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      3439: }
                   3440: 
1.47      www      3441: # -------------------------------------------------------------- Critical Store
                   3442: 
                   3443: sub cstore {
1.124     www      3444:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3445:     my $home='';
                   3446: 
1.168     albertel 3447:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3448: 
1.213     www      3449:     $symb=&symbclean($symb);
1.122     albertel 3450:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3451: 
1.620     albertel 3452:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3453:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3454: 
                   3455:     &devalidate($symb,$stuname,$domain);
1.109     www      3456: 
                   3457:     $symb=escape($symb);
1.187     www      3458:     if (!$namespace) { 
1.620     albertel 3459:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3460:           return ''; 
                   3461:        } 
                   3462:     }
1.620     albertel 3463:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3464: 
                   3465:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3466:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 3467: 
1.47      www      3468:     my $namevalue='';
1.800     albertel 3469:     foreach my $key (keys(%$storehash)) {
                   3470:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3471:     }
1.47      www      3472:     $namevalue=~s/\&$//;
1.187     www      3473:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      3474:     return critical
                   3475:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      3476: }
                   3477: 
1.9       www      3478: # --------------------------------------------------------------------- Restore
                   3479: 
                   3480: sub restore {
1.124     www      3481:     my ($symb,$namespace,$domain,$stuname) = @_;
                   3482:     my $home='';
                   3483: 
1.168     albertel 3484:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3485: 
1.122     albertel 3486:     if (!$symb) {
                   3487:       unless ($symb=escape(&symbread())) { return ''; }
                   3488:     } else {
1.213     www      3489:       $symb=&escape(&symbclean($symb));
1.122     albertel 3490:     }
1.188     www      3491:     if (!$namespace) { 
1.620     albertel 3492:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      3493:           return ''; 
                   3494:        } 
                   3495:     }
1.620     albertel 3496:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3497:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   3498:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 3499:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   3500: 
1.12      www      3501:     my %returnhash=();
1.800     albertel 3502:     foreach my $line (split(/\&/,$answer)) {
                   3503: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 3504:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 3505:     }
1.75      www      3506:     my $version;
                   3507:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 3508:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   3509:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 3510:        }
1.75      www      3511:     }
1.13      www      3512:     return %returnhash;
1.34      www      3513: }
                   3514: 
                   3515: # ---------------------------------------------------------- Course Description
                   3516: 
                   3517: sub coursedescription {
1.731     albertel 3518:     my ($courseid,$args)=@_;
1.34      www      3519:     $courseid=~s/^\///;
1.49      www      3520:     $courseid=~s/\_/\//g;
1.34      www      3521:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 3522:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 3523:     my $normalid=$cdomain.'_'.$cnum;
                   3524:     # need to always cache even if we get errors otherwise we keep 
                   3525:     # trying and trying and trying to get the course description.
                   3526:     my %envhash=();
                   3527:     my %returnhash=();
1.731     albertel 3528:     
                   3529:     my $expiretime=600;
                   3530:     if ($env{'request.course.id'} eq $normalid) {
                   3531: 	$expiretime=120;
                   3532:     }
                   3533: 
                   3534:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   3535:     if (!$args->{'freshen_cache'}
                   3536: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   3537: 	foreach my $key (keys(%env)) {
                   3538: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   3539: 	    my ($setting) = $1;
                   3540: 	    $returnhash{$setting} = $env{$key};
                   3541: 	}
                   3542: 	return %returnhash;
                   3543:     }
                   3544: 
                   3545:     # get the data agin
                   3546:     if (!$args->{'one_time'}) {
                   3547: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   3548:     }
1.811     albertel 3549: 
1.34      www      3550:     if ($chome ne 'no_host') {
1.302     albertel 3551:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 3552:        if (!exists($returnhash{'con_lost'})) {
                   3553:            $returnhash{'home'}= $chome;
                   3554: 	   $returnhash{'domain'} = $cdomain;
                   3555: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  3556:            if (!defined($returnhash{'type'})) {
                   3557:                $returnhash{'type'} = 'Course';
                   3558:            }
1.130     albertel 3559:            while (my ($name,$value) = each %returnhash) {
1.53      www      3560:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 3561:            }
1.270     www      3562:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      3563:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 3564: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      3565:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   3566:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   3567:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      3568:        }
                   3569:     }
1.731     albertel 3570:     if (!$args->{'one_time'}) {
1.949     raeburn  3571: 	&appenv(\%envhash);
1.731     albertel 3572:     }
1.302     albertel 3573:     return %returnhash;
1.461     www      3574: }
                   3575: 
                   3576: # -------------------------------------------------See if a user is privileged
                   3577: 
                   3578: sub privileged {
                   3579:     my ($username,$domain)=@_;
                   3580:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   3581: 			&homeserver($username,$domain));
                   3582:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
                   3583:     my $now=time;
                   3584:     if ($rolesdump ne '') {
1.800     albertel 3585:         foreach my $entry (split(/&/,$rolesdump)) {
                   3586: 	    if ($entry!~/^rolesdef_/) {
                   3587: 		my ($area,$role)=split(/=/,$entry);
1.461     www      3588: 		$area=~s/\_\w\w$//;
                   3589: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   3590: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   3591: 		    my $active=1;
                   3592: 		    if ($tend) {
                   3593: 			if ($tend<$now) { $active=0; }
                   3594: 		    }
                   3595: 		    if ($tstart) {
                   3596: 			if ($tstart>$now) { $active=0; }
                   3597: 		    }
                   3598: 		    if ($active) { return 1; }
                   3599: 		}
                   3600: 	    }
                   3601: 	}
                   3602:     }
                   3603:     return 0;
1.9       www      3604: }
1.1       albertel 3605: 
1.103     harris41 3606: # -------------------------------------------------------- Get user privileges
1.11      www      3607: 
                   3608: sub rolesinit {
                   3609:     my ($domain,$username,$authhost)=@_;
1.966     raeburn  3610:     my %userroles;
1.11      www      3611:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.966     raeburn  3612:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return \%userroles; }
1.11      www      3613:     my %allroles=();
1.678     raeburn  3614:     my %allgroups=();   
1.11      www      3615:     my $now=time;
1.966     raeburn  3616:     %userroles = ('user.login.time' => $now);
1.678     raeburn  3617:     my $group_privs;
1.11      www      3618: 
                   3619:     if ($rolesdump ne '') {
1.800     albertel 3620:         foreach my $entry (split(/&/,$rolesdump)) {
                   3621: 	  if ($entry!~/^rolesdef_/) {
                   3622:             my ($area,$role)=split(/=/,$entry);
1.587     albertel 3623: 	    $area=~s/\_\w\w$//;
1.678     raeburn  3624:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 3625: 	    if ($role=~/^cr/) { 
1.807     albertel 3626: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   3627: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655     albertel 3628: 		    ($tend,$tstart)=split('_',$trest);
                   3629: 		} else {
                   3630: 		    $trole=$role;
                   3631: 		}
1.678     raeburn  3632:             } elsif ($role =~ m|^gr/|) {
                   3633:                 ($trole,$tend,$tstart) = split(/_/,$role);
                   3634:                 ($trole,$group_privs) = split(/\//,$trole);
                   3635:                 $group_privs = &unescape($group_privs);
1.587     albertel 3636: 	    } else {
                   3637: 		($trole,$tend,$tstart)=split(/_/,$role);
                   3638: 	    }
1.743     albertel 3639: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   3640: 					 $username);
                   3641: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  3642:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   3643:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      3644:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 3645: 		my $spec=$trole.'.'.$area;
                   3646: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   3647: 		if ($trole =~ /^cr\//) {
1.567     raeburn  3648:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  3649:                 } elsif ($trole eq 'gr') {
                   3650:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 3651: 		} else {
1.567     raeburn  3652:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 3653: 		}
1.12      www      3654:             }
1.662     raeburn  3655:           }
1.191     harris41 3656:         }
1.743     albertel 3657:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   3658:         $userroles{'user.adv'}    = $adv;
                   3659: 	$userroles{'user.author'} = $author;
1.620     albertel 3660:         $env{'user.adv'}=$adv;
1.11      www      3661:     }
1.743     albertel 3662:     return \%userroles;  
1.11      www      3663: }
                   3664: 
1.567     raeburn  3665: sub set_arearole {
                   3666:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   3667: # log the associated role with the area
                   3668:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 3669:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  3670: }
                   3671: 
                   3672: sub custom_roleprivs {
                   3673:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   3674:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   3675:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 3676:     if (&hostname($homsvr) ne '') {
1.567     raeburn  3677:         my ($rdummy,$roledef)=
                   3678:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   3679:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   3680:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   3681:             if (defined($syspriv)) {
                   3682:                 $$allroles{'cm./'}.=':'.$syspriv;
                   3683:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   3684:             }
                   3685:             if ($tdomain ne '') {
                   3686:                 if (defined($dompriv)) {
                   3687:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   3688:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   3689:                 }
                   3690:                 if (($trest ne '') && (defined($coursepriv))) {
                   3691:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   3692:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   3693:                 }
                   3694:             }
                   3695:         }
                   3696:     }
                   3697: }
                   3698: 
1.678     raeburn  3699: sub group_roleprivs {
                   3700:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   3701:     my $access = 1;
                   3702:     my $now = time;
                   3703:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   3704:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   3705:     if ($access) {
1.811     albertel 3706:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  3707:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   3708:     }
                   3709: }
1.567     raeburn  3710: 
                   3711: sub standard_roleprivs {
                   3712:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   3713:     if (defined($pr{$trole.':s'})) {
                   3714:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   3715:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   3716:     }
                   3717:     if ($tdomain ne '') {
                   3718:         if (defined($pr{$trole.':d'})) {
                   3719:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3720:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3721:         }
                   3722:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   3723:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   3724:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   3725:         }
                   3726:     }
                   3727: }
                   3728: 
                   3729: sub set_userprivs {
1.678     raeburn  3730:     my ($userroles,$allroles,$allgroups) = @_; 
1.567     raeburn  3731:     my $author=0;
                   3732:     my $adv=0;
1.678     raeburn  3733:     my %grouproles = ();
                   3734:     if (keys(%{$allgroups}) > 0) {
                   3735:         foreach my $role (keys %{$allroles}) {
1.681     raeburn  3736:             my ($trole,$area,$sec,$extendedarea);
1.881     raeburn  3737:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
1.678     raeburn  3738:                 $trole = $1;
                   3739:                 $area = $2;
1.681     raeburn  3740:                 $sec = $3;
                   3741:                 $extendedarea = $area.$sec;
                   3742:                 if (exists($$allgroups{$area})) {
                   3743:                     foreach my $group (keys(%{$$allgroups{$area}})) {
                   3744:                         my $spec = $trole.'.'.$extendedarea;
                   3745:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
                   3746:                                                 $$allgroups{$area}{$group};
1.678     raeburn  3747:                     }
                   3748:                 }
                   3749:             }
                   3750:         }
                   3751:     }
1.800     albertel 3752:     foreach my $group (keys(%grouproles)) {
                   3753:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  3754:     }
1.800     albertel 3755:     foreach my $role (keys(%{$allroles})) {
                   3756:         my %thesepriv;
1.941     raeburn  3757:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 3758:         foreach my $item (split(/:/,$$allroles{$role})) {
                   3759:             if ($item ne '') {
                   3760:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  3761:                 if ($restrictions eq '') {
                   3762:                     $thesepriv{$privilege}='F';
                   3763:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   3764:                     $thesepriv{$privilege}.=$restrictions;
                   3765:                 }
                   3766:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   3767:             }
                   3768:         }
                   3769:         my $thesestr='';
1.800     albertel 3770:         foreach my $priv (keys(%thesepriv)) {
                   3771: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   3772: 	}
                   3773:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  3774:     }
                   3775:     return ($author,$adv);
                   3776: }
                   3777: 
1.12      www      3778: # --------------------------------------------------------------- get interface
                   3779: 
                   3780: sub get {
1.131     albertel 3781:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3782:    my $items='';
1.800     albertel 3783:    foreach my $item (@$storearr) {
                   3784:        $items.=&escape($item).'&';
1.191     harris41 3785:    }
1.12      www      3786:    $items=~s/\&$//;
1.620     albertel 3787:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3788:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 3789:    my $uhome=&homeserver($uname,$udomain);
                   3790: 
1.133     albertel 3791:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3792:    my @pairs=split(/\&/,$rep);
1.273     albertel 3793:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   3794:      return @pairs;
                   3795:    }
1.15      www      3796:    my %returnhash=();
1.42      www      3797:    my $i=0;
1.800     albertel 3798:    foreach my $item (@$storearr) {
                   3799:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      3800:       $i++;
1.191     harris41 3801:    }
1.15      www      3802:    return %returnhash;
1.27      www      3803: }
                   3804: 
                   3805: # --------------------------------------------------------------- del interface
                   3806: 
                   3807: sub del {
1.133     albertel 3808:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      3809:    my $items='';
1.800     albertel 3810:    foreach my $item (@$storearr) {
                   3811:        $items.=&escape($item).'&';
1.191     harris41 3812:    }
1.27      www      3813:    $items=~s/\&$//;
1.620     albertel 3814:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3815:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3816:    my $uhome=&homeserver($uname,$udomain);
                   3817: 
                   3818:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3819: }
                   3820: 
                   3821: # -------------------------------------------------------------- dump interface
                   3822: 
                   3823: sub dump {
1.755     albertel 3824:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   3825:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3826:     if (!$uname) { $uname=$env{'user.name'}; }
                   3827:     my $uhome=&homeserver($uname,$udomain);
                   3828:     if ($regexp) {
                   3829: 	$regexp=&escape($regexp);
                   3830:     } else {
                   3831: 	$regexp='.';
                   3832:     }
                   3833:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3834:     my @pairs=split(/\&/,$rep);
                   3835:     my %returnhash=();
                   3836:     foreach my $item (@pairs) {
                   3837: 	my ($key,$value)=split(/=/,$item,2);
                   3838: 	$key = &unescape($key);
                   3839: 	next if ($key =~ /^error: 2 /);
                   3840: 	$returnhash{$key}=&thaw_unescape($value);
                   3841:     }
                   3842:     return %returnhash;
1.407     www      3843: }
                   3844: 
1.717     albertel 3845: # --------------------------------------------------------- dumpstore interface
                   3846: 
                   3847: sub dumpstore {
                   3848:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822     albertel 3849:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3850:    if (!$uname) { $uname=$env{'user.name'}; }
                   3851:    my $uhome=&homeserver($uname,$udomain);
                   3852:    if ($regexp) {
                   3853:        $regexp=&escape($regexp);
                   3854:    } else {
                   3855:        $regexp='.';
                   3856:    }
                   3857:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3858:    my @pairs=split(/\&/,$rep);
                   3859:    my %returnhash=();
                   3860:    foreach my $item (@pairs) {
                   3861:        my ($key,$value)=split(/=/,$item,2);
                   3862:        next if ($key =~ /^error: 2 /);
                   3863:        $returnhash{$key}=&thaw_unescape($value);
                   3864:    }
                   3865:    return %returnhash;
1.717     albertel 3866: }
                   3867: 
1.407     www      3868: # -------------------------------------------------------------- keys interface
                   3869: 
                   3870: sub getkeys {
                   3871:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 3872:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3873:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      3874:    my $uhome=&homeserver($uname,$udomain);
                   3875:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   3876:    my @keyarray=();
1.800     albertel 3877:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  3878:       next if ($key =~ /^error: 2 /);
1.800     albertel 3879:       push(@keyarray,&unescape($key));
1.407     www      3880:    }
                   3881:    return @keyarray;
1.318     matthew  3882: }
                   3883: 
1.319     matthew  3884: # --------------------------------------------------------------- currentdump
                   3885: sub currentdump {
1.328     matthew  3886:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 3887:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   3888:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   3889:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  3890:    my $uhome = &homeserver($sname,$sdom);
                   3891:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  3892:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  3893:    #
1.318     matthew  3894:    my %returnhash=();
1.319     matthew  3895:    #
                   3896:    if ($rep eq "unknown_cmd") { 
                   3897:        # an old lond will not know currentdump
                   3898:        # Do a dump and make it look like a currentdump
1.822     albertel 3899:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  3900:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   3901:        my %hash = @tmp;
                   3902:        @tmp=();
1.424     matthew  3903:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  3904:    } else {
                   3905:        my @pairs=split(/\&/,$rep);
1.800     albertel 3906:        foreach my $pair (@pairs) {
                   3907:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  3908:            my ($symb,$param) = split(/:/,$key);
                   3909:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 3910:                                                         &thaw_unescape($value);
1.319     matthew  3911:        }
1.191     harris41 3912:    }
1.12      www      3913:    return %returnhash;
1.424     matthew  3914: }
                   3915: 
                   3916: sub convert_dump_to_currentdump{
                   3917:     my %hash = %{shift()};
                   3918:     my %returnhash;
                   3919:     # Code ripped from lond, essentially.  The only difference
                   3920:     # here is the unescaping done by lonnet::dump().  Conceivably
                   3921:     # we might run in to problems with parameter names =~ /^v\./
                   3922:     while (my ($key,$value) = each(%hash)) {
                   3923:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 3924: 	$symb  = &unescape($symb);
                   3925: 	$param = &unescape($param);
1.424     matthew  3926:         next if ($v eq 'version' || $symb eq 'keys');
                   3927:         next if (exists($returnhash{$symb}) &&
                   3928:                  exists($returnhash{$symb}->{$param}) &&
                   3929:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   3930:         $returnhash{$symb}->{$param}=$value;
                   3931:         $returnhash{$symb}->{'v.'.$param}=$v;
                   3932:     }
                   3933:     #
                   3934:     # Remove all of the keys in the hashes which keep track of
                   3935:     # the version of the parameter.
                   3936:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   3937:         # use a foreach because we are going to delete from the hash.
                   3938:         foreach my $key (keys(%$param_hash)) {
                   3939:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   3940:         }
                   3941:     }
                   3942:     return \%returnhash;
1.12      www      3943: }
                   3944: 
1.627     albertel 3945: # ------------------------------------------------------ critical inc interface
                   3946: 
                   3947: sub cinc {
                   3948:     return &inc(@_,'critical');
                   3949: }
                   3950: 
1.449     matthew  3951: # --------------------------------------------------------------- inc interface
                   3952: 
                   3953: sub inc {
1.627     albertel 3954:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 3955:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3956:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  3957:     my $uhome=&homeserver($uname,$udomain);
                   3958:     my $items='';
                   3959:     if (! ref($store)) {
                   3960:         # got a single value, so use that instead
                   3961:         $items = &escape($store).'=&';
                   3962:     } elsif (ref($store) eq 'SCALAR') {
                   3963:         $items = &escape($$store).'=&';        
                   3964:     } elsif (ref($store) eq 'ARRAY') {
                   3965:         $items = join('=&',map {&escape($_);} @{$store});
                   3966:     } elsif (ref($store) eq 'HASH') {
                   3967:         while (my($key,$value) = each(%{$store})) {
                   3968:             $items.= &escape($key).'='.&escape($value).'&';
                   3969:         }
                   3970:     }
                   3971:     $items=~s/\&$//;
1.627     albertel 3972:     if ($critical) {
                   3973: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3974:     } else {
                   3975: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3976:     }
1.449     matthew  3977: }
                   3978: 
1.12      www      3979: # --------------------------------------------------------------- put interface
                   3980: 
                   3981: sub put {
1.134     albertel 3982:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3983:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3984:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3985:    my $uhome=&homeserver($uname,$udomain);
1.12      www      3986:    my $items='';
1.800     albertel 3987:    foreach my $item (keys(%$storehash)) {
                   3988:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 3989:    }
1.12      www      3990:    $items=~s/\&$//;
1.134     albertel 3991:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      3992: }
                   3993: 
1.631     albertel 3994: # ------------------------------------------------------------ newput interface
                   3995: 
                   3996: sub newput {
                   3997:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   3998:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3999:    if (!$uname) { $uname=$env{'user.name'}; }
                   4000:    my $uhome=&homeserver($uname,$udomain);
                   4001:    my $items='';
                   4002:    foreach my $key (keys(%$storehash)) {
                   4003:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   4004:    }
                   4005:    $items=~s/\&$//;
                   4006:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   4007: }
                   4008: 
                   4009: # ---------------------------------------------------------  putstore interface
                   4010: 
1.524     raeburn  4011: sub putstore {
1.715     albertel 4012:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 4013:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4014:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  4015:    my $uhome=&homeserver($uname,$udomain);
                   4016:    my $items='';
1.715     albertel 4017:    foreach my $key (keys(%$storehash)) {
                   4018:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  4019:    }
1.715     albertel 4020:    $items=~s/\&$//;
1.716     albertel 4021:    my $esc_symb=&escape($symb);
                   4022:    my $esc_v=&escape($version);
1.715     albertel 4023:    my $reply =
1.716     albertel 4024:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 4025: 	      $uhome);
                   4026:    if ($reply eq 'unknown_cmd') {
1.716     albertel 4027:        # gfall back to way things use to be done
1.715     albertel 4028:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   4029: 			    $uname);
1.524     raeburn  4030:    }
1.715     albertel 4031:    return $reply;
                   4032: }
                   4033: 
                   4034: sub old_putstore {
1.716     albertel 4035:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   4036:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4037:     if (!$uname) { $uname=$env{'user.name'}; }
                   4038:     my $uhome=&homeserver($uname,$udomain);
                   4039:     my %newstorehash;
1.800     albertel 4040:     foreach my $item (keys(%$storehash)) {
                   4041: 	my $key = $version.':'.&escape($symb).':'.$item;
                   4042: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 4043:     }
                   4044:     my $items='';
                   4045:     my %allitems = ();
1.800     albertel 4046:     foreach my $item (keys(%newstorehash)) {
                   4047: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 4048: 	    my $key = $1.':keys:'.$2;
                   4049: 	    $allitems{$key} .= $3.':';
                   4050: 	}
1.800     albertel 4051: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 4052:     }
1.800     albertel 4053:     foreach my $item (keys(%allitems)) {
                   4054: 	$allitems{$item} =~ s/\:$//;
                   4055: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 4056:     }
                   4057:     $items=~s/\&$//;
                   4058:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  4059: }
                   4060: 
1.47      www      4061: # ------------------------------------------------------ critical put interface
                   4062: 
                   4063: sub cput {
1.134     albertel 4064:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 4065:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4066:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 4067:    my $uhome=&homeserver($uname,$udomain);
1.47      www      4068:    my $items='';
1.800     albertel 4069:    foreach my $item (keys(%$storehash)) {
                   4070:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 4071:    }
1.47      www      4072:    $items=~s/\&$//;
1.134     albertel 4073:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      4074: }
                   4075: 
                   4076: # -------------------------------------------------------------- eget interface
                   4077: 
                   4078: sub eget {
1.133     albertel 4079:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      4080:    my $items='';
1.800     albertel 4081:    foreach my $item (@$storearr) {
                   4082:        $items.=&escape($item).'&';
1.191     harris41 4083:    }
1.12      www      4084:    $items=~s/\&$//;
1.620     albertel 4085:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4086:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 4087:    my $uhome=&homeserver($uname,$udomain);
                   4088:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      4089:    my @pairs=split(/\&/,$rep);
                   4090:    my %returnhash=();
1.42      www      4091:    my $i=0;
1.800     albertel 4092:    foreach my $item (@$storearr) {
                   4093:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      4094:       $i++;
1.191     harris41 4095:    }
1.12      www      4096:    return %returnhash;
                   4097: }
                   4098: 
1.667     albertel 4099: # ------------------------------------------------------------ tmpput interface
                   4100: sub tmpput {
1.802     raeburn  4101:     my ($storehash,$server,$context)=@_;
1.667     albertel 4102:     my $items='';
1.800     albertel 4103:     foreach my $item (keys(%$storehash)) {
                   4104: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 4105:     }
                   4106:     $items=~s/\&$//;
1.802     raeburn  4107:     if (defined($context)) {
                   4108:         $items .= ':'.&escape($context);
                   4109:     }
1.667     albertel 4110:     return &reply("tmpput:$items",$server);
                   4111: }
                   4112: 
                   4113: # ------------------------------------------------------------ tmpget interface
                   4114: sub tmpget {
1.688     albertel 4115:     my ($token,$server)=@_;
                   4116:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   4117:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 4118:     my %returnhash;
                   4119:     foreach my $item (split(/\&/,$rep)) {
                   4120: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  4121:         next if ($key =~ /^error: 2 /);
1.667     albertel 4122: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   4123:     }
                   4124:     return %returnhash;
                   4125: }
                   4126: 
1.688     albertel 4127: # ------------------------------------------------------------ tmpget interface
                   4128: sub tmpdel {
                   4129:     my ($token,$server)=@_;
                   4130:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   4131:     return &reply("tmpdel:$token",$server);
                   4132: }
                   4133: 
1.765     albertel 4134: # -------------------------------------------------- portfolio access checking
                   4135: 
                   4136: sub portfolio_access {
1.766     albertel 4137:     my ($requrl) = @_;
1.765     albertel 4138:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   4139:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  4140:     if ($result) {
                   4141:         my %setters;
                   4142:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4143:             my ($startblock,$endblock) =
                   4144:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   4145:             if ($startblock && $endblock) {
                   4146:                 return 'B';
                   4147:             }
                   4148:         } else {
                   4149:             my ($startblock,$endblock) =
                   4150:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   4151:             if ($startblock && $endblock) {
                   4152:                 return 'B';
                   4153:             }
                   4154:         }
                   4155:     }
1.765     albertel 4156:     if ($result eq 'ok') {
1.766     albertel 4157:        return 'F';
1.765     albertel 4158:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 4159:        return 'A';
1.765     albertel 4160:     }
1.766     albertel 4161:     return '';
1.765     albertel 4162: }
                   4163: 
                   4164: sub get_portfolio_access {
1.767     albertel 4165:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   4166: 
                   4167:     if (!ref($access_hash)) {
                   4168: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   4169: 	my %access_controls = &get_access_controls($current_perms,$group,
                   4170: 						   $file_name);
                   4171: 	$access_hash = $access_controls{$file_name};
                   4172:     }
                   4173: 
1.765     albertel 4174:     my ($public,$guest,@domains,@users,@courses,@groups);
                   4175:     my $now = time;
                   4176:     if (ref($access_hash) eq 'HASH') {
                   4177:         foreach my $key (keys(%{$access_hash})) {
                   4178:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   4179:             if ($start > $now) {
                   4180:                 next;
                   4181:             }
                   4182:             if ($end && $end<$now) {
                   4183:                 next;
                   4184:             }
                   4185:             if ($scope eq 'public') {
                   4186:                 $public = $key;
                   4187:                 last;
                   4188:             } elsif ($scope eq 'guest') {
                   4189:                 $guest = $key;
                   4190:             } elsif ($scope eq 'domains') {
                   4191:                 push(@domains,$key);
                   4192:             } elsif ($scope eq 'users') {
                   4193:                 push(@users,$key);
                   4194:             } elsif ($scope eq 'course') {
                   4195:                 push(@courses,$key);
                   4196:             } elsif ($scope eq 'group') {
                   4197:                 push(@groups,$key);
                   4198:             }
                   4199:         }
                   4200:         if ($public) {
                   4201:             return 'ok';
                   4202:         }
                   4203:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4204:             if ($guest) {
                   4205:                 return $guest;
                   4206:             }
                   4207:         } else {
                   4208:             if (@domains > 0) {
                   4209:                 foreach my $domkey (@domains) {
                   4210:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   4211:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   4212:                             return 'ok';
                   4213:                         }
                   4214:                     }
                   4215:                 }
                   4216:             }
                   4217:             if (@users > 0) {
                   4218:                 foreach my $userkey (@users) {
1.865     raeburn  4219:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   4220:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   4221:                             if (ref($item) eq 'HASH') {
                   4222:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   4223:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   4224:                                     return 'ok';
                   4225:                                 }
                   4226:                             }
                   4227:                         }
                   4228:                     } 
1.765     albertel 4229:                 }
                   4230:             }
                   4231:             my %roleshash;
                   4232:             my @courses_and_groups = @courses;
                   4233:             push(@courses_and_groups,@groups); 
                   4234:             if (@courses_and_groups > 0) {
                   4235:                 my (%allgroups,%allroles); 
                   4236:                 my ($start,$end,$role,$sec,$group);
                   4237:                 foreach my $envkey (%env) {
1.811     albertel 4238:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 4239:                         my $cid = $2.'_'.$3; 
                   4240:                         if ($1 eq 'gr') {
                   4241:                             $group = $4;
                   4242:                             $allgroups{$cid}{$group} = $env{$envkey};
                   4243:                         } else {
                   4244:                             if ($4 eq '') {
                   4245:                                 $sec = 'none';
                   4246:                             } else {
                   4247:                                 $sec = $4;
                   4248:                             }
                   4249:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   4250:                         }
1.811     albertel 4251:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 4252:                         my $cid = $2.'_'.$3;
                   4253:                         if ($4 eq '') {
                   4254:                             $sec = 'none';
                   4255:                         } else {
                   4256:                             $sec = $4;
                   4257:                         }
                   4258:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   4259:                     }
                   4260:                 }
                   4261:                 if (keys(%allroles) == 0) {
                   4262:                     return;
                   4263:                 }
                   4264:                 foreach my $key (@courses_and_groups) {
                   4265:                     my %content = %{$$access_hash{$key}};
                   4266:                     my $cnum = $content{'number'};
                   4267:                     my $cdom = $content{'domain'};
                   4268:                     my $cid = $cdom.'_'.$cnum;
                   4269:                     if (!exists($allroles{$cid})) {
                   4270:                         next;
                   4271:                     }    
                   4272:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   4273:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   4274:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   4275:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   4276:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   4277:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   4278:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   4279:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   4280:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   4281:                                         if (grep/^all$/,@sections) {
                   4282:                                             return 'ok';
                   4283:                                         } else {
                   4284:                                             if (grep/^$sec$/,@sections) {
                   4285:                                                 return 'ok';
                   4286:                                             }
                   4287:                                         }
                   4288:                                     }
                   4289:                                 }
                   4290:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   4291:                                     if (grep/^none$/,@groups) {
                   4292:                                         return 'ok';
                   4293:                                     }
                   4294:                                 } else {
                   4295:                                     if (grep/^all$/,@groups) {
                   4296:                                         return 'ok';
                   4297:                                     } 
                   4298:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   4299:                                         if (grep/^$group$/,@groups) {
                   4300:                                             return 'ok';
                   4301:                                         }
                   4302:                                     }
                   4303:                                 } 
                   4304:                             }
                   4305:                         }
                   4306:                     }
                   4307:                 }
                   4308:             }
                   4309:             if ($guest) {
                   4310:                 return $guest;
                   4311:             }
                   4312:         }
                   4313:     }
                   4314:     return;
                   4315: }
                   4316: 
                   4317: sub course_group_datechecker {
                   4318:     my ($dates,$now,$status) = @_;
                   4319:     my ($start,$end) = split(/\./,$dates);
                   4320:     if (!$start && !$end) {
                   4321:         return 'ok';
                   4322:     }
                   4323:     if (grep/^active$/,@{$status}) {
                   4324:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   4325:             return 'ok';
                   4326:         }
                   4327:     }
                   4328:     if (grep/^previous$/,@{$status}) {
                   4329:         if ($end > $now ) {
                   4330:             return 'ok';
                   4331:         }
                   4332:     }
                   4333:     if (grep/^future$/,@{$status}) {
                   4334:         if ($start > $now) {
                   4335:             return 'ok';
                   4336:         }
                   4337:     }
                   4338:     return; 
                   4339: }
                   4340: 
                   4341: sub parse_portfolio_url {
                   4342:     my ($url) = @_;
                   4343: 
                   4344:     my ($type,$udom,$unum,$group,$file_name);
                   4345:     
1.823     albertel 4346:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 4347: 	$type = 1;
                   4348:         $udom = $1;
                   4349:         $unum = $2;
                   4350:         $file_name = $3;
1.823     albertel 4351:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 4352: 	$type = 2;
                   4353:         $udom = $1;
                   4354:         $unum = $2;
                   4355:         $group = $3;
                   4356:         $file_name = $3.'/'.$4;
                   4357:     }
                   4358:     if (wantarray) {
                   4359: 	return ($type,$udom,$unum,$file_name,$group);
                   4360:     }
                   4361:     return $type;
                   4362: }
                   4363: 
                   4364: sub is_portfolio_url {
                   4365:     my ($url) = @_;
                   4366:     return scalar(&parse_portfolio_url($url));
                   4367: }
                   4368: 
1.798     raeburn  4369: sub is_portfolio_file {
                   4370:     my ($file) = @_;
1.820     raeburn  4371:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  4372:         return 1;
                   4373:     }
                   4374:     return;
                   4375: }
                   4376: 
1.976   ! raeburn  4377: sub usertools_access {
        !          4378:     my ($uname,$udom,$tool) = @_;
        !          4379:     my $access;
        !          4380:     my %tools = (
        !          4381:                   aboutme   => 1,
        !          4382:                   blog      => 1,
        !          4383:                   portfolio => 1,
        !          4384:                 );
        !          4385:     return if (!defined($tools{$tool}));
        !          4386: 
        !          4387:     if ((!defined($udom)) || (!defined($uname))) {
        !          4388:         $udom = $env{'user.domain'};
        !          4389:         $uname = $env{'user.name'};
        !          4390:     }
        !          4391: 
        !          4392:     my $hashid=$uname.':'.$udom;
        !          4393:     my ($result,$cached) = &is_cached_new('usertools.'.$tool,$hashid);
        !          4394:     if (defined($cached)) {
        !          4395:         return $result;
        !          4396:     }
        !          4397: 
        !          4398:     my ($toolstatus,$inststatus);
        !          4399: 
        !          4400:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
        !          4401:         $toolstatus = $env{'environment.tools.'.$tool};
        !          4402:         $inststatus = $env{'environment.inststatus'};
        !          4403:     } else {
        !          4404:         my %userenv = &userenvironment($udom,$uname,'tools.'.$tool);
        !          4405:         $toolstatus = $userenv{'tools.'.$tool};
        !          4406:         $inststatus = $userenv{'inststatus'};
        !          4407:     }
        !          4408: 
        !          4409:     if ($toolstatus ne '') {
        !          4410:         if ($toolstatus) {
        !          4411:             $access = 1;
        !          4412:         } else {
        !          4413:             $access = 0;
        !          4414:         }
        !          4415:         &do_cache_new('usertools.'.$tool,$hashid,$access,600);
        !          4416:         return $access;
        !          4417:     }
        !          4418: 
        !          4419:     my $is_adv = &is_advanced_user($udom,$uname);
        !          4420:     my %domdef = &get_domain_defaults($udom);
        !          4421:     if (ref($domdef{$tool}) eq 'HASH') {
        !          4422:         if ($is_adv) {
        !          4423:             if ($domdef{$tool}{'_LC_adv'} ne '') {
        !          4424:                 if ($domdef{$tool}{'_LC_adv'}) { 
        !          4425:                     $access = 1;
        !          4426:                 } else {
        !          4427:                     $access = 0;
        !          4428:                 }
        !          4429:                 &do_cache_new('usertools.'.$tool,$hashid,$access,600);
        !          4430:                 return $access;
        !          4431:             }
        !          4432:         }
        !          4433:         if ($inststatus ne '') {
        !          4434:             my ($hasaccess,$hasnoaccess);
        !          4435:             foreach my $affiliation (split(/:/,$inststatus)) {
        !          4436:                 if ($domdef{$tool}{$affiliation} ne '') { 
        !          4437:                     if ($domdef{$tool}{$affiliation}) {
        !          4438:                         $hasaccess = 1;
        !          4439:                     } else {
        !          4440:                         $hasnoaccess = 1;
        !          4441:                     }
        !          4442:                 }
        !          4443:             }
        !          4444:             if ($hasaccess || $hasnoaccess) {
        !          4445:                 if ($hasaccess) {
        !          4446:                     $access = 1;
        !          4447:                 } elsif ($hasnoaccess) {
        !          4448:                     $access = 0; 
        !          4449:                 }
        !          4450:                 &do_cache_new('usertools.'.$tool,$hashid,$access,600);
        !          4451:                 return $access;
        !          4452:             }
        !          4453:         } else {
        !          4454:             if ($domdef{$tool}{'default'} ne '') {
        !          4455:                 if ($domdef{$tool}{'default'}) {
        !          4456:                     $access = 1;
        !          4457:                 } elsif ($domdef{$tool}{'default'} == 0) {
        !          4458:                     $access = 0;
        !          4459:                 }
        !          4460:                 &do_cache_new('usertools.'.$tool,$hashid,$access,600);
        !          4461:                 return $access;
        !          4462:             }
        !          4463:         }
        !          4464:     } else {
        !          4465:         $access = 1;
        !          4466:         &do_cache_new('usertools.'.$tool,$hashid,$access,600);
        !          4467:         return $access;
        !          4468:     }
        !          4469: }
        !          4470: 
        !          4471: sub is_advanced_user {
        !          4472:     my ($udom,$uname) = @_;
        !          4473:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
        !          4474:     my %allroles;
        !          4475:     my $is_adv;
        !          4476:     foreach my $role (keys(%roleshash)) {
        !          4477:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
        !          4478:         my $area = '/'.$tdomain.'/'.$trest;
        !          4479:         if ($sec ne '') {
        !          4480:             $area .= '/'.$sec;
        !          4481:         }
        !          4482:         if (($area ne '') && ($trole ne '')) {
        !          4483:             my $spec=$trole.'.'.$area;
        !          4484:             if ($trole =~ /^cr\//) {
        !          4485:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
        !          4486:             } elsif ($trole ne 'gr') {
        !          4487:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
        !          4488:             }
        !          4489:         }
        !          4490:     }
        !          4491:     foreach my $role (keys(%allroles)) {
        !          4492:         last if ($is_adv);
        !          4493:         foreach my $item (split(/:/,$allroles{$role})) {
        !          4494:             if ($item ne '') {
        !          4495:                 my ($privilege,$restrictions)=split(/&/,$item);
        !          4496:                 if ($privilege eq 'adv') {
        !          4497:                     $is_adv = 1;
        !          4498:                     last;
        !          4499:                 }
        !          4500:             }
        !          4501:         }
        !          4502:     }
        !          4503:     return $is_adv;
        !          4504: }
1.798     raeburn  4505: 
1.341     www      4506: # ---------------------------------------------- Custom access rule evaluation
                   4507: 
                   4508: sub customaccess {
                   4509:     my ($priv,$uri)=@_;
1.807     albertel 4510:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      4511:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 4512:     $udom = &LONCAPA::clean_domain($udom);
                   4513:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      4514:     my $access=0;
1.800     albertel 4515:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 4516: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   4517: 	if ($type eq 'user') {
                   4518: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 4519: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 4520: 		if ($tdom) {
                   4521: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   4522: 		}
1.896     albertel 4523: 		if ($tuname) {
                   4524: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 4525: 		}
                   4526: 		$access=($effect eq 'allow');
                   4527: 		last;
                   4528: 	    }
                   4529: 	} else {
                   4530: 	    if ($role) {
                   4531: 		if ($role ne $urole) { next; }
                   4532: 	    }
                   4533: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   4534: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   4535: 		if ($tdom) {
                   4536: 		    if ($tdom ne $udom) { next; }
                   4537: 		}
                   4538: 		if ($tcrs) {
                   4539: 		    if ($tcrs ne $ucrs) { next; }
                   4540: 		}
                   4541: 		if ($tsec) {
                   4542: 		    if ($tsec ne $usec) { next; }
                   4543: 		}
                   4544: 		$access=($effect eq 'allow');
                   4545: 		last;
                   4546: 	    }
                   4547: 	    if ($realm eq '' && $role eq '') {
                   4548: 		$access=($effect eq 'allow');
                   4549: 	    }
1.402     bowersj2 4550: 	}
1.341     www      4551:     }
                   4552:     return $access;
                   4553: }
                   4554: 
1.103     harris41 4555: # ------------------------------------------------- Check for a user privilege
1.12      www      4556: 
                   4557: sub allowed {
1.810     raeburn  4558:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 4559:     my $ver_orguri=$uri;
1.439     www      4560:     $uri=&deversion($uri);
1.152     www      4561:     my $orguri=$uri;
1.52      www      4562:     $uri=&declutter($uri);
1.809     raeburn  4563: 
1.810     raeburn  4564:     if ($priv eq 'evb') {
                   4565: # Evade communication block restrictions for specified role in a course
                   4566:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   4567:             return $1;
                   4568:         } else {
                   4569:             return;
                   4570:         }
                   4571:     }
                   4572: 
1.620     albertel 4573:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      4574: # Free bre access to adm and meta resources
1.775     albertel 4575:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 4576: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   4577: 	&& ($priv eq 'bre')) {
1.14      www      4578: 	return 'F';
1.159     www      4579:     }
                   4580: 
1.545     banghart 4581: # Free bre access to user's own portfolio contents
1.714     raeburn  4582:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  4583:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  4584: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  4585:         my %setters;
                   4586:         my ($startblock,$endblock) = 
                   4587:             &Apache::loncommon::blockcheck(\%setters,'port');
                   4588:         if ($startblock && $endblock) {
                   4589:             return 'B';
                   4590:         } else {
                   4591:             return 'F';
                   4592:         }
1.545     banghart 4593:     }
                   4594: 
1.762     raeburn  4595: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  4596:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   4597:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   4598:         if (exists($env{'request.course.id'})) {
                   4599:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4600:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4601:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   4602:                 my $courseprivid=$env{'request.course.id'};
                   4603:                 $courseprivid=~s/\_/\//;
                   4604:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   4605:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   4606:                     return $1; 
1.762     raeburn  4607:                 } else {
                   4608:                     if ($env{'request.course.sec'}) {
                   4609:                         $courseprivid.='/'.$env{'request.course.sec'};
                   4610:                     }
                   4611:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   4612:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   4613:                         return $2;
                   4614:                     }
1.714     raeburn  4615:                 }
                   4616:             }
                   4617:         }
                   4618:     }
                   4619: 
1.159     www      4620: # Free bre to public access
                   4621: 
                   4622:     if ($priv eq 'bre') {
1.238     www      4623:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 4624: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      4625:            return 'F'; 
                   4626:         }
1.238     www      4627:         if ($copyright eq 'priv') {
                   4628:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 4629: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      4630: 		return '';
                   4631:             }
                   4632:         }
                   4633:         if ($copyright eq 'domain') {
                   4634:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 4635: 	    unless (($env{'user.domain'} eq $1) ||
                   4636:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      4637: 		return '';
                   4638:             }
1.262     matthew  4639:         }
1.620     albertel 4640:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  4641:             # Library role, so allow browsing of resources in this domain.
                   4642:             return 'F';
1.238     www      4643:         }
1.341     www      4644:         if ($copyright eq 'custom') {
                   4645: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   4646:         }
1.14      www      4647:     }
1.264     matthew  4648:     # Domain coordinator is trying to create a course
1.620     albertel 4649:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  4650:         # uri is the requested domain in this case.
                   4651:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  4652:         # a role of dc for the domain in question.
1.620     albertel 4653:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  4654:     }
1.29      www      4655: 
1.52      www      4656:     my $thisallowed='';
                   4657:     my $statecond=0;
                   4658:     my $courseprivid='';
                   4659: 
                   4660: # Course
                   4661: 
1.620     albertel 4662:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4663:        $thisallowed.=$1;
                   4664:     }
1.29      www      4665: 
1.52      www      4666: # Domain
                   4667: 
1.620     albertel 4668:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 4669:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      4670:        $thisallowed.=$1;
                   4671:     }
1.52      www      4672: 
                   4673: # Course: uri itself is a course
1.66      www      4674:     my $courseuri=$uri;
                   4675:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      4676:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      4677: 
1.620     albertel 4678:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 4679:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      4680:        $thisallowed.=$1;
                   4681:     }
1.29      www      4682: 
1.665     albertel 4683: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 4684: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 4685:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 4686: 	$thisallowed='';
1.671     raeburn  4687:         my ($match)=&is_on_map($uri);
                   4688:         if ($match) {
                   4689:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   4690:                   =~/\Q$priv\E\&([^\:]*)/) {
                   4691:                 $thisallowed.=$1;
                   4692:             }
                   4693:         } else {
1.705     albertel 4694:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  4695:             if ($refuri) {
                   4696:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  4697:                     $thisallowed='F';
1.671     raeburn  4698:                 } else {
                   4699:                     $refuri=&declutter($refuri);
                   4700:                     my ($match) = &is_on_map($refuri);
                   4701:                     if ($match) {
                   4702:                         $thisallowed='F';
                   4703:                     }
1.669     raeburn  4704:                 }
1.671     raeburn  4705:             }
                   4706:         }
1.314     www      4707:     }
1.492     albertel 4708: 
1.766     albertel 4709:     if ($priv eq 'bre'
                   4710: 	&& $thisallowed ne 'F' 
                   4711: 	&& $thisallowed ne '2'
                   4712: 	&& &is_portfolio_url($uri)) {
                   4713: 	$thisallowed = &portfolio_access($uri);
                   4714:     }
                   4715:     
1.52      www      4716: # Full access at system, domain or course-wide level? Exit.
1.29      www      4717:     if ($thisallowed=~/F/) {
                   4718: 	return 'F';
                   4719:     }
                   4720: 
1.52      www      4721: # If this is generating or modifying users, exit with special codes
1.29      www      4722: 
1.643     www      4723:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   4724: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 4725: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      4726: # no author name given, so this just checks on the general right to make a co-author in this domain
                   4727: 	    unless ($auname) { return $thisallowed; }
                   4728: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 4729: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   4730: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   4731: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   4732: 	}
1.52      www      4733: 	return $thisallowed;
                   4734:     }
                   4735: #
1.103     harris41 4736: # Gathered so far: system, domain and course wide privileges
1.52      www      4737: #
                   4738: # Course: See if uri or referer is an individual resource that is part of 
                   4739: # the course
                   4740: 
1.620     albertel 4741:     if ($env{'request.course.id'}) {
1.232     www      4742: 
1.620     albertel 4743:        $courseprivid=$env{'request.course.id'};
                   4744:        if ($env{'request.course.sec'}) {
                   4745:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      4746:        }
                   4747:        $courseprivid=~s/\_/\//;
                   4748:        my $checkreferer=1;
1.232     www      4749:        my ($match,$cond)=&is_on_map($uri);
                   4750:        if ($match) {
                   4751:            $statecond=$cond;
1.620     albertel 4752:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 4753:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4754:                $thisallowed.=$1;
                   4755:                $checkreferer=0;
                   4756:            }
1.29      www      4757:        }
1.83      www      4758:        
1.148     www      4759:        if ($checkreferer) {
1.620     albertel 4760: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      4761:             unless ($refuri) {
1.800     albertel 4762:                 foreach my $key (keys(%env)) {
                   4763: 		    if ($key=~/^httpref\..*\*/) {
                   4764: 			my $pattern=$key;
1.156     www      4765:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      4766:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   4767:                         $pattern=~s/\//\\\//g;
1.152     www      4768:                         if ($orguri=~/$pattern/) {
1.800     albertel 4769: 			    $refuri=$env{$key};
1.148     www      4770:                         }
                   4771:                     }
1.191     harris41 4772:                 }
1.148     www      4773:             }
1.232     www      4774: 
1.148     www      4775:          if ($refuri) { 
1.152     www      4776: 	  $refuri=&declutter($refuri);
1.232     www      4777:           my ($match,$cond)=&is_on_map($refuri);
                   4778:             if ($match) {
                   4779:               my $refstatecond=$cond;
1.620     albertel 4780:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 4781:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4782:                   $thisallowed.=$1;
1.53      www      4783:                   $uri=$refuri;
                   4784:                   $statecond=$refstatecond;
1.52      www      4785:               }
                   4786:           }
1.148     www      4787:         }
1.29      www      4788:        }
1.52      www      4789:    }
1.29      www      4790: 
1.52      www      4791: #
1.103     harris41 4792: # Gathered now: all privileges that could apply, and condition number
1.52      www      4793: # 
                   4794: #
                   4795: # Full or no access?
                   4796: #
1.29      www      4797: 
1.52      www      4798:     if ($thisallowed=~/F/) {
                   4799: 	return 'F';
                   4800:     }
1.29      www      4801: 
1.52      www      4802:     unless ($thisallowed) {
                   4803:         return '';
                   4804:     }
1.29      www      4805: 
1.52      www      4806: # Restrictions exist, deal with them
                   4807: #
                   4808: #   C:according to course preferences
                   4809: #   R:according to resource settings
                   4810: #   L:unless locked
                   4811: #   X:according to user session state
                   4812: #
                   4813: 
                   4814: # Possibly locked functionality, check all courses
1.54      www      4815: # Locks might take effect only after 10 minutes cache expiration for other
                   4816: # courses, and 2 minutes for current course
1.52      www      4817: 
                   4818:     my $envkey;
                   4819:     if ($thisallowed=~/L/) {
1.620     albertel 4820:         foreach $envkey (keys %env) {
1.54      www      4821:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   4822:                my $courseid=$2;
                   4823:                my $roleid=$1.'.'.$2;
1.92      www      4824:                $courseid=~s/^\///;
1.54      www      4825:                my $expiretime=600;
1.620     albertel 4826:                if ($env{'request.role'} eq $roleid) {
1.54      www      4827: 		  $expiretime=120;
                   4828:                }
                   4829: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   4830:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 4831:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 4832: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      4833:                }
1.620     albertel 4834:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   4835:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   4836: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   4837:                        &log($env{'user.domain'},$env{'user.name'},
                   4838:                             $env{'user.home'},
1.57      www      4839:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      4840:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 4841:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      4842: 		       return '';
                   4843:                    }
                   4844:                }
1.620     albertel 4845:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   4846:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   4847: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   4848:                        &log($env{'user.domain'},$env{'user.name'},
                   4849:                             $env{'user.home'},
1.57      www      4850:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      4851:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 4852:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      4853: 		       return '';
                   4854:                    }
                   4855:                }
                   4856: 	   }
1.29      www      4857:        }
1.52      www      4858:     }
                   4859:    
                   4860: #
                   4861: # Rest of the restrictions depend on selected course
                   4862: #
                   4863: 
1.620     albertel 4864:     unless ($env{'request.course.id'}) {
1.766     albertel 4865: 	if ($thisallowed eq 'A') {
                   4866: 	    return 'A';
1.814     raeburn  4867:         } elsif ($thisallowed eq 'B') {
                   4868:             return 'B';
1.766     albertel 4869: 	} else {
                   4870: 	    return '1';
                   4871: 	}
1.52      www      4872:     }
1.29      www      4873: 
1.52      www      4874: #
                   4875: # Now user is definitely in a course
                   4876: #
1.53      www      4877: 
                   4878: 
                   4879: # Course preferences
                   4880: 
                   4881:    if ($thisallowed=~/C/) {
1.620     albertel 4882:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   4883:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   4884:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 4885: 	   =~/\Q$rolecode\E/) {
1.689     albertel 4886: 	   if ($priv ne 'pch') { 
                   4887: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   4888: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   4889: 			$env{'request.course.id'});
                   4890: 	   }
1.237     www      4891:            return '';
                   4892:        }
                   4893: 
1.620     albertel 4894:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 4895: 	   =~/\Q$unamedom\E/) {
1.689     albertel 4896: 	   if ($priv ne 'pch') { 
                   4897: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   4898: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   4899: 			$env{'request.course.id'});
                   4900: 	   }
1.54      www      4901:            return '';
                   4902:        }
1.53      www      4903:    }
                   4904: 
                   4905: # Resource preferences
                   4906: 
                   4907:    if ($thisallowed=~/R/) {
1.620     albertel 4908:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 4909:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689     albertel 4910: 	   if ($priv ne 'pch') { 
                   4911: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   4912: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   4913: 	   }
                   4914: 	   return '';
1.54      www      4915:        }
1.53      www      4916:    }
1.30      www      4917: 
1.246     www      4918: # Restricted by state or randomout?
1.30      www      4919: 
1.52      www      4920:    if ($thisallowed=~/X/) {
1.620     albertel 4921:       if ($env{'acc.randomout'}) {
1.579     albertel 4922: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 4923:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      4924:             return ''; 
                   4925:          }
1.247     www      4926:       }
                   4927:       if (&condval($statecond)) {
1.52      www      4928: 	 return '2';
                   4929:       } else {
                   4930:          return '';
                   4931:       }
                   4932:    }
1.30      www      4933: 
1.766     albertel 4934:     if ($thisallowed eq 'A') {
                   4935: 	return 'A';
1.814     raeburn  4936:     } elsif ($thisallowed eq 'B') {
                   4937:         return 'B';
1.766     albertel 4938:     }
1.52      www      4939:    return 'F';
1.232     www      4940: }
                   4941: 
1.710     albertel 4942: sub split_uri_for_cond {
                   4943:     my $uri=&deversion(&declutter(shift));
                   4944:     my @uriparts=split(/\//,$uri);
                   4945:     my $filename=pop(@uriparts);
                   4946:     my $pathname=join('/',@uriparts);
                   4947:     return ($pathname,$filename);
                   4948: }
1.232     www      4949: # --------------------------------------------------- Is a resource on the map?
                   4950: 
                   4951: sub is_on_map {
1.710     albertel 4952:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 4953:     #Trying to find the conditional for the file
1.620     albertel 4954:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 4955: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      4956:     if ($match) {
1.289     bowersj2 4957: 	return (1,$1);
                   4958:     } else {
1.434     www      4959: 	return (0,0);
1.289     bowersj2 4960:     }
1.12      www      4961: }
                   4962: 
1.427     www      4963: # --------------------------------------------------------- Get symb from alias
                   4964: 
                   4965: sub get_symb_from_alias {
                   4966:     my $symb=shift;
                   4967:     my ($map,$resid,$url)=&decode_symb($symb);
                   4968: # Already is a symb
                   4969:     if ($url) { return $symb; }
                   4970: # Must be an alias
                   4971:     my $aliassymb='';
                   4972:     my %bighash;
1.620     albertel 4973:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      4974:                             &GDBM_READER(),0640)) {
                   4975:         my $rid=$bighash{'mapalias_'.$symb};
                   4976: 	if ($rid) {
                   4977: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 4978: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   4979: 				    $resid,$bighash{'src_'.$rid});
1.427     www      4980: 	}
                   4981:         untie %bighash;
                   4982:     }
                   4983:     return $aliassymb;
                   4984: }
                   4985: 
1.12      www      4986: # ----------------------------------------------------------------- Define Role
                   4987: 
                   4988: sub definerole {
                   4989:   if (allowed('mcr','/')) {
                   4990:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 4991:     foreach my $role (split(':',$sysrole)) {
                   4992: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4993:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   4994:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   4995: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      4996:                return "refused:s:$crole&$cqual"; 
                   4997:             }
                   4998:         }
1.191     harris41 4999:     }
1.800     albertel 5000:     foreach my $role (split(':',$domrole)) {
                   5001: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5002:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   5003:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   5004: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      5005:                return "refused:d:$crole&$cqual"; 
                   5006:             }
                   5007:         }
1.191     harris41 5008:     }
1.800     albertel 5009:     foreach my $role (split(':',$courole)) {
                   5010: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5011:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   5012:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   5013: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      5014:                return "refused:c:$crole&$cqual"; 
                   5015:             }
                   5016:         }
1.191     harris41 5017:     }
1.620     albertel 5018:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   5019:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      5020: 	        "rolesdef_$rolename=".
                   5021:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 5022:     return reply($command,$env{'user.home'});
1.12      www      5023:   } else {
                   5024:     return 'refused';
                   5025:   }
1.105     harris41 5026: }
                   5027: 
                   5028: # ---------------- Make a metadata query against the network of library servers
                   5029: 
                   5030: sub metadata_query {
1.244     matthew  5031:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 5032:     my %rhash;
1.845     albertel 5033:     my %libserv = &all_library();
1.244     matthew  5034:     my @server_list = (defined($server_array) ? @$server_array
                   5035:                                               : keys(%libserv) );
                   5036:     for my $server (@server_list) {
1.118     harris41 5037: 	unless ($custom or $customshow) {
                   5038: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   5039: 	    $rhash{$server}=$reply;
                   5040: 	}
                   5041: 	else {
                   5042: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   5043: 			     &escape($custom).':'.&escape($customshow),
                   5044: 			     $server);
                   5045: 	    $rhash{$server}=$reply;
                   5046: 	}
1.112     harris41 5047:     }
1.118     harris41 5048:     return \%rhash;
1.240     www      5049: }
                   5050: 
                   5051: # ----------------------------------------- Send log queries and wait for reply
                   5052: 
                   5053: sub log_query {
                   5054:     my ($uname,$udom,$query,%filters)=@_;
                   5055:     my $uhome=&homeserver($uname,$udom);
                   5056:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 5057:     my $uhost=&hostname($uhome);
1.800     albertel 5058:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      5059:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   5060:                        $uhome);
1.479     albertel 5061:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      5062:     return get_query_reply($queryid);
                   5063: }
                   5064: 
1.818     raeburn  5065: # -------------------------- Update MySQL table for portfolio file
                   5066: 
                   5067: sub update_portfolio_table {
1.821     raeburn  5068:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  5069:     if ($group ne '') {
                   5070:         $file_name =~s /^\Q$group\E//;
                   5071:     }
1.818     raeburn  5072:     my $homeserver = &homeserver($uname,$udom);
                   5073:     my $queryid=
1.821     raeburn  5074:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   5075:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  5076:     my $reply = &get_query_reply($queryid);
                   5077:     return $reply;
                   5078: }
                   5079: 
1.899     raeburn  5080: # -------------------------- Update MySQL allusers table
                   5081: 
                   5082: sub update_allusers_table {
                   5083:     my ($uname,$udom,$names) = @_;
                   5084:     my $homeserver = &homeserver($uname,$udom);
                   5085:     my $queryid=
                   5086:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   5087:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   5088:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   5089:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   5090:                'generation='.&escape($names->{'generation'}).'%%'.
                   5091:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   5092:                'id='.&escape($names->{'id'}),$homeserver);
                   5093:     my $reply = &get_query_reply($queryid);
                   5094:     return $reply;
                   5095: }
                   5096: 
1.508     raeburn  5097: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  5098: 
                   5099: sub fetch_enrollment_query {
1.511     raeburn  5100:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  5101:     my $homeserver;
1.547     raeburn  5102:     my $maxtries = 1;
1.508     raeburn  5103:     if ($context eq 'automated') {
                   5104:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  5105:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  5106:     } else {
                   5107:         $homeserver = &homeserver($cnum,$dom);
                   5108:     }
1.838     albertel 5109:     my $host=&hostname($homeserver);
1.506     raeburn  5110:     my $cmd = '';
1.800     albertel 5111:     foreach my $affiliate (keys %{$affiliatesref}) {
                   5112:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  5113:     }
                   5114:     $cmd =~ s/%%$//;
                   5115:     $cmd = &escape($cmd);
                   5116:     my $query = 'fetchenrollment';
1.620     albertel 5117:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  5118:     unless ($queryid=~/^\Q$host\E\_/) { 
                   5119:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   5120:         return 'error: '.$queryid;
                   5121:     }
1.506     raeburn  5122:     my $reply = &get_query_reply($queryid);
1.547     raeburn  5123:     my $tries = 1;
                   5124:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   5125:         $reply = &get_query_reply($queryid);
                   5126:         $tries ++;
                   5127:     }
1.526     raeburn  5128:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 5129:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  5130:     } else {
1.901     albertel 5131:         my @responses = split(/:/,$reply);
1.515     raeburn  5132:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 5133:             foreach my $line (@responses) {
                   5134:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  5135:                 $$replyref{$key} = $value;
                   5136:             }
                   5137:         } else {
1.506     raeburn  5138:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800     albertel 5139:             foreach my $line (@responses) {
                   5140:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  5141:                 $$replyref{$key} = $value;
                   5142:                 if ($value > 0) {
1.800     albertel 5143:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   5144:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  5145:                         my $destname = $pathname.'/'.$filename;
                   5146:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  5147:                         if ($xml_classlist =~ /^error/) {
                   5148:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   5149:                         } else {
1.506     raeburn  5150:                             if ( open(FILE,">$destname") ) {
                   5151:                                 print FILE &unescape($xml_classlist);
                   5152:                                 close(FILE);
1.526     raeburn  5153:                             } else {
                   5154:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  5155:                             }
                   5156:                         }
                   5157:                     }
                   5158:                 }
                   5159:             }
                   5160:         }
                   5161:         return 'ok';
                   5162:     }
                   5163:     return 'error';
                   5164: }
                   5165: 
1.242     www      5166: sub get_query_reply {
                   5167:     my $queryid=shift;
1.240     www      5168:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   5169:     my $reply='';
                   5170:     for (1..100) {
                   5171: 	sleep 2;
                   5172:         if (-e $replyfile.'.end') {
1.448     albertel 5173: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 5174: 		$reply = join('',<$fh>);
                   5175: 		close($fh);
1.240     www      5176: 	   } else { return 'error: reply_file_error'; }
1.242     www      5177:            return &unescape($reply);
                   5178: 	}
1.240     www      5179:     }
1.242     www      5180:     return 'timeout:'.$queryid;
1.240     www      5181: }
                   5182: 
                   5183: sub courselog_query {
1.241     www      5184: #
                   5185: # possible filters:
                   5186: # url: url or symb
                   5187: # username
                   5188: # domain
                   5189: # action: view, submit, grade
                   5190: # start: timestamp
                   5191: # end: timestamp
                   5192: #
1.240     www      5193:     my (%filters)=@_;
1.620     albertel 5194:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      5195:     if ($filters{'url'}) {
                   5196: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   5197:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   5198:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   5199:     }
1.620     albertel 5200:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5201:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      5202:     return &log_query($cname,$cdom,'courselog',%filters);
                   5203: }
                   5204: 
                   5205: sub userlog_query {
1.858     raeburn  5206: #
                   5207: # possible filters:
                   5208: # action: log check role
                   5209: # start: timestamp
                   5210: # end: timestamp
                   5211: #
1.240     www      5212:     my ($uname,$udom,%filters)=@_;
                   5213:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      5214: }
                   5215: 
1.506     raeburn  5216: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   5217: 
                   5218: sub auto_run {
1.508     raeburn  5219:     my ($cnum,$cdom) = @_;
1.876     raeburn  5220:     my $response = 0;
                   5221:     my $settings;
                   5222:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   5223:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   5224:         $settings = $domconfig{'autoenroll'};
                   5225:         if ($settings->{'run'} eq '1') {
                   5226:             $response = 1;
                   5227:         }
                   5228:     } else {
1.934     raeburn  5229:         my $homeserver;
                   5230:         if (&is_course($cdom,$cnum)) {
                   5231:             $homeserver = &homeserver($cnum,$cdom);
                   5232:         } else {
                   5233:             $homeserver = &domain($cdom,'primary');
                   5234:         }
                   5235:         if ($homeserver ne 'no_host') {
                   5236:             $response = &reply('autorun:'.$cdom,$homeserver);
                   5237:         }
1.876     raeburn  5238:     }
1.506     raeburn  5239:     return $response;
                   5240: }
1.776     albertel 5241: 
1.506     raeburn  5242: sub auto_get_sections {
1.508     raeburn  5243:     my ($cnum,$cdom,$inst_coursecode) = @_;
                   5244:     my $homeserver = &homeserver($cnum,$cdom);
1.506     raeburn  5245:     my @secs = ();
1.511     raeburn  5246:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506     raeburn  5247:     unless ($response eq 'refused') {
1.901     albertel 5248:         @secs = split(/:/,$response);
1.506     raeburn  5249:     }
                   5250:     return @secs;
                   5251: }
1.776     albertel 5252: 
1.506     raeburn  5253: sub auto_new_course {
1.508     raeburn  5254:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
                   5255:     my $homeserver = &homeserver($cnum,$cdom);
1.515     raeburn  5256:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506     raeburn  5257:     return $response;
                   5258: }
1.776     albertel 5259: 
1.506     raeburn  5260: sub auto_validate_courseID {
1.508     raeburn  5261:     my ($cnum,$cdom,$inst_course_id) = @_;
                   5262:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  5263:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  5264:     return $response;
                   5265: }
1.776     albertel 5266: 
1.506     raeburn  5267: sub auto_create_password {
1.873     raeburn  5268:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   5269:     my ($homeserver,$response);
1.506     raeburn  5270:     my $create_passwd = 0;
                   5271:     my $authchk = '';
1.873     raeburn  5272:     if ($udom =~ /^$match_domain$/) {
                   5273:         $homeserver = &domain($udom,'primary');
                   5274:     }
                   5275:     if ($homeserver eq '') {
                   5276:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   5277:             $homeserver = &homeserver($cnum,$cdom);
                   5278:         }
                   5279:     }
                   5280:     if ($homeserver eq '') {
                   5281:         $authchk = 'nodomain';
1.506     raeburn  5282:     } else {
1.873     raeburn  5283:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   5284:         if ($response eq 'refused') {
                   5285:             $authchk = 'refused';
                   5286:         } else {
1.901     albertel 5287:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  5288:         }
1.506     raeburn  5289:     }
                   5290:     return ($authparam,$create_passwd,$authchk);
                   5291: }
                   5292: 
1.706     raeburn  5293: sub auto_photo_permission {
                   5294:     my ($cnum,$cdom,$students) = @_;
                   5295:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 5296:     my ($outcome,$perm_reqd,$conditions) = 
                   5297: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 5298:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5299: 	return (undef,undef);
                   5300:     }
1.706     raeburn  5301:     return ($outcome,$perm_reqd,$conditions);
                   5302: }
                   5303: 
                   5304: sub auto_checkphotos {
                   5305:     my ($uname,$udom,$pid) = @_;
                   5306:     my $homeserver = &homeserver($uname,$udom);
                   5307:     my ($result,$resulttype);
                   5308:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 5309: 				   &escape($uname).':'.&escape($pid),
                   5310: 				   $homeserver));
1.709     albertel 5311:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5312: 	return (undef,undef);
                   5313:     }
1.706     raeburn  5314:     if ($outcome) {
                   5315:         ($result,$resulttype) = split(/:/,$outcome);
                   5316:     } 
                   5317:     return ($result,$resulttype);
                   5318: }
                   5319: 
                   5320: sub auto_photochoice {
                   5321:     my ($cnum,$cdom) = @_;
                   5322:     my $homeserver = &homeserver($cnum,$cdom);
                   5323:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 5324: 						       &escape($cdom),
                   5325: 						       $homeserver)));
1.709     albertel 5326:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5327: 	return (undef,undef);
                   5328:     }
1.706     raeburn  5329:     return ($update,$comment);
                   5330: }
                   5331: 
                   5332: sub auto_photoupdate {
                   5333:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   5334:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 5335:     my $host=&hostname($homeserver);
1.706     raeburn  5336:     my $cmd = '';
                   5337:     my $maxtries = 1;
1.800     albertel 5338:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   5339:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  5340:     }
                   5341:     $cmd =~ s/%%$//;
                   5342:     $cmd = &escape($cmd);
                   5343:     my $query = 'institutionalphotos';
                   5344:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   5345:     unless ($queryid=~/^\Q$host\E\_/) {
                   5346:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   5347:         return 'error: '.$queryid;
                   5348:     }
                   5349:     my $reply = &get_query_reply($queryid);
                   5350:     my $tries = 1;
                   5351:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   5352:         $reply = &get_query_reply($queryid);
                   5353:         $tries ++;
                   5354:     }
                   5355:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   5356:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   5357:     } else {
                   5358:         my @responses = split(/:/,$reply);
                   5359:         my $outcome = shift(@responses); 
                   5360:         foreach my $item (@responses) {
                   5361:             my ($key,$value) = split(/=/,$item);
                   5362:             $$photo{$key} = $value;
                   5363:         }
                   5364:         return $outcome;
                   5365:     }
                   5366:     return 'error';
                   5367: }
                   5368: 
1.521     raeburn  5369: sub auto_instcode_format {
1.793     albertel 5370:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   5371: 	$cat_order) = @_;
1.521     raeburn  5372:     my $courses = '';
1.772     raeburn  5373:     my @homeservers;
1.521     raeburn  5374:     if ($caller eq 'global') {
1.841     albertel 5375: 	my %servers = &get_servers($codedom,'library');
                   5376: 	foreach my $tryserver (keys(%servers)) {
                   5377: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   5378: 		push(@homeservers,$tryserver);
                   5379: 	    }
1.584     raeburn  5380:         }
1.521     raeburn  5381:     } else {
1.772     raeburn  5382:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  5383:     }
1.793     albertel 5384:     foreach my $code (keys(%{$instcodes})) {
                   5385:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  5386:     }
                   5387:     chop($courses);
1.772     raeburn  5388:     my $ok_response = 0;
                   5389:     my $response;
                   5390:     while (@homeservers > 0 && $ok_response == 0) {
                   5391:         my $server = shift(@homeservers); 
                   5392:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   5393:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   5394:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 5395: 		split(/:/,$response);
1.772     raeburn  5396:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   5397:             push(@{$codetitles},&str2array($codetitles_str));
                   5398:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   5399:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   5400:             $ok_response = 1;
                   5401:         }
                   5402:     }
                   5403:     if ($ok_response) {
1.521     raeburn  5404:         return 'ok';
1.772     raeburn  5405:     } else {
                   5406:         return $response;
1.521     raeburn  5407:     }
                   5408: }
                   5409: 
1.792     raeburn  5410: sub auto_instcode_defaults {
                   5411:     my ($domain,$returnhash,$code_order) = @_;
                   5412:     my @homeservers;
1.841     albertel 5413: 
                   5414:     my %servers = &get_servers($domain,'library');
                   5415:     foreach my $tryserver (keys(%servers)) {
                   5416: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   5417: 	    push(@homeservers,$tryserver);
                   5418: 	}
1.792     raeburn  5419:     }
1.841     albertel 5420: 
1.792     raeburn  5421:     my $response;
1.841     albertel 5422:     foreach my $server (@homeservers) {
1.792     raeburn  5423:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 5424:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   5425: 	
                   5426: 	foreach my $pair (split(/\&/,$response)) {
                   5427: 	    my ($name,$value)=split(/\=/,$pair);
                   5428: 	    if ($name eq 'code_order') {
                   5429: 		@{$code_order} = split(/\&/,&unescape($value));
                   5430: 	    } else {
                   5431: 		$returnhash->{&unescape($name)}=&unescape($value);
                   5432: 	    }
                   5433: 	}
                   5434: 	return 'ok';
1.792     raeburn  5435:     }
1.841     albertel 5436: 
                   5437:     return $response;
1.792     raeburn  5438: } 
                   5439: 
1.777     albertel 5440: sub auto_validate_class_sec {
1.918     raeburn  5441:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  5442:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  5443:     my $ownerlist;
                   5444:     if (ref($owners) eq 'ARRAY') {
                   5445:         $ownerlist = join(',',@{$owners});
                   5446:     } else {
                   5447:         $ownerlist = $owners;
                   5448:     }
1.773     raeburn  5449:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  5450:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  5451:     return $response;
                   5452: }
                   5453: 
1.679     raeburn  5454: # ------------------------------------------------------- Course Group routines
                   5455: 
                   5456: sub get_coursegroups {
1.809     raeburn  5457:     my ($cdom,$cnum,$group,$namespace) = @_;
                   5458:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  5459: }
                   5460: 
1.679     raeburn  5461: sub modify_coursegroup {
                   5462:     my ($cdom,$cnum,$groupsettings) = @_;
                   5463:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   5464: }
                   5465: 
1.809     raeburn  5466: sub toggle_coursegroup_status {
                   5467:     my ($cdom,$cnum,$group,$action) = @_;
                   5468:     my ($from_namespace,$to_namespace);
                   5469:     if ($action eq 'delete') {
                   5470:         $from_namespace = 'coursegroups';
                   5471:         $to_namespace = 'deleted_groups';
                   5472:     } else {
                   5473:         $from_namespace = 'deleted_groups';
                   5474:         $to_namespace = 'coursegroups';
                   5475:     }
                   5476:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  5477:     if (my $tmp = &error(%curr_group)) {
                   5478:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   5479:         return ('read error',$tmp);
                   5480:     } else {
                   5481:         my %savedsettings = %curr_group; 
1.809     raeburn  5482:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  5483:         my $deloutcome;
                   5484:         if ($result eq 'ok') {
1.809     raeburn  5485:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  5486:         } else {
                   5487:             return ('write error',$result);
                   5488:         }
                   5489:         if ($deloutcome eq 'ok') {
                   5490:             return 'ok';
                   5491:         } else {
                   5492:             return ('delete error',$deloutcome);
                   5493:         }
                   5494:     }
                   5495: }
                   5496: 
1.679     raeburn  5497: sub modify_group_roles {
1.957     raeburn  5498:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  5499:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   5500:     my $role = 'gr/'.&escape($userprivs);
                   5501:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  5502:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  5503:     if ($result eq 'ok') {
                   5504:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   5505:     }
1.679     raeburn  5506:     return $result;
                   5507: }
                   5508: 
                   5509: sub modify_coursegroup_membership {
                   5510:     my ($cdom,$cnum,$membership) = @_;
                   5511:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   5512:     return $result;
                   5513: }
                   5514: 
1.682     raeburn  5515: sub get_active_groups {
                   5516:     my ($udom,$uname,$cdom,$cnum) = @_;
                   5517:     my $now = time;
                   5518:     my %groups = ();
                   5519:     foreach my $key (keys(%env)) {
1.811     albertel 5520:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  5521:             my ($start,$end) = split(/\./,$env{$key});
                   5522:             if (($end!=0) && ($end<$now)) { next; }
                   5523:             if (($start!=0) && ($start>$now)) { next; }
                   5524:             if ($1 eq $cdom && $2 eq $cnum) {
                   5525:                 $groups{$3} = $env{$key} ;
                   5526:             }
                   5527:         }
                   5528:     }
                   5529:     return %groups;
                   5530: }
                   5531: 
1.683     raeburn  5532: sub get_group_membership {
                   5533:     my ($cdom,$cnum,$group) = @_;
                   5534:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   5535: }
                   5536: 
                   5537: sub get_users_groups {
                   5538:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  5539:     my @usersgroups;
1.683     raeburn  5540:     my $cachetime=1800;
                   5541: 
                   5542:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  5543:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   5544:     if (defined($cached)) {
1.734     albertel 5545:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  5546:     } else {  
                   5547:         $grouplist = '';
1.816     raeburn  5548:         my $courseurl = &courseid_to_courseurl($courseid);
                   5549:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  5550:         my $access_end = $env{'course.'.$courseid.
                   5551:                               '.default_enrollment_end_date'};
                   5552:         my $now = time;
                   5553:         foreach my $key (keys(%roleshash)) {
                   5554:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   5555:                 my $group = $1;
                   5556:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   5557:                     my $start = $2;
                   5558:                     my $end = $1;
                   5559:                     if ($start == -1) { next; } # deleted from group
                   5560:                     if (($start!=0) && ($start>$now)) { next; }
                   5561:                     if (($end!=0) && ($end<$now)) {
                   5562:                         if ($access_end && $access_end < $now) {
                   5563:                             if ($access_end - $end < 86400) {
                   5564:                                 push(@usersgroups,$group);
1.733     raeburn  5565:                             }
                   5566:                         }
1.817     raeburn  5567:                         next;
1.733     raeburn  5568:                     }
1.817     raeburn  5569:                     push(@usersgroups,$group);
1.683     raeburn  5570:                 }
                   5571:             }
                   5572:         }
1.817     raeburn  5573:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   5574:         $grouplist = join(':',@usersgroups);
                   5575:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  5576:     }
1.733     raeburn  5577:     return @usersgroups;
1.683     raeburn  5578: }
                   5579: 
                   5580: sub devalidate_getgroups_cache {
                   5581:     my ($udom,$uname,$cdom,$cnum)=@_;
                   5582:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 5583: 
1.683     raeburn  5584:     my $hashid="$udom:$uname:$courseid";
                   5585:     &devalidate_cache_new('getgroups',$hashid);
                   5586: }
                   5587: 
1.12      www      5588: # ------------------------------------------------------------------ Plain Text
                   5589: 
                   5590: sub plaintext {
1.742     raeburn  5591:     my ($short,$type,$cid) = @_;
1.758     albertel 5592:     if ($short =~ /^cr/) {
                   5593: 	return (split('/',$short))[-1];
                   5594:     }
1.742     raeburn  5595:     if (!defined($cid)) {
                   5596:         $cid = $env{'request.course.id'};
                   5597:     }
                   5598:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
                   5599:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
                   5600:                                           '.plaintext'});
                   5601:     }
                   5602:     my %rolenames = (
                   5603:                       Course => 'std',
                   5604:                       Group => 'alt1',
                   5605:                     );
                   5606:     if (defined($type) && 
                   5607:          defined($rolenames{$type}) && 
                   5608:          defined($prp{$short}{$rolenames{$type}})) {
                   5609:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
                   5610:     } else {
                   5611:         return &Apache::lonlocal::mt($prp{$short}{'std'});
                   5612:     }
1.12      www      5613: }
                   5614: 
                   5615: # ----------------------------------------------------------------- Assign Role
                   5616: 
                   5617: sub assignrole {
1.957     raeburn  5618:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   5619:         $context)=@_;
1.21      www      5620:     my $mrole;
                   5621:     if ($role =~ /^cr\//) {
1.393     www      5622:         my $cwosec=$url;
1.811     albertel 5623:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      5624: 	unless (&allowed('ccr',$cwosec)) {
1.104     www      5625:            &logthis('Refused custom assignrole: '.
                   5626:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 5627: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      5628:            return 'refused'; 
                   5629:         }
1.21      www      5630:         $mrole='cr';
1.678     raeburn  5631:     } elsif ($role =~ /^gr\//) {
                   5632:         my $cwogrp=$url;
1.811     albertel 5633:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  5634:         unless (&allowed('mdg',$cwogrp)) {
                   5635:             &logthis('Refused group assignrole: '.
                   5636:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   5637:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   5638:             return 'refused';
                   5639:         }
                   5640:         $mrole='gr';
1.21      www      5641:     } else {
1.82      www      5642:         my $cwosec=$url;
1.811     albertel 5643:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  5644:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   5645:             my $refused;
                   5646:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   5647:                 if (!(&allowed('c'.$role,$url))) {
                   5648:                     $refused = 1;
                   5649:                 }
                   5650:             } else {
                   5651:                 $refused = 1;
                   5652:             }
1.947     raeburn  5653:             if ($refused) {
                   5654:                 if (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   5655:                     $refused = '';
                   5656:                 } else {
                   5657:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   5658:                              ' '.$role.' '.$end.' '.$start.' by '.
                   5659: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   5660:                     return 'refused';
                   5661:                 }
1.932     raeburn  5662:             }
1.104     www      5663:         }
1.21      www      5664:         $mrole=$role;
                   5665:     }
1.620     albertel 5666:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      5667:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      5668:     if ($end) { $command.='_'.$end; }
1.21      www      5669:     if ($start) {
                   5670: 	if ($end) { 
1.81      www      5671:            $command.='_'.$start; 
1.21      www      5672:         } else {
1.81      www      5673:            $command.='_0_'.$start;
1.21      www      5674:         }
                   5675:     }
1.739     raeburn  5676:     my $origstart = $start;
                   5677:     my $origend = $end;
1.957     raeburn  5678:     my $delflag;
1.357     www      5679: # actually delete
                   5680:     if ($deleteflag) {
1.373     www      5681: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      5682: # modify command to delete the role
1.620     albertel 5683:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      5684:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 5685: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      5686: # set start and finish to negative values for userrolelog
                   5687:            $start=-1;
                   5688:            $end=-1;
1.957     raeburn  5689:            $delflag = 1;
1.357     www      5690:         }
                   5691:     }
                   5692: # send command
1.349     www      5693:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      5694: # log new user role if status is ok
1.349     www      5695:     if ($answer eq 'ok') {
1.663     raeburn  5696: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  5697: # for course roles, perform group memberships changes triggered by role change.
1.957     raeburn  5698:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739     raeburn  5699:         unless ($role =~ /^gr/) {
                   5700:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957     raeburn  5701:                                              $origstart,$selfenroll,$context);
1.739     raeburn  5702:         }
1.349     www      5703:     }
                   5704:     return $answer;
1.169     harris41 5705: }
                   5706: 
                   5707: # -------------------------------------------------- Modify user authentication
1.197     www      5708: # Overrides without validation
                   5709: 
1.169     harris41 5710: sub modifyuserauth {
                   5711:     my ($udom,$uname,$umode,$upass)=@_;
                   5712:     my $uhome=&homeserver($uname,$udom);
1.197     www      5713:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   5714:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 5715:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   5716:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 5717:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   5718: 		     &escape($upass),$uhome);
1.620     albertel 5719:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      5720:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   5721:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   5722:     &log($udom,,$uname,$uhome,
1.620     albertel 5723:         'Authentication changed by '.$env{'user.domain'}.', '.
                   5724:                                      $env{'user.name'}.', '.$umode.
1.197     www      5725:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 5726:     unless ($reply eq 'ok') {
1.197     www      5727:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 5728: 	return 'error: '.$reply;
                   5729:     }   
1.170     harris41 5730:     return 'ok';
1.80      www      5731: }
                   5732: 
1.81      www      5733: # --------------------------------------------------------------- Modify a user
1.80      www      5734: 
1.81      www      5735: sub modifyuser {
1.206     matthew  5736:     my ($udom,    $uname, $uid,
                   5737:         $umode,   $upass, $first,
                   5738:         $middle,  $last,  $gene,
1.963     raeburn  5739:         $forceid, $desiredhome, $email, $inststatus)=@_;
1.807     albertel 5740:     $udom= &LONCAPA::clean_domain($udom);
                   5741:     $uname=&LONCAPA::clean_username($uname);
1.81      www      5742:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      5743:              $umode.', '.$first.', '.$middle.', '.
1.206     matthew  5744: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
                   5745:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   5746:                                      ' desiredhome not specified'). 
1.620     albertel 5747:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   5748:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 5749:     my $uhome=&homeserver($uname,$udom,'true');
1.80      www      5750: # ----------------------------------------------------------------- Create User
1.406     albertel 5751:     if (($uhome eq 'no_host') && 
                   5752: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      5753:         my $unhome='';
1.844     albertel 5754:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  5755:             $unhome = $desiredhome;
1.620     albertel 5756: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   5757: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  5758:         } else { # load balancing routine for determining $unhome
1.81      www      5759:             my $loadm=10000000;
1.841     albertel 5760: 	    my %servers = &get_servers($udom,'library');
                   5761: 	    foreach my $tryserver (keys(%servers)) {
                   5762: 		my $answer=reply('load',$tryserver);
                   5763: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   5764: 		    $loadm=$answer;
                   5765: 		    $unhome=$tryserver;
                   5766: 		}
1.80      www      5767: 	    }
                   5768:         }
                   5769:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  5770: 	    return 'error: unable to find a home server for '.$uname.
                   5771:                    ' in domain '.$udom;
1.80      www      5772:         }
                   5773:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   5774:                          &escape($upass),$unhome);
                   5775: 	unless ($reply eq 'ok') {
                   5776:             return 'error: '.$reply;
                   5777:         }   
1.230     stredwic 5778:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      5779:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  5780: 	    return 'error: unable verify users home machine.';
1.80      www      5781:         }
1.209     matthew  5782:     }   # End of creation of new user
1.80      www      5783: # ---------------------------------------------------------------------- Add ID
                   5784:     if ($uid) {
                   5785:        $uid=~tr/A-Z/a-z/;
                   5786:        my %uidhash=&idrget($udom,$uname);
1.196     www      5787:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   5788:          && (!$forceid)) {
1.80      www      5789: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  5790: 	      return 'error: user id "'.$uid.'" does not match '.
                   5791:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      5792:           }
                   5793:        } else {
                   5794: 	  &idput($udom,($uname => $uid));
                   5795:        }
                   5796:     }
                   5797: # -------------------------------------------------------------- Add names, etc
1.313     matthew  5798:     my @tmp=&get('environment',
1.899     raeburn  5799: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  5800:                     'permanentemail','inststatus'],
1.134     albertel 5801: 		   $udom,$uname);
1.313     matthew  5802:     my %names;
                   5803:     if ($tmp[0] =~ m/^error:.*/) { 
                   5804:         %names=(); 
                   5805:     } else {
                   5806:         %names = @tmp;
                   5807:     }
1.388     www      5808: #
                   5809: # Make sure to not trash student environment if instructor does not bother
                   5810: # to supply name and email information
                   5811: #
                   5812:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  5813:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      5814:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  5815:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      5816:     if ($email) {
                   5817:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  5818:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      5819:     }
1.899     raeburn  5820:     if ($uid) { $names{'id'}  = $uid; }
1.963     raeburn  5821:     if (defined($inststatus)) { $names{'inststatus'} = $inststatus; } 
1.134     albertel 5822:     my $reply = &put('environment', \%names, $udom,$uname);
                   5823:     if ($reply ne 'ok') { return 'error: '.$reply; }
1.899     raeburn  5824:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
1.680     www      5825:     &devalidate_cache_new('namescache',$uname.':'.$udom);
1.963     raeburn  5826:     my $logmsg = 'Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
                   5827:                  $umode.', '.$first.', '.$middle.', '.
                   5828: 	         $last.', '.$gene.', '.$email.', '.$inststatus;
                   5829:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   5830:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   5831:     } else {
                   5832:         $logmsg .= ' during self creation';
                   5833:     }
                   5834:     &logthis($logmsg);
1.134     albertel 5835:     return 'ok';
1.80      www      5836: }
                   5837: 
1.81      www      5838: # -------------------------------------------------------------- Modify student
1.80      www      5839: 
1.81      www      5840: sub modifystudent {
                   5841:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  5842:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
                   5843:         $selfenroll,$context)=@_;
1.455     albertel 5844:     if (!$cid) {
1.620     albertel 5845: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 5846: 	    return 'not_in_class';
                   5847: 	}
1.80      www      5848:     }
                   5849: # --------------------------------------------------------------- Make the user
1.81      www      5850:     my $reply=&modifyuser
1.209     matthew  5851: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387     www      5852:          $desiredhome,$email);
1.80      www      5853:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  5854:     # This will cause &modify_student_enrollment to get the uid from the
                   5855:     # students environment
                   5856:     $uid = undef if (!$forceid);
1.455     albertel 5857:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957     raeburn  5858: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297     matthew  5859:     return $reply;
                   5860: }
                   5861: 
                   5862: sub modify_student_enrollment {
1.957     raeburn  5863:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455     albertel 5864:     my ($cdom,$cnum,$chome);
                   5865:     if (!$cid) {
1.620     albertel 5866: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 5867: 	    return 'not_in_class';
                   5868: 	}
1.620     albertel 5869: 	$cdom=$env{'course.'.$cid.'.domain'};
                   5870: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 5871:     } else {
                   5872: 	($cdom,$cnum)=split(/_/,$cid);
                   5873:     }
1.620     albertel 5874:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 5875:     if (!$chome) {
1.457     raeburn  5876: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  5877:     }
1.455     albertel 5878:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  5879:     # Make sure the user exists
1.81      www      5880:     my $uhome=&homeserver($uname,$udom);
                   5881:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   5882: 	return 'error: no such user';
                   5883:     }
1.297     matthew  5884:     # Get student data if we were not given enough information
                   5885:     if (!defined($first)  || $first  eq '' || 
                   5886:         !defined($last)   || $last   eq '' || 
                   5887:         !defined($uid)    || $uid    eq '' || 
                   5888:         !defined($middle) || $middle eq '' || 
                   5889:         !defined($gene)   || $gene   eq '') {
1.294     matthew  5890:         # They did not supply us with enough data to enroll the student, so
                   5891:         # we need to pick up more information.
1.297     matthew  5892:         my %tmp = &get('environment',
1.294     matthew  5893:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  5894:                        ,$udom,$uname);
                   5895: 
1.800     albertel 5896:         #foreach my $key (keys(%tmp)) {
                   5897:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 5898:         #}
1.294     matthew  5899:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   5900:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   5901:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  5902:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  5903:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   5904:     }
1.556     albertel 5905:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 5906:     my $reply=cput('classlist',
                   5907: 		   {"$uname:$udom" => 
1.515     raeburn  5908: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 5909: 		   $cdom,$cnum);
1.81      www      5910:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   5911: 	return 'error: '.$reply;
1.652     albertel 5912:     } else {
                   5913: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      5914:     }
1.297     matthew  5915:     # Add student role to user
1.83      www      5916:     my $uurl='/'.$cid;
1.81      www      5917:     $uurl=~s/\_/\//g;
                   5918:     if ($usec) {
                   5919: 	$uurl.='/'.$usec;
                   5920:     }
1.957     raeburn  5921:     return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
1.21      www      5922: }
                   5923: 
1.556     albertel 5924: sub format_name {
                   5925:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   5926:     my $name;
                   5927:     if ($first ne 'lastname') {
                   5928: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   5929:     } else {
                   5930: 	if ($lastname=~/\S/) {
                   5931: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   5932: 	    $name=~s/\s+,/,/;
                   5933: 	} else {
                   5934: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   5935: 	}
                   5936:     }
                   5937:     $name=~s/^\s+//;
                   5938:     $name=~s/\s+$//;
                   5939:     $name=~s/\s+/ /g;
                   5940:     return $name;
                   5941: }
                   5942: 
1.84      www      5943: # ------------------------------------------------- Write to course preferences
                   5944: 
                   5945: sub writecoursepref {
                   5946:     my ($courseid,%prefs)=@_;
                   5947:     $courseid=~s/^\///;
                   5948:     $courseid=~s/\_/\//g;
                   5949:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   5950:     my $chome=homeserver($cnum,$cdomain);
                   5951:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   5952: 	return 'error: no such course';
                   5953:     }
                   5954:     my $cstring='';
1.800     albertel 5955:     foreach my $pref (keys(%prefs)) {
                   5956: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 5957:     }
1.84      www      5958:     $cstring=~s/\&$//;
                   5959:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   5960: }
                   5961: 
                   5962: # ---------------------------------------------------------- Make/modify course
                   5963: 
                   5964: sub createcourse {
1.741     raeburn  5965:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
                   5966:         $course_owner,$crstype)=@_;
1.84      www      5967:     $url=&declutter($url);
                   5968:     my $cid='';
1.264     matthew  5969:     unless (&allowed('ccc',$udom)) {
1.84      www      5970:         return 'refused';
                   5971:     }
                   5972: # ------------------------------------------------------------------- Create ID
1.674     www      5973:    my $uname=int(1+rand(9)).
                   5974:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   5975:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
1.84      www      5976:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   5977: # ----------------------------------------------- Make sure that does not exist
1.230     stredwic 5978:    my $uhome=&homeserver($uname,$udom,'true');
1.84      www      5979:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   5980:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   5981:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230     stredwic 5982:        $uhome=&homeserver($uname,$udom,'true');       
1.84      www      5983:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   5984:            return 'error: unable to generate unique course-ID';
                   5985:        } 
                   5986:    }
1.264     matthew  5987: # ------------------------------------------------ Check supplied server name
1.620     albertel 5988:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.845     albertel 5989:     if (! &is_library($course_server)) {
1.264     matthew  5990:         return 'error:bad server name '.$course_server;
                   5991:     }
1.84      www      5992: # ------------------------------------------------------------- Make the course
                   5993:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  5994:                       $course_server);
1.84      www      5995:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230     stredwic 5996:     $uhome=&homeserver($uname,$udom,'true');
1.84      www      5997:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   5998: 	return 'error: no such course';
                   5999:     }
1.271     www      6000: # ----------------------------------------------------------------- Course made
1.516     raeburn  6001: # log existence
1.918     raeburn  6002:     my $newcourse = {
                   6003:                     $udom.'_'.$uname => {
1.921     raeburn  6004:                                      description => $description,
                   6005:                                      inst_code   => $inst_code,
                   6006:                                      owner       => $course_owner,
                   6007:                                      type        => $crstype,
1.918     raeburn  6008:                                                 },
                   6009:                     };
1.921     raeburn  6010:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      6011: # set toplevel url
1.271     www      6012:     my $topurl=$url;
                   6013:     unless ($nonstandard) {
                   6014: # ------------------------------------------ For standard courses, make top url
                   6015:         my $mapurl=&clutter($url);
1.278     www      6016:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 6017:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      6018: <map>
                   6019: <resource id="1" type="start"></resource>
                   6020: <resource id="2" src="$mapurl"></resource>
                   6021: <resource id="3" type="finish"></resource>
                   6022: <link index="1" from="1" to="2"></link>
                   6023: <link index="2" from="2" to="3"></link>
                   6024: </map>
                   6025: ENDINITMAP
                   6026:         $topurl=&declutter(
1.638     albertel 6027:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      6028:                           );
                   6029:     }
                   6030: # ----------------------------------------------------------- Write preferences
1.84      www      6031:     &writecoursepref($udom.'_'.$uname,
                   6032:                      ('description' => $description,
1.271     www      6033:                       'url'         => $topurl));
1.84      www      6034:     return '/'.$udom.'/'.$uname;
                   6035: }
                   6036: 
1.813     albertel 6037: sub is_course {
                   6038:     my ($cdom,$cnum) = @_;
                   6039:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.946     raeburn  6040: 				undef,'.');
1.813     albertel 6041:     if (exists($courses{$cdom.'_'.$cnum})) {
                   6042:         return 1;
                   6043:     }
                   6044:     return 0;
                   6045: }
                   6046: 
1.21      www      6047: # ---------------------------------------------------------- Assign Custom Role
                   6048: 
                   6049: sub assigncustomrole {
1.957     raeburn  6050:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      6051:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  6052:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      6053: }
                   6054: 
                   6055: # ----------------------------------------------------------------- Revoke Role
                   6056: 
                   6057: sub revokerole {
1.957     raeburn  6058:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      6059:     my $now=time;
1.965     raeburn  6060:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      6061: }
                   6062: 
                   6063: # ---------------------------------------------------------- Revoke Custom Role
                   6064: 
                   6065: sub revokecustomrole {
1.957     raeburn  6066:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      6067:     my $now=time;
1.357     www      6068:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  6069:            $deleteflag,$selfenroll,$context);
1.17      www      6070: }
                   6071: 
1.533     banghart 6072: # ------------------------------------------------------------ Disk usage
1.535     albertel 6073: sub diskusage {
1.955     raeburn  6074:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   6075:     $directorypath =~ s/\/$//;
                   6076:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   6077:                        .&escape($getpropath).':'.&escape($uname).':'
                   6078:                        .&escape($udom),homeserver($uname,$udom));
                   6079:     if ($listing eq 'unknown_cmd') {
                   6080:         if ($getpropath) {
                   6081:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   6082:         }
                   6083:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   6084:     }
1.514     albertel 6085:     return $listing;
1.512     banghart 6086: }
                   6087: 
1.566     banghart 6088: sub is_locked {
                   6089:     my ($file_name, $domain, $user) = @_;
                   6090:     my @check;
                   6091:     my $is_locked;
                   6092:     push @check, $file_name;
1.613     albertel 6093:     my %locked = &get('file_permissions',\@check,
1.620     albertel 6094: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 6095:     my ($tmp)=keys(%locked);
                   6096:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  6097:     
1.566     banghart 6098:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  6099:         $is_locked = 'false';
                   6100:         foreach my $entry (@{$locked{$file_name}}) {
                   6101:            if (ref($entry) eq 'ARRAY') { 
1.746     raeburn  6102:                $is_locked = 'true';
                   6103:                last;
1.745     raeburn  6104:            }
                   6105:        }
1.566     banghart 6106:     } else {
                   6107:         $is_locked = 'false';
                   6108:     }
                   6109: }
                   6110: 
1.759     albertel 6111: sub declutter_portfile {
                   6112:     my ($file) = @_;
1.833     albertel 6113:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 6114:     return $file;
                   6115: }
                   6116: 
1.559     banghart 6117: # ------------------------------------------------------------- Mark as Read Only
                   6118: 
                   6119: sub mark_as_readonly {
                   6120:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 6121:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 6122:     my ($tmp)=keys(%current_permissions);
                   6123:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 6124:     foreach my $file (@{$files}) {
1.759     albertel 6125: 	$file = &declutter_portfile($file);
1.561     banghart 6126:         push(@{$current_permissions{$file}},$what);
1.559     banghart 6127:     }
1.613     albertel 6128:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 6129:     return;
                   6130: }
                   6131: 
1.572     banghart 6132: # ------------------------------------------------------------Save Selected Files
                   6133: 
                   6134: sub save_selected_files {
                   6135:     my ($user, $path, @files) = @_;
                   6136:     my $filename = $user."savedfiles";
1.573     banghart 6137:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 6138:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 6139:     foreach my $file (@files) {
1.620     albertel 6140:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 6141:     }
                   6142:     foreach my $file (@other_files) {
1.574     banghart 6143:         print (OUT $file."\n");
1.572     banghart 6144:     }
1.574     banghart 6145:     close (OUT);
1.572     banghart 6146:     return 'ok';
                   6147: }
                   6148: 
1.574     banghart 6149: sub clear_selected_files {
                   6150:     my ($user) = @_;
                   6151:     my $filename = $user."savedfiles";
                   6152:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   6153:     print (OUT undef);
                   6154:     close (OUT);
                   6155:     return ("ok");    
                   6156: }
                   6157: 
1.572     banghart 6158: sub files_in_path {
                   6159:     my ($user, $path) = @_;
                   6160:     my $filename = $user."savedfiles";
                   6161:     my %return_files;
1.574     banghart 6162:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 6163:     while (my $line_in = <IN>) {
1.574     banghart 6164:         chomp ($line_in);
                   6165:         my @paths_and_file = split (m!/!, $line_in);
                   6166:         my $file_part = pop (@paths_and_file);
                   6167:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 6168:         $path_part.='/';
                   6169:         my $path_and_file = $path_part.$file_part;
                   6170:         if ($path_part eq $path) {
                   6171:             $return_files{$file_part}= 'selected';
                   6172:         }
                   6173:     }
1.574     banghart 6174:     close (IN);
                   6175:     return (\%return_files);
1.572     banghart 6176: }
                   6177: 
                   6178: # called in portfolio select mode, to show files selected NOT in current directory
                   6179: sub files_not_in_path {
                   6180:     my ($user, $path) = @_;
                   6181:     my $filename = $user."savedfiles";
                   6182:     my @return_files;
                   6183:     my $path_part;
1.800     albertel 6184:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   6185:     while (my $line = <IN>) {
1.572     banghart 6186:         #ok, I know it's clunky, but I want it to work
1.800     albertel 6187:         my @paths_and_file = split(m|/|, $line);
                   6188:         my $file_part = pop(@paths_and_file);
                   6189:         chomp($file_part);
                   6190:         my $path_part = join('/', @paths_and_file);
1.572     banghart 6191:         $path_part .= '/';
                   6192:         my $path_and_file = $path_part.$file_part;
                   6193:         if ($path_part ne $path) {
1.800     albertel 6194:             push(@return_files, ($path_and_file));
1.572     banghart 6195:         }
                   6196:     }
1.800     albertel 6197:     close(OUT);
1.574     banghart 6198:     return (@return_files);
1.572     banghart 6199: }
                   6200: 
1.745     raeburn  6201: #----------------------------------------------Get portfolio file permissions
1.629     banghart 6202: 
1.745     raeburn  6203: sub get_portfile_permissions {
                   6204:     my ($domain,$user) = @_;
1.613     albertel 6205:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 6206:     my ($tmp)=keys(%current_permissions);
                   6207:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  6208:     return \%current_permissions;
                   6209: }
                   6210: 
                   6211: #---------------------------------------------Get portfolio file access controls
                   6212: 
1.749     raeburn  6213: sub get_access_controls {
1.745     raeburn  6214:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 6215:     my %access;
                   6216:     my $real_file = $file;
                   6217:     $file =~ s/\.meta$//;
1.745     raeburn  6218:     if (defined($file)) {
1.749     raeburn  6219:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   6220:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 6221:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  6222:             }
                   6223:         }
1.745     raeburn  6224:     } else {
1.749     raeburn  6225:         foreach my $key (keys(%{$current_permissions})) {
                   6226:             if ($key =~ /\0accesscontrol$/) {
                   6227:                 if (defined($group)) {
                   6228:                     if ($key !~ m-^\Q$group\E/-) {
                   6229:                         next;
                   6230:                     }
                   6231:                 }
                   6232:                 my ($fullpath) = split(/\0/,$key);
                   6233:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   6234:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   6235:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   6236:                     }
                   6237:                 }
                   6238:             }
                   6239:         }
                   6240:     }
                   6241:     return %access;
                   6242: }
                   6243: 
                   6244: sub modify_access_controls {
                   6245:     my ($file_name,$changes,$domain,$user)=@_;
                   6246:     my ($outcome,$deloutcome);
                   6247:     my %store_permissions;
                   6248:     my %new_values;
                   6249:     my %new_control;
                   6250:     my %translation;
                   6251:     my @deletions = ();
                   6252:     my $now = time;
                   6253:     if (exists($$changes{'activate'})) {
                   6254:         if (ref($$changes{'activate'}) eq 'HASH') {
                   6255:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   6256:             my $numnew = scalar(@newitems);
                   6257:             for (my $i=0; $i<$numnew; $i++) {
                   6258:                 my $newkey = $newitems[$i];
                   6259:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  6260:                 if ($newkey =~ /^\d+:/) { 
                   6261:                     $newkey =~ s/^(\d+)/$newid/;
                   6262:                     $translation{$1} = $newid;
                   6263:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   6264:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   6265:                     $translation{$1} = $newid;
                   6266:                 }
1.749     raeburn  6267:                 $new_values{$file_name."\0".$newkey} = 
                   6268:                                           $$changes{'activate'}{$newitems[$i]};
                   6269:                 $new_control{$newkey} = $now;
                   6270:             }
                   6271:         }
                   6272:     }
                   6273:     my %todelete;
                   6274:     my %changed_items;
                   6275:     foreach my $action ('delete','update') {
                   6276:         if (exists($$changes{$action})) {
                   6277:             if (ref($$changes{$action}) eq 'HASH') {
                   6278:                 foreach my $key (keys(%{$$changes{$action}})) {
                   6279:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   6280:                     if ($action eq 'delete') { 
                   6281:                         $todelete{$itemnum} = 1;
                   6282:                     } else {
                   6283:                         $changed_items{$itemnum} = $key;
                   6284:                     }
                   6285:                 }
1.745     raeburn  6286:             }
                   6287:         }
1.749     raeburn  6288:     }
                   6289:     # get lock on access controls for file.
                   6290:     my $lockhash = {
                   6291:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   6292:                                                        ':'.$env{'user.domain'},
                   6293:                    }; 
                   6294:     my $tries = 0;
                   6295:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   6296:    
                   6297:     while (($gotlock ne 'ok') && $tries <3) {
                   6298:         $tries ++;
                   6299:         sleep 1;
                   6300:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   6301:     }
                   6302:     if ($gotlock eq 'ok') {
                   6303:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   6304:         my ($tmp)=keys(%curr_permissions);
                   6305:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   6306:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   6307:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   6308:             if (ref($curr_controls) eq 'HASH') {
                   6309:                 foreach my $control_item (keys(%{$curr_controls})) {
                   6310:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   6311:                     if (defined($todelete{$itemnum})) {
                   6312:                         push(@deletions,$file_name."\0".$control_item);
                   6313:                     } else {
                   6314:                         if (defined($changed_items{$itemnum})) {
                   6315:                             $new_control{$changed_items{$itemnum}} = $now;
                   6316:                             push(@deletions,$file_name."\0".$control_item);
                   6317:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   6318:                         } else {
                   6319:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   6320:                         }
                   6321:                     }
1.745     raeburn  6322:                 }
                   6323:             }
                   6324:         }
1.970     raeburn  6325:         my ($group);
                   6326:         if (&is_course($domain,$user)) {
                   6327:             ($group,my $file) = split(/\//,$file_name,2);
                   6328:         }
1.749     raeburn  6329:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   6330:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   6331:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   6332:         #  remove lock
                   6333:         my @del_lock = ($file_name."\0".'locked_access_records');
                   6334:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  6335:         my $sqlresult =
1.970     raeburn  6336:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  6337:                                     $group);
1.749     raeburn  6338:     } else {
                   6339:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  6340:     }
1.749     raeburn  6341:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  6342: }
                   6343: 
1.827     raeburn  6344: sub make_public_indefinitely {
                   6345:     my ($requrl) = @_;
                   6346:     my $now = time;
                   6347:     my $action = 'activate';
                   6348:     my $aclnum = 0;
                   6349:     if (&is_portfolio_url($requrl)) {
                   6350:         my (undef,$udom,$unum,$file_name,$group) =
                   6351:             &parse_portfolio_url($requrl);
                   6352:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   6353:         my %access_controls = &get_access_controls($current_perms,
                   6354:                                                    $group,$file_name);
                   6355:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   6356:             my ($num,$scope,$end,$start) = 
                   6357:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   6358:             if ($scope eq 'public') {
                   6359:                 if ($start <= $now && $end == 0) {
                   6360:                     $action = 'none';
                   6361:                 } else {
                   6362:                     $action = 'update';
                   6363:                     $aclnum = $num;
                   6364:                 }
                   6365:                 last;
                   6366:             }
                   6367:         }
                   6368:         if ($action eq 'none') {
                   6369:              return 'ok';
                   6370:         } else {
                   6371:             my %changes;
                   6372:             my $newend = 0;
                   6373:             my $newstart = $now;
                   6374:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   6375:             $changes{$action}{$newkey} = {
                   6376:                 type => 'public',
                   6377:                 time => {
                   6378:                     start => $newstart,
                   6379:                     end   => $newend,
                   6380:                 },
                   6381:             };
                   6382:             my ($outcome,$deloutcome,$new_values,$translation) =
                   6383:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   6384:             return $outcome;
                   6385:         }
                   6386:     } else {
                   6387:         return 'invalid';
                   6388:     }
                   6389: }
                   6390: 
1.745     raeburn  6391: #------------------------------------------------------Get Marked as Read Only
                   6392: 
                   6393: sub get_marked_as_readonly {
                   6394:     my ($domain,$user,$what,$group) = @_;
                   6395:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 6396:     my @readonly_files;
1.629     banghart 6397:     my $cmp1=$what;
                   6398:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  6399:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   6400:         if (defined($group)) {
                   6401:             if ($file_name !~ m-^\Q$group\E/-) {
                   6402:                 next;
                   6403:             }
                   6404:         }
1.561     banghart 6405:         if (ref($value) eq "ARRAY"){
                   6406:             foreach my $stored_what (@{$value}) {
1.629     banghart 6407:                 my $cmp2=$stored_what;
1.759     albertel 6408:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  6409:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  6410:                 }
1.629     banghart 6411:                 if ($cmp1 eq $cmp2) {
1.561     banghart 6412:                     push(@readonly_files, $file_name);
1.745     raeburn  6413:                     last;
1.563     banghart 6414:                 } elsif (!defined($what)) {
                   6415:                     push(@readonly_files, $file_name);
1.745     raeburn  6416:                     last;
1.561     banghart 6417:                 }
                   6418:             }
1.745     raeburn  6419:         }
1.561     banghart 6420:     }
                   6421:     return @readonly_files;
                   6422: }
1.577     banghart 6423: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 6424: 
1.577     banghart 6425: sub get_marked_as_readonly_hash {
1.745     raeburn  6426:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 6427:     my %readonly_files;
1.745     raeburn  6428:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   6429:         if (defined($group)) {
                   6430:             if ($file_name !~ m-^\Q$group\E/-) {
                   6431:                 next;
                   6432:             }
                   6433:         }
1.577     banghart 6434:         if (ref($value) eq "ARRAY"){
                   6435:             foreach my $stored_what (@{$value}) {
1.745     raeburn  6436:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 6437:                     foreach my $lock_descriptor(@{$stored_what}) {
                   6438:                         if ($lock_descriptor eq 'graded') {
                   6439:                             $readonly_files{$file_name} = 'graded';
                   6440:                         } elsif ($lock_descriptor eq 'handback') {
                   6441:                             $readonly_files{$file_name} = 'handback';
                   6442:                         } else {
                   6443:                             if (!exists($readonly_files{$file_name})) {
                   6444:                                 $readonly_files{$file_name} = 'locked';
                   6445:                             }
                   6446:                         }
1.745     raeburn  6447:                     }
1.750     banghart 6448:                 } 
1.577     banghart 6449:             }
                   6450:         } 
                   6451:     }
                   6452:     return %readonly_files;
                   6453: }
1.559     banghart 6454: # ------------------------------------------------------------ Unmark as Read Only
                   6455: 
                   6456: sub unmark_as_readonly {
1.629     banghart 6457:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   6458:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  6459:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 6460:     $file_name = &declutter_portfile($file_name);
1.634     albertel 6461:     my $symb_crs = $what;
                   6462:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  6463:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 6464:     my ($tmp)=keys(%current_permissions);
                   6465:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  6466:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 6467:     foreach my $file (@readonly_files) {
1.759     albertel 6468: 	my $clean_file = &declutter_portfile($file);
                   6469: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 6470: 	my $current_locks = $current_permissions{$file};
1.563     banghart 6471:         my @new_locks;
                   6472:         my @del_keys;
                   6473:         if (ref($current_locks) eq "ARRAY"){
                   6474:             foreach my $locker (@{$current_locks}) {
1.632     albertel 6475:                 my $compare=$locker;
1.749     raeburn  6476:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  6477:                     $compare=join('',@{$locker});
1.746     raeburn  6478:                     if ($compare ne $symb_crs) {
                   6479:                         push(@new_locks, $locker);
                   6480:                     }
1.563     banghart 6481:                 }
                   6482:             }
1.650     albertel 6483:             if (scalar(@new_locks) > 0) {
1.563     banghart 6484:                 $current_permissions{$file} = \@new_locks;
                   6485:             } else {
                   6486:                 push(@del_keys, $file);
1.613     albertel 6487:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 6488:                 delete($current_permissions{$file});
1.563     banghart 6489:             }
                   6490:         }
1.561     banghart 6491:     }
1.613     albertel 6492:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 6493:     return;
                   6494: }
1.512     banghart 6495: 
1.17      www      6496: # ------------------------------------------------------------ Directory lister
                   6497: 
                   6498: sub dirlist {
1.955     raeburn  6499:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      6500:     $uri=~s/^\///;
                   6501:     $uri=~s/\/$//;
1.253     stredwic 6502:     my ($udom, $uname);
1.955     raeburn  6503:     if ($getuserdir) {
1.253     stredwic 6504:         $udom = $userdomain;
                   6505:         $uname = $username;
1.955     raeburn  6506:     } else {
                   6507:         (undef,$udom,$uname)=split(/\//,$uri);
                   6508:         if(defined($userdomain)) {
                   6509:             $udom = $userdomain;
                   6510:         }
                   6511:         if(defined($username)) {
                   6512:             $uname = $username;
                   6513:         }
1.253     stredwic 6514:     }
1.955     raeburn  6515:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 6516: 
1.955     raeburn  6517:     $dirRoot = $perlvar{'lonDocRoot'};
                   6518:     if (defined($getpropath)) {
                   6519:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 6520:         $dirRoot =~ s/\/$//;
1.955     raeburn  6521:     } elsif (defined($getuserdir)) {
                   6522:         my $subdir=$uname.'__';
                   6523:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   6524:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   6525:                    ."/$udom/$subdir/$uname";
                   6526:     } elsif (defined($alternateRoot)) {
                   6527:         $dirRoot = $alternateRoot;
1.751     banghart 6528:     }
1.253     stredwic 6529: 
                   6530:     if($udom) {
                   6531:         if($uname) {
1.955     raeburn  6532:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  6533:                               .$getuserdir.':'.&escape($dirRoot)
1.955     raeburn  6534:                               .':'.&escape($uname).':'.&escape($udom),
                   6535:                               &homeserver($uname,$udom));
                   6536:             if ($listing eq 'unknown_cmd') {
                   6537:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
                   6538:                                   &homeserver($uname,$udom));
                   6539:             } else {
                   6540:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   6541:             }
1.605     matthew  6542:             if ($listing eq 'unknown_cmd') {
1.800     albertel 6543:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
                   6544: 				  &homeserver($uname,$udom));
1.605     matthew  6545:                 @listing_results = split(/:/,$listing);
                   6546:             } else {
                   6547:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   6548:             }
                   6549:             return @listing_results;
1.955     raeburn  6550:         } elsif(!$alternateRoot) {
1.800     albertel 6551:             my %allusers;
1.841     albertel 6552: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  6553:  	    foreach my $tryserver (keys(%servers)) {
                   6554:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   6555:                                   &escape($udom),$tryserver);
                   6556:                 if ($listing eq 'unknown_cmd') {
                   6557: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   6558: 				      $udom, $tryserver);
                   6559:                 } else {
                   6560:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   6561:                 }
1.841     albertel 6562: 		if ($listing eq 'unknown_cmd') {
                   6563: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   6564: 				      $udom, $tryserver);
                   6565: 		    @listing_results = split(/:/,$listing);
                   6566: 		} else {
                   6567: 		    @listing_results =
                   6568: 			map { &unescape($_); } split(/:/,$listing);
                   6569: 		}
                   6570: 		if ($listing_results[0] ne 'no_such_dir' && 
                   6571: 		    $listing_results[0] ne 'empty'       &&
                   6572: 		    $listing_results[0] ne 'con_lost') {
                   6573: 		    foreach my $line (@listing_results) {
                   6574: 			my ($entry) = split(/&/,$line,2);
                   6575: 			$allusers{$entry} = 1;
                   6576: 		    }
                   6577: 		}
1.253     stredwic 6578:             }
                   6579:             my $alluserstr='';
1.800     albertel 6580:             foreach my $user (sort(keys(%allusers))) {
                   6581:                 $alluserstr.=$user.'&user:';
1.253     stredwic 6582:             }
                   6583:             $alluserstr=~s/:$//;
                   6584:             return split(/:/,$alluserstr);
                   6585:         } else {
1.800     albertel 6586:             return ('missing user name');
1.253     stredwic 6587:         }
1.955     raeburn  6588:     } elsif(!defined($getpropath)) {
1.841     albertel 6589:         my @all_domains = sort(&all_domains());
1.955     raeburn  6590:         foreach my $domain (@all_domains) {
                   6591:             $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
                   6592:         }
                   6593:         return @all_domains;
                   6594:     } else {
1.800     albertel 6595:         return ('missing domain');
1.275     stredwic 6596:     }
                   6597: }
                   6598: 
                   6599: # --------------------------------------------- GetFileTimestamp
                   6600: # This function utilizes dirlist and returns the date stamp for
                   6601: # when it was last modified.  It will also return an error of -1
                   6602: # if an error occurs
                   6603: 
                   6604: sub GetFileTimestamp {
1.955     raeburn  6605:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 6606:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   6607:     $studentName   = &LONCAPA::clean_username($studentName);
1.955     raeburn  6608:     my ($fileStat) = 
                   6609:         &Apache::lonnet::dirlist($filename,$studentDomain,$studentName, 
                   6610:                                  undef,$getuserdir);
1.275     stredwic 6611:     my @stats = split('&', $fileStat);
                   6612:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  6613:         # @stats contains first the filename, then the stat output
                   6614:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 6615:     } else {
                   6616:         return -1;
1.253     stredwic 6617:     }
1.26      www      6618: }
                   6619: 
1.712     albertel 6620: sub stat_file {
                   6621:     my ($uri) = @_;
1.787     albertel 6622:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 6623: 
1.955     raeburn  6624:     my ($udom,$uname,$file);
1.712     albertel 6625:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   6626: 	($udom,$uname,$file) =
1.811     albertel 6627: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 6628: 	$file = 'userfiles/'.$file;
                   6629:     }
                   6630:     if ($uri =~ m-^/res/-) {
                   6631: 	($udom,$uname) = 
1.807     albertel 6632: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 6633: 	$file = $uri;
                   6634:     }
                   6635: 
                   6636:     if (!$udom || !$uname || !$file) {
                   6637: 	# unable to handle the uri
                   6638: 	return ();
                   6639:     }
1.956     raeburn  6640:     my $getpropath;
                   6641:     if ($file =~ /^userfiles\//) {
                   6642:         $getpropath = 1;
                   6643:     }
1.955     raeburn  6644:     my ($result) = &dirlist($file,$udom,$uname,$getpropath);
1.712     albertel 6645:     my @stats = split('&', $result);
1.721     banghart 6646:     
1.712     albertel 6647:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   6648: 	shift(@stats); #filename is first
                   6649: 	return @stats;
                   6650:     }
                   6651:     return ();
                   6652: }
                   6653: 
1.26      www      6654: # -------------------------------------------------------- Value of a Condition
                   6655: 
1.713     albertel 6656: # gets the value of a specific preevaluated condition
                   6657: #    stored in the string  $env{user.state.<cid>}
                   6658: # or looks up a condition reference in the bighash and if if hasn't
                   6659: # already been evaluated recurses into docondval to get the value of
                   6660: # the condition, then memoizing it to 
                   6661: #   $env{user.state.<cid>.<condition>}
1.40      www      6662: sub directcondval {
                   6663:     my $number=shift;
1.620     albertel 6664:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 6665: 	&Apache::lonuserstate::evalstate();
                   6666:     }
1.713     albertel 6667:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   6668: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   6669:     } elsif ($number =~ /^_/) {
                   6670: 	my $sub_condition;
                   6671: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   6672: 		&GDBM_READER(),0640)) {
                   6673: 	    $sub_condition=$bighash{'conditions'.$number};
                   6674: 	    untie(%bighash);
                   6675: 	}
                   6676: 	my $value = &docondval($sub_condition);
1.949     raeburn  6677: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 6678: 	return $value;
                   6679:     }
1.620     albertel 6680:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   6681:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      6682:     } else {
                   6683:        return 2;
                   6684:     }
                   6685: }
                   6686: 
1.713     albertel 6687: # get the collection of conditions for this resource
1.26      www      6688: sub condval {
                   6689:     my $condidx=shift;
1.54      www      6690:     my $allpathcond='';
1.713     albertel 6691:     foreach my $cond (split(/\|/,$condidx)) {
                   6692: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   6693: 	    $allpathcond.=
                   6694: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   6695: 	}
1.191     harris41 6696:     }
1.54      www      6697:     $allpathcond=~s/\|$//;
1.713     albertel 6698:     return &docondval($allpathcond);
                   6699: }
                   6700: 
                   6701: #evaluates an expression of conditions
                   6702: sub docondval {
                   6703:     my ($allpathcond) = @_;
                   6704:     my $result=0;
                   6705:     if ($env{'request.course.id'}
                   6706: 	&& defined($allpathcond)) {
                   6707: 	my $operand='|';
                   6708: 	my @stack;
                   6709: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   6710: 	    if ($chunk eq '(') {
                   6711: 		push @stack,($operand,$result);
                   6712: 	    } elsif ($chunk eq ')') {
                   6713: 		my $before=pop @stack;
                   6714: 		if (pop @stack eq '&') {
                   6715: 		    $result=$result>$before?$before:$result;
                   6716: 		} else {
                   6717: 		    $result=$result>$before?$result:$before;
                   6718: 		}
                   6719: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   6720: 		$operand=$chunk;
                   6721: 	    } else {
                   6722: 		my $new=directcondval($chunk);
                   6723: 		if ($operand eq '&') {
                   6724: 		    $result=$result>$new?$new:$result;
                   6725: 		} else {
                   6726: 		    $result=$result>$new?$result:$new;
                   6727: 		}
                   6728: 	    }
                   6729: 	}
1.26      www      6730:     }
                   6731:     return $result;
1.421     albertel 6732: }
                   6733: 
                   6734: # ---------------------------------------------------- Devalidate courseresdata
                   6735: 
                   6736: sub devalidatecourseresdata {
                   6737:     my ($coursenum,$coursedomain)=@_;
                   6738:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 6739:     &devalidate_cache_new('courseres',$hashid);
1.28      www      6740: }
                   6741: 
1.763     www      6742: 
1.200     www      6743: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     6744: #
                   6745: #  Parameters:
                   6746: #      $coursenum    - Number of the course.
                   6747: #      $coursedomain - Domain at which the course was created.
                   6748: #  Returns:
                   6749: #     A hash of the course parameters along (I think) with timestamps
                   6750: #     and version info.
1.877     foxr     6751: 
1.624     albertel 6752: sub get_courseresdata {
                   6753:     my ($coursenum,$coursedomain)=@_;
1.200     www      6754:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   6755:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 6756:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 6757:     my %dumpreply;
1.417     albertel 6758:     unless (defined($cached)) {
1.624     albertel 6759: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 6760: 	$result=\%dumpreply;
1.251     albertel 6761: 	my ($tmp) = keys(%dumpreply);
                   6762: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 6763: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 6764: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   6765: 	    return $tmp;
1.416     albertel 6766: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 6767: 	    $result=undef;
1.599     albertel 6768: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 6769: 	}
                   6770:     }
1.624     albertel 6771:     return $result;
                   6772: }
                   6773: 
1.633     albertel 6774: sub devalidateuserresdata {
                   6775:     my ($uname,$udom)=@_;
                   6776:     my $hashid="$udom:$uname";
                   6777:     &devalidate_cache_new('userres',$hashid);
                   6778: }
                   6779: 
1.624     albertel 6780: sub get_userresdata {
                   6781:     my ($uname,$udom)=@_;
                   6782:     #most student don\'t have any data set, check if there is some data
                   6783:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   6784: 
                   6785:     my $hashid="$udom:$uname";
                   6786:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   6787:     if (!defined($cached)) {
                   6788: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   6789: 	$result=\%resourcedata;
                   6790: 	&do_cache_new('userres',$hashid,$result,600);
                   6791:     }
                   6792:     my ($tmp)=keys(%$result);
                   6793:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   6794: 	return $result;
                   6795:     }
                   6796:     #error 2 occurs when the .db doesn't exist
                   6797:     if ($tmp!~/error: 2 /) {
1.672     albertel 6798: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 6799: 		 " Trying to get resource data for ".
                   6800: 		 $uname." at ".$udom.": ".
                   6801: 		 $tmp."</font>");
                   6802:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 6803: 	#&EXT_cache_set($udom,$uname);
                   6804: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 6805: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 6806:     }
                   6807:     return $tmp;
                   6808: }
1.879     foxr     6809: #----------------------------------------------- resdata - return resource data
                   6810: #  Purpose:
                   6811: #    Return resource data for either users or for a course.
                   6812: #  Parameters:
                   6813: #     $name      - Course/user name.
                   6814: #     $domain    - Name of the domain the user/course is registered on.
                   6815: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   6816: #     @which     - Array of names of resources desired.
                   6817: #  Returns:
                   6818: #     The value of the first reasource in @which that is found in the
                   6819: #     resource hash.
                   6820: #  Exceptional Conditions:
                   6821: #     If the $type passed in is not valid (not the string 'course' or 
                   6822: #     'user', an undefined  reference is returned.
                   6823: #     If none of the resources are found, an undef is returned
1.624     albertel 6824: sub resdata {
                   6825:     my ($name,$domain,$type,@which)=@_;
                   6826:     my $result;
                   6827:     if ($type eq 'course') {
                   6828: 	$result=&get_courseresdata($name,$domain);
                   6829:     } elsif ($type eq 'user') {
                   6830: 	$result=&get_userresdata($name,$domain);
                   6831:     }
                   6832:     if (!ref($result)) { return $result; }    
1.251     albertel 6833:     foreach my $item (@which) {
1.927     albertel 6834: 	if (defined($result->{$item->[0]})) {
                   6835: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 6836: 	}
1.250     albertel 6837:     }
1.291     albertel 6838:     return undef;
1.200     www      6839: }
                   6840: 
1.379     matthew  6841: #
                   6842: # EXT resource caching routines
                   6843: #
                   6844: 
                   6845: sub clear_EXT_cache_status {
1.383     albertel 6846:     &delenv('cache.EXT.');
1.379     matthew  6847: }
                   6848: 
                   6849: sub EXT_cache_status {
                   6850:     my ($target_domain,$target_user) = @_;
1.383     albertel 6851:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 6852:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  6853:         # We know already the user has no data
                   6854:         return 1;
                   6855:     } else {
                   6856:         return 0;
                   6857:     }
                   6858: }
                   6859: 
                   6860: sub EXT_cache_set {
                   6861:     my ($target_domain,$target_user) = @_;
1.383     albertel 6862:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  6863:     #&appenv({$cachename => time});
1.379     matthew  6864: }
                   6865: 
1.28      www      6866: # --------------------------------------------------------- Value of a Variable
1.58      www      6867: sub EXT {
1.715     albertel 6868: 
1.395     albertel 6869:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      6870:     unless ($varname) { return ''; }
1.218     albertel 6871:     #get real user name/domain, courseid and symb
                   6872:     my $courseid;
1.359     albertel 6873:     my $publicuser;
1.427     www      6874:     if ($symbparm) {
                   6875: 	$symbparm=&get_symb_from_alias($symbparm);
                   6876:     }
1.218     albertel 6877:     if (!($uname && $udom)) {
1.790     albertel 6878:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 6879:       if (!$symbparm) {	$symbparm=$cursymb; }
                   6880:     } else {
1.620     albertel 6881: 	$courseid=$env{'request.course.id'};
1.218     albertel 6882:     }
1.48      www      6883:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   6884:     my $rest;
1.320     albertel 6885:     if (defined($therest[0])) {
1.48      www      6886:        $rest=join('.',@therest);
                   6887:     } else {
                   6888:        $rest='';
                   6889:     }
1.320     albertel 6890: 
1.57      www      6891:     my $qualifierrest=$qualifier;
                   6892:     if ($rest) { $qualifierrest.='.'.$rest; }
                   6893:     my $spacequalifierrest=$space;
                   6894:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      6895:     if ($realm eq 'user') {
1.48      www      6896: # --------------------------------------------------------------- user.resource
                   6897: 	if ($space eq 'resource') {
1.651     albertel 6898: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   6899: 		  || defined($Apache::lonhomework::parsing_a_task))
                   6900: 		 &&
1.744     albertel 6901: 		 ($symbparm eq &symbread()) ) {	
                   6902: 		# if we are in the middle of processing the resource the
                   6903: 		# get the value we are planning on committing
                   6904:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   6905:                     return $Apache::lonhomework::results{$qualifierrest};
                   6906:                 } else {
                   6907:                     return $Apache::lonhomework::history{$qualifierrest};
                   6908:                 }
1.335     albertel 6909: 	    } else {
1.359     albertel 6910: 		my %restored;
1.620     albertel 6911: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 6912: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   6913: 		} else {
                   6914: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   6915: 		}
1.335     albertel 6916: 		return $restored{$qualifierrest};
                   6917: 	    }
1.48      www      6918: # ----------------------------------------------------------------- user.access
                   6919:         } elsif ($space eq 'access') {
1.218     albertel 6920: 	    # FIXME - not supporting calls for a specific user
1.48      www      6921:             return &allowed($qualifier,$rest);
                   6922: # ------------------------------------------ user.preferences, user.environment
                   6923:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 6924: 	    if (($uname eq $env{'user.name'}) &&
                   6925: 		($udom eq $env{'user.domain'})) {
                   6926: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 6927: 	    } else {
1.359     albertel 6928: 		my %returnhash;
                   6929: 		if (!$publicuser) {
                   6930: 		    %returnhash=&userenvironment($udom,$uname,
                   6931: 						 $qualifierrest);
                   6932: 		}
1.218     albertel 6933: 		return $returnhash{$qualifierrest};
                   6934: 	    }
1.48      www      6935: # ----------------------------------------------------------------- user.course
                   6936:         } elsif ($space eq 'course') {
1.218     albertel 6937: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 6938:             return $env{join('.',('request.course',$qualifier))};
1.48      www      6939: # ------------------------------------------------------------------- user.role
                   6940:         } elsif ($space eq 'role') {
1.218     albertel 6941: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 6942:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      6943:             if ($qualifier eq 'value') {
                   6944: 		return $role;
                   6945:             } elsif ($qualifier eq 'extent') {
                   6946:                 return $where;
                   6947:             }
                   6948: # ----------------------------------------------------------------- user.domain
                   6949:         } elsif ($space eq 'domain') {
1.218     albertel 6950:             return $udom;
1.48      www      6951: # ------------------------------------------------------------------- user.name
                   6952:         } elsif ($space eq 'name') {
1.218     albertel 6953:             return $uname;
1.48      www      6954: # ---------------------------------------------------- Any other user namespace
1.29      www      6955:         } else {
1.359     albertel 6956: 	    my %reply;
                   6957: 	    if (!$publicuser) {
                   6958: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   6959: 	    }
                   6960: 	    return $reply{$qualifierrest};
1.48      www      6961:         }
1.236     www      6962:     } elsif ($realm eq 'query') {
                   6963: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 6964:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   6965: 						[$spacequalifierrest]);
1.620     albertel 6966: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      6967:    } elsif ($realm eq 'request') {
1.48      www      6968: # ------------------------------------------------------------- request.browser
                   6969:         if ($space eq 'browser') {
1.430     www      6970: 	    if ($qualifier eq 'textremote') {
1.676     albertel 6971: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      6972: 		    return 1;
                   6973: 		} else {
                   6974: 		    return 0;
                   6975: 		}
                   6976: 	    } else {
1.620     albertel 6977: 		return $env{'browser.'.$qualifier};
1.430     www      6978: 	    }
1.57      www      6979: # ------------------------------------------------------------ request.filename
                   6980:         } else {
1.620     albertel 6981:             return $env{'request.'.$spacequalifierrest};
1.29      www      6982:         }
1.28      www      6983:     } elsif ($realm eq 'course') {
1.48      www      6984: # ---------------------------------------------------------- course.description
1.620     albertel 6985:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      6986:     } elsif ($realm eq 'resource') {
1.165     www      6987: 
1.620     albertel 6988: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 6989: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   6990: 	}
1.693     albertel 6991: 
                   6992: 	if ($space eq 'title') {
                   6993: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   6994: 	    return &gettitle($symbparm);
                   6995: 	}
                   6996: 	
                   6997: 	if ($space eq 'map') {
                   6998: 	    my ($map) = &decode_symb($symbparm);
                   6999: 	    return &symbread($map);
                   7000: 	}
1.905     albertel 7001: 	if ($space eq 'filename') {
                   7002: 	    if ($symbparm) {
                   7003: 		return &clutter((&decode_symb($symbparm))[2]);
                   7004: 	    }
                   7005: 	    return &hreflocation('',$env{'request.filename'});
                   7006: 	}
1.693     albertel 7007: 
                   7008: 	my ($section, $group, @groups);
1.593     albertel 7009: 	my ($courselevelm,$courselevel);
1.539     albertel 7010: 	if ($symbparm && defined($courseid) && 
1.620     albertel 7011: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      7012: 
1.218     albertel 7013: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      7014: 
1.60      www      7015: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 7016: 	    my $symbp=$symbparm;
1.735     albertel 7017: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 7018: 
                   7019: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   7020: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   7021: 
1.620     albertel 7022: 	    if (($env{'user.name'} eq $uname) &&
                   7023: 		($env{'user.domain'} eq $udom)) {
                   7024: 		$section=$env{'request.course.sec'};
1.733     raeburn  7025:                 @groups = split(/:/,$env{'request.course.groups'});  
                   7026:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 7027: 	    } else {
1.539     albertel 7028: 		if (! defined($usection)) {
1.551     albertel 7029: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 7030: 		} else {
                   7031: 		    $section = $usection;
                   7032: 		}
1.733     raeburn  7033:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 7034: 	    }
                   7035: 
                   7036: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   7037: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   7038: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   7039: 
1.593     albertel 7040: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 7041: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 7042: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      7043: 
1.60      www      7044: # ----------------------------------------------------------- first, check user
1.624     albertel 7045: 
                   7046: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 7047: 				       ([$courselevelr,'resource'],
                   7048: 					[$courselevelm,'map'     ],
                   7049: 					[$courselevel, 'course'  ]));
1.931     albertel 7050: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      7051: 
1.594     albertel 7052: # ------------------------------------------------ second, check some of course
1.684     raeburn  7053:             my $coursereply;
1.691     raeburn  7054:             if (@groups > 0) {
                   7055:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   7056:                                        $mapparm,$spacequalifierrest);
1.927     albertel 7057:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  7058:             }
1.96      www      7059: 
1.684     raeburn  7060: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 7061: 				  $env{'course.'.$courseid.'.domain'},
                   7062: 				  'course',
                   7063: 				  ([$seclevelr,   'resource'],
                   7064: 				   [$seclevelm,   'map'     ],
                   7065: 				   [$seclevel,    'course'  ],
                   7066: 				   [$courselevelr,'resource']));
                   7067: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      7068: 
1.60      www      7069: # ------------------------------------------------------ third, check map parms
1.218     albertel 7070: 	    my %parmhash=();
                   7071: 	    my $thisparm='';
                   7072: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 7073: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 7074: 		    &GDBM_READER(),0640)) {
1.218     albertel 7075: 		$thisparm=$parmhash{$symbparm};
                   7076: 		untie(%parmhash);
                   7077: 	    }
1.927     albertel 7078: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 7079: 	}
1.594     albertel 7080: # ------------------------------------------ fourth, look in resource metadata
1.71      www      7081: 
1.218     albertel 7082: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 7083: 	my $filename;
                   7084: 	if (!$symbparm) { $symbparm=&symbread(); }
                   7085: 	if ($symbparm) {
1.409     www      7086: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 7087: 	} else {
1.620     albertel 7088: 	    $filename=$env{'request.filename'};
1.282     albertel 7089: 	}
                   7090: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 7091: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 7092: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 7093: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      7094: 
1.927     albertel 7095: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 7096: 	if ($symbparm && defined($courseid) && 
1.620     albertel 7097: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 7098: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   7099: 				     $env{'course.'.$courseid.'.domain'},
                   7100: 				     'course',
1.927     albertel 7101: 				     ([$courselevelm,'map'   ],
                   7102: 				      [$courselevel, 'course']));
                   7103: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 7104: 	}
1.145     www      7105: # ------------------------------------------------------------------ Cascade up
1.218     albertel 7106: 	unless ($space eq '0') {
1.336     albertel 7107: 	    my @parts=split(/_/,$space);
                   7108: 	    my $id=pop(@parts);
                   7109: 	    my $part=join('_',@parts);
                   7110: 	    if ($part eq '') { $part='0'; }
1.927     albertel 7111: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 7112: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  7113: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 7114: 	}
1.395     albertel 7115: 	if ($recurse) { return undef; }
                   7116: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 7117: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      7118: # ---------------------------------------------------- Any other user namespace
                   7119:     } elsif ($realm eq 'environment') {
                   7120: # ----------------------------------------------------------------- environment
1.620     albertel 7121: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   7122: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 7123: 	} else {
1.770     albertel 7124: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   7125: 		return '';
                   7126: 	    }
1.219     albertel 7127: 	    my %returnhash=&userenvironment($udom,$uname,
                   7128: 					    $spacequalifierrest);
                   7129: 	    return $returnhash{$spacequalifierrest};
                   7130: 	}
1.28      www      7131:     } elsif ($realm eq 'system') {
1.48      www      7132: # ----------------------------------------------------------------- system.time
                   7133: 	if ($space eq 'time') {
                   7134: 	    return time;
                   7135:         }
1.696     albertel 7136:     } elsif ($realm eq 'server') {
                   7137: # ----------------------------------------------------------------- system.time
                   7138: 	if ($space eq 'name') {
                   7139: 	    return $ENV{'SERVER_NAME'};
                   7140:         }
1.28      www      7141:     }
1.48      www      7142:     return '';
1.61      www      7143: }
                   7144: 
1.927     albertel 7145: sub get_reply {
                   7146:     my ($reply_value) = @_;
1.940     raeburn  7147:     if (ref($reply_value) eq 'ARRAY') {
                   7148:         if (wantarray) {
                   7149: 	    return @$reply_value;
                   7150:         }
                   7151:         return $reply_value->[0];
                   7152:     } else {
                   7153:         return $reply_value;
1.927     albertel 7154:     }
                   7155: }
                   7156: 
1.691     raeburn  7157: sub check_group_parms {
                   7158:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   7159:     my @groupitems = ();
                   7160:     my $resultitem;
1.927     albertel 7161:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  7162:     foreach my $group (@{$groups}) {
                   7163:         foreach my $level (@levels) {
1.927     albertel 7164:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   7165:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  7166:         }
                   7167:     }
                   7168:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   7169:                             $env{'course.'.$courseid.'.domain'},
                   7170:                                      'course',@groupitems);
                   7171:     return $coursereply;
                   7172: }
                   7173: 
                   7174: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  7175:     my ($courseid,@groups) = @_;
                   7176:     @groups = sort(@groups);
1.691     raeburn  7177:     return @groups;
                   7178: }
                   7179: 
1.395     albertel 7180: sub packages_tab_default {
                   7181:     my ($uri,$varname)=@_;
                   7182:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 7183: 
                   7184:     my (@extension,@specifics,$do_default);
                   7185:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 7186: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 7187: 	if ($pack_type eq 'default') {
                   7188: 	    $do_default=1;
                   7189: 	} elsif ($pack_type eq 'extension') {
                   7190: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 7191: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 7192: 	    # only look at packages defaults for packages that this id is
1.738     albertel 7193: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   7194: 	}
                   7195:     }
                   7196:     # first look for a package that matches the requested part id
                   7197:     foreach my $package (@specifics) {
                   7198: 	my (undef,$pack_type,$pack_part)=@{$package};
                   7199: 	next if ($pack_part ne $part);
                   7200: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   7201: 	    return $packagetab{"$pack_type&$name&default"};
                   7202: 	}
                   7203:     }
                   7204:     # look for any possible matching non extension_ package
                   7205:     foreach my $package (@specifics) {
                   7206: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 7207: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   7208: 	    return $packagetab{"$pack_type&$name&default"};
                   7209: 	}
1.585     albertel 7210: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 7211: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   7212: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 7213: 	}
                   7214:     }
1.738     albertel 7215:     # look for any posible extension_ match
                   7216:     foreach my $package (@extension) {
                   7217: 	my ($package,$pack_type)=@{$package};
                   7218: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   7219: 	    return $packagetab{"$pack_type&$name&default"};
                   7220: 	}
                   7221: 	if (defined($packagetab{$package."&$name&default"})) {
                   7222: 	    return $packagetab{$package."&$name&default"};
                   7223: 	}
                   7224:     }
                   7225:     # look for a global default setting
                   7226:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   7227: 	return $packagetab{"default&$name&default"};
                   7228:     }
1.395     albertel 7229:     return undef;
                   7230: }
                   7231: 
1.334     albertel 7232: sub add_prefix_and_part {
                   7233:     my ($prefix,$part)=@_;
                   7234:     my $keyroot;
                   7235:     if (defined($prefix) && $prefix !~ /^__/) {
                   7236: 	# prefix that has a part already
                   7237: 	$keyroot=$prefix;
                   7238:     } elsif (defined($prefix)) {
                   7239: 	# prefix that is missing a part
                   7240: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   7241:     } else {
                   7242: 	# no prefix at all
                   7243: 	if (defined($part)) { $keyroot='_'.$part; }
                   7244:     }
                   7245:     return $keyroot;
                   7246: }
                   7247: 
1.71      www      7248: # ---------------------------------------------------------------- Get metadata
                   7249: 
1.599     albertel 7250: my %metaentry;
1.71      www      7251: sub metadata {
1.176     www      7252:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      7253:     $uri=&declutter($uri);
1.288     albertel 7254:     # if it is a non metadata possible uri return quickly
1.529     albertel 7255:     if (($uri eq '') || 
                   7256: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 7257: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.924     albertel 7258:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
                   7259: 	return undef;
                   7260:     }
                   7261:     if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) 
                   7262: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 7263: 	return undef;
1.288     albertel 7264:     }
1.73      www      7265:     my $filename=$uri;
                   7266:     $uri=~s/\.meta$//;
1.172     www      7267: #
                   7268: # Is the metadata already cached?
1.177     www      7269: # Look at timestamp of caching
1.172     www      7270: # Everything is cached by the main uri, libraries are never directly cached
                   7271: #
1.428     albertel 7272:     if (!defined($liburi)) {
1.599     albertel 7273: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 7274: 	if (defined($cached)) { return $result->{':'.$what}; }
                   7275:     }
                   7276:     {
1.172     www      7277: #
                   7278: # Is this a recursive call for a library?
                   7279: #
1.599     albertel 7280: #	if (! exists($metacache{$uri})) {
                   7281: #	    $metacache{$uri}={};
                   7282: #	}
1.924     albertel 7283: 	my $cachetime = 60*60;
1.171     www      7284:         if ($liburi) {
                   7285: 	    $liburi=&declutter($liburi);
                   7286:             $filename=$liburi;
1.401     bowersj2 7287:         } else {
1.599     albertel 7288: 	    &devalidate_cache_new('meta',$uri);
                   7289: 	    undef(%metaentry);
1.401     bowersj2 7290: 	}
1.140     www      7291:         my %metathesekeys=();
1.73      www      7292:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 7293: 	my $metastring;
1.924     albertel 7294: 	if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
1.929     albertel 7295: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 7296: 	    $metastring = 
1.929     albertel 7297: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 7298: 					  ('grade_target' => 'meta'));
                   7299: 	    $cachetime = 1; # only want this cached in the child not long term
                   7300: 	} elsif ($uri !~ m -^(editupload)/-) {
1.543     albertel 7301: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 7302: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 7303: 	    $metastring=&getfile($file);
1.489     albertel 7304: 	}
1.208     albertel 7305:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      7306:         my $token;
1.140     www      7307:         undef %metathesekeys;
1.71      www      7308:         while ($token=$parser->get_token) {
1.339     albertel 7309: 	    if ($token->[0] eq 'S') {
                   7310: 		if (defined($token->[2]->{'package'})) {
1.172     www      7311: #
                   7312: # This is a package - get package info
                   7313: #
1.339     albertel 7314: 		    my $package=$token->[2]->{'package'};
                   7315: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   7316: 		    if (defined($token->[2]->{'id'})) { 
                   7317: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   7318: 		    }
1.599     albertel 7319: 		    if ($metaentry{':packages'}) {
                   7320: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 7321: 		    } else {
1.599     albertel 7322: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 7323: 		    }
1.736     albertel 7324: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 7325: 			my $part=$keyroot;
                   7326: 			$part=~s/^\_//;
1.736     albertel 7327: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   7328: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   7329: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 7330: 			    # ignore package.tab specified default values
                   7331:                             # here &package_tab_default() will fetch those
                   7332: 			    if ($subp eq 'default') { next; }
1.736     albertel 7333: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 7334: 			    my $unikey;
                   7335: 			    if ($pack =~ /_0$/) {
                   7336: 				$unikey='parameter_0_'.$name;
                   7337: 				$part=0;
                   7338: 			    } else {
                   7339: 				$unikey='parameter'.$keyroot.'_'.$name;
                   7340: 			    }
1.339     albertel 7341: 			    if ($subp eq 'display') {
                   7342: 				$value.=' [Part: '.$part.']';
                   7343: 			    }
1.599     albertel 7344: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 7345: 			    $metathesekeys{$unikey}=1;
1.599     albertel 7346: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   7347: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 7348: 			    }
1.599     albertel 7349: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   7350: 				$metaentry{':'.$unikey}=
                   7351: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 7352: 			    }
1.339     albertel 7353: 			}
                   7354: 		    }
                   7355: 		} else {
1.172     www      7356: #
                   7357: # This is not a package - some other kind of start tag
1.339     albertel 7358: #
                   7359: 		    my $entry=$token->[1];
                   7360: 		    my $unikey;
                   7361: 		    if ($entry eq 'import') {
                   7362: 			$unikey='';
                   7363: 		    } else {
                   7364: 			$unikey=$entry;
                   7365: 		    }
                   7366: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   7367: 
                   7368: 		    if (defined($token->[2]->{'id'})) { 
                   7369: 			$unikey.='_'.$token->[2]->{'id'}; 
                   7370: 		    }
1.175     www      7371: 
1.339     albertel 7372: 		    if ($entry eq 'import') {
1.175     www      7373: #
                   7374: # Importing a library here
1.339     albertel 7375: #
                   7376: 			if ($depthcount<20) {
                   7377: 			    my $location=$parser->get_text('/import');
                   7378: 			    my $dir=$filename;
                   7379: 			    $dir=~s|[^/]*$||;
                   7380: 			    $location=&filelocation($dir,$location);
1.736     albertel 7381: 			    my $metadata = 
                   7382: 				&metadata($uri,'keys', $location,$unikey,
                   7383: 					  $depthcount+1);
                   7384: 			    foreach my $meta (split(',',$metadata)) {
                   7385: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   7386: 				$metathesekeys{$meta}=1;
1.339     albertel 7387: 			    }
                   7388: 			}
                   7389: 		    } else { 
                   7390: 			
                   7391: 			if (defined($token->[2]->{'name'})) { 
                   7392: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   7393: 			}
                   7394: 			$metathesekeys{$unikey}=1;
1.736     albertel 7395: 			foreach my $param (@{$token->[3]}) {
                   7396: 			    $metaentry{':'.$unikey.'.'.$param} =
                   7397: 				$token->[2]->{$param};
1.339     albertel 7398: 			}
                   7399: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 7400: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 7401: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   7402: 		 # only ws inside the tag, and not in default, so use default
                   7403: 		 # as value
1.599     albertel 7404: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 7405: 			} elsif ( $internaltext =~ /\S/ ) {
                   7406: 		  # something interesting inside the tag
                   7407: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 7408: 			} else {
1.908     albertel 7409: 		  # no interesting values, don't set a default
1.339     albertel 7410: 			}
1.172     www      7411: # end of not-a-package not-a-library import
1.339     albertel 7412: 		    }
1.172     www      7413: # end of not-a-package start tag
1.339     albertel 7414: 		}
1.172     www      7415: # the next is the end of "start tag"
1.339     albertel 7416: 	    }
                   7417: 	}
1.483     albertel 7418: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 7419: 	$extension = lc($extension);
                   7420: 	if ($extension eq 'htm') { $extension='html'; }
                   7421: 
1.737     albertel 7422: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 7423: 	    #no specific packages #how's our extension
                   7424: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 7425: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 7426: 					 \%metathesekeys);
                   7427: 	}
1.883     albertel 7428: 
                   7429: 	if (!exists($metaentry{':packages'})
                   7430: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 7431: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 7432: 		#no specific packages well let's get default then
                   7433: 		if ($key!~/^default&/) { next; }
1.488     albertel 7434: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 7435: 					     \%metathesekeys);
                   7436: 	    }
                   7437: 	}
1.338     www      7438: # are there custom rights to evaluate
1.599     albertel 7439: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 7440: 
1.338     www      7441:     #
                   7442:     # Importing a rights file here
1.339     albertel 7443:     #
                   7444: 	    unless ($depthcount) {
1.599     albertel 7445: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 7446: 		my $dir=$filename;
                   7447: 		$dir=~s|[^/]*$||;
                   7448: 		$location=&filelocation($dir,$location);
1.736     albertel 7449: 		my $rights_metadata =
                   7450: 		    &metadata($uri,'keys',$location,'_rights',
                   7451: 			      $depthcount+1);
                   7452: 		foreach my $rights (split(',',$rights_metadata)) {
                   7453: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   7454: 		    $metathesekeys{$rights}=1;
1.339     albertel 7455: 		}
                   7456: 	    }
                   7457: 	}
1.737     albertel 7458: 	# uniqifiy package listing
                   7459: 	my %seen;
                   7460: 	my @uniq_packages =
                   7461: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   7462: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   7463: 
                   7464: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 7465: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   7466: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924     albertel 7467: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      7468: # this is the end of "was not already recently cached
1.71      www      7469:     }
1.599     albertel 7470:     return $metaentry{':'.$what};
1.261     albertel 7471: }
                   7472: 
1.488     albertel 7473: sub metadata_create_package_def {
1.483     albertel 7474:     my ($uri,$key,$package,$metathesekeys)=@_;
                   7475:     my ($pack,$name,$subp)=split(/\&/,$key);
                   7476:     if ($subp eq 'default') { next; }
                   7477:     
1.599     albertel 7478:     if (defined($metaentry{':packages'})) {
                   7479: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 7480:     } else {
1.599     albertel 7481: 	$metaentry{':packages'}=$package;
1.483     albertel 7482:     }
                   7483:     my $value=$packagetab{$key};
                   7484:     my $unikey;
                   7485:     $unikey='parameter_0_'.$name;
1.599     albertel 7486:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 7487:     $$metathesekeys{$unikey}=1;
1.599     albertel 7488:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   7489: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 7490:     }
1.599     albertel 7491:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   7492: 	$metaentry{':'.$unikey}=
                   7493: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 7494:     }
                   7495: }
                   7496: 
1.261     albertel 7497: sub metadata_generate_part0 {
                   7498:     my ($metadata,$metacache,$uri) = @_;
                   7499:     my %allnames;
1.737     albertel 7500:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 7501: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 7502: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   7503: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 7504: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 7505: 	    $allnames{$name}=$part;
                   7506: 	  }
                   7507: 	}
                   7508:     }
                   7509:     foreach my $name (keys(%allnames)) {
                   7510:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 7511:       my $key=":parameter_0_$name";
1.261     albertel 7512:       $$metacache{"$key.part"}='0';
                   7513:       $$metacache{"$key.name"}=$name;
1.428     albertel 7514:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 7515: 					   $allnames{$name}.'_'.$name.
                   7516: 					   '.type'};
1.428     albertel 7517:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 7518: 			     '.display'};
1.644     www      7519:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 7520:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 7521:       $$metacache{"$key.display"}=$olddis;
                   7522:     }
1.71      www      7523: }
                   7524: 
1.764     albertel 7525: # ------------------------------------------------------ Devalidate title cache
                   7526: 
                   7527: sub devalidate_title_cache {
                   7528:     my ($url)=@_;
                   7529:     if (!$env{'request.course.id'}) { return; }
                   7530:     my $symb=&symbread($url);
                   7531:     if (!$symb) { return; }
                   7532:     my $key=$env{'request.course.id'}."\0".$symb;
                   7533:     &devalidate_cache_new('title',$key);
                   7534: }
                   7535: 
1.301     www      7536: # ------------------------------------------------- Get the title of a resource
                   7537: 
                   7538: sub gettitle {
                   7539:     my $urlsymb=shift;
                   7540:     my $symb=&symbread($urlsymb);
1.534     albertel 7541:     if ($symb) {
1.620     albertel 7542: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 7543: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 7544: 	if (defined($cached)) { 
                   7545: 	    return $result;
                   7546: 	}
1.534     albertel 7547: 	my ($map,$resid,$url)=&decode_symb($symb);
                   7548: 	my $title='';
1.907     albertel 7549: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   7550: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   7551: 	} else {
                   7552: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   7553: 		    &GDBM_READER(),0640)) {
                   7554: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   7555: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   7556: 		untie(%bighash);
                   7557: 	    }
1.534     albertel 7558: 	}
                   7559: 	$title=~s/\&colon\;/\:/gs;
                   7560: 	if ($title) {
1.599     albertel 7561: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 7562: 	}
                   7563: 	$urlsymb=$url;
                   7564:     }
                   7565:     my $title=&metadata($urlsymb,'title');
                   7566:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   7567:     return $title;
1.301     www      7568: }
1.613     albertel 7569: 
1.614     albertel 7570: sub get_slot {
                   7571:     my ($which,$cnum,$cdom)=@_;
                   7572:     if (!$cnum || !$cdom) {
1.790     albertel 7573: 	(undef,my $courseid)=&whichuser();
1.620     albertel 7574: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   7575: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 7576:     }
1.703     albertel 7577:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   7578:     my %slotinfo;
                   7579:     if (exists($remembered{$key})) {
                   7580: 	$slotinfo{$which} = $remembered{$key};
                   7581:     } else {
                   7582: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   7583: 	&Apache::lonhomework::showhash(%slotinfo);
                   7584: 	my ($tmp)=keys(%slotinfo);
                   7585: 	if ($tmp=~/^error:/) { return (); }
                   7586: 	$remembered{$key} = $slotinfo{$which};
                   7587:     }
1.616     albertel 7588:     if (ref($slotinfo{$which}) eq 'HASH') {
                   7589: 	return %{$slotinfo{$which}};
                   7590:     }
                   7591:     return $slotinfo{$which};
1.614     albertel 7592: }
1.31      www      7593: # ------------------------------------------------- Update symbolic store links
                   7594: 
                   7595: sub symblist {
                   7596:     my ($mapname,%newhash)=@_;
1.438     www      7597:     $mapname=&deversion(&declutter($mapname));
1.31      www      7598:     my %hash;
1.620     albertel 7599:     if (($env{'request.course.fn'}) && (%newhash)) {
                   7600:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 7601:                       &GDBM_WRCREAT(),0640)) {
1.711     albertel 7602: 	    foreach my $url (keys %newhash) {
                   7603: 		next if ($url eq 'last_known'
                   7604: 			 && $env{'form.no_update_last_known'});
                   7605: 		$hash{declutter($url)}=&encode_symb($mapname,
                   7606: 						    $newhash{$url}->[1],
                   7607: 						    $newhash{$url}->[0]);
1.191     harris41 7608:             }
1.31      www      7609:             if (untie(%hash)) {
                   7610: 		return 'ok';
                   7611:             }
                   7612:         }
                   7613:     }
                   7614:     return 'error';
1.212     www      7615: }
                   7616: 
                   7617: # --------------------------------------------------------------- Verify a symb
                   7618: 
                   7619: sub symbverify {
1.510     www      7620:     my ($symb,$thisurl)=@_;
                   7621:     my $thisfn=$thisurl;
1.439     www      7622:     $thisfn=&declutter($thisfn);
1.215     www      7623: # direct jump to resource in page or to a sequence - will construct own symbs
                   7624:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   7625: # check URL part
1.409     www      7626:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      7627: 
1.431     www      7628:     unless ($url eq $thisfn) { return 0; }
1.213     www      7629: 
1.216     www      7630:     $symb=&symbclean($symb);
1.510     www      7631:     $thisurl=&deversion($thisurl);
1.439     www      7632:     $thisfn=&deversion($thisfn);
1.213     www      7633: 
                   7634:     my %bighash;
                   7635:     my $okay=0;
1.431     www      7636: 
1.620     albertel 7637:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 7638:                             &GDBM_READER(),0640)) {
1.510     www      7639:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      7640:         unless ($ids) { 
1.510     www      7641:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      7642:         }
                   7643:         if ($ids) {
                   7644: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 7645: 	    foreach my $id (split(/\,/,$ids)) {
                   7646: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      7647:                if (
                   7648:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   7649:    eq $symb) { 
1.620     albertel 7650: 		   if (($env{'request.role.adv'}) ||
1.800     albertel 7651: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582     albertel 7652: 		       $okay=1; 
                   7653: 		   }
                   7654: 	       }
1.216     www      7655: 	   }
                   7656:         }
1.213     www      7657: 	untie(%bighash);
                   7658:     }
                   7659:     return $okay;
1.31      www      7660: }
                   7661: 
1.210     www      7662: # --------------------------------------------------------------- Clean-up symb
                   7663: 
                   7664: sub symbclean {
                   7665:     my $symb=shift;
1.568     albertel 7666:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      7667: # remove version from map
                   7668:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      7669: 
1.210     www      7670: # remove version from URL
                   7671:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      7672: 
1.507     www      7673: # remove wrapper
                   7674: 
1.510     www      7675:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 7676:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      7677:     return $symb;
1.409     www      7678: }
                   7679: 
                   7680: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 7681: 
                   7682: sub encode_symb {
                   7683:     my ($map,$resid,$url)=@_;
                   7684:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   7685: }
1.409     www      7686: 
                   7687: sub decode_symb {
1.568     albertel 7688:     my $symb=shift;
                   7689:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   7690:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      7691:     return (&fixversion($map),$resid,&fixversion($url));
                   7692: }
                   7693: 
                   7694: sub fixversion {
                   7695:     my $fn=shift;
1.609     banghart 7696:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      7697:     my %bighash;
                   7698:     my $uri=&clutter($fn);
1.620     albertel 7699:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      7700: # is this cached?
1.599     albertel 7701:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      7702:     if (defined($cached)) { return $result; }
                   7703: # unfortunately not cached, or expired
1.620     albertel 7704:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      7705: 	    &GDBM_READER(),0640)) {
                   7706:  	if ($bighash{'version_'.$uri}) {
                   7707:  	    my $version=$bighash{'version_'.$uri};
1.444     www      7708:  	    unless (($version eq 'mostrecent') || 
                   7709: 		    ($version==&getversion($uri))) {
1.440     www      7710:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   7711:  	    }
                   7712:  	}
                   7713:  	untie %bighash;
1.413     www      7714:     }
1.599     albertel 7715:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      7716: }
                   7717: 
                   7718: sub deversion {
                   7719:     my $url=shift;
                   7720:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   7721:     return $url;
1.210     www      7722: }
                   7723: 
1.31      www      7724: # ------------------------------------------------------ Return symb list entry
                   7725: 
                   7726: sub symbread {
1.249     www      7727:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 7728:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 7729:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      7730: # no filename provided? try from environment
1.44      www      7731:     unless ($thisfn) {
1.620     albertel 7732:         if ($env{'request.symb'}) {
                   7733: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 7734: 	}
1.620     albertel 7735: 	$thisfn=$env{'request.filename'};
1.44      www      7736:     }
1.569     albertel 7737:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      7738: # is that filename actually a symb? Verify, clean, and return
                   7739:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 7740: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 7741: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 7742: 	}
1.242     www      7743:     }
1.44      www      7744:     $thisfn=declutter($thisfn);
1.31      www      7745:     my %hash;
1.37      www      7746:     my %bighash;
                   7747:     my $syval='';
1.620     albertel 7748:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  7749:         my $targetfn = $thisfn;
1.609     banghart 7750:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  7751:             $targetfn = 'adm/wrapper/'.$thisfn;
                   7752:         }
1.687     albertel 7753: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   7754: 	    $targetfn=$1;
                   7755: 	}
1.620     albertel 7756:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 7757:                       &GDBM_READER(),0640)) {
1.481     raeburn  7758: 	    $syval=$hash{$targetfn};
1.37      www      7759:             untie(%hash);
                   7760:         }
                   7761: # ---------------------------------------------------------- There was an entry
                   7762:         if ($syval) {
1.601     albertel 7763: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 7764: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  7765: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 7766: 		    #return $env{$cache_str}='';
1.601     albertel 7767: 		#}    
                   7768: 		#$syval.=$1;
                   7769: 	    #}
1.37      www      7770:         } else {
                   7771: # ------------------------------------------------------- Was not in symb table
1.620     albertel 7772:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 7773:                             &GDBM_READER(),0640)) {
1.37      www      7774: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      7775:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      7776:               unless ($ids) { 
                   7777:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      7778:               }
                   7779:               unless ($ids) {
                   7780: # alias?
                   7781: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      7782:               }
1.37      www      7783:               if ($ids) {
                   7784: # ------------------------------------------------------------------- Has ID(s)
                   7785:                  my @possibilities=split(/\,/,$ids);
1.39      www      7786:                  if ($#possibilities==0) {
                   7787: # ----------------------------------------------- There is only one possibility
1.37      www      7788: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 7789: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   7790: 						    $resid,$thisfn);
1.249     www      7791:                  } elsif (!$donotrecurse) {
1.39      www      7792: # ------------------------------------------ There is more than one possibility
                   7793:                      my $realpossible=0;
1.800     albertel 7794:                      foreach my $id (@possibilities) {
                   7795: 			 my $file=$bighash{'src_'.$id};
1.39      www      7796:                          if (&allowed('bre',$file)) {
1.800     albertel 7797:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      7798:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   7799: 				$realpossible++;
1.626     albertel 7800:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   7801: 						    $resid,$thisfn);
1.39      www      7802:                             }
                   7803: 			 }
1.191     harris41 7804:                      }
1.39      www      7805: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      7806:                  } else {
                   7807:                      $syval='';
1.37      www      7808:                  }
                   7809: 	      }
                   7810:               untie(%bighash)
1.481     raeburn  7811:            }
1.31      www      7812:         }
1.62      www      7813:         if ($syval) {
1.620     albertel 7814: 	    return $env{$cache_str}=$syval;
1.62      www      7815:         }
1.31      www      7816:     }
1.949     raeburn  7817:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 7818:     return $env{$cache_str}='';
1.31      www      7819: }
                   7820: 
                   7821: # ---------------------------------------------------------- Return random seed
                   7822: 
1.32      www      7823: sub numval {
                   7824:     my $txt=shift;
                   7825:     $txt=~tr/A-J/0-9/;
                   7826:     $txt=~tr/a-j/0-9/;
                   7827:     $txt=~tr/K-T/0-9/;
                   7828:     $txt=~tr/k-t/0-9/;
                   7829:     $txt=~tr/U-Z/0-5/;
                   7830:     $txt=~tr/u-z/0-5/;
                   7831:     $txt=~s/\D//g;
1.564     albertel 7832:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      7833:     return int($txt);
1.368     albertel 7834: }
                   7835: 
1.484     albertel 7836: sub numval2 {
                   7837:     my $txt=shift;
                   7838:     $txt=~tr/A-J/0-9/;
                   7839:     $txt=~tr/a-j/0-9/;
                   7840:     $txt=~tr/K-T/0-9/;
                   7841:     $txt=~tr/k-t/0-9/;
                   7842:     $txt=~tr/U-Z/0-5/;
                   7843:     $txt=~tr/u-z/0-5/;
                   7844:     $txt=~s/\D//g;
                   7845:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   7846:     my $total;
                   7847:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 7848:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 7849:     return int($total);
                   7850: }
                   7851: 
1.575     albertel 7852: sub numval3 {
                   7853:     use integer;
                   7854:     my $txt=shift;
                   7855:     $txt=~tr/A-J/0-9/;
                   7856:     $txt=~tr/a-j/0-9/;
                   7857:     $txt=~tr/K-T/0-9/;
                   7858:     $txt=~tr/k-t/0-9/;
                   7859:     $txt=~tr/U-Z/0-5/;
                   7860:     $txt=~tr/u-z/0-5/;
                   7861:     $txt=~s/\D//g;
                   7862:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   7863:     my $total;
                   7864:     foreach my $val (@txts) { $total+=$val; }
                   7865:     if ($_64bit) { $total=(($total<<32)>>32); }
                   7866:     return $total;
                   7867: }
                   7868: 
1.675     albertel 7869: sub digest {
                   7870:     my ($data)=@_;
                   7871:     my $digest=&Digest::MD5::md5($data);
                   7872:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   7873:     my ($e,$f);
                   7874:     {
                   7875:         use integer;
                   7876:         $e=($a+$b);
                   7877:         $f=($c+$d);
                   7878:         if ($_64bit) {
                   7879:             $e=(($e<<32)>>32);
                   7880:             $f=(($f<<32)>>32);
                   7881:         }
                   7882:     }
                   7883:     if (wantarray) {
                   7884: 	return ($e,$f);
                   7885:     } else {
                   7886: 	my $g;
                   7887: 	{
                   7888: 	    use integer;
                   7889: 	    $g=($e+$f);
                   7890: 	    if ($_64bit) {
                   7891: 		$g=(($g<<32)>>32);
                   7892: 	    }
                   7893: 	}
                   7894: 	return $g;
                   7895:     }
                   7896: }
                   7897: 
1.368     albertel 7898: sub latest_rnd_algorithm_id {
1.675     albertel 7899:     return '64bit5';
1.366     albertel 7900: }
1.32      www      7901: 
1.503     albertel 7902: sub get_rand_alg {
                   7903:     my ($courseid)=@_;
1.790     albertel 7904:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 7905:     if ($courseid) {
1.620     albertel 7906: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 7907:     }
                   7908:     return &latest_rnd_algorithm_id();
                   7909: }
                   7910: 
1.562     albertel 7911: sub validCODE {
                   7912:     my ($CODE)=@_;
                   7913:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   7914:     return 0;
                   7915: }
                   7916: 
1.491     albertel 7917: sub getCODE {
1.620     albertel 7918:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 7919:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   7920: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   7921: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 7922: 	return $Apache::lonhomework::history{'resource.CODE'};
                   7923:     }
                   7924:     return undef;
                   7925: }
                   7926: 
1.31      www      7927: sub rndseed {
1.155     albertel 7928:     my ($symb,$courseid,$domain,$username)=@_;
1.790     albertel 7929:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 7930:     if (!defined($symb)) {
1.366     albertel 7931: 	unless ($symb=$wsymb) { return time; }
                   7932:     }
                   7933:     if (!$courseid) { $courseid=$wcourseid; }
                   7934:     if (!$domain) { $domain=$wdomain; }
                   7935:     if (!$username) { $username=$wusername }
1.503     albertel 7936:     my $which=&get_rand_alg();
1.803     albertel 7937: 
1.491     albertel 7938:     if (defined(&getCODE())) {
1.675     albertel 7939: 	if ($which eq '64bit5') {
                   7940: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   7941: 	} elsif ($which eq '64bit4') {
1.575     albertel 7942: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   7943: 	} else {
                   7944: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   7945: 	}
1.675     albertel 7946:     } elsif ($which eq '64bit5') {
                   7947: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 7948:     } elsif ($which eq '64bit4') {
                   7949: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 7950:     } elsif ($which eq '64bit3') {
                   7951: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 7952:     } elsif ($which eq '64bit2') {
                   7953: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 7954:     } elsif ($which eq '64bit') {
                   7955: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   7956:     }
                   7957:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   7958: }
                   7959: 
                   7960: sub rndseed_32bit {
                   7961:     my ($symb,$courseid,$domain,$username)=@_;
                   7962:     {
                   7963: 	use integer;
                   7964: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   7965: 	my $symbseed=numval($symb) << 22;
                   7966: 	my $namechck=unpack("%32C*",$username) << 17;
                   7967: 	my $nameseed=numval($username) << 12;
                   7968: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   7969: 	my $courseseed=unpack("%32C*",$courseid);
                   7970: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 7971: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7972: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 7973: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 7974: 	return $num;
                   7975:     }
                   7976: }
                   7977: 
                   7978: sub rndseed_64bit {
                   7979:     my ($symb,$courseid,$domain,$username)=@_;
                   7980:     {
                   7981: 	use integer;
                   7982: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   7983: 	my $symbseed=numval($symb) << 10;
                   7984: 	my $namechck=unpack("%32S*",$username);
                   7985: 	
                   7986: 	my $nameseed=numval($username) << 21;
                   7987: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   7988: 	my $courseseed=unpack("%32S*",$courseid);
                   7989: 	
                   7990: 	my $num1=$symbchck+$symbseed+$namechck;
                   7991: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7992: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7993: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 7994: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 7995: 	return "$num1,$num2";
1.155     albertel 7996:     }
1.366     albertel 7997: }
                   7998: 
1.443     albertel 7999: sub rndseed_64bit2 {
                   8000:     my ($symb,$courseid,$domain,$username)=@_;
                   8001:     {
                   8002: 	use integer;
                   8003: 	# strings need to be an even # of cahracters long, it it is odd the
                   8004:         # last characters gets thrown away
                   8005: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   8006: 	my $symbseed=numval($symb) << 10;
                   8007: 	my $namechck=unpack("%32S*",$username.' ');
                   8008: 	
                   8009: 	my $nameseed=numval($username) << 21;
1.501     albertel 8010: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   8011: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   8012: 	
                   8013: 	my $num1=$symbchck+$symbseed+$namechck;
                   8014: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 8015: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   8016: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 8017: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 8018: 	return "$num1,$num2";
                   8019:     }
                   8020: }
                   8021: 
                   8022: sub rndseed_64bit3 {
                   8023:     my ($symb,$courseid,$domain,$username)=@_;
                   8024:     {
                   8025: 	use integer;
                   8026: 	# strings need to be an even # of cahracters long, it it is odd the
                   8027:         # last characters gets thrown away
                   8028: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   8029: 	my $symbseed=numval2($symb) << 10;
                   8030: 	my $namechck=unpack("%32S*",$username.' ');
                   8031: 	
                   8032: 	my $nameseed=numval2($username) << 21;
1.443     albertel 8033: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   8034: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   8035: 	
                   8036: 	my $num1=$symbchck+$symbseed+$namechck;
                   8037: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 8038: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   8039: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 8040: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   8041: 	
1.503     albertel 8042: 	return "$num1:$num2";
1.443     albertel 8043:     }
                   8044: }
                   8045: 
1.575     albertel 8046: sub rndseed_64bit4 {
                   8047:     my ($symb,$courseid,$domain,$username)=@_;
                   8048:     {
                   8049: 	use integer;
                   8050: 	# strings need to be an even # of cahracters long, it it is odd the
                   8051:         # last characters gets thrown away
                   8052: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   8053: 	my $symbseed=numval3($symb) << 10;
                   8054: 	my $namechck=unpack("%32S*",$username.' ');
                   8055: 	
                   8056: 	my $nameseed=numval3($username) << 21;
                   8057: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   8058: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   8059: 	
                   8060: 	my $num1=$symbchck+$symbseed+$namechck;
                   8061: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 8062: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   8063: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 8064: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   8065: 	
                   8066: 	return "$num1:$num2";
                   8067:     }
                   8068: }
                   8069: 
1.675     albertel 8070: sub rndseed_64bit5 {
                   8071:     my ($symb,$courseid,$domain,$username)=@_;
                   8072:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   8073:     return "$num1:$num2";
                   8074: }
                   8075: 
1.366     albertel 8076: sub rndseed_CODE_64bit {
                   8077:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 8078:     {
1.366     albertel 8079: 	use integer;
1.443     albertel 8080: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 8081: 	my $symbseed=numval2($symb);
1.491     albertel 8082: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   8083: 	my $CODEseed=numval(&getCODE());
1.443     albertel 8084: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 8085: 	my $num1=$symbseed+$CODEchck;
                   8086: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 8087: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   8088: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 8089: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   8090: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 8091: 	return "$num1:$num2";
1.366     albertel 8092:     }
                   8093: }
                   8094: 
1.575     albertel 8095: sub rndseed_CODE_64bit4 {
                   8096:     my ($symb,$courseid,$domain,$username)=@_;
                   8097:     {
                   8098: 	use integer;
                   8099: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   8100: 	my $symbseed=numval3($symb);
                   8101: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   8102: 	my $CODEseed=numval3(&getCODE());
                   8103: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   8104: 	my $num1=$symbseed+$CODEchck;
                   8105: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 8106: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   8107: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 8108: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   8109: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   8110: 	return "$num1:$num2";
                   8111:     }
                   8112: }
                   8113: 
1.675     albertel 8114: sub rndseed_CODE_64bit5 {
                   8115:     my ($symb,$courseid,$domain,$username)=@_;
                   8116:     my $code = &getCODE();
                   8117:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   8118:     return "$num1:$num2";
                   8119: }
                   8120: 
1.366     albertel 8121: sub setup_random_from_rndseed {
                   8122:     my ($rndseed)=@_;
1.503     albertel 8123:     if ($rndseed =~/([,:])/) {
                   8124: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 8125: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   8126:     } else {
                   8127: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 8128:     }
1.36      albertel 8129: }
                   8130: 
1.474     albertel 8131: sub latest_receipt_algorithm_id {
1.835     albertel 8132:     return 'receipt3';
1.474     albertel 8133: }
                   8134: 
1.480     www      8135: sub recunique {
                   8136:     my $fucourseid=shift;
                   8137:     my $unique;
1.835     albertel 8138:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   8139: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 8140: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      8141:     } else {
                   8142: 	$unique=$perlvar{'lonReceipt'};
                   8143:     }
                   8144:     return unpack("%32C*",$unique);
                   8145: }
                   8146: 
                   8147: sub recprefix {
                   8148:     my $fucourseid=shift;
                   8149:     my $prefix;
1.835     albertel 8150:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   8151: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 8152: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      8153:     } else {
                   8154: 	$prefix=$perlvar{'lonHostID'};
                   8155:     }
                   8156:     return unpack("%32C*",$prefix);
                   8157: }
                   8158: 
1.76      www      8159: sub ireceipt {
1.474     albertel 8160:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 8161: 
                   8162:     my $return =&recprefix($fucourseid).'-';
                   8163: 
                   8164:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   8165: 	$env{'request.state'} eq 'construct') {
                   8166: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   8167: 	return $return;
                   8168:     }
                   8169: 
1.76      www      8170:     my $cuname=unpack("%32C*",$funame);
                   8171:     my $cudom=unpack("%32C*",$fudom);
                   8172:     my $cucourseid=unpack("%32C*",$fucourseid);
                   8173:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      8174:     my $cunique=&recunique($fucourseid);
1.474     albertel 8175:     my $cpart=unpack("%32S*",$part);
1.835     albertel 8176:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   8177: 
1.790     albertel 8178: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 8179: 			       
                   8180: 	$return.= ($cunique%$cuname+
                   8181: 		   $cunique%$cudom+
                   8182: 		   $cusymb%$cuname+
                   8183: 		   $cusymb%$cudom+
                   8184: 		   $cucourseid%$cuname+
                   8185: 		   $cucourseid%$cudom+
                   8186: 		   $cpart%$cuname+
                   8187: 		   $cpart%$cudom);
                   8188:     } else {
                   8189: 	$return.= ($cunique%$cuname+
                   8190: 		   $cunique%$cudom+
                   8191: 		   $cusymb%$cuname+
                   8192: 		   $cusymb%$cudom+
                   8193: 		   $cucourseid%$cuname+
                   8194: 		   $cucourseid%$cudom);
                   8195:     }
                   8196:     return $return;
1.76      www      8197: }
                   8198: 
                   8199: sub receipt {
1.474     albertel 8200:     my ($part)=@_;
1.790     albertel 8201:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 8202:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      8203: }
1.260     ng       8204: 
1.790     albertel 8205: sub whichuser {
                   8206:     my ($passedsymb)=@_;
                   8207:     my ($symb,$courseid,$domain,$name,$publicuser);
                   8208:     if (defined($env{'form.grade_symb'})) {
                   8209: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   8210: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   8211: 	if (!$allowed &&
                   8212: 	    exists($env{'request.course.sec'}) &&
                   8213: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   8214: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   8215: 			      '/'.$env{'request.course.sec'});
                   8216: 	}
                   8217: 	if ($allowed) {
                   8218: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   8219: 	    $courseid=$tmp_courseid;
                   8220: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   8221: 	    ($name)=&get_env_multiple('form.grade_username');
                   8222: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   8223: 	}
                   8224:     }
                   8225:     if (!$passedsymb) {
                   8226: 	$symb=&symbread();
                   8227:     } else {
                   8228: 	$symb=$passedsymb;
                   8229:     }
                   8230:     $courseid=$env{'request.course.id'};
                   8231:     $domain=$env{'user.domain'};
                   8232:     $name=$env{'user.name'};
                   8233:     if ($name eq 'public' && $domain eq 'public') {
                   8234: 	if (!defined($env{'form.username'})) {
                   8235: 	    $env{'form.username'}.=time.rand(10000000);
                   8236: 	}
                   8237: 	$name.=$env{'form.username'};
                   8238:     }
                   8239:     return ($symb,$courseid,$domain,$name,$publicuser);
                   8240: 
                   8241: }
                   8242: 
1.36      albertel 8243: # ------------------------------------------------------------ Serves up a file
1.472     albertel 8244: # returns either the contents of the file or 
                   8245: # -1 if the file doesn't exist
1.481     raeburn  8246: #
                   8247: # if the target is a file that was uploaded via DOCS, 
                   8248: # a check will be made to see if a current copy exists on the local server,
                   8249: # if it does this will be served, otherwise a copy will be retrieved from
                   8250: # the home server for the course and stored in /home/httpd/html/userfiles on
                   8251: # the local server.   
1.472     albertel 8252: 
1.36      albertel 8253: sub getfile {
1.538     albertel 8254:     my ($file) = @_;
1.609     banghart 8255:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 8256:     &repcopy($file);
                   8257:     return &readfile($file);
                   8258: }
                   8259: 
                   8260: sub repcopy_userfile {
                   8261:     my ($file)=@_;
1.609     banghart 8262:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 8263:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 8264:     my ($cdom,$cnum,$filename) = 
1.811     albertel 8265: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 8266:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   8267:     if (-e "$file") {
1.828     www      8268: # we already have a local copy, check it out
1.538     albertel 8269: 	my @fileinfo = stat($file);
1.828     www      8270: 	my $rtncode;
                   8271: 	my $info;
1.538     albertel 8272: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 8273: 	if ($lwpresp ne 'ok') {
1.828     www      8274: # there is no such file anymore, even though we had a local copy
1.482     albertel 8275: 	    if ($rtncode eq '404') {
1.538     albertel 8276: 		unlink($file);
1.482     albertel 8277: 	    }
                   8278: 	    return -1;
                   8279: 	}
                   8280: 	if ($info < $fileinfo[9]) {
1.828     www      8281: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  8282: 	    return 'ok';
1.828     www      8283: 	} else {
                   8284: # the file is outdated, get rid of it
                   8285: 	    unlink($file);
1.482     albertel 8286: 	}
1.828     www      8287:     }
                   8288: # one way or the other, at this point, we don't have the file
                   8289: # construct the correct path for the file
                   8290:     my @parts = ($cdom,$cnum); 
                   8291:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   8292: 	push @parts, split(/\//,$1);
                   8293:     }
                   8294:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   8295:     foreach my $part (@parts) {
                   8296: 	$path .= '/'.$part;
                   8297: 	if (!-e $path) {
                   8298: 	    mkdir($path,0770);
1.482     albertel 8299: 	}
                   8300:     }
1.828     www      8301: # now the path exists for sure
                   8302: # get a user agent
                   8303:     my $ua=new LWP::UserAgent;
                   8304:     my $transferfile=$file.'.in.transfer';
                   8305: # FIXME: this should flock
                   8306:     if (-e $transferfile) { return 'ok'; }
                   8307:     my $request;
                   8308:     $uri=~s/^\///;
1.838     albertel 8309:     $request=new HTTP::Request('GET','http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri);
1.828     www      8310:     my $response=$ua->request($request,$transferfile);
                   8311: # did it work?
                   8312:     if ($response->is_error()) {
                   8313: 	unlink($transferfile);
                   8314: 	&logthis("Userfile repcopy failed for $uri");
                   8315: 	return -1;
                   8316:     }
                   8317: # worked, rename the transfer file
                   8318:     rename($transferfile,$file);
1.607     raeburn  8319:     return 'ok';
1.481     raeburn  8320: }
                   8321: 
1.517     albertel 8322: sub tokenwrapper {
                   8323:     my $uri=shift;
1.552     albertel 8324:     $uri=~s|^http\://([^/]+)||;
                   8325:     $uri=~s|^/||;
1.620     albertel 8326:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 8327:     my $token=$1;
1.552     albertel 8328:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   8329:     if ($udom && $uname && $file) {
                   8330: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  8331:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.838     albertel 8332:         return 'http://'.&hostname(&homeserver($uname,$udom)).'/'.$uri.
1.517     albertel 8333:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   8334:                                '&tokenissued='.$perlvar{'lonHostID'};
                   8335:     } else {
                   8336:         return '/adm/notfound.html';
                   8337:     }
                   8338: }
                   8339: 
1.828     www      8340: # call with reqtype HEAD: get last modification time
                   8341: # call with reqtype GET: get the file contents
                   8342: # Do not call this with reqtype GET for large files! It loads everything into memory
                   8343: #
1.481     raeburn  8344: sub getuploaded {
                   8345:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   8346:     $uri=~s/^\///;
1.838     albertel 8347:     $uri = 'http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri;
1.481     raeburn  8348:     my $ua=new LWP::UserAgent;
                   8349:     my $request=new HTTP::Request($reqtype,$uri);
                   8350:     my $response=$ua->request($request);
                   8351:     $$rtncode = $response->code;
1.482     albertel 8352:     if (! $response->is_success()) {
                   8353: 	return 'failed';
                   8354:     }      
                   8355:     if ($reqtype eq 'HEAD') {
1.486     www      8356: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 8357:     } elsif ($reqtype eq 'GET') {
                   8358: 	$$info = $response->content;
1.472     albertel 8359:     }
1.482     albertel 8360:     return 'ok';
1.36      albertel 8361: }
                   8362: 
1.481     raeburn  8363: sub readfile {
                   8364:     my $file = shift;
                   8365:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   8366:     my $fh;
                   8367:     open($fh,"<$file");
                   8368:     my $a='';
1.800     albertel 8369:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  8370:     return $a;
                   8371: }
                   8372: 
1.36      albertel 8373: sub filelocation {
1.590     banghart 8374:     my ($dir,$file) = @_;
                   8375:     my $location;
                   8376:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 8377: 
                   8378:     if ($file =~ m-^/adm/-) {
                   8379: 	$file=~s-^/adm/wrapper/-/-;
                   8380: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   8381:     }
1.882     albertel 8382: 
1.590     banghart 8383:     if ($file=~m:^/~:) { # is a contruction space reference
                   8384:         $location = $file;
                   8385:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807     albertel 8386:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649     albertel 8387: 	# is a correct contruction space reference
                   8388:         $location = $file;
1.956     raeburn  8389:     } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
                   8390:         $location = $file;
1.609     banghart 8391:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 8392:         my ($udom,$uname,$filename)=
1.811     albertel 8393:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 8394:         my $home=&homeserver($uname,$udom);
                   8395:         my $is_me=0;
                   8396:         my @ids=&current_machine_ids();
                   8397:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   8398:         if ($is_me) {
1.955     raeburn  8399:   	    $location=&propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 8400:         } else {
                   8401:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   8402:   	      $udom.'/'.$uname.'/'.$filename;
                   8403:         }
1.882     albertel 8404:     } elsif ($file =~ m-^/adm/-) {
                   8405: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 8406:     } else {
                   8407:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   8408:         $file=~s:^/res/:/:;
                   8409:         if ( !( $file =~ m:^/:) ) {
                   8410:             $location = $dir. '/'.$file;
                   8411:         } else {
                   8412:             $location = '/home/httpd/html/res'.$file;
                   8413:         }
1.59      albertel 8414:     }
1.590     banghart 8415:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 8416:     while ($location=~m{/\.\./}) {
                   8417: 	if ($location =~ m{/[^/]+/\.\./}) {
                   8418: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   8419: 	} else {
                   8420: 	    $location=~ s{/\.\./}{/}g;
                   8421: 	}
                   8422:     } #remove dir/..
1.590     banghart 8423:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   8424:     return $location;
1.46      www      8425: }
1.36      albertel 8426: 
1.46      www      8427: sub hreflocation {
                   8428:     my ($dir,$file)=@_;
1.460     albertel 8429:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
1.666     albertel 8430: 	$file=filelocation($dir,$file);
1.700     albertel 8431:     } elsif ($file=~m-^/adm/-) {
                   8432: 	$file=~s-^/adm/wrapper/-/-;
                   8433: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 8434:     }
                   8435:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   8436: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807     albertel 8437:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
                   8438: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666     albertel 8439:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811     albertel 8440: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666     albertel 8441: 	    -/uploaded/$1/$2/-x;
1.46      www      8442:     }
1.913     albertel 8443:     if ($file=~ m{^/userfiles/}) {
                   8444: 	$file =~ s{^/userfiles/}{/uploaded/};
                   8445:     }
1.462     albertel 8446:     return $file;
1.465     albertel 8447: }
                   8448: 
                   8449: sub current_machine_domains {
1.853     albertel 8450:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   8451: }
                   8452: 
                   8453: sub machine_domains {
                   8454:     my ($hostname) = @_;
1.465     albertel 8455:     my @domains;
1.838     albertel 8456:     my %hostname = &all_hostnames();
1.465     albertel 8457:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  8458: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 8459: 	if ($hostname eq $name) {
1.844     albertel 8460: 	    push(@domains,&host_domain($id));
1.465     albertel 8461: 	}
                   8462:     }
                   8463:     return @domains;
                   8464: }
                   8465: 
                   8466: sub current_machine_ids {
1.853     albertel 8467:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   8468: }
                   8469: 
                   8470: sub machine_ids {
                   8471:     my ($hostname) = @_;
                   8472:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 8473:     my @ids;
1.888     albertel 8474:     my %name_to_host = &all_names();
1.889     albertel 8475:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   8476: 	return @{ $name_to_host{$hostname} };
                   8477:     }
                   8478:     return;
1.31      www      8479: }
                   8480: 
1.824     raeburn  8481: sub additional_machine_domains {
                   8482:     my @domains;
                   8483:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   8484:     while( my $line = <$fh>) {
                   8485:         $line =~ s/\s//g;
                   8486:         push(@domains,$line);
                   8487:     }
                   8488:     return @domains;
                   8489: }
                   8490: 
                   8491: sub default_login_domain {
                   8492:     my $domain = $perlvar{'lonDefDomain'};
                   8493:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   8494:     foreach my $posdom (&current_machine_domains(),
                   8495:                         &additional_machine_domains()) {
                   8496:         if (lc($posdom) eq lc($testdomain)) {
                   8497:             $domain=$posdom;
                   8498:             last;
                   8499:         }
                   8500:     }
                   8501:     return $domain;
                   8502: }
                   8503: 
1.31      www      8504: # ------------------------------------------------------------- Declutters URLs
                   8505: 
                   8506: sub declutter {
                   8507:     my $thisfn=shift;
1.569     albertel 8508:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 8509:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      8510:     $thisfn=~s/^\///;
1.697     albertel 8511:     $thisfn=~s|^adm/wrapper/||;
                   8512:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      8513:     $thisfn=~s/^res\///;
1.235     www      8514:     $thisfn=~s/\?.+$//;
1.268     www      8515:     return $thisfn;
                   8516: }
                   8517: 
                   8518: # ------------------------------------------------------------- Clutter up URLs
                   8519: 
                   8520: sub clutter {
                   8521:     my $thisfn='/'.&declutter(shift);
1.887     albertel 8522:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 8523: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      8524:        $thisfn='/res'.$thisfn; 
                   8525:     }
1.694     albertel 8526:     if ($thisfn !~m|/adm|) {
1.695     albertel 8527: 	if ($thisfn =~ m|/ext/|) {
1.694     albertel 8528: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 8529: 	} else {
                   8530: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   8531: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 8532: 	    if ($embstyle eq 'ssi'
                   8533: 		|| ($embstyle eq 'hdn')
                   8534: 		|| ($embstyle eq 'rat')
                   8535: 		|| ($embstyle eq 'prv')
                   8536: 		|| ($embstyle eq 'ign')) {
                   8537: 		#do nothing with these
                   8538: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 8539: 		|| ($embstyle eq 'emb')
                   8540: 		|| ($embstyle eq 'wrp')) {
                   8541: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 8542: 	    } elsif ($embstyle eq 'unk'
                   8543: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 8544: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 8545: 	    } else {
1.718     www      8546: #		&logthis("Got a blank emb style");
1.695     albertel 8547: 	    }
1.694     albertel 8548: 	}
                   8549:     }
1.31      www      8550:     return $thisfn;
1.12      www      8551: }
                   8552: 
1.787     albertel 8553: sub clutter_with_no_wrapper {
                   8554:     my $uri = &clutter(shift);
                   8555:     if ($uri =~ m-^/adm/-) {
                   8556: 	$uri =~ s-^/adm/wrapper/-/-;
                   8557: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   8558:     }
                   8559:     return $uri;
                   8560: }
                   8561: 
1.557     albertel 8562: sub freeze_escape {
                   8563:     my ($value)=@_;
                   8564:     if (ref($value)) {
                   8565: 	$value=&nfreeze($value);
                   8566: 	return '__FROZEN__'.&escape($value);
                   8567:     }
                   8568:     return &escape($value);
                   8569: }
                   8570: 
1.11      www      8571: 
1.557     albertel 8572: sub thaw_unescape {
                   8573:     my ($value)=@_;
                   8574:     if ($value =~ /^__FROZEN__/) {
                   8575: 	substr($value,0,10,undef);
                   8576: 	$value=&unescape($value);
                   8577: 	return &thaw($value);
                   8578:     }
                   8579:     return &unescape($value);
                   8580: }
                   8581: 
1.436     albertel 8582: sub correct_line_ends {
                   8583:     my ($result)=@_;
                   8584:     $$result =~s/\r\n/\n/mg;
                   8585:     $$result =~s/\r/\n/mg;
1.415     albertel 8586: }
1.1       albertel 8587: # ================================================================ Main Program
                   8588: 
1.184     www      8589: sub goodbye {
1.204     albertel 8590:    &logthis("Starting Shut down");
1.443     albertel 8591: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 8592:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 8593: #converted
1.599     albertel 8594: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 8595:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   8596: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   8597: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 8598: #1.1 only
1.870     albertel 8599: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   8600: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   8601: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   8602: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   8603:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 8604:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   8605:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      8606:    &flushcourselogs();
                   8607:    &logthis("Shutting down");
                   8608: }
                   8609: 
1.852     albertel 8610: sub get_dns {
1.869     albertel 8611:     my ($url,$func,$ignore_cache) = @_;
                   8612:     if (!$ignore_cache) {
                   8613: 	my ($content,$cached)=
                   8614: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   8615: 	if ($cached) {
                   8616: 	    &$func($content);
                   8617: 	    return;
                   8618: 	}
                   8619:     }
                   8620: 
                   8621:     my %alldns;
1.852     albertel 8622:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   8623:     foreach my $dns (<$config>) {
                   8624: 	next if ($dns !~ /^\^(\S*)/x);
1.869     albertel 8625: 	$alldns{$1} = 1;
                   8626:     }
                   8627:     while (%alldns) {
                   8628: 	my ($dns) = keys(%alldns);
                   8629: 	delete($alldns{$dns});
1.852     albertel 8630: 	my $ua=new LWP::UserAgent;
                   8631: 	my $request=new HTTP::Request('GET',"http://$dns$url");
                   8632: 	my $response=$ua->request($request);
                   8633: 	next if ($response->is_error());
                   8634: 	my @content = split("\n",$response->content);
1.869     albertel 8635: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852     albertel 8636: 	&$func(\@content);
1.869     albertel 8637: 	return;
1.852     albertel 8638:     }
                   8639:     close($config);
1.871     albertel 8640:     my $which = (split('/',$url))[3];
                   8641:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   8642:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 8643:     my @content = <$config>;
                   8644:     &$func(\@content);
                   8645:     return;
1.852     albertel 8646: }
1.327     albertel 8647: # ------------------------------------------------------------ Read domain file
                   8648: {
1.852     albertel 8649:     my $loaded;
1.846     albertel 8650:     my %domain;
                   8651: 
1.852     albertel 8652:     sub parse_domain_tab {
                   8653: 	my ($lines) = @_;
                   8654: 	foreach my $line (@$lines) {
                   8655: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      8656: 
1.846     albertel 8657: 	    chomp($line);
1.852     albertel 8658: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 8659: 	    my %this_domain;
                   8660: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   8661: 			       'lang_def', 'city', 'longi', 'lati',
                   8662: 			       'primary') {
                   8663: 		$this_domain{$field} = shift(@elements);
                   8664: 	    }
                   8665: 	    $domain{$name} = \%this_domain;
1.852     albertel 8666: 	}
                   8667:     }
1.864     albertel 8668: 
                   8669:     sub reset_domain_info {
                   8670: 	undef($loaded);
                   8671: 	undef(%domain);
                   8672:     }
                   8673: 
1.852     albertel 8674:     sub load_domain_tab {
1.869     albertel 8675: 	my ($ignore_cache) = @_;
                   8676: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 8677: 	my $fh;
                   8678: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   8679: 	    my @lines = <$fh>;
                   8680: 	    &parse_domain_tab(\@lines);
1.448     albertel 8681: 	}
1.852     albertel 8682: 	close($fh);
                   8683: 	$loaded = 1;
1.327     albertel 8684:     }
1.846     albertel 8685: 
                   8686:     sub domain {
1.852     albertel 8687: 	&load_domain_tab() if (!$loaded);
                   8688: 
1.846     albertel 8689: 	my ($name,$what) = @_;
                   8690: 	return if ( !exists($domain{$name}) );
                   8691: 
                   8692: 	if (!$what) {
                   8693: 	    return $domain{$name}{'description'};
                   8694: 	}
                   8695: 	return $domain{$name}{$what};
                   8696:     }
1.974     raeburn  8697: 
                   8698:     sub domain_info {
                   8699:         &load_domain_tab() if (!$loaded);
                   8700:         return %domain;
                   8701:     }
                   8702: 
1.327     albertel 8703: }
                   8704: 
                   8705: 
1.1       albertel 8706: # ------------------------------------------------------------- Read hosts file
                   8707: {
1.838     albertel 8708:     my %hostname;
1.844     albertel 8709:     my %hostdom;
1.845     albertel 8710:     my %libserv;
1.852     albertel 8711:     my $loaded;
1.888     albertel 8712:     my %name_to_host;
1.852     albertel 8713: 
                   8714:     sub parse_hosts_tab {
                   8715: 	my ($file) = @_;
                   8716: 	foreach my $configline (@$file) {
                   8717: 	    next if ($configline =~ /^(\#|\s*$ )/x);
                   8718: 	    next if ($configline =~ /^\^/);
                   8719: 	    chomp($configline);
1.968     raeburn  8720: 	    my ($id,$domain,$role,$name,$protocol)=split(/:/,$configline);
1.852     albertel 8721: 	    $name=~s/\s//g;
                   8722: 	    if ($id && $domain && $role && $name) {
                   8723: 		$hostname{$id}=$name;
1.888     albertel 8724: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 8725: 		$hostdom{$id}=$domain;
                   8726: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  8727:                 if (defined($protocol)) {
                   8728:                     if ($protocol eq 'https') {
                   8729:                         $protocol{$id} = $protocol;
                   8730:                     } else {
                   8731:                         $protocol{$id} = 'http'; 
                   8732:                     }
1.968     raeburn  8733:                 } else {
1.969     raeburn  8734:                     $protocol{$id} = 'http';
1.968     raeburn  8735:                 }
1.852     albertel 8736: 	    }
                   8737: 	}
                   8738:     }
1.864     albertel 8739:     
                   8740:     sub reset_hosts_info {
1.897     albertel 8741: 	&purge_remembered();
1.864     albertel 8742: 	&reset_domain_info();
                   8743: 	&reset_hosts_ip_info();
1.892     albertel 8744: 	undef(%name_to_host);
1.864     albertel 8745: 	undef(%hostname);
                   8746: 	undef(%hostdom);
                   8747: 	undef(%libserv);
                   8748: 	undef($loaded);
                   8749:     }
1.1       albertel 8750: 
1.852     albertel 8751:     sub load_hosts_tab {
1.869     albertel 8752: 	my ($ignore_cache) = @_;
                   8753: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 8754: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   8755: 	my @config = <$config>;
                   8756: 	&parse_hosts_tab(\@config);
                   8757: 	close($config);
                   8758: 	$loaded=1;
1.1       albertel 8759:     }
1.852     albertel 8760: 
1.838     albertel 8761:     sub hostname {
1.852     albertel 8762: 	&load_hosts_tab() if (!$loaded);
                   8763: 
1.838     albertel 8764: 	my ($lonid) = @_;
                   8765: 	return $hostname{$lonid};
                   8766:     }
1.845     albertel 8767: 
1.838     albertel 8768:     sub all_hostnames {
1.852     albertel 8769: 	&load_hosts_tab() if (!$loaded);
                   8770: 
1.838     albertel 8771: 	return %hostname;
                   8772:     }
1.845     albertel 8773: 
1.888     albertel 8774:     sub all_names {
                   8775: 	&load_hosts_tab() if (!$loaded);
                   8776: 
                   8777: 	return %name_to_host;
                   8778:     }
                   8779: 
1.974     raeburn  8780:     sub all_host_domain {
                   8781:         &load_hosts_tab() if (!$loaded);
                   8782:         return %hostdom;
                   8783:     }
                   8784: 
1.845     albertel 8785:     sub is_library {
1.852     albertel 8786: 	&load_hosts_tab() if (!$loaded);
                   8787: 
1.845     albertel 8788: 	return exists($libserv{$_[0]});
                   8789:     }
                   8790: 
                   8791:     sub all_library {
1.852     albertel 8792: 	&load_hosts_tab() if (!$loaded);
                   8793: 
1.845     albertel 8794: 	return %libserv;
                   8795:     }
                   8796: 
1.841     albertel 8797:     sub get_servers {
1.852     albertel 8798: 	&load_hosts_tab() if (!$loaded);
                   8799: 
1.841     albertel 8800: 	my ($domain,$type) = @_;
                   8801: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   8802: 	                                          : %hostname;
                   8803: 	my %result;
1.842     albertel 8804: 	if (ref($domain) eq 'ARRAY') {
                   8805: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 8806: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 8807: 		    $result{$host} = $hostname;
                   8808: 		}
                   8809: 	    }
                   8810: 	} else {
                   8811: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   8812: 		if ($hostdom{$host} eq $domain) {
                   8813: 		    $result{$host} = $hostname;
                   8814: 		}
1.841     albertel 8815: 	    }
                   8816: 	}
                   8817: 	return %result;
                   8818:     }
1.845     albertel 8819: 
1.844     albertel 8820:     sub host_domain {
1.852     albertel 8821: 	&load_hosts_tab() if (!$loaded);
                   8822: 
1.844     albertel 8823: 	my ($lonid) = @_;
                   8824: 	return $hostdom{$lonid};
                   8825:     }
                   8826: 
1.841     albertel 8827:     sub all_domains {
1.852     albertel 8828: 	&load_hosts_tab() if (!$loaded);
                   8829: 
1.841     albertel 8830: 	my %seen;
                   8831: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   8832: 	return @uniq;
                   8833:     }
1.1       albertel 8834: }
                   8835: 
1.847     albertel 8836: { 
                   8837:     my %iphost;
1.856     albertel 8838:     my %name_to_ip;
                   8839:     my %lonid_to_ip;
1.869     albertel 8840: 
1.847     albertel 8841:     sub get_hosts_from_ip {
                   8842: 	my ($ip) = @_;
                   8843: 	my %iphosts = &get_iphost();
                   8844: 	if (ref($iphosts{$ip})) {
                   8845: 	    return @{$iphosts{$ip}};
                   8846: 	}
                   8847: 	return;
1.839     albertel 8848:     }
1.864     albertel 8849:     
                   8850:     sub reset_hosts_ip_info {
                   8851: 	undef(%iphost);
                   8852: 	undef(%name_to_ip);
                   8853: 	undef(%lonid_to_ip);
                   8854:     }
1.856     albertel 8855: 
                   8856:     sub get_host_ip {
                   8857: 	my ($lonid) = @_;
                   8858: 	if (exists($lonid_to_ip{$lonid})) {
                   8859: 	    return $lonid_to_ip{$lonid};
                   8860: 	}
                   8861: 	my $name=&hostname($lonid);
                   8862:    	my $ip = gethostbyname($name);
                   8863: 	return if (!$ip || length($ip) ne 4);
                   8864: 	$ip=inet_ntoa($ip);
                   8865: 	$name_to_ip{$name}   = $ip;
                   8866: 	$lonid_to_ip{$lonid} = $ip;
                   8867: 	return $ip;
                   8868:     }
1.847     albertel 8869:     
                   8870:     sub get_iphost {
1.869     albertel 8871: 	my ($ignore_cache) = @_;
1.894     albertel 8872: 
1.869     albertel 8873: 	if (!$ignore_cache) {
                   8874: 	    if (%iphost) {
                   8875: 		return %iphost;
                   8876: 	    }
                   8877: 	    my ($ip_info,$cached)=
                   8878: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   8879: 	    if ($cached) {
                   8880: 		%iphost      = %{$ip_info->[0]};
                   8881: 		%name_to_ip  = %{$ip_info->[1]};
                   8882: 		%lonid_to_ip = %{$ip_info->[2]};
                   8883: 		return %iphost;
                   8884: 	    }
                   8885: 	}
1.894     albertel 8886: 
                   8887: 	# get yesterday's info for fallback
                   8888: 	my %old_name_to_ip;
                   8889: 	my ($ip_info,$cached)=
                   8890: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   8891: 	if ($cached) {
                   8892: 	    %old_name_to_ip = %{$ip_info->[1]};
                   8893: 	}
                   8894: 
1.888     albertel 8895: 	my %name_to_host = &all_names();
                   8896: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 8897: 	    my $ip;
                   8898: 	    if (!exists($name_to_ip{$name})) {
                   8899: 		$ip = gethostbyname($name);
                   8900: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 8901: 		    if (defined($old_name_to_ip{$name})) {
                   8902: 			$ip = $old_name_to_ip{$name};
                   8903: 			&logthis("Can't find $name defaulting to old $ip");
                   8904: 		    } else {
                   8905: 			&logthis("Name $name no IP found");
                   8906: 			next;
                   8907: 		    }
                   8908: 		} else {
                   8909: 		    $ip=inet_ntoa($ip);
1.847     albertel 8910: 		}
                   8911: 		$name_to_ip{$name} = $ip;
                   8912: 	    } else {
                   8913: 		$ip = $name_to_ip{$name};
1.653     albertel 8914: 	    }
1.888     albertel 8915: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   8916: 		$lonid_to_ip{$id} = $ip;
                   8917: 	    }
                   8918: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 8919: 	}
1.869     albertel 8920: 	&Apache::lonnet::do_cache_new('iphost','iphost',
                   8921: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894     albertel 8922: 				      48*60*60);
1.869     albertel 8923: 
1.847     albertel 8924: 	return %iphost;
1.598     albertel 8925:     }
                   8926: }
                   8927: 
1.862     albertel 8928: BEGIN {
                   8929: 
                   8930: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   8931:     unless ($readit) {
                   8932: {
                   8933:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   8934:     %perlvar = (%perlvar,%{$configvars});
                   8935: }
                   8936: 
                   8937: 
1.1       albertel 8938: # ------------------------------------------------------ Read spare server file
                   8939: {
1.448     albertel 8940:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 8941: 
                   8942:     while (my $configline=<$config>) {
                   8943:        chomp($configline);
1.284     matthew  8944:        if ($configline) {
1.784     albertel 8945: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 8946: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 8947: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 8948:        }
                   8949:     }
1.448     albertel 8950:     close($config);
1.1       albertel 8951: }
1.11      www      8952: # ------------------------------------------------------------ Read permissions
                   8953: {
1.448     albertel 8954:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      8955: 
                   8956:     while (my $configline=<$config>) {
1.448     albertel 8957: 	chomp($configline);
                   8958: 	if ($configline) {
                   8959: 	    my ($role,$perm)=split(/ /,$configline);
                   8960: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   8961: 	}
1.11      www      8962:     }
1.448     albertel 8963:     close($config);
1.11      www      8964: }
                   8965: 
                   8966: # -------------------------------------------- Read plain texts for permissions
                   8967: {
1.448     albertel 8968:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      8969: 
                   8970:     while (my $configline=<$config>) {
1.448     albertel 8971: 	chomp($configline);
                   8972: 	if ($configline) {
1.742     raeburn  8973: 	    my ($short,@plain)=split(/:/,$configline);
                   8974:             %{$prp{$short}} = ();
                   8975: 	    if (@plain > 0) {
                   8976:                 $prp{$short}{'std'} = $plain[0];
                   8977:                 for (my $i=1; $i<@plain; $i++) {
                   8978:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   8979:                 }
                   8980:             }
1.448     albertel 8981: 	}
1.135     www      8982:     }
1.448     albertel 8983:     close($config);
1.135     www      8984: }
                   8985: 
                   8986: # ---------------------------------------------------------- Read package table
                   8987: {
1.448     albertel 8988:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      8989: 
                   8990:     while (my $configline=<$config>) {
1.483     albertel 8991: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 8992: 	chomp($configline);
                   8993: 	my ($short,$plain)=split(/:/,$configline);
                   8994: 	my ($pack,$name)=split(/\&/,$short);
                   8995: 	if ($plain ne '') {
                   8996: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   8997: 	    $packagetab{$short}=$plain; 
                   8998: 	}
1.11      www      8999:     }
1.448     albertel 9000:     close($config);
1.329     matthew  9001: }
                   9002: 
                   9003: # ------------- set up temporary directory
                   9004: {
                   9005:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   9006: 
1.11      www      9007: }
                   9008: 
1.794     albertel 9009: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   9010: 				'compress_threshold'=> 20_000,
                   9011:  			        });
1.185     www      9012: 
1.281     www      9013: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      9014: $dumpcount=0;
1.958     www      9015: $locknum=0;
1.22      www      9016: 
1.163     harris41 9017: &logtouch();
1.672     albertel 9018: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      9019: $readit=1;
1.564     albertel 9020:     {
                   9021: 	use integer;
                   9022: 	my $test=(2**32)+1;
1.568     albertel 9023: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 9024: 	&logthis(" Detected 64bit platform ($_64bit)");
                   9025:     }
1.195     www      9026: }
1.1       albertel 9027: }
1.179     www      9028: 
1.1       albertel 9029: 1;
1.191     harris41 9030: __END__
                   9031: 
1.243     albertel 9032: =pod
                   9033: 
1.191     harris41 9034: =head1 NAME
                   9035: 
1.243     albertel 9036: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 9037: 
                   9038: =head1 SYNOPSIS
                   9039: 
1.243     albertel 9040: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 9041: 
                   9042:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   9043: 
1.243     albertel 9044: Common parameters:
                   9045: 
                   9046: =over 4
                   9047: 
                   9048: =item *
                   9049: 
                   9050: $uname : an internal username (if $cname expecting a course Id specifically)
                   9051: 
                   9052: =item *
                   9053: 
                   9054: $udom : a domain (if $cdom expecting a course's domain specifically)
                   9055: 
                   9056: =item *
                   9057: 
                   9058: $symb : a resource instance identifier
                   9059: 
                   9060: =item *
                   9061: 
                   9062: $namespace : the name of a .db file that contains the data needed or
                   9063: being set.
                   9064: 
                   9065: =back
                   9066: 
1.394     bowersj2 9067: =head1 OVERVIEW
1.191     harris41 9068: 
1.394     bowersj2 9069: lonnet provides subroutines which interact with the
                   9070: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   9071: about classes, users, and resources.
1.243     albertel 9072: 
                   9073: For many of these objects you can also use this to store data about
                   9074: them or modify them in various ways.
1.191     harris41 9075: 
1.394     bowersj2 9076: =head2 Symbs
1.191     harris41 9077: 
1.394     bowersj2 9078: To identify a specific instance of a resource, LON-CAPA uses symbols
                   9079: or "symbs"X<symb>. These identifiers are built from the URL of the
                   9080: map, the resource number of the resource in the map, and the URL of
                   9081: the resource itself. The latter is somewhat redundant, but might help
                   9082: if maps change.
                   9083: 
                   9084: An example is
                   9085: 
                   9086:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   9087: 
                   9088: The respective map entry is
                   9089: 
                   9090:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   9091:   title="Problem 2">
                   9092:  </resource>
                   9093: 
                   9094: Symbs are used by the random number generator, as well as to store and
                   9095: restore data specific to a certain instance of for example a problem.
                   9096: 
                   9097: =head2 Storing And Retrieving Data
                   9098: 
                   9099: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   9100: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   9101: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   9102: is is the non-critical message twin of cstore. These functions are for
                   9103: handlers to store a perl hash to a user's permanent data space in an
                   9104: easy manner, and to retrieve it again on another call. It is expected
                   9105: that a handler would use this once at the beginning to retrieve data,
                   9106: and then again once at the end to send only the new data back.
                   9107: 
                   9108: The data is stored in the user's data directory on the user's
                   9109: homeserver under the ID of the course.
                   9110: 
                   9111: The hash that is returned by restore will have all of the previous
                   9112: value for all of the elements of the hash.
                   9113: 
                   9114: Example:
                   9115: 
                   9116:  #creating a hash
                   9117:  my %hash;
                   9118:  $hash{'foo'}='bar';
                   9119: 
                   9120:  #storing it
                   9121:  &Apache::lonnet::cstore(\%hash);
                   9122: 
                   9123:  #changing a value
                   9124:  $hash{'foo'}='notbar';
                   9125: 
                   9126:  #adding a new value
                   9127:  $hash{'bar'}='foo';
                   9128:  &Apache::lonnet::cstore(\%hash);
                   9129: 
                   9130:  #retrieving the hash
                   9131:  my %history=&Apache::lonnet::restore();
                   9132: 
                   9133:  #print the hash
                   9134:  foreach my $key (sort(keys(%history))) {
                   9135:    print("\%history{$key} = $history{$key}");
                   9136:  }
                   9137: 
                   9138: Will print out:
1.191     harris41 9139: 
1.394     bowersj2 9140:  %history{1:foo} = bar
                   9141:  %history{1:keys} = foo:timestamp
                   9142:  %history{1:timestamp} = 990455579
                   9143:  %history{2:bar} = foo
                   9144:  %history{2:foo} = notbar
                   9145:  %history{2:keys} = foo:bar:timestamp
                   9146:  %history{2:timestamp} = 990455580
                   9147:  %history{bar} = foo
                   9148:  %history{foo} = notbar
                   9149:  %history{timestamp} = 990455580
                   9150:  %history{version} = 2
                   9151: 
                   9152: Note that the special hash entries C<keys>, C<version> and
                   9153: C<timestamp> were added to the hash. C<version> will be equal to the
                   9154: total number of versions of the data that have been stored. The
                   9155: C<timestamp> attribute will be the UNIX time the hash was
                   9156: stored. C<keys> is available in every historical section to list which
                   9157: keys were added or changed at a specific historical revision of a
                   9158: hash.
                   9159: 
                   9160: B<Warning>: do not store the hash that restore returns directly. This
                   9161: will cause a mess since it will restore the historical keys as if the
                   9162: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 9163: 
1.394     bowersj2 9164: Calling convention:
1.191     harris41 9165: 
1.394     bowersj2 9166:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   9167:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 9168: 
1.394     bowersj2 9169: For more detailed information, see lonnet specific documentation.
1.191     harris41 9170: 
1.394     bowersj2 9171: =head1 RETURN MESSAGES
1.191     harris41 9172: 
1.394     bowersj2 9173: =over 4
1.191     harris41 9174: 
1.394     bowersj2 9175: =item * B<con_lost>: unable to contact remote host
1.191     harris41 9176: 
1.394     bowersj2 9177: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   9178: when the connection is brought back up
1.191     harris41 9179: 
1.394     bowersj2 9180: =item * B<con_failed>: unable to contact remote host and unable to save message
                   9181: for later delivery
1.191     harris41 9182: 
1.967     bisitz   9183: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 9184: 
1.394     bowersj2 9185: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 9186: that was requested
1.191     harris41 9187: 
1.243     albertel 9188: =back
1.191     harris41 9189: 
1.243     albertel 9190: =head1 PUBLIC SUBROUTINES
1.191     harris41 9191: 
1.243     albertel 9192: =head2 Session Environment Functions
1.191     harris41 9193: 
1.243     albertel 9194: =over 4
1.191     harris41 9195: 
1.394     bowersj2 9196: =item * 
                   9197: X<appenv()>
1.949     raeburn  9198: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 9199: the user envirnoment file, and will be restored for each access this
1.620     albertel 9200: user makes during this session, also modifies the %env for the current
1.949     raeburn  9201: process. Optional rolesarrayref - if defined contains a reference to an array
                   9202: of roles which are exempt from the restriction on modifying user.role entries 
                   9203: in the user's environment.db and in %env.    
1.191     harris41 9204: 
                   9205: =item *
1.394     bowersj2 9206: X<delenv()>
                   9207: B<delenv($regexp)>: removes all items from the session
                   9208: environment file that matches the regular expression in $regexp. The
1.620     albertel 9209: values are also delted from the current processes %env.
1.191     harris41 9210: 
1.795     albertel 9211: =item * get_env_multiple($name) 
                   9212: 
                   9213: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   9214: values may be defined and end up as an array ref.
                   9215: 
                   9216: returns an array of values
                   9217: 
1.243     albertel 9218: =back
                   9219: 
                   9220: =head2 User Information
1.191     harris41 9221: 
1.243     albertel 9222: =over 4
1.191     harris41 9223: 
                   9224: =item *
1.394     bowersj2 9225: X<queryauthenticate()>
                   9226: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 9227: authentication scheme
                   9228: 
                   9229: =item *
1.394     bowersj2 9230: X<authenticate()>
                   9231: B<authenticate($uname,$upass,$udom)>: try to
                   9232: authenticate user from domain's lib servers (first use the current
                   9233: one). C<$upass> should be the users password.
1.191     harris41 9234: 
                   9235: =item *
1.394     bowersj2 9236: X<homeserver()>
                   9237: B<homeserver($uname,$udom)>: find the server which has
                   9238: the user's directory and files (there must be only one), this caches
                   9239: the answer, and also caches if there is a borken connection.
1.191     harris41 9240: 
                   9241: =item *
1.394     bowersj2 9242: X<idget()>
                   9243: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   9244: (IDs are a unique resource in a domain, there must be only 1 ID per
                   9245: username, and only 1 username per ID in a specific domain) (returns
                   9246: hash: id=>name,id=>name)
1.191     harris41 9247: 
                   9248: =item *
1.394     bowersj2 9249: X<idrget()>
                   9250: B<idrget($udom,@unames)>: find the IDs behind a list of
                   9251: usernames (returns hash: name=>id,name=>id)
1.191     harris41 9252: 
                   9253: =item *
1.394     bowersj2 9254: X<idput()>
                   9255: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 9256: 
                   9257: =item *
1.394     bowersj2 9258: X<rolesinit()>
                   9259: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 9260: 
                   9261: =item *
1.551     albertel 9262: X<getsection()>
                   9263: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 9264: course $cname, return section name/number or '' for "not in course"
                   9265: and '-1' for "no section"
                   9266: 
                   9267: =item *
1.394     bowersj2 9268: X<userenvironment()>
                   9269: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 9270: passed in @what from the requested user's environment, returns a hash
                   9271: 
1.858     raeburn  9272: =item * 
                   9273: X<userlog_query()>
1.859     albertel 9274: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   9275: activity.log file. %filters defines filters applied when parsing the
                   9276: log file. These can be start or end timestamps, or the type of action
                   9277: - log to look for Login or Logout events, check for Checkin or
                   9278: Checkout, role for role selection. The response is in the form
                   9279: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   9280: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  9281: 
1.243     albertel 9282: =back
                   9283: 
                   9284: =head2 User Roles
                   9285: 
                   9286: =over 4
                   9287: 
                   9288: =item *
                   9289: 
1.810     raeburn  9290: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 9291:  F: full access
                   9292:  U,I,K: authentication modes (cxx only)
                   9293:  '': forbidden
                   9294:  1: user needs to choose course
                   9295:  2: browse allowed
1.766     albertel 9296:  A: passphrase authentication needed
1.243     albertel 9297: 
                   9298: =item *
                   9299: 
                   9300: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   9301: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   9302: and course level
                   9303: 
                   9304: =item *
                   9305: 
                   9306: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
                   9307: explanation of a user role term
                   9308: 
1.832     raeburn  9309: =item *
                   9310: 
1.935     raeburn  9311: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858     raeburn  9312: All arguments are optional. Returns a hash of a roles, either for
                   9313: co-author/assistant author roles for a user's Construction Space
1.906     albertel 9314: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  9315: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   9316: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   9317: For each key, value is set to colon-separated start and end times for
                   9318: the role.  If no username and domain are specified, will default to
1.934     raeburn  9319: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  9320: of role statuses (active, future or previous), roles 
                   9321: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   9322: to restrict the list of roles reported. If no array ref is 
                   9323: provided for types, will default to return only active roles.
1.834     albertel 9324: 
1.243     albertel 9325: =back
                   9326: 
                   9327: =head2 User Modification
                   9328: 
                   9329: =over 4
                   9330: 
                   9331: =item *
                   9332: 
1.957     raeburn  9333: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 9334: user for the level given by URL.  Optional start and end dates (leave empty
                   9335: string or zero for "no date")
1.191     harris41 9336: 
                   9337: =item *
                   9338: 
1.243     albertel 9339: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   9340: change a users, password, possible return values are: ok,
                   9341: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   9342: refused
1.191     harris41 9343: 
                   9344: =item *
                   9345: 
1.243     albertel 9346: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 9347: 
                   9348: =item *
                   9349: 
1.963     raeburn  9350: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,
                   9351:            $forceid,$desiredhome,$email,$inststatus) : 
1.243     albertel 9352: modify user
1.191     harris41 9353: 
                   9354: =item *
                   9355: 
1.286     matthew  9356: modifystudent
                   9357: 
1.957     raeburn  9358: modify a student's enrollment and identification information.
1.286     matthew  9359: The course id is resolved based on the current users environment.  
                   9360: This means the envoking user must be a course coordinator or otherwise
                   9361: associated with a course.
                   9362: 
1.297     matthew  9363: This call is essentially a wrapper for lonnet::modifyuser and
                   9364: lonnet::modify_student_enrollment
1.286     matthew  9365: 
                   9366: Inputs: 
                   9367: 
                   9368: =over 4
                   9369: 
1.957     raeburn  9370: =item B<$udom> Student's loncapa domain
1.286     matthew  9371: 
1.957     raeburn  9372: =item B<$uname> Student's loncapa login name
1.286     matthew  9373: 
1.964     bisitz   9374: =item B<$uid> Student/Employee ID
1.286     matthew  9375: 
1.957     raeburn  9376: =item B<$umode> Student's authentication mode
1.286     matthew  9377: 
1.957     raeburn  9378: =item B<$upass> Student's password
1.286     matthew  9379: 
1.957     raeburn  9380: =item B<$first> Student's first name
1.286     matthew  9381: 
1.957     raeburn  9382: =item B<$middle> Student's middle name
1.286     matthew  9383: 
1.957     raeburn  9384: =item B<$last> Student's last name
1.286     matthew  9385: 
1.957     raeburn  9386: =item B<$gene> Student's generation
1.286     matthew  9387: 
1.957     raeburn  9388: =item B<$usec> Student's section in course
1.286     matthew  9389: 
                   9390: =item B<$end> Unix time of the roles expiration
                   9391: 
                   9392: =item B<$start> Unix time of the roles start date
                   9393: 
                   9394: =item B<$forceid> If defined, allow $uid to be changed
                   9395: 
                   9396: =item B<$desiredhome> server to use as home server for student
                   9397: 
1.957     raeburn  9398: =item B<$email> Student's permanent e-mail address
                   9399: 
                   9400: =item B<$type> Type of enrollment (auto or manual)
                   9401: 
1.963     raeburn  9402: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   9403: 
                   9404: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  9405: 
1.963     raeburn  9406: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  9407: 
1.963     raeburn  9408: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  9409: 
1.963     raeburn  9410: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
1.957     raeburn  9411: 
1.286     matthew  9412: =back
1.297     matthew  9413: 
                   9414: =item *
                   9415: 
                   9416: modify_student_enrollment
                   9417: 
                   9418: Change a students enrollment status in a class.  The environment variable
                   9419: 'role.request.course' must be defined for this function to proceed.
                   9420: 
                   9421: Inputs:
                   9422: 
                   9423: =over 4
                   9424: 
                   9425: =item $udom, students domain
                   9426: 
                   9427: =item $uname, students name
                   9428: 
                   9429: =item $uid, students user id
                   9430: 
                   9431: =item $first, students first name
                   9432: 
                   9433: =item $middle
                   9434: 
                   9435: =item $last
                   9436: 
                   9437: =item $gene
                   9438: 
                   9439: =item $usec
                   9440: 
                   9441: =item $end
                   9442: 
                   9443: =item $start
                   9444: 
1.957     raeburn  9445: =item $type
                   9446: 
                   9447: =item $locktype
                   9448: 
                   9449: =item $cid
                   9450: 
                   9451: =item $selfenroll
                   9452: 
                   9453: =item $context
                   9454: 
1.297     matthew  9455: =back
                   9456: 
1.191     harris41 9457: 
                   9458: =item *
                   9459: 
1.243     albertel 9460: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   9461: custom role; give a custom role to a user for the level given by URL.  Specify
                   9462: name and domain of role author, and role name
1.191     harris41 9463: 
                   9464: =item *
                   9465: 
1.243     albertel 9466: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 9467: 
                   9468: =item *
                   9469: 
1.243     albertel 9470: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   9471: 
                   9472: =back
                   9473: 
                   9474: =head2 Course Infomation
                   9475: 
                   9476: =over 4
1.191     harris41 9477: 
                   9478: =item *
                   9479: 
1.631     albertel 9480: coursedescription($courseid) : returns a hash of information about the
                   9481: specified course id, including all environment settings for the
                   9482: course, the description of the course will be in the hash under the
                   9483: key 'description'
1.191     harris41 9484: 
                   9485: =item *
                   9486: 
1.624     albertel 9487: resdata($name,$domain,$type,@which) : request for current parameter
                   9488: setting for a specific $type, where $type is either 'course' or 'user',
                   9489: @what should be a list of parameters to ask about. This routine caches
                   9490: answers for 5 minutes.
1.243     albertel 9491: 
1.877     foxr     9492: =item *
                   9493: 
                   9494: get_courseresdata($courseid, $domain) : dump the entire course resource
                   9495: data base, returning a hash that is keyed by the resource name and has
                   9496: values that are the resource value.  I believe that the timestamps and
                   9497: versions are also returned.
                   9498: 
                   9499: 
1.243     albertel 9500: =back
                   9501: 
                   9502: =head2 Course Modification
                   9503: 
                   9504: =over 4
1.191     harris41 9505: 
                   9506: =item *
                   9507: 
1.243     albertel 9508: writecoursepref($courseid,%prefs) : write preferences (environment
                   9509: database) for a course
1.191     harris41 9510: 
                   9511: =item *
                   9512: 
1.243     albertel 9513: createcourse($udom,$description,$url) : make/modify course
                   9514: 
                   9515: =back
                   9516: 
                   9517: =head2 Resource Subroutines
                   9518: 
                   9519: =over 4
1.191     harris41 9520: 
                   9521: =item *
                   9522: 
1.243     albertel 9523: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 9524: 
                   9525: =item *
                   9526: 
1.243     albertel 9527: repcopy($filename) : subscribes to the requested file, and attempts to
                   9528: replicate from the owning library server, Might return
1.607     raeburn  9529: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   9530: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 9531: resource. Expects the local filesystem pathname
                   9532: (/home/httpd/html/res/....)
                   9533: 
                   9534: =back
                   9535: 
                   9536: =head2 Resource Information
                   9537: 
                   9538: =over 4
1.191     harris41 9539: 
                   9540: =item *
                   9541: 
1.243     albertel 9542: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   9543: a vairety of different possible values, $varname should be a request
                   9544: string, and the other parameters can be used to specify who and what
                   9545: one is asking about.
                   9546: 
                   9547: Possible values for $varname are environment.lastname (or other item
                   9548: from the envirnment hash), user.name (or someother aspect about the
                   9549: user), resource.0.maxtries (or some other part and parameter of a
                   9550: resource)
1.204     albertel 9551: 
                   9552: =item *
                   9553: 
1.243     albertel 9554: directcondval($number) : get current value of a condition; reads from a state
                   9555: string
1.204     albertel 9556: 
                   9557: =item *
                   9558: 
1.243     albertel 9559: condval($condidx) : value of condition index based on state
1.204     albertel 9560: 
                   9561: =item *
                   9562: 
1.243     albertel 9563: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   9564: resource's metadata, $what should be either a specific key, or either
                   9565: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   9566: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   9567: 
                   9568: this function automatically caches all requests
1.191     harris41 9569: 
                   9570: =item *
                   9571: 
1.243     albertel 9572: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   9573: network of library servers; returns file handle of where SQL and regex results
                   9574: will be stored for query
1.191     harris41 9575: 
                   9576: =item *
                   9577: 
1.243     albertel 9578: symbread($filename) : return symbolic list entry (filename argument optional);
                   9579: returns the data handle
1.191     harris41 9580: 
                   9581: =item *
                   9582: 
1.243     albertel 9583: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 9584: a possible symb for the URL in $thisfn, and if is an encryypted
                   9585: resource that the user accessed using /enc/ returns a 1 on success, 0
                   9586: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 9587: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 9588: 
1.191     harris41 9589: 
                   9590: =item *
                   9591: 
1.243     albertel 9592: symbclean($symb) : removes versions numbers from a symb, returns the
                   9593: cleaned symb
1.191     harris41 9594: 
                   9595: =item *
                   9596: 
1.243     albertel 9597: is_on_map($uri) : checks if the $uri is somewhere on the current
                   9598: course map, user must be in a course for it to work.
1.191     harris41 9599: 
                   9600: =item *
                   9601: 
1.243     albertel 9602: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 9603: 
                   9604: =item *
                   9605: 
1.243     albertel 9606: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   9607: a random seed, all arguments are optional, if they aren't sent it uses the
                   9608: environment to derive them. Note: if symb isn't sent and it can't get one
                   9609: from &symbread it will use the current time as its return value
1.191     harris41 9610: 
                   9611: =item *
                   9612: 
1.243     albertel 9613: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   9614: unfakeable, receipt
1.191     harris41 9615: 
                   9616: =item *
                   9617: 
1.620     albertel 9618: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 9619: 
                   9620: =item *
                   9621: 
1.243     albertel 9622: countacc($url) : count the number of accesses to a given URL
1.191     harris41 9623: 
                   9624: =item *
                   9625: 
1.243     albertel 9626: 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 9627: 
                   9628: =item *
                   9629: 
1.243     albertel 9630: 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 9631: 
                   9632: =item *
                   9633: 
1.243     albertel 9634: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 9635: 
                   9636: =item *
                   9637: 
1.243     albertel 9638: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   9639: forcing spreadsheet to reevaluate the resource scores next time.
                   9640: 
                   9641: =back
                   9642: 
                   9643: =head2 Storing/Retreiving Data
                   9644: 
                   9645: =over 4
1.191     harris41 9646: 
                   9647: =item *
                   9648: 
1.243     albertel 9649: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   9650: for this url; hashref needs to be given and should be a \%hashname; the
                   9651: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 9652: be derived from the env
1.191     harris41 9653: 
                   9654: =item *
                   9655: 
1.243     albertel 9656: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   9657: uses critical subroutine
1.191     harris41 9658: 
                   9659: =item *
                   9660: 
1.243     albertel 9661: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   9662: all args are optional
1.191     harris41 9663: 
                   9664: =item *
                   9665: 
1.717     albertel 9666: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   9667: dumps the complete (or key matching regexp) namespace into a hash
                   9668: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   9669: normally &store()ed into
                   9670: 
                   9671: $range should be either an integer '100' (give me the first 100
                   9672:                                            matching records)
                   9673:               or be  two integers sperated by a - with no spaces
                   9674:                  '30-50' (give me the 30th through the 50th matching
                   9675:                           records)
                   9676: 
                   9677: 
                   9678: =item *
                   9679: 
                   9680: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   9681: replaces a &store() version of data with a replacement set of data
                   9682: for a particular resource in a namespace passed in the $storehash hash 
                   9683: reference
                   9684: 
                   9685: =item *
                   9686: 
1.243     albertel 9687: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   9688: works very similar to store/cstore, but all data is stored in a
                   9689: temporary location and can be reset using tmpreset, $storehash should
                   9690: be a hash reference, returns nothing on success
1.191     harris41 9691: 
                   9692: =item *
                   9693: 
1.243     albertel 9694: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   9695: similar to restore, but all data is stored in a temporary location and
                   9696: can be reset using tmpreset. Returns a hash of values on success,
                   9697: error string otherwise.
1.191     harris41 9698: 
                   9699: =item *
                   9700: 
1.243     albertel 9701: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   9702: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 9703: 
                   9704: =item *
                   9705: 
1.243     albertel 9706: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   9707: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 9708: 
                   9709: =item *
                   9710: 
1.243     albertel 9711: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   9712: namesp ($udom and $uname are optional)
1.191     harris41 9713: 
                   9714: =item *
                   9715: 
1.702     albertel 9716: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 9717: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 9718: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  9719: 
1.702     albertel 9720: $range should be either an integer '100' (give me the first 100
                   9721:                                            matching records)
                   9722:               or be  two integers sperated by a - with no spaces
                   9723:                  '30-50' (give me the 30th through the 50th matching
                   9724:                           records)
1.449     matthew  9725: =item *
                   9726: 
                   9727: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   9728: $store can be a scalar, an array reference, or if the amount to be 
                   9729: incremented is > 1, a hash reference.
                   9730: 
                   9731: ($udom and $uname are optional)
1.191     harris41 9732: 
                   9733: =item *
                   9734: 
1.243     albertel 9735: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   9736: ($udom and $uname are optional)
1.191     harris41 9737: 
                   9738: =item *
                   9739: 
1.243     albertel 9740: cput($namespace,$storehash,$udom,$uname) : critical put
                   9741: ($udom and $uname are optional)
1.191     harris41 9742: 
                   9743: =item *
                   9744: 
1.748     albertel 9745: newput($namespace,$storehash,$udom,$uname) :
                   9746: 
                   9747: Attempts to store the items in the $storehash, but only if they don't
                   9748: currently exist, if this succeeds you can be certain that you have 
                   9749: successfully created a new key value pair in the $namespace db.
                   9750: 
                   9751: 
                   9752: Args:
                   9753:  $namespace: name of database to store values to
                   9754:  $storehash: hashref to store to the db
                   9755:  $udom: (optional) domain of user containing the db
                   9756:  $uname: (optional) name of user caontaining the db
                   9757: 
                   9758: Returns:
                   9759:  'ok' -> succeeded in storing all keys of $storehash
                   9760:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   9761:                         least <key> already existed in the db (other
                   9762:                         requested keys may also already exist)
1.967     bisitz   9763:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 9764:  'con_lost' -> unable to contact request server
                   9765:  'refused' -> action was not allowed by remote machine
                   9766: 
                   9767: 
                   9768: =item *
                   9769: 
1.243     albertel 9770: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   9771: reference filled in from namesp (encrypts the return communication)
                   9772: ($udom and $uname are optional)
1.191     harris41 9773: 
                   9774: =item *
                   9775: 
1.243     albertel 9776: log($udom,$name,$home,$message) : write to permanent log for user; use
                   9777: critical subroutine
                   9778: 
1.806     raeburn  9779: =item *
                   9780: 
1.860     raeburn  9781: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   9782: array reference filled in from namespace found in domain level on either
                   9783: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  9784: 
                   9785: =item *
                   9786: 
1.860     raeburn  9787: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   9788: domain level either on specified domain server ($uhome) or primary domain 
                   9789: server ($udom and $uhome are optional)
1.806     raeburn  9790: 
1.943     raeburn  9791: =item * 
                   9792: 
                   9793: get_domain_defaults($target_domain) : returns hash with defaults for
                   9794: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
                   9795: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
                   9796: or localauth), initial password or a kerberos realm, language (e.g., en-us).
                   9797: Values are retrieved from cache (if current), or from domain's configuration.db
                   9798: (if available), or lastly from values in lonTabs/dns_domain,tab, 
                   9799: or lonTabs/domain.tab. 
                   9800: 
                   9801: %domdefaults = &get_auth_defaults($target_domain);
                   9802: 
1.243     albertel 9803: =back
                   9804: 
                   9805: =head2 Network Status Functions
                   9806: 
                   9807: =over 4
1.191     harris41 9808: 
                   9809: =item *
                   9810: 
                   9811: dirlist($uri) : return directory list based on URI
                   9812: 
                   9813: =item *
                   9814: 
1.243     albertel 9815: spareserver() : find server with least workload from spare.tab
                   9816: 
                   9817: =back
                   9818: 
                   9819: =head2 Apache Request
                   9820: 
                   9821: =over 4
1.191     harris41 9822: 
                   9823: =item *
                   9824: 
1.243     albertel 9825: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   9826: localhost, posts hash
                   9827: 
                   9828: =back
                   9829: 
                   9830: =head2 Data to String to Data
                   9831: 
                   9832: =over 4
1.191     harris41 9833: 
                   9834: =item *
                   9835: 
1.243     albertel 9836: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   9837: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 9838: 
                   9839: =item *
                   9840: 
1.243     albertel 9841: hashref2str($hashref) : convert a hashref into a string complete with
                   9842: escaping and '=' and '&' separators, supports elements that are
                   9843: arrayrefs and hashrefs
1.191     harris41 9844: 
                   9845: =item *
                   9846: 
1.243     albertel 9847: arrayref2str($arrayref) : convert an arrayref into a string complete
                   9848: with escaping and '&' separators, supports elements that are arrayrefs
                   9849: and hashrefs
1.191     harris41 9850: 
                   9851: =item *
                   9852: 
1.243     albertel 9853: str2hash($string) : convert string to hash using unescaping and
                   9854: splitting on '=' and '&', supports elements that are arrayrefs and
                   9855: hashrefs
1.191     harris41 9856: 
                   9857: =item *
                   9858: 
1.243     albertel 9859: str2array($string) : convert string to hash using unescaping and
                   9860: splitting on '&', supports elements that are arrayrefs and hashrefs
                   9861: 
                   9862: =back
                   9863: 
                   9864: =head2 Logging Routines
                   9865: 
                   9866: =over 4
                   9867: 
                   9868: These routines allow one to make log messages in the lonnet.log and
                   9869: lonnet.perm logfiles.
1.191     harris41 9870: 
                   9871: =item *
                   9872: 
1.243     albertel 9873: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 9874: 
                   9875: =item *
                   9876: 
1.243     albertel 9877: logthis() : append message to the normal lonnet.log file, it gets
                   9878: preiodically rolled over and deleted.
1.191     harris41 9879: 
                   9880: =item *
                   9881: 
1.243     albertel 9882: logperm() : append a permanent message to lonnet.perm.log, this log
                   9883: file never gets deleted by any automated portion of the system, only
                   9884: messages of critical importance should go in here.
                   9885: 
                   9886: =back
                   9887: 
                   9888: =head2 General File Helper Routines
                   9889: 
                   9890: =over 4
1.191     harris41 9891: 
                   9892: =item *
                   9893: 
1.481     raeburn  9894: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   9895: (a) files in /uploaded
                   9896:   (i) If a local copy of the file exists - 
                   9897:       compares modification date of local copy with last-modified date for 
                   9898:       definitive version stored on home server for course. If local copy is 
                   9899:       stale, requests a new version from the home server and stores it. 
                   9900:       If the original has been removed from the home server, then local copy 
                   9901:       is unlinked.
                   9902:   (ii) If local copy does not exist -
                   9903:       requests the file from the home server and stores it. 
                   9904:   
                   9905:   If $caller is 'uploadrep':  
                   9906:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   9907:     for request for files originally uploaded via DOCS. 
                   9908:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   9909:   
                   9910:   Otherwise:
                   9911:      This indicates a call from the content generation phase of the request.
                   9912:      -  returns the entire contents of the file or -1.
                   9913:      
                   9914: (b) files in /res
                   9915:    - returns the entire contents of a file or -1; 
                   9916:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 9917: 
1.712     albertel 9918: 
                   9919: =item *
                   9920: 
                   9921: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   9922:                   reference
                   9923: 
                   9924: returns either a stat() list of data about the file or an empty list
                   9925: if the file doesn't exist or couldn't find out about it (connection
                   9926: problems or user unknown)
                   9927: 
1.191     harris41 9928: =item *
                   9929: 
1.243     albertel 9930: filelocation($dir,$file) : returns file system location of a file
                   9931: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   9932: directory that relative $file lookups are to looked in ($dir of /a/dir
                   9933: and a file of ../bob will become /a/bob)
1.191     harris41 9934: 
                   9935: =item *
                   9936: 
                   9937: hreflocation($dir,$file) : returns file system location or a URL; same as
                   9938: filelocation except for hrefs
                   9939: 
                   9940: =item *
                   9941: 
                   9942: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   9943: 
1.243     albertel 9944: =back
                   9945: 
1.608     albertel 9946: =head2 Usererfile file routines (/uploaded*)
                   9947: 
                   9948: =over 4
                   9949: 
                   9950: =item *
                   9951: 
                   9952: userfileupload(): main rotine for putting a file in a user or course's
                   9953:                   filespace, arguments are,
                   9954: 
1.620     albertel 9955:  formname - required - this is the name of the element in $env where the
1.608     albertel 9956:            filename, and the contents of the file to create/modifed exist
1.620     albertel 9957:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   9958:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 9959:  coursedoc - if true, store the file in the course of the active role
                   9960:              of the current user
                   9961:  subdir - required - subdirectory to put the file in under ../userfiles/
                   9962:          if undefined, it will be placed in "unknown"
                   9963: 
                   9964:  (This routine calls clean_filename() to remove any dangerous
                   9965:  characters from the filename, and then calls finuserfileupload() to
                   9966:  complete the transaction)
                   9967: 
                   9968:  returns either the url of the uploaded file (/uploaded/....) if successful
                   9969:  and /adm/notfound.html if unsuccessful
                   9970: 
                   9971: =item *
                   9972: 
                   9973: clean_filename(): routine for cleaing a filename up for storage in
                   9974:                  userfile space, argument is:
                   9975: 
                   9976:  filename - proposed filename
                   9977: 
                   9978: returns: the new clean filename
                   9979: 
                   9980: =item *
                   9981: 
                   9982: finishuserfileupload(): routine that creaes and sends the file to
                   9983: userspace, probably shouldn't be called directly
                   9984: 
                   9985:   docuname: username or courseid of destination for the file
                   9986:   docudom: domain of user/course of destination for the file
                   9987:   formname: same as for userfileupload()
                   9988:   fname: filename (inculding subdirectories) for the file
                   9989: 
                   9990:  returns either the url of the uploaded file (/uploaded/....) if successful
                   9991:  and /adm/notfound.html if unsuccessful
                   9992: 
                   9993: =item *
                   9994: 
                   9995: renameuserfile(): renames an existing userfile to a new name
                   9996: 
                   9997:   Args:
                   9998:    docuname: username or courseid of destination for the file
                   9999:    docudom: domain of user/course of destination for the file
                   10000:    old: current file name (including any subdirs under userfiles)
                   10001:    new: desired file name (including any subdirs under userfiles)
                   10002: 
                   10003: =item *
                   10004: 
                   10005: mkdiruserfile(): creates a directory is a userfiles dir
                   10006: 
                   10007:   Args:
                   10008:    docuname: username or courseid of destination for the file
                   10009:    docudom: domain of user/course of destination for the file
                   10010:    dir: dir to create (including any subdirs under userfiles)
                   10011: 
                   10012: =item *
                   10013: 
                   10014: removeuserfile(): removes a file that exists in userfiles
                   10015: 
                   10016:   Args:
                   10017:    docuname: username or courseid of destination for the file
                   10018:    docudom: domain of user/course of destination for the file
                   10019:    fname: filname to delete (including any subdirs under userfiles)
                   10020: 
                   10021: =item *
                   10022: 
                   10023: removeuploadedurl(): convience function for removeuserfile()
                   10024: 
                   10025:   Args:
                   10026:    url:  a full /uploaded/... url to delete
                   10027: 
1.747     albertel 10028: =item * 
                   10029: 
                   10030: get_portfile_permissions():
                   10031:   Args:
                   10032:     domain: domain of user or course contain the portfolio files
                   10033:     user: name of user or num of course contain the portfolio files
                   10034:   Returns:
                   10035:     hashref of a dump of the proper file_permissions.db
                   10036:    
                   10037: 
                   10038: =item * 
                   10039: 
                   10040: get_access_controls():
                   10041: 
                   10042: Args:
                   10043:   current_permissions: the hash ref returned from get_portfile_permissions()
                   10044:   group: (optional) the group you want the files associated with
                   10045:   file: (optional) the file you want access info on
                   10046: 
                   10047: Returns:
1.749     raeburn  10048:     a hash (keys are file names) of hashes containing
                   10049:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   10050:         values are XML containing access control settings (see below) 
1.747     albertel 10051: 
                   10052: Internal notes:
                   10053: 
1.749     raeburn  10054:  access controls are stored in file_permissions.db as key=value pairs.
                   10055:     key -> path to file/file_name\0uniqueID:scope_end_start
                   10056:         where scope -> public,guest,course,group,domains or users.
                   10057:               end -> UNIX time for end of access (0 -> no end date)
                   10058:               start -> UNIX time for start of access
                   10059: 
                   10060:     value -> XML description of access control
                   10061:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   10062:             <start></start>
                   10063:             <end></end>
                   10064: 
                   10065:             <password></password>  for scope type = guest
                   10066: 
                   10067:             <domain></domain>     for scope type = course or group
                   10068:             <number></number>
                   10069:             <roles id="">
                   10070:              <role></role>
                   10071:              <access></access>
                   10072:              <section></section>
                   10073:              <group></group>
                   10074:             </roles>
                   10075: 
                   10076:             <dom></dom>         for scope type = domains
                   10077: 
                   10078:             <users>             for scope type = users
                   10079:              <user>
                   10080:               <uname></uname>
                   10081:               <udom></udom>
                   10082:              </user>
                   10083:             </users>
                   10084:            </scope> 
                   10085:               
                   10086:  Access data is also aggregated for each file in an additional key=value pair:
                   10087:  key -> path to file/file_name\0accesscontrol 
                   10088:  value -> reference to hash
                   10089:           hash contains key = value pairs
                   10090:           where key = uniqueID:scope_end_start
                   10091:                 value = UNIX time record was last updated
                   10092: 
                   10093:           Used to improve speed of look-ups of access controls for each file.  
                   10094:  
                   10095:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   10096: 
                   10097: modify_access_controls():
                   10098: 
                   10099: Modifies access controls for a portfolio file
                   10100: Args
                   10101: 1. file name
                   10102: 2. reference to hash of required changes,
                   10103: 3. domain
                   10104: 4. username
                   10105:   where domain,username are the domain of the portfolio owner 
                   10106:   (either a user or a course) 
                   10107: 
                   10108: Returns:
                   10109: 1. result of additions or updates ('ok' or 'error', with error message). 
                   10110: 2. result of deletions ('ok' or 'error', with error message).
                   10111: 3. reference to hash of any new or updated access controls.
                   10112: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   10113:    key = integer (inbound ID)
                   10114:    value = uniqueID  
1.747     albertel 10115: 
1.608     albertel 10116: =back
                   10117: 
1.243     albertel 10118: =head2 HTTP Helper Routines
                   10119: 
                   10120: =over 4
                   10121: 
1.191     harris41 10122: =item *
                   10123: 
                   10124: escape() : unpack non-word characters into CGI-compatible hex codes
                   10125: 
                   10126: =item *
                   10127: 
                   10128: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   10129: 
1.243     albertel 10130: =back
                   10131: 
                   10132: =head1 PRIVATE SUBROUTINES
                   10133: 
                   10134: =head2 Underlying communication routines (Shouldn't call)
                   10135: 
                   10136: =over 4
                   10137: 
                   10138: =item *
                   10139: 
                   10140: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   10141: 
                   10142: =item *
                   10143: 
                   10144: reply() : uses subreply to send a message to remote machine, logs all failures
                   10145: 
                   10146: =item *
                   10147: 
                   10148: critical() : passes a critical message to another server; if cannot
                   10149: get through then place message in connection buffer directory and
                   10150: returns con_delayed, if incapable of saving message, returns
                   10151: con_failed
                   10152: 
                   10153: =item *
                   10154: 
                   10155: reconlonc() : tries to reconnect lonc client processes.
                   10156: 
                   10157: =back
                   10158: 
                   10159: =head2 Resource Access Logging
                   10160: 
                   10161: =over 4
                   10162: 
                   10163: =item *
                   10164: 
                   10165: flushcourselogs() : flush (save) buffer logs and access logs
                   10166: 
                   10167: =item *
                   10168: 
                   10169: courselog($what) : save message for course in hash
                   10170: 
                   10171: =item *
                   10172: 
                   10173: courseacclog($what) : save message for course using &courselog().  Perform
                   10174: special processing for specific resource types (problems, exams, quizzes, etc).
                   10175: 
1.191     harris41 10176: =item *
                   10177: 
                   10178: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   10179: as a PerlChildExitHandler
1.243     albertel 10180: 
                   10181: =back
                   10182: 
                   10183: =head2 Other
                   10184: 
                   10185: =over 4
                   10186: 
                   10187: =item *
                   10188: 
                   10189: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 10190: 
                   10191: =back
                   10192: 
                   10193: =cut
1.877     foxr     10194: 

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