File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1195: download - view: text, annotated - select for diffs
Fri Nov 9 17:27:18 2012 UTC (11 years, 8 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Consistent Interface for templated pages (bug 6128).
- Make functions for Templated "About Me" page visible.
- Additional arg for lonnet::in_course() -- $hideprivileged
  - if true, exclude DC + SU users, unless overridden in course environment.
- perldoc (lonnet.pm): &in_course(), &can_edit_resource(), &is_course_upload()

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1195 2012/11/09 17:27:18 raeburn Exp $
    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: #
   28: ###
   29: 
   30: =pod
   31: 
   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: 
   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: 
   71: package Apache::lonnet;
   72: 
   73: use strict;
   74: use LWP::UserAgent();
   75: use HTTP::Date;
   76: use Image::Magick;
   77: 
   78: 
   79: use Encode;
   80: 
   81: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
   82:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
   83:             %managerstab);
   84: 
   85: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
   86:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
   87:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
   88:     %courseownerbuf, %coursetypebuf,$locknum);
   89: 
   90: use IO::Socket;
   91: use GDBM_File;
   92: use HTML::LCParser;
   93: use Fcntl qw(:flock);
   94: use Storable qw(thaw nfreeze);
   95: use Time::HiRes qw( gettimeofday tv_interval );
   96: use Cache::Memcached;
   97: use Digest::MD5;
   98: use Math::Random;
   99: use File::MMagic;
  100: use LONCAPA qw(:DEFAULT :match);
  101: use LONCAPA::Configuration;
  102: use LONCAPA::lonmetadata;
  103: use LONCAPA::Lond;
  104: 
  105: use File::Copy;
  106: 
  107: my $readit;
  108: my $max_connection_retries = 10;     # Or some such value.
  109: 
  110: require Exporter;
  111: 
  112: our @ISA = qw (Exporter);
  113: our @EXPORT = qw(%env);
  114: 
  115: 
  116: # ------------------------------------ Logging (parameters, docs, slots, roles)
  117: {
  118:     my $logid;
  119:     sub write_log {
  120: 	my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
  121:         if ($context eq 'course') {
  122:             if (($cnum eq '') || ($cdom eq '')) {
  123:                 $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
  124:                 $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
  125:             }
  126:         }
  127: 	$logid ++;
  128:         my $now = time();
  129: 	my $id=$now.'00000'.$$.'00000'.$logid;
  130:         my $logentry = { 
  131:                           $id => {
  132:                                    'exe_uname' => $env{'user.name'},
  133:                                    'exe_udom'  => $env{'user.domain'},
  134:                                    'exe_time'  => $now,
  135:                                    'exe_ip'    => $ENV{'REMOTE_ADDR'},
  136:                                    'delflag'   => $delflag,
  137:                                    'logentry'  => $storehash,
  138:                                    'uname'     => $uname,
  139:                                    'udom'      => $udom,
  140:                                   }
  141:                        };
  142: 	return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
  143:     }
  144: }
  145: 
  146: sub logtouch {
  147:     my $execdir=$perlvar{'lonDaemons'};
  148:     unless (-e "$execdir/logs/lonnet.log") {	
  149: 	open(my $fh,">>$execdir/logs/lonnet.log");
  150: 	close $fh;
  151:     }
  152:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
  153:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
  154: }
  155: 
  156: sub logthis {
  157:     my $message=shift;
  158:     my $execdir=$perlvar{'lonDaemons'};
  159:     my $now=time;
  160:     my $local=localtime($now);
  161:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
  162: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
  163: 	print $fh $logstring;
  164: 	close($fh);
  165:     }
  166:     return 1;
  167: }
  168: 
  169: sub logperm {
  170:     my $message=shift;
  171:     my $execdir=$perlvar{'lonDaemons'};
  172:     my $now=time;
  173:     my $local=localtime($now);
  174:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
  175: 	print $fh "$now:$message:$local\n";
  176: 	close($fh);
  177:     }
  178:     return 1;
  179: }
  180: 
  181: sub create_connection {
  182:     my ($hostname,$lonid) = @_;
  183:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
  184: 				     Type    => SOCK_STREAM,
  185: 				     Timeout => 10);
  186:     return 0 if (!$client);
  187:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
  188:     my $result = <$client>;
  189:     chomp($result);
  190:     return 1 if ($result eq 'done');
  191:     return 0;
  192: }
  193: 
  194: sub get_server_timezone {
  195:     my ($cnum,$cdom) = @_;
  196:     my $home=&homeserver($cnum,$cdom);
  197:     if ($home ne 'no_host') {
  198:         my $cachetime = 24*3600;
  199:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
  200:         if (defined($cached)) {
  201:             return $timezone;
  202:         } else {
  203:             my $timezone = &reply('servertimezone',$home);
  204:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
  205:         }
  206:     }
  207: }
  208: 
  209: sub get_server_distarch {
  210:     my ($lonhost,$ignore_cache) = @_;
  211:     if (defined($lonhost)) {
  212:         if (!defined(&hostname($lonhost))) {
  213:             return;
  214:         }
  215:         my $cachetime = 12*3600;
  216:         if (!$ignore_cache) {
  217:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
  218:             if (defined($cached)) {
  219:                 return $distarch;
  220:             }
  221:         }
  222:         my $rep = &reply('serverdistarch',$lonhost);
  223:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
  224:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
  225:                 $rep eq '') {
  226:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
  227:         }
  228:     }
  229:     return;
  230: }
  231: 
  232: sub get_server_loncaparev {
  233:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
  234:     if (defined($lonhost)) {
  235:         if (!defined(&hostname($lonhost))) {
  236:             undef($lonhost);
  237:         }
  238:     }
  239:     if (!defined($lonhost)) {
  240:         if (defined(&domain($dom,'primary'))) {
  241:             $lonhost=&domain($dom,'primary');
  242:             if ($lonhost eq 'no_host') {
  243:                 undef($lonhost);
  244:             }
  245:         }
  246:     }
  247:     if (defined($lonhost)) {
  248:         my $cachetime = 12*3600;
  249:         if (!$ignore_cache) {
  250:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
  251:             if (defined($cached)) {
  252:                 return $loncaparev;
  253:             }
  254:         }
  255:         my ($answer,$loncaparev);
  256:         my @ids=&current_machine_ids();
  257:         if (grep(/^\Q$lonhost\E$/,@ids)) {
  258:             $answer = $perlvar{'lonVersion'};
  259:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  260:                 $loncaparev = $1;
  261:             }
  262:         } else {
  263:             $answer = &reply('serverloncaparev',$lonhost);
  264:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
  265:                 if ($caller eq 'loncron') {
  266:                     my $ua=new LWP::UserAgent;
  267:                     $ua->timeout(4);
  268:                     my $protocol = $protocol{$lonhost};
  269:                     $protocol = 'http' if ($protocol ne 'https');
  270:                     my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
  271:                     my $request=new HTTP::Request('GET',$url);
  272:                     my $response=$ua->request($request);
  273:                     unless ($response->is_error()) {
  274:                         my $content = $response->content;
  275:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
  276:                             $loncaparev = $1;
  277:                         }
  278:                     }
  279:                 } else {
  280:                     $loncaparev = $loncaparevs{$lonhost};
  281:                 }
  282:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  283:                 $loncaparev = $1;
  284:             }
  285:         }
  286:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
  287:     }
  288: }
  289: 
  290: sub get_server_homeID {
  291:     my ($hostname,$ignore_cache,$caller) = @_;
  292:     unless ($ignore_cache) {
  293:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
  294:         if (defined($cached)) {
  295:             return $serverhomeID;
  296:         }
  297:     }
  298:     my $cachetime = 12*3600;
  299:     my $serverhomeID;
  300:     if ($caller eq 'loncron') { 
  301:         my @machine_ids = &machine_ids($hostname);
  302:         foreach my $id (@machine_ids) {
  303:             my $response = &reply('serverhomeID',$id);
  304:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
  305:                 $serverhomeID = $response;
  306:                 last;
  307:             }
  308:         }
  309:         if ($serverhomeID eq '') {
  310:             $serverhomeID = $machine_ids[-1];
  311:         }
  312:     } else {
  313:         $serverhomeID = $serverhomeIDs{$hostname};
  314:     }
  315:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
  316: }
  317: 
  318: sub get_remote_globals {
  319:     my ($lonhost,$whathash,$ignore_cache) = @_;
  320:     my ($result,%returnhash,%whatneeded);
  321:     if (ref($whathash) eq 'HASH') {
  322:         foreach my $what (sort(keys(%{$whathash}))) {
  323:             my $hashid = $lonhost.'-'.$what;
  324:             my ($response,$cached);
  325:             unless ($ignore_cache) {
  326:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
  327:             }
  328:             if (defined($cached)) {
  329:                 $returnhash{$what} = $response;
  330:             } else {
  331:                 $whatneeded{$what} = 1;
  332:             }
  333:         }
  334:         if (keys(%whatneeded) == 0) {
  335:             $result = 'ok';
  336:         } else {
  337:             my $requested = &freeze_escape(\%whatneeded);
  338:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
  339:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
  340:                 ($rep eq 'unknown_cmd')) {
  341:                 $result = $rep;
  342:             } else {
  343:                 $result = 'ok';
  344:                 my @pairs=split(/\&/,$rep);
  345:                 foreach my $item (@pairs) {
  346:                     my ($key,$value)=split(/=/,$item,2);
  347:                     my $what = &unescape($key);
  348:                     my $hashid = $lonhost.'-'.$what;
  349:                     $returnhash{$what}=&thaw_unescape($value);
  350:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
  351:                 }
  352:             }
  353:         }
  354:     }
  355:     return ($result,\%returnhash);
  356: }
  357: 
  358: sub remote_devalidate_cache {
  359:     my ($lonhost,$name,$id) = @_;
  360:     my $response = &reply('devalidatecache:'.&escape($name).':'.&escape($id),$lonhost);
  361:     return $response;
  362: }
  363: 
  364: # -------------------------------------------------- Non-critical communication
  365: sub subreply {
  366:     my ($cmd,$server)=@_;
  367:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
  368:     #
  369:     #  With loncnew process trimming, there's a timing hole between lonc server
  370:     #  process exit and the master server picking up the listen on the AF_UNIX
  371:     #  socket.  In that time interval, a lock file will exist:
  372: 
  373:     my $lockfile=$peerfile.".lock";
  374:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
  375: 	sleep(1);
  376:     }
  377:     # At this point, either a loncnew parent is listening or an old lonc
  378:     # or loncnew child is listening so we can connect or everything's dead.
  379:     #
  380:     #   We'll give the connection a few tries before abandoning it.  If
  381:     #   connection is not possible, we'll con_lost back to the client.
  382:     #   
  383:     my $client;
  384:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
  385: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  386: 				      Type    => SOCK_STREAM,
  387: 				      Timeout => 10);
  388: 	if ($client) {
  389: 	    last;		# Connected!
  390: 	} else {
  391: 	    &create_connection(&hostname($server),$server);
  392: 	}
  393:         sleep(1);		# Try again later if failed connection.
  394:     }
  395:     my $answer;
  396:     if ($client) {
  397: 	print $client "sethost:$server:$cmd\n";
  398: 	$answer=<$client>;
  399: 	if (!$answer) { $answer="con_lost"; }
  400: 	chomp($answer);
  401:     } else {
  402: 	$answer = 'con_lost';	# Failed connection.
  403:     }
  404:     return $answer;
  405: }
  406: 
  407: sub reply {
  408:     my ($cmd,$server)=@_;
  409:     unless (defined(&hostname($server))) { return 'no_such_host'; }
  410:     my $answer=subreply($cmd,$server);
  411:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
  412:        &logthis("<font color=\"blue\">WARNING:".
  413:                 " $cmd to $server returned $answer</font>");
  414:     }
  415:     return $answer;
  416: }
  417: 
  418: # ----------------------------------------------------------- Send USR1 to lonc
  419: 
  420: sub reconlonc {
  421:     my ($lonid) = @_;
  422:     my $hostname = &hostname($lonid);
  423:     if ($lonid) {
  424: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
  425: 	if ($hostname && -e $peerfile) {
  426: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
  427: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
  428: 					     Type    => SOCK_STREAM,
  429: 					     Timeout => 10);
  430: 	    if ($client) {
  431: 		print $client ("reset_retries\n");
  432: 		my $answer=<$client>;
  433: 		#reset just this one.
  434: 	    }
  435: 	}
  436: 	return;
  437:     }
  438: 
  439:     &logthis("Trying to reconnect lonc");
  440:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  441:     if (open(my $fh,"<$loncfile")) {
  442: 	my $loncpid=<$fh>;
  443:         chomp($loncpid);
  444:         if (kill 0 => $loncpid) {
  445: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  446:             kill USR1 => $loncpid;
  447:             sleep 1;
  448:          } else {
  449: 	    &logthis(
  450:                "<font color=\"blue\">WARNING:".
  451:                " lonc at pid $loncpid not responding, giving up</font>");
  452:         }
  453:     } else {
  454: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
  455:     }
  456: }
  457: 
  458: # ------------------------------------------------------ Critical communication
  459: 
  460: sub critical {
  461:     my ($cmd,$server)=@_;
  462:     unless (&hostname($server)) {
  463:         &logthis("<font color=\"blue\">WARNING:".
  464:                " Critical message to unknown server ($server)</font>");
  465:         return 'no_such_host';
  466:     }
  467:     my $answer=reply($cmd,$server);
  468:     if ($answer eq 'con_lost') {
  469: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
  470: 	my $answer=reply($cmd,$server);
  471:         if ($answer eq 'con_lost') {
  472:             my $now=time;
  473:             my $middlename=$cmd;
  474:             $middlename=substr($middlename,0,16);
  475:             $middlename=~s/\W//g;
  476:             my $dfilename=
  477:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
  478:             $dumpcount++;
  479:             {
  480: 		my $dfh;
  481: 		if (open($dfh,">$dfilename")) {
  482: 		    print $dfh "$cmd\n"; 
  483: 		    close($dfh);
  484: 		}
  485:             }
  486:             sleep 2;
  487:             my $wcmd='';
  488:             {
  489: 		my $dfh;
  490: 		if (open($dfh,"<$dfilename")) {
  491: 		    $wcmd=<$dfh>; 
  492: 		    close($dfh);
  493: 		}
  494:             }
  495:             chomp($wcmd);
  496:             if ($wcmd eq $cmd) {
  497: 		&logthis("<font color=\"blue\">WARNING: ".
  498:                          "Connection buffer $dfilename: $cmd</font>");
  499:                 &logperm("D:$server:$cmd");
  500: 	        return 'con_delayed';
  501:             } else {
  502:                 &logthis("<font color=\"red\">CRITICAL:"
  503:                         ." Critical connection failed: $server $cmd</font>");
  504:                 &logperm("F:$server:$cmd");
  505:                 return 'con_failed';
  506:             }
  507:         }
  508:     }
  509:     return $answer;
  510: }
  511: 
  512: # ------------------------------------------- check if return value is an error
  513: 
  514: sub error {
  515:     my ($result) = @_;
  516:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
  517: 	if ($2 == 2) { return undef; }
  518: 	return $1;
  519:     }
  520:     return undef;
  521: }
  522: 
  523: sub convert_and_load_session_env {
  524:     my ($lonidsdir,$handle)=@_;
  525:     my @profile;
  526:     {
  527: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  528: 	if (!$opened) {
  529: 	    return 0;
  530: 	}
  531: 	flock($idf,LOCK_SH);
  532: 	@profile=<$idf>;
  533: 	close($idf);
  534:     }
  535:     my %temp_env;
  536:     foreach my $line (@profile) {
  537: 	if ($line !~ m/=/) {
  538: 	    return 0;
  539: 	}
  540: 	chomp($line);
  541: 	my ($envname,$envvalue)=split(/=/,$line,2);
  542: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
  543:     }
  544:     unlink("$lonidsdir/$handle.id");
  545:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
  546: 	    0640)) {
  547: 	%disk_env = %temp_env;
  548: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
  549: 	untie(%disk_env);
  550:     }
  551:     return 1;
  552: }
  553: 
  554: # ------------------------------------------- Transfer profile into environment
  555: my $env_loaded;
  556: sub transfer_profile_to_env {
  557:     my ($lonidsdir,$handle,$force_transfer) = @_;
  558:     if (!$force_transfer && $env_loaded) { return; } 
  559: 
  560:     if (!defined($lonidsdir)) {
  561: 	$lonidsdir = $perlvar{'lonIDsDir'};
  562:     }
  563:     if (!defined($handle)) {
  564:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
  565:     }
  566: 
  567:     my $convert;
  568:     {
  569:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  570: 	if (!$opened) {
  571: 	    return;
  572: 	}
  573: 	flock($idf,LOCK_SH);
  574: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  575: 		&GDBM_READER(),0640)) {
  576: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
  577: 	    untie(%disk_env);
  578: 	} else {
  579: 	    $convert = 1;
  580: 	}
  581:     }
  582:     if ($convert) {
  583: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
  584: 	    &logthis("Failed to load session, or convert session.");
  585: 	}
  586:     }
  587: 
  588:     my %remove;
  589:     while ( my $envname = each(%env) ) {
  590:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  591:             if ($time < time-300) {
  592:                 $remove{$key}++;
  593:             }
  594:         }
  595:     }
  596: 
  597:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  598:     $env_loaded=1;
  599:     foreach my $expired_key (keys(%remove)) {
  600:         &delenv($expired_key);
  601:     }
  602: }
  603: 
  604: # ---------------------------------------------------- Check for valid session 
  605: sub check_for_valid_session {
  606:     my ($r,$name) = @_;
  607:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
  608:     if ($name eq '') {
  609:         $name = 'lonID';
  610:     }
  611:     my $lonid=$cookies{$name};
  612:     return undef if (!$lonid);
  613: 
  614:     my $handle=&LONCAPA::clean_handle($lonid->value);
  615:     my $lonidsdir;
  616:     if ($name eq 'lonDAV') {
  617:         $lonidsdir=$r->dir_config('lonDAVsessDir');
  618:     } else {
  619:         $lonidsdir=$r->dir_config('lonIDsDir');
  620:     }
  621:     return undef if (!-e "$lonidsdir/$handle.id");
  622: 
  623:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  624:     return undef if (!$opened);
  625: 
  626:     flock($idf,LOCK_SH);
  627:     my %disk_env;
  628:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  629: 	    &GDBM_READER(),0640)) {
  630: 	return undef;	
  631:     }
  632: 
  633:     if (!defined($disk_env{'user.name'})
  634: 	|| !defined($disk_env{'user.domain'})) {
  635: 	return undef;
  636:     }
  637:     return $handle;
  638: }
  639: 
  640: sub timed_flock {
  641:     my ($file,$lock_type) = @_;
  642:     my $failed=0;
  643:     eval {
  644: 	local $SIG{__DIE__}='DEFAULT';
  645: 	local $SIG{ALRM}=sub {
  646: 	    $failed=1;
  647: 	    die("failed lock");
  648: 	};
  649: 	alarm(13);
  650: 	flock($file,$lock_type);
  651: 	alarm(0);
  652:     };
  653:     if ($failed) {
  654: 	return undef;
  655:     } else {
  656: 	return 1;
  657:     }
  658: }
  659: 
  660: # ---------------------------------------------------------- Append Environment
  661: 
  662: sub appenv {
  663:     my ($newenv,$roles) = @_;
  664:     if (ref($newenv) eq 'HASH') {
  665:         foreach my $key (keys(%{$newenv})) {
  666:             my $refused = 0;
  667: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
  668:                 $refused = 1;
  669:                 if (ref($roles) eq 'ARRAY') {
  670:                     my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
  671:                     if (grep(/^\Q$role\E$/,@{$roles})) {
  672:                         $refused = 0;
  673:                     }
  674:                 }
  675:             }
  676:             if ($refused) {
  677:                 &logthis("<font color=\"blue\">WARNING: ".
  678:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
  679:                          .'</font>');
  680: 	        delete($newenv->{$key});
  681:             } else {
  682:                 $env{$key}=$newenv->{$key};
  683:             }
  684:         }
  685:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
  686:         if ($opened
  687: 	    && &timed_flock($env_file,LOCK_EX)
  688: 	    &&
  689: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  690: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  691: 	    while (my ($key,$value) = each(%{$newenv})) {
  692: 	        $disk_env{$key} = $value;
  693: 	    }
  694: 	    untie(%disk_env);
  695:         }
  696:     }
  697:     return 'ok';
  698: }
  699: # ----------------------------------------------------- Delete from Environment
  700: 
  701: sub delenv {
  702:     my ($delthis,$regexp,$roles) = @_;
  703:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
  704:         my $refused = 1;
  705:         if (ref($roles) eq 'ARRAY') {
  706:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
  707:             if (grep(/^\Q$role\E$/,@{$roles})) {
  708:                 $refused = 0;
  709:             }
  710:         }
  711:         if ($refused) {
  712:             &logthis("<font color=\"blue\">WARNING: ".
  713:                      "Attempt to delete from environment ".$delthis);
  714:             return 'error';
  715:         }
  716:     }
  717:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
  718:     if ($opened
  719: 	&& &timed_flock($env_file,LOCK_EX)
  720: 	&&
  721: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  722: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  723: 	foreach my $key (keys(%disk_env)) {
  724: 	    if ($regexp) {
  725:                 if ($key=~/^$delthis/) {
  726:                     delete($env{$key});
  727:                     delete($disk_env{$key});
  728:                 } 
  729:             } else {
  730:                 if ($key=~/^\Q$delthis\E/) {
  731: 		    delete($env{$key});
  732: 		    delete($disk_env{$key});
  733: 	        }
  734:             }
  735: 	}
  736: 	untie(%disk_env);
  737:     }
  738:     return 'ok';
  739: }
  740: 
  741: sub get_env_multiple {
  742:     my ($name) = @_;
  743:     my @values;
  744:     if (defined($env{$name})) {
  745:         # exists is it an array
  746:         if (ref($env{$name})) {
  747:             @values=@{ $env{$name} };
  748:         } else {
  749:             $values[0]=$env{$name};
  750:         }
  751:     }
  752:     return(@values);
  753: }
  754: 
  755: # ------------------------------------------------------------------- Locking
  756: 
  757: sub set_lock {
  758:     my ($text)=@_;
  759:     $locknum++;
  760:     my $id=$$.'-'.$locknum;
  761:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
  762:              'session.lock.'.$id => $text});
  763:     return $id;
  764: }
  765: 
  766: sub get_locks {
  767:     my $num=0;
  768:     my %texts=();
  769:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  770:        if ($lock=~/\w/) {
  771:           $num++;
  772:           $texts{$lock}=$env{'session.lock.'.$lock};
  773:        }
  774:    }
  775:    return ($num,%texts);
  776: }
  777: 
  778: sub remove_lock {
  779:     my ($id)=@_;
  780:     my $newlocks='';
  781:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  782:        if (($lock=~/\w/) && ($lock ne $id)) {
  783:           $newlocks.=','.$lock;
  784:        }
  785:     }
  786:     &appenv({'session.locks' => $newlocks});
  787:     &delenv('session.lock.'.$id);
  788: }
  789: 
  790: sub remove_all_locks {
  791:     my $activelocks=$env{'session.locks'};
  792:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  793:        if ($lock=~/\w/) {
  794:           &remove_lock($lock);
  795:        }
  796:     }
  797: }
  798: 
  799: 
  800: # ------------------------------------------ Find out current server userload
  801: sub userload {
  802:     my $numusers=0;
  803:     {
  804: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  805: 	my $filename;
  806: 	my $curtime=time;
  807: 	while ($filename=readdir(LONIDS)) {
  808: 	    next if ($filename eq '.' || $filename eq '..');
  809: 	    next if ($filename =~ /publicuser_\d+\.id/);
  810: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  811: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  812: 	}
  813: 	closedir(LONIDS);
  814:     }
  815:     my $userloadpercent=0;
  816:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  817:     if ($maxuserload) {
  818: 	$userloadpercent=100*$numusers/$maxuserload;
  819:     }
  820:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  821:     return $userloadpercent;
  822: }
  823: 
  824: # ------------------------------ Find server with least workload from spare.tab
  825: 
  826: sub spareserver {
  827:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
  828:     my $spare_server;
  829:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  830:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
  831:                                                      :  $userloadpercent;
  832:     my ($uint_dom,$remotesessions);
  833:     if (($udom ne '') && (&domain($udom) ne '')) {
  834:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
  835:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
  836:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
  837:         $remotesessions = $udomdefaults{'remotesessions'};
  838:     }
  839:     my $spareshash = &this_host_spares($udom);
  840:     if (ref($spareshash) eq 'HASH') {
  841:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
  842:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
  843:                 if ($uint_dom) {
  844:                     next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
  845:                                                  $try_server));
  846:                 }
  847: 	        ($spare_server, $lowest_load) =
  848: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
  849:             }
  850:         }
  851: 
  852:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
  853: 
  854:         if (!$found_server) {
  855:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
  856: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
  857:                     if ($uint_dom) {
  858:                         next unless (&spare_can_host($udom,$uint_dom,
  859:                                                      $remotesessions,$try_server));
  860:                     }
  861: 	            ($spare_server, $lowest_load) =
  862: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
  863:                 }
  864: 	    }
  865:         }
  866:     }
  867: 
  868:     if (!$want_server_name) {
  869:         my $protocol = 'http';
  870:         if ($protocol{$spare_server} eq 'https') {
  871:             $protocol = $protocol{$spare_server};
  872:         }
  873:         if (defined($spare_server)) {
  874:             my $hostname = &hostname($spare_server);
  875:             if (defined($hostname)) {
  876: 	        $spare_server = $protocol.'://'.$hostname;
  877:             }
  878:         }
  879:     }
  880:     return $spare_server;
  881: }
  882: 
  883: sub compare_server_load {
  884:     my ($try_server, $spare_server, $lowest_load) = @_;
  885: 
  886:     my $loadans     = &reply('load',    $try_server);
  887:     my $userloadans = &reply('userload',$try_server);
  888: 
  889:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
  890: 	return ($spare_server, $lowest_load); #didn't get a number from the server
  891:     }
  892: 
  893:     my $load;
  894:     if ($loadans =~ /\d/) {
  895: 	if ($userloadans =~ /\d/) {
  896: 	    #both are numbers, pick the bigger one
  897: 	    $load = ($loadans > $userloadans) ? $loadans 
  898: 		                              : $userloadans;
  899: 	} else {
  900: 	    $load = $loadans;
  901: 	}
  902:     } else {
  903: 	$load = $userloadans;
  904:     }
  905: 
  906:     if (($load =~ /\d/) && ($load < $lowest_load)) {
  907: 	$spare_server = $try_server;
  908: 	$lowest_load  = $load;
  909:     }
  910:     return ($spare_server,$lowest_load);
  911: }
  912: 
  913: # --------------------------- ask offload servers if user already has a session
  914: sub find_existing_session {
  915:     my ($udom,$uname) = @_;
  916:     my $spareshash = &this_host_spares($udom);
  917:     if (ref($spareshash) eq 'HASH') {
  918:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
  919:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
  920:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
  921:             }
  922:         }
  923:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
  924:             foreach my $try_server (@{ $spareshash->{'default'} }) {
  925:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
  926:             }
  927:         }
  928:     }
  929:     return;
  930: }
  931: 
  932: # -------------------------------- ask if server already has a session for user
  933: sub has_user_session {
  934:     my ($lonid,$udom,$uname) = @_;
  935:     my $result = &reply(join(':','userhassession',
  936: 			     map {&escape($_)} ($udom,$uname)),$lonid);
  937:     return 1 if ($result eq 'ok');
  938: 
  939:     return 0;
  940: }
  941: 
  942: # --------- determine least loaded server in a user's domain which allows login
  943: 
  944: sub choose_server {
  945:     my ($udom,$checkloginvia) = @_;
  946:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
  947:     my %servers = &get_servers($udom);
  948:     my $lowest_load = 30000;
  949:     my ($login_host,$hostname,$portal_path,$isredirect);
  950:     foreach my $lonhost (keys(%servers)) {
  951:         my $loginvia;
  952:         if ($checkloginvia) {
  953:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
  954:             if ($loginvia) {
  955:                 my ($server,$path) = split(/:/,$loginvia);
  956:                 ($login_host, $lowest_load) =
  957:                     &compare_server_load($server, $login_host, $lowest_load);
  958:                 if ($login_host eq $server) {
  959:                     $portal_path = $path;
  960:                     $isredirect = 1;
  961:                 }
  962:             } else {
  963:                 ($login_host, $lowest_load) =
  964:                     &compare_server_load($lonhost, $login_host, $lowest_load);
  965:                 if ($login_host eq $lonhost) {
  966:                     $portal_path = '';
  967:                     $isredirect = ''; 
  968:                 }
  969:             }
  970:         } else {
  971:             ($login_host, $lowest_load) =
  972:                 &compare_server_load($lonhost, $login_host, $lowest_load);
  973:         }
  974:     }
  975:     if ($login_host ne '') {
  976:         $hostname = &hostname($login_host);
  977:     }
  978:     return ($login_host,$hostname,$portal_path,$isredirect);
  979: }
  980: 
  981: # --------------------------------------------- Try to change a user's password
  982: 
  983: sub changepass {
  984:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
  985:     $currentpass = &escape($currentpass);
  986:     $newpass     = &escape($newpass);
  987:     my $lonhost = $perlvar{'lonHostID'};
  988:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
  989: 		       $server);
  990:     if (! $answer) {
  991: 	&logthis("No reply on password change request to $server ".
  992: 		 "by $uname in domain $udom.");
  993:     } elsif ($answer =~ "^ok") {
  994:         &logthis("$uname in $udom successfully changed their password ".
  995: 		 "on $server.");
  996:     } elsif ($answer =~ "^pwchange_failure") {
  997: 	&logthis("$uname in $udom was unable to change their password ".
  998: 		 "on $server.  The action was blocked by either lcpasswd ".
  999: 		 "or pwchange");
 1000:     } elsif ($answer =~ "^non_authorized") {
 1001:         &logthis("$uname in $udom did not get their password correct when ".
 1002: 		 "attempting to change it on $server.");
 1003:     } elsif ($answer =~ "^auth_mode_error") {
 1004:         &logthis("$uname in $udom attempted to change their password despite ".
 1005: 		 "not being locally or internally authenticated on $server.");
 1006:     } elsif ($answer =~ "^unknown_user") {
 1007:         &logthis("$uname in $udom attempted to change their password ".
 1008: 		 "on $server but were unable to because $server is not ".
 1009: 		 "their home server.");
 1010:     } elsif ($answer =~ "^refused") {
 1011: 	&logthis("$server refused to change $uname in $udom password because ".
 1012: 		 "it was sent an unencrypted request to change the password.");
 1013:     } elsif ($answer =~ "invalid_client") {
 1014:         &logthis("$server refused to change $uname in $udom password because ".
 1015:                  "it was a reset by e-mail originating from an invalid server.");
 1016:     }
 1017:     return $answer;
 1018: }
 1019: 
 1020: # ----------------------- Try to determine user's current authentication scheme
 1021: 
 1022: sub queryauthenticate {
 1023:     my ($uname,$udom)=@_;
 1024:     my $uhome=&homeserver($uname,$udom);
 1025:     if (!$uhome) {
 1026: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
 1027: 	return 'no_host';
 1028:     }
 1029:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
 1030:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
 1031: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1032:     }
 1033:     return $answer;
 1034: }
 1035: 
 1036: # --------- Try to authenticate user from domain's lib servers (first this one)
 1037: 
 1038: sub authenticate {
 1039:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
 1040:     $upass=&escape($upass);
 1041:     $uname= &LONCAPA::clean_username($uname);
 1042:     my $uhome=&homeserver($uname,$udom,1);
 1043:     my $newhome;
 1044:     if ((!$uhome) || ($uhome eq 'no_host')) {
 1045: # Maybe the machine was offline and only re-appeared again recently?
 1046:         &reconlonc();
 1047: # One more
 1048: 	$uhome=&homeserver($uname,$udom,1);
 1049:         if (($uhome eq 'no_host') && $checkdefauth) {
 1050:             if (defined(&domain($udom,'primary'))) {
 1051:                 $newhome=&domain($udom,'primary');
 1052:             }
 1053:             if ($newhome ne '') {
 1054:                 $uhome = $newhome;
 1055:             }
 1056:         }
 1057: 	if ((!$uhome) || ($uhome eq 'no_host')) {
 1058: 	    &logthis("User $uname at $udom is unknown in authenticate");
 1059: 	    return 'no_host';
 1060:         }
 1061:     }
 1062:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
 1063:     if ($answer eq 'authorized') {
 1064:         if ($newhome) {
 1065:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
 1066:             return 'no_account_on_host'; 
 1067:         } else {
 1068:             &logthis("User $uname at $udom authorized by $uhome");
 1069:             return $uhome;
 1070:         }
 1071:     }
 1072:     if ($answer eq 'non_authorized') {
 1073: 	&logthis("User $uname at $udom rejected by $uhome");
 1074: 	return 'no_host'; 
 1075:     }
 1076:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1077:     return 'no_host';
 1078: }
 1079: 
 1080: sub can_host_session {
 1081:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
 1082:     my $canhost = 1;
 1083:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
 1084:     if (ref($remotesessions) eq 'HASH') {
 1085:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
 1086:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
 1087:                 $canhost = 0;
 1088:             } else {
 1089:                 $canhost = 1;
 1090:             }
 1091:         }
 1092:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
 1093:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
 1094:                 $canhost = 1;
 1095:             } else {
 1096:                 $canhost = 0;
 1097:             }
 1098:         }
 1099:         if ($canhost) {
 1100:             if ($remotesessions->{'version'} ne '') {
 1101:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
 1102:                 if ($reqmajor ne '' && $reqminor ne '') {
 1103:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
 1104:                         my $major = $1;
 1105:                         my $minor = $2;
 1106:                         if (($major < $reqmajor ) ||
 1107:                             (($major == $reqmajor) && ($minor < $reqminor))) {
 1108:                             $canhost = 0;
 1109:                         }
 1110:                     } else {
 1111:                         $canhost = 0;
 1112:                     }
 1113:                 }
 1114:             }
 1115:         }
 1116:     }
 1117:     if ($canhost) {
 1118:         if (ref($hostedsessions) eq 'HASH') {
 1119:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1120:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
 1121:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
 1122:                 if (($uint_dom ne '') && 
 1123:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
 1124:                     $canhost = 0;
 1125:                 } else {
 1126:                     $canhost = 1;
 1127:                 }
 1128:             }
 1129:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
 1130:                 if (($uint_dom ne '') && 
 1131:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
 1132:                     $canhost = 1;
 1133:                 } else {
 1134:                     $canhost = 0;
 1135:                 }
 1136:             }
 1137:         }
 1138:     }
 1139:     return $canhost;
 1140: }
 1141: 
 1142: sub spare_can_host {
 1143:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
 1144:     my $canhost=1;
 1145:     my @intdoms;
 1146:     my $internet_names = &Apache::lonnet::get_internet_names($try_server);
 1147:     if (ref($internet_names) eq 'ARRAY') {
 1148:         @intdoms = @{$internet_names};
 1149:     }
 1150:     unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
 1151:         my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
 1152:         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
 1153:         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
 1154:         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
 1155:         $canhost = &can_host_session($udom,$try_server,$remoterev,
 1156:                                      $remotesessions,
 1157:                                      $defdomdefaults{'hostedsessions'});
 1158:     }
 1159:     return $canhost;
 1160: }
 1161: 
 1162: sub this_host_spares {
 1163:     my ($dom) = @_;
 1164:     my ($dom_in_use,$lonhost_in_use,$result);
 1165:     my @hosts = &current_machine_ids();
 1166:     foreach my $lonhost (@hosts) {
 1167:         if (&host_domain($lonhost) eq $dom) {
 1168:             $dom_in_use = $dom;
 1169:             $lonhost_in_use = $lonhost;
 1170:             last;
 1171:         }
 1172:     }
 1173:     if ($dom_in_use ne '') {
 1174:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1175:     }
 1176:     if (ref($result) ne 'HASH') {
 1177:         $lonhost_in_use = $perlvar{'lonHostID'};
 1178:         $dom_in_use = &host_domain($lonhost_in_use);
 1179:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1180:         if (ref($result) ne 'HASH') {
 1181:             $result = \%spareid;
 1182:         }
 1183:     }
 1184:     return $result;
 1185: }
 1186: 
 1187: sub spares_for_offload  {
 1188:     my ($dom_in_use,$lonhost_in_use) = @_;
 1189:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
 1190:     if (defined($cached)) {
 1191:         return $result;
 1192:     } else {
 1193:         my $cachetime = 60*60*24;
 1194:         my %domconfig =
 1195:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
 1196:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
 1197:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
 1198:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
 1199:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
 1200:                 }
 1201:             }
 1202:         }
 1203:     }
 1204:     return;
 1205: }
 1206: 
 1207: sub get_lonbalancer_config {
 1208:     my ($servers) = @_;
 1209:     my ($currbalancer,$currtargets);
 1210:     if (ref($servers) eq 'HASH') {
 1211:         foreach my $server (keys(%{$servers})) {
 1212:             my %what = (
 1213:                          spareid => 1,
 1214:                          perlvar => 1,
 1215:                        );
 1216:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
 1217:             if ($result eq 'ok') {
 1218:                 if (ref($returnhash) eq 'HASH') {
 1219:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
 1220:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
 1221:                             $currbalancer = $server;
 1222:                             $currtargets = {};
 1223:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
 1224:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
 1225:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
 1226:                                 }
 1227:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
 1228:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
 1229:                                 }
 1230:                             }
 1231:                             last;
 1232:                         }
 1233:                     }
 1234:                 }
 1235:             }
 1236:         }
 1237:     }
 1238:     return ($currbalancer,$currtargets);
 1239: }
 1240: 
 1241: sub check_loadbalancing {
 1242:     my ($uname,$udom) = @_;
 1243:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
 1244:         $rule_in_effect,$offloadto,$otherserver);
 1245:     my $lonhost = $perlvar{'lonHostID'};
 1246:     my @hosts = &current_machine_ids();
 1247:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1248:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
 1249:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
 1250:     my $serverhomedom = &host_domain($lonhost);
 1251: 
 1252:     my $cachetime = 60*60*24;
 1253: 
 1254:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1255:         $dom_in_use = $udom;
 1256:         $homeintdom = 1;
 1257:     } else {
 1258:         $dom_in_use = $serverhomedom;
 1259:     }
 1260:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
 1261:     unless (defined($cached)) {
 1262:         my %domconfig =
 1263:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
 1264:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1265:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1266:         }
 1267:     }
 1268:     if (ref($result) eq 'HASH') {
 1269:         ($is_balancer,$currtargets,$currrules) = 
 1270:             &check_balancer_result($result,@hosts);
 1271:         if ($is_balancer) {
 1272:             if (ref($currrules) eq 'HASH') {
 1273:                 if ($homeintdom) {
 1274:                     if ($uname ne '') {
 1275:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
 1276:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
 1277:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
 1278:                                 $rule_in_effect = $currrules->{'_LC_author'};
 1279:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
 1280:                                 $rule_in_effect = $currrules->{'_LC_adv'}
 1281:                             }
 1282:                         }
 1283:                         if ($rule_in_effect eq '') {
 1284:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
 1285:                             if ($userenv{'inststatus'} ne '') {
 1286:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
 1287:                                 my ($othertitle,$usertypes,$types) =
 1288:                                     &Apache::loncommon::sorted_inst_types($udom);
 1289:                                 if (ref($types) eq 'ARRAY') {
 1290:                                     foreach my $type (@{$types}) {
 1291:                                         if (grep(/^\Q$type\E$/,@statuses)) {
 1292:                                             if (exists($currrules->{$type})) {
 1293:                                                 $rule_in_effect = $currrules->{$type};
 1294:                                             }
 1295:                                         }
 1296:                                     }
 1297:                                 }
 1298:                             } else {
 1299:                                 if (exists($currrules->{'default'})) {
 1300:                                     $rule_in_effect = $currrules->{'default'};
 1301:                                 }
 1302:                             }
 1303:                         }
 1304:                     } else {
 1305:                         if (exists($currrules->{'default'})) {
 1306:                             $rule_in_effect = $currrules->{'default'};
 1307:                         }
 1308:                     }
 1309:                 } else {
 1310:                     if ($currrules->{'_LC_external'} ne '') {
 1311:                         $rule_in_effect = $currrules->{'_LC_external'};
 1312:                     }
 1313:                 }
 1314:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1315:                                                        $uname,$udom);
 1316:             }
 1317:         }
 1318:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
 1319:         my ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
 1320:         unless (defined($cached)) {
 1321:             my %domconfig =
 1322:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
 1323:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1324:                 $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1325:             }
 1326:         }
 1327:         if (ref($result) eq 'HASH') {
 1328:             ($is_balancer,$currtargets,$currrules) = 
 1329:                 &check_balancer_result($result,@hosts);
 1330:             if ($is_balancer) {
 1331:                 if (ref($currrules) eq 'HASH') {
 1332:                     if ($currrules->{'_LC_internetdom'} ne '') {
 1333:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
 1334:                     }
 1335:                 }
 1336:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1337:                                                        $uname,$udom);
 1338:             }
 1339:         } else {
 1340:             if ($perlvar{'lonBalancer'} eq 'yes') {
 1341:                 $is_balancer = 1;
 1342:                 $offloadto = &this_host_spares($dom_in_use);
 1343:             }
 1344:         }
 1345:     } else {
 1346:         if ($perlvar{'lonBalancer'} eq 'yes') {
 1347:             $is_balancer = 1;
 1348:             $offloadto = &this_host_spares($dom_in_use);
 1349:         }
 1350:     }
 1351:     if ($is_balancer) {
 1352:         my $lowest_load = 30000;
 1353:         if (ref($offloadto) eq 'HASH') {
 1354:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
 1355:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
 1356:                     ($otherserver,$lowest_load) =
 1357:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1358:                 }
 1359:             }
 1360:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
 1361: 
 1362:             if (!$found_server) {
 1363:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
 1364:                     foreach my $try_server (@{$offloadto->{'default'}}) {
 1365:                         ($otherserver,$lowest_load) =
 1366:                             &compare_server_load($try_server,$otherserver,$lowest_load);
 1367:                     }
 1368:                 }
 1369:             }
 1370:         } elsif (ref($offloadto) eq 'ARRAY') {
 1371:             if (@{$offloadto} == 1) {
 1372:                 $otherserver = $offloadto->[0];
 1373:             } elsif (@{$offloadto} > 1) {
 1374:                 foreach my $try_server (@{$offloadto}) {
 1375:                     ($otherserver,$lowest_load) =
 1376:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1377:                 }
 1378:             }
 1379:         }
 1380:         if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
 1381:             $is_balancer = 0;
 1382:             if ($uname ne '' && $udom ne '') {
 1383:                 if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
 1384:                     
 1385:                     &appenv({'user.loadbalexempt'     => $lonhost,  
 1386:                              'user.loadbalcheck.time' => time});
 1387:                 }
 1388:             }
 1389:         }
 1390:     }
 1391:     return ($is_balancer,$otherserver);
 1392: }
 1393: 
 1394: sub check_balancer_result {
 1395:     my ($result,@hosts) = @_;
 1396:     my ($is_balancer,$currtargets,$currrules);
 1397:     if (ref($result) eq 'HASH') {
 1398:         if ($result->{'lonhost'} ne '') {
 1399:             my $currbalancer = $result->{'lonhost'};
 1400:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
 1401:                 $is_balancer = 1;
 1402:                 $currtargets = $result->{'targets'};
 1403:                 $currrules = $result->{'rules'};
 1404:             }
 1405:         } else {
 1406:             foreach my $key (keys(%{$result})) {
 1407:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
 1408:                     (ref($result->{$key}) eq 'HASH')) {
 1409:                     $is_balancer = 1;
 1410:                     $currrules = $result->{$key}{'rules'};
 1411:                     $currtargets = $result->{$key}{'targets'};
 1412:                     last;
 1413:                 }
 1414:             }
 1415:         }
 1416:     }
 1417:     return ($is_balancer,$currtargets,$currrules);
 1418: }
 1419: 
 1420: sub get_loadbalancer_targets {
 1421:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
 1422:     my $offloadto;
 1423:     if ($rule_in_effect eq 'none') {
 1424:         return [$perlvar{'lonHostID'}];
 1425:     } elsif ($rule_in_effect eq '') {
 1426:         $offloadto = $currtargets;
 1427:     } else {
 1428:         if ($rule_in_effect eq 'homeserver') {
 1429:             my $homeserver = &homeserver($uname,$udom);
 1430:             if ($homeserver ne 'no_host') {
 1431:                 $offloadto = [$homeserver];
 1432:             }
 1433:         } elsif ($rule_in_effect eq 'externalbalancer') {
 1434:             my %domconfig =
 1435:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
 1436:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1437:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
 1438:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
 1439:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
 1440:                     }
 1441:                 }
 1442:             } else {
 1443:                 my %servers = &internet_dom_servers($udom);
 1444:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
 1445:                 if (&hostname($remotebalancer) ne '') {
 1446:                     $offloadto = [$remotebalancer];
 1447:                 }
 1448:             }
 1449:         } elsif (&hostname($rule_in_effect) ne '') {
 1450:             $offloadto = [$rule_in_effect];
 1451:         }
 1452:     }
 1453:     return $offloadto;
 1454: }
 1455: 
 1456: sub internet_dom_servers {
 1457:     my ($dom) = @_;
 1458:     my (%uniqservers,%servers);
 1459:     my $primaryserver = &hostname(&domain($dom,'primary'));
 1460:     my @machinedoms = &machine_domains($primaryserver);
 1461:     foreach my $mdom (@machinedoms) {
 1462:         my %currservers = %servers;
 1463:         my %server = &get_servers($mdom);
 1464:         %servers = (%currservers,%server);
 1465:     }
 1466:     my %by_hostname;
 1467:     foreach my $id (keys(%servers)) {
 1468:         push(@{$by_hostname{$servers{$id}}},$id);
 1469:     }
 1470:     foreach my $hostname (sort(keys(%by_hostname))) {
 1471:         if (@{$by_hostname{$hostname}} > 1) {
 1472:             my $match = 0;
 1473:             foreach my $id (@{$by_hostname{$hostname}}) {
 1474:                 if (&host_domain($id) eq $dom) {
 1475:                     $uniqservers{$id} = $hostname;
 1476:                     $match = 1;
 1477:                 }
 1478:             }
 1479:             unless ($match) {
 1480:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1481:             }
 1482:         } else {
 1483:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1484:         }
 1485:     }
 1486:     return %uniqservers;
 1487: }
 1488: 
 1489: # ---------------------- Find the homebase for a user from domain's lib servers
 1490: 
 1491: my %homecache;
 1492: sub homeserver {
 1493:     my ($uname,$udom,$ignoreBadCache)=@_;
 1494:     my $index="$uname:$udom";
 1495: 
 1496:     if (exists($homecache{$index})) { return $homecache{$index}; }
 1497: 
 1498:     my %servers = &get_servers($udom,'library');
 1499:     foreach my $tryserver (keys(%servers)) {
 1500:         next if ($ignoreBadCache ne 'true' && 
 1501: 		 exists($badServerCache{$tryserver}));
 1502: 
 1503: 	my $answer=reply("home:$udom:$uname",$tryserver);
 1504: 	if ($answer eq 'found') {
 1505: 	    delete($badServerCache{$tryserver}); 
 1506: 	    return $homecache{$index}=$tryserver;
 1507: 	} elsif ($answer eq 'no_host') {
 1508: 	    $badServerCache{$tryserver}=1;
 1509: 	}
 1510:     }    
 1511:     return 'no_host';
 1512: }
 1513: 
 1514: # ------------------------------------- Find the usernames behind a list of IDs
 1515: 
 1516: sub idget {
 1517:     my ($udom,@ids)=@_;
 1518:     my %returnhash=();
 1519:     
 1520:     my %servers = &get_servers($udom,'library');
 1521:     foreach my $tryserver (keys(%servers)) {
 1522: 	my $idlist=join('&',@ids);
 1523: 	$idlist=~tr/A-Z/a-z/; 
 1524: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
 1525: 	my @answer=();
 1526: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
 1527: 	    @answer=split(/\&/,$reply);
 1528: 	}                    ;
 1529: 	my $i;
 1530: 	for ($i=0;$i<=$#ids;$i++) {
 1531: 	    if ($answer[$i]) {
 1532: 		$returnhash{$ids[$i]}=$answer[$i];
 1533: 	    } 
 1534: 	}
 1535:     } 
 1536:     return %returnhash;
 1537: }
 1538: 
 1539: # ------------------------------------- Find the IDs behind a list of usernames
 1540: 
 1541: sub idrget {
 1542:     my ($udom,@unames)=@_;
 1543:     my %returnhash=();
 1544:     foreach my $uname (@unames) {
 1545:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
 1546:     }
 1547:     return %returnhash;
 1548: }
 1549: 
 1550: # ------------------------------- Store away a list of names and associated IDs
 1551: 
 1552: sub idput {
 1553:     my ($udom,%ids)=@_;
 1554:     my %servers=();
 1555:     foreach my $uname (keys(%ids)) {
 1556: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
 1557:         my $uhom=&homeserver($uname,$udom);
 1558:         if ($uhom ne 'no_host') {
 1559:             my $id=&escape($ids{$uname});
 1560:             $id=~tr/A-Z/a-z/;
 1561:             my $esc_unam=&escape($uname);
 1562: 	    if ($servers{$uhom}) {
 1563: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
 1564:             } else {
 1565:                 $servers{$uhom}=$id.'='.$esc_unam;
 1566:             }
 1567:         }
 1568:     }
 1569:     foreach my $server (keys(%servers)) {
 1570:         &critical('idput:'.$udom.':'.$servers{$server},$server);
 1571:     }
 1572: }
 1573: 
 1574: # ------------------------------dump from db file owned by domainconfig user
 1575: sub dump_dom {
 1576:     my ($namespace, $udom, $regexp) = @_;
 1577: 
 1578:     $udom ||= $env{'user.domain'};
 1579: 
 1580:     return () unless $udom;
 1581: 
 1582:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
 1583: }
 1584: 
 1585: # ------------------------------------------ get items from domain db files   
 1586: 
 1587: sub get_dom {
 1588:     my ($namespace,$storearr,$udom,$uhome)=@_;
 1589:     my $items='';
 1590:     foreach my $item (@$storearr) {
 1591:         $items.=&escape($item).'&';
 1592:     }
 1593:     $items=~s/\&$//;
 1594:     if (!$udom) {
 1595:         $udom=$env{'user.domain'};
 1596:         if (defined(&domain($udom,'primary'))) {
 1597:             $uhome=&domain($udom,'primary');
 1598:         } else {
 1599:             undef($uhome);
 1600:         }
 1601:     } else {
 1602:         if (!$uhome) {
 1603:             if (defined(&domain($udom,'primary'))) {
 1604:                 $uhome=&domain($udom,'primary');
 1605:             }
 1606:         }
 1607:     }
 1608:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1609:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
 1610:         my %returnhash;
 1611:         if ($rep eq '' || $rep =~ /^error: 2 /) {
 1612:             return %returnhash;
 1613:         }
 1614:         my @pairs=split(/\&/,$rep);
 1615:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 1616:             return @pairs;
 1617:         }
 1618:         my $i=0;
 1619:         foreach my $item (@$storearr) {
 1620:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
 1621:             $i++;
 1622:         }
 1623:         return %returnhash;
 1624:     } else {
 1625:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
 1626:     }
 1627: }
 1628: 
 1629: # -------------------------------------------- put items in domain db files 
 1630: 
 1631: sub put_dom {
 1632:     my ($namespace,$storehash,$udom,$uhome)=@_;
 1633:     if (!$udom) {
 1634:         $udom=$env{'user.domain'};
 1635:         if (defined(&domain($udom,'primary'))) {
 1636:             $uhome=&domain($udom,'primary');
 1637:         } else {
 1638:             undef($uhome);
 1639:         }
 1640:     } else {
 1641:         if (!$uhome) {
 1642:             if (defined(&domain($udom,'primary'))) {
 1643:                 $uhome=&domain($udom,'primary');
 1644:             }
 1645:         }
 1646:     } 
 1647:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1648:         my $items='';
 1649:         foreach my $item (keys(%$storehash)) {
 1650:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 1651:         }
 1652:         $items=~s/\&$//;
 1653:         return &reply("putdom:$udom:$namespace:$items",$uhome);
 1654:     } else {
 1655:         &logthis("put_dom failed - no homeserver and/or domain");
 1656:     }
 1657: }
 1658: 
 1659: # --------------------- newput for items in db file owned by domainconfig user
 1660: sub newput_dom {
 1661:     my ($namespace,$storehash,$udom) = @_;
 1662:     my $result;
 1663:     if (!$udom) {
 1664:         $udom=$env{'user.domain'};
 1665:     }
 1666:     if ($udom) {
 1667:         my $uname = &get_domainconfiguser($udom);
 1668:         $result = &newput($namespace,$storehash,$udom,$uname);
 1669:     }
 1670:     return $result;
 1671: }
 1672: 
 1673: # --------------------- delete for items in db file owned by domainconfig user
 1674: sub del_dom {
 1675:     my ($namespace,$storearr,$udom)=@_;
 1676:     if (ref($storearr) eq 'ARRAY') {
 1677:         if (!$udom) {
 1678:             $udom=$env{'user.domain'};
 1679:         }
 1680:         if ($udom) {
 1681:             my $uname = &get_domainconfiguser($udom); 
 1682:             return &del($namespace,$storearr,$udom,$uname);
 1683:         }
 1684:     }
 1685: }
 1686: 
 1687: # ----------------------------------construct domainconfig user for a domain 
 1688: sub get_domainconfiguser {
 1689:     my ($udom) = @_;
 1690:     return $udom.'-domainconfig';
 1691: }
 1692: 
 1693: sub retrieve_inst_usertypes {
 1694:     my ($udom) = @_;
 1695:     my (%returnhash,@order);
 1696:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 1697:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
 1698:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
 1699:         %returnhash = %{$domdefs{'inststatustypes'}};
 1700:         @order = @{$domdefs{'inststatusorder'}};
 1701:     } else {
 1702:         if (defined(&domain($udom,'primary'))) {
 1703:             my $uhome=&domain($udom,'primary');
 1704:             my $rep=&reply("inst_usertypes:$udom",$uhome);
 1705:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
 1706:                 &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
 1707:                 return (\%returnhash,\@order);
 1708:             }
 1709:             my ($hashitems,$orderitems) = split(/:/,$rep); 
 1710:             my @pairs=split(/\&/,$hashitems);
 1711:             foreach my $item (@pairs) {
 1712:                 my ($key,$value)=split(/=/,$item,2);
 1713:                 $key = &unescape($key);
 1714:                 next if ($key =~ /^error: 2 /);
 1715:                 $returnhash{$key}=&thaw_unescape($value);
 1716:             }
 1717:             my @esc_order = split(/\&/,$orderitems);
 1718:             foreach my $item (@esc_order) {
 1719:                 push(@order,&unescape($item));
 1720:             }
 1721:         } else {
 1722:             &logthis("get_dom failed - no primary domain server for $udom");
 1723:         }
 1724:     }
 1725:     return (\%returnhash,\@order);
 1726: }
 1727: 
 1728: sub is_domainimage {
 1729:     my ($url) = @_;
 1730:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
 1731:         if (&domain($1) ne '') {
 1732:             return '1';
 1733:         }
 1734:     }
 1735:     return;
 1736: }
 1737: 
 1738: sub inst_directory_query {
 1739:     my ($srch) = @_;
 1740:     my $udom = $srch->{'srchdomain'};
 1741:     my %results;
 1742:     my $homeserver = &domain($udom,'primary');
 1743:     my $outcome;
 1744:     if ($homeserver ne '') {
 1745: 	my $queryid=&reply("querysend:instdirsearch:".
 1746: 			   &escape($srch->{'srchby'}).':'.
 1747: 			   &escape($srch->{'srchterm'}).':'.
 1748: 			   &escape($srch->{'srchtype'}),$homeserver);
 1749: 	my $host=&hostname($homeserver);
 1750: 	if ($queryid !~/^\Q$host\E\_/) {
 1751: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1752: 	    return;
 1753: 	}
 1754: 	my $response = &get_query_reply($queryid);
 1755: 	my $maxtries = 5;
 1756: 	my $tries = 1;
 1757: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1758: 	    $response = &get_query_reply($queryid);
 1759: 	    $tries ++;
 1760: 	}
 1761: 
 1762:         if (!&error($response) && $response ne 'refused') {
 1763:             if ($response eq 'unavailable') {
 1764:                 $outcome = $response;
 1765:             } else {
 1766:                 $outcome = 'ok';
 1767:                 my @matches = split(/\n/,$response);
 1768:                 foreach my $match (@matches) {
 1769:                     my ($key,$value) = split(/=/,$match);
 1770:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 1771:                 }
 1772:             }
 1773:         }
 1774:     }
 1775:     return ($outcome,%results);
 1776: }
 1777: 
 1778: sub usersearch {
 1779:     my ($srch) = @_;
 1780:     my $dom = $srch->{'srchdomain'};
 1781:     my %results;
 1782:     my %libserv = &all_library();
 1783:     my $query = 'usersearch';
 1784:     foreach my $tryserver (keys(%libserv)) {
 1785:         if (&host_domain($tryserver) eq $dom) {
 1786:             my $host=&hostname($tryserver);
 1787:             my $queryid=
 1788:                 &reply("querysend:".&escape($query).':'.
 1789:                        &escape($srch->{'srchby'}).':'.
 1790:                        &escape($srch->{'srchtype'}).':'.
 1791:                        &escape($srch->{'srchterm'}),$tryserver);
 1792:             if ($queryid !~/^\Q$host\E\_/) {
 1793:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 1794:                 next;
 1795:             }
 1796:             my $reply = &get_query_reply($queryid);
 1797:             my $maxtries = 1;
 1798:             my $tries = 1;
 1799:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 1800:                 $reply = &get_query_reply($queryid);
 1801:                 $tries ++;
 1802:             }
 1803:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 1804:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 1805:             } else {
 1806:                 my @matches;
 1807:                 if ($reply =~ /\n/) {
 1808:                     @matches = split(/\n/,$reply);
 1809:                 } else {
 1810:                     @matches = split(/\&/,$reply);
 1811:                 }
 1812:                 foreach my $match (@matches) {
 1813:                     my ($uname,$udom,%userhash);
 1814:                     foreach my $entry (split(/:/,$match)) {
 1815:                         my ($key,$value) =
 1816:                             map {&unescape($_);} split(/=/,$entry);
 1817:                         $userhash{$key} = $value;
 1818:                         if ($key eq 'username') {
 1819:                             $uname = $value;
 1820:                         } elsif ($key eq 'domain') {
 1821:                             $udom = $value;
 1822:                         }
 1823:                     }
 1824:                     $results{$uname.':'.$udom} = \%userhash;
 1825:                 }
 1826:             }
 1827:         }
 1828:     }
 1829:     return %results;
 1830: }
 1831: 
 1832: sub get_instuser {
 1833:     my ($udom,$uname,$id) = @_;
 1834:     my $homeserver = &domain($udom,'primary');
 1835:     my ($outcome,%results);
 1836:     if ($homeserver ne '') {
 1837:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 1838:                            &escape($id).':'.&escape($udom),$homeserver);
 1839:         my $host=&hostname($homeserver);
 1840:         if ($queryid !~/^\Q$host\E\_/) {
 1841:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1842:             return;
 1843:         }
 1844:         my $response = &get_query_reply($queryid);
 1845:         my $maxtries = 5;
 1846:         my $tries = 1;
 1847:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1848:             $response = &get_query_reply($queryid);
 1849:             $tries ++;
 1850:         }
 1851:         if (!&error($response) && $response ne 'refused') {
 1852:             if ($response eq 'unavailable') {
 1853:                 $outcome = $response;
 1854:             } else {
 1855:                 $outcome = 'ok';
 1856:                 my @matches = split(/\n/,$response);
 1857:                 foreach my $match (@matches) {
 1858:                     my ($key,$value) = split(/=/,$match);
 1859:                     $results{&unescape($key)} = &thaw_unescape($value);
 1860:                 }
 1861:             }
 1862:         }
 1863:     }
 1864:     my %userinfo;
 1865:     if (ref($results{$uname}) eq 'HASH') {
 1866:         %userinfo = %{$results{$uname}};
 1867:     } 
 1868:     return ($outcome,%userinfo);
 1869: }
 1870: 
 1871: sub inst_rulecheck {
 1872:     my ($udom,$uname,$id,$item,$rules) = @_;
 1873:     my %returnhash;
 1874:     if ($udom ne '') {
 1875:         if (ref($rules) eq 'ARRAY') {
 1876:             @{$rules} = map {&escape($_);} (@{$rules});
 1877:             my $rulestr = join(':',@{$rules});
 1878:             my $homeserver=&domain($udom,'primary');
 1879:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1880:                 my $response;
 1881:                 if ($item eq 'username') {                
 1882:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 1883:                                               ':'.&escape($uname).':'.$rulestr,
 1884:                                               $homeserver));
 1885:                 } elsif ($item eq 'id') {
 1886:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 1887:                                               ':'.&escape($id).':'.$rulestr,
 1888:                                               $homeserver));
 1889:                 } elsif ($item eq 'selfcreate') {
 1890:                     $response=&unescape(&reply('instselfcreatecheck:'.
 1891:                                                &escape($udom).':'.&escape($uname).
 1892:                                               ':'.$rulestr,$homeserver));
 1893:                 }
 1894:                 if ($response ne 'refused') {
 1895:                     my @pairs=split(/\&/,$response);
 1896:                     foreach my $item (@pairs) {
 1897:                         my ($key,$value)=split(/=/,$item,2);
 1898:                         $key = &unescape($key);
 1899:                         next if ($key =~ /^error: 2 /);
 1900:                         $returnhash{$key}=&thaw_unescape($value);
 1901:                     }
 1902:                 }
 1903:             }
 1904:         }
 1905:     }
 1906:     return %returnhash;
 1907: }
 1908: 
 1909: sub inst_userrules {
 1910:     my ($udom,$check) = @_;
 1911:     my (%ruleshash,@ruleorder);
 1912:     if ($udom ne '') {
 1913:         my $homeserver=&domain($udom,'primary');
 1914:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1915:             my $response;
 1916:             if ($check eq 'id') {
 1917:                 $response=&reply('instidrules:'.&escape($udom),
 1918:                                  $homeserver);
 1919:             } elsif ($check eq 'email') {
 1920:                 $response=&reply('instemailrules:'.&escape($udom),
 1921:                                  $homeserver);
 1922:             } else {
 1923:                 $response=&reply('instuserrules:'.&escape($udom),
 1924:                                  $homeserver);
 1925:             }
 1926:             if (($response ne 'refused') && ($response ne 'error') && 
 1927:                 ($response ne 'unknown_cmd') && 
 1928:                 ($response ne 'no_such_host')) {
 1929:                 my ($hashitems,$orderitems) = split(/:/,$response);
 1930:                 my @pairs=split(/\&/,$hashitems);
 1931:                 foreach my $item (@pairs) {
 1932:                     my ($key,$value)=split(/=/,$item,2);
 1933:                     $key = &unescape($key);
 1934:                     next if ($key =~ /^error: 2 /);
 1935:                     $ruleshash{$key}=&thaw_unescape($value);
 1936:                 }
 1937:                 my @esc_order = split(/\&/,$orderitems);
 1938:                 foreach my $item (@esc_order) {
 1939:                     push(@ruleorder,&unescape($item));
 1940:                 }
 1941:             }
 1942:         }
 1943:     }
 1944:     return (\%ruleshash,\@ruleorder);
 1945: }
 1946: 
 1947: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 1948: 
 1949: sub get_domain_defaults {
 1950:     my ($domain) = @_;
 1951:     my $cachetime = 60*60*24;
 1952:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 1953:     if (defined($cached)) {
 1954:         if (ref($result) eq 'HASH') {
 1955:             return %{$result};
 1956:         }
 1957:     }
 1958:     my %domdefaults;
 1959:     my %domconfig =
 1960:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
 1961:                                   'requestcourses','inststatus',
 1962:                                   'coursedefaults','usersessions',
 1963:                                   'requestauthor'],$domain);
 1964:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 1965:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 1966:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 1967:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 1968:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 1969:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
 1970:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
 1971:     } else {
 1972:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 1973:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 1974:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 1975:     }
 1976:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 1977:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 1978:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 1979:         } else {
 1980:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 1981:         } 
 1982:         my @usertools = ('aboutme','blog','webdav','portfolio');
 1983:         foreach my $item (@usertools) {
 1984:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 1985:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 1986:             }
 1987:         }
 1988:     }
 1989:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 1990:         foreach my $item ('official','unofficial','community') {
 1991:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
 1992:         }
 1993:     }
 1994:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
 1995:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
 1996:     }
 1997:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
 1998:         foreach my $item ('inststatustypes','inststatusorder') {
 1999:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
 2000:         }
 2001:     }
 2002:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
 2003:         foreach my $item ('canuse_pdfforms') {
 2004:             $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
 2005:         }
 2006:     }
 2007:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
 2008:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
 2009:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
 2010:         }
 2011:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
 2012:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
 2013:         }
 2014:     }
 2015:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
 2016:                                   $cachetime);
 2017:     return %domdefaults;
 2018: }
 2019: 
 2020: # --------------------------------------------------- Assign a key to a student
 2021: 
 2022: sub assign_access_key {
 2023: #
 2024: # a valid key looks like uname:udom#comments
 2025: # comments are being appended
 2026: #
 2027:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 2028:     $kdom=
 2029:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 2030:     $knum=
 2031:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 2032:     $cdom=
 2033:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2034:     $cnum=
 2035:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2036:     $udom=$env{'user.name'} unless (defined($udom));
 2037:     $uname=$env{'user.domain'} unless (defined($uname));
 2038:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 2039:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 2040:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 2041:                                                   # assigned to this person
 2042:                                                   # - this should not happen,
 2043:                                                   # unless something went wrong
 2044:                                                   # the first time around
 2045: # ready to assign
 2046:         $logentry=$1.'; '.$logentry;
 2047:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 2048:                                                  $kdom,$knum) eq 'ok') {
 2049: # key now belongs to user
 2050: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 2051:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 2052:                 &appenv({'environment.'.$envkey => $ckey});
 2053:                 return 'ok';
 2054:             } else {
 2055:                 return 
 2056:   'error: Count not permanently assign key, will need to be re-entered later.';
 2057: 	    }
 2058:         } else {
 2059:             return 'error: Could not assign key, try again later.';
 2060:         }
 2061:     } elsif (!$existing{$ckey}) {
 2062: # the key does not exist
 2063: 	return 'error: The key does not exist';
 2064:     } else {
 2065: # the key is somebody else's
 2066: 	return 'error: The key is already in use';
 2067:     }
 2068: }
 2069: 
 2070: # ------------------------------------------ put an additional comment on a key
 2071: 
 2072: sub comment_access_key {
 2073: #
 2074: # a valid key looks like uname:udom#comments
 2075: # comments are being appended
 2076: #
 2077:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 2078:     $cdom=
 2079:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2080:     $cnum=
 2081:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2082:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2083:     if ($existing{$ckey}) {
 2084:         $existing{$ckey}.='; '.$logentry;
 2085: # ready to assign
 2086:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 2087:                                                  $cdom,$cnum) eq 'ok') {
 2088: 	    return 'ok';
 2089:         } else {
 2090: 	    return 'error: Count not store comment.';
 2091:         }
 2092:     } else {
 2093: # the key does not exist
 2094: 	return 'error: The key does not exist';
 2095:     }
 2096: }
 2097: 
 2098: # ------------------------------------------------------ Generate a set of keys
 2099: 
 2100: sub generate_access_keys {
 2101:     my ($number,$cdom,$cnum,$logentry)=@_;
 2102:     $cdom=
 2103:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2104:     $cnum=
 2105:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2106:     unless (&allowed('mky',$cdom)) { return 0; }
 2107:     unless (($cdom) && ($cnum)) { return 0; }
 2108:     if ($number>10000) { return 0; }
 2109:     sleep(2); # make sure don't get same seed twice
 2110:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 2111:     my $total=0;
 2112:     for (my $i=1;$i<=$number;$i++) {
 2113:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 2114:                   sprintf("%lx",int(100000*rand)).'-'.
 2115:                   sprintf("%lx",int(100000*rand));
 2116:        $newkey=~s/1/g/g; # folks mix up 1 and l
 2117:        $newkey=~s/0/h/g; # and also 0 and O
 2118:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 2119:        if ($existing{$newkey}) {
 2120:            $i--;
 2121:        } else {
 2122: 	  if (&put('accesskeys',
 2123:               { $newkey => '# generated '.localtime().
 2124:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 2125:                            '; '.$logentry },
 2126: 		   $cdom,$cnum) eq 'ok') {
 2127:               $total++;
 2128: 	  }
 2129:        }
 2130:     }
 2131:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 2132:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 2133:     return $total;
 2134: }
 2135: 
 2136: # ------------------------------------------------------- Validate an accesskey
 2137: 
 2138: sub validate_access_key {
 2139:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 2140:     $cdom=
 2141:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2142:     $cnum=
 2143:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2144:     $udom=$env{'user.domain'} unless (defined($udom));
 2145:     $uname=$env{'user.name'} unless (defined($uname));
 2146:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2147:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 2148: }
 2149: 
 2150: # ------------------------------------- Find the section of student in a course
 2151: sub devalidate_getsection_cache {
 2152:     my ($udom,$unam,$courseid)=@_;
 2153:     my $hashid="$udom:$unam:$courseid";
 2154:     &devalidate_cache_new('getsection',$hashid);
 2155: }
 2156: 
 2157: sub courseid_to_courseurl {
 2158:     my ($courseid) = @_;
 2159:     #already url style courseid
 2160:     return $courseid if ($courseid =~ m{^/});
 2161: 
 2162:     if (exists($env{'course.'.$courseid.'.num'})) {
 2163: 	my $cnum = $env{'course.'.$courseid.'.num'};
 2164: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 2165: 	return "/$cdom/$cnum";
 2166:     }
 2167: 
 2168:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 2169:     if (exists($courseinfo{'num'})) {
 2170: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 2171:     }
 2172: 
 2173:     return undef;
 2174: }
 2175: 
 2176: sub getsection {
 2177:     my ($udom,$unam,$courseid)=@_;
 2178:     my $cachetime=1800;
 2179: 
 2180:     my $hashid="$udom:$unam:$courseid";
 2181:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 2182:     if (defined($cached)) { return $result; }
 2183: 
 2184:     my %Pending; 
 2185:     my %Expired;
 2186:     #
 2187:     # Each role can either have not started yet (pending), be active, 
 2188:     #    or have expired.
 2189:     #
 2190:     # If there is an active role, we are done.
 2191:     #
 2192:     # If there is more than one role which has not started yet, 
 2193:     #     choose the one which will start sooner
 2194:     # If there is one role which has not started yet, return it.
 2195:     #
 2196:     # If there is more than one expired role, choose the one which ended last.
 2197:     # If there is a role which has expired, return it.
 2198:     #
 2199:     $courseid = &courseid_to_courseurl($courseid);
 2200:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 2201:     foreach my $key (keys(%roleshash)) {
 2202:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 2203:         my $section=$1;
 2204:         if ($key eq $courseid.'_st') { $section=''; }
 2205:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 2206:         my $now=time;
 2207:         if (defined($end) && $end && ($now > $end)) {
 2208:             $Expired{$end}=$section;
 2209:             next;
 2210:         }
 2211:         if (defined($start) && $start && ($now < $start)) {
 2212:             $Pending{$start}=$section;
 2213:             next;
 2214:         }
 2215:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 2216:     }
 2217:     #
 2218:     # Presumedly there will be few matching roles from the above
 2219:     # loop and the sorting time will be negligible.
 2220:     if (scalar(keys(%Pending))) {
 2221:         my ($time) = sort {$a <=> $b} keys(%Pending);
 2222:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 2223:     } 
 2224:     if (scalar(keys(%Expired))) {
 2225:         my @sorted = sort {$a <=> $b} keys(%Expired);
 2226:         my $time = pop(@sorted);
 2227:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 2228:     }
 2229:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 2230: }
 2231: 
 2232: sub save_cache {
 2233:     &purge_remembered();
 2234:     #&Apache::loncommon::validate_page();
 2235:     undef(%env);
 2236:     undef($env_loaded);
 2237: }
 2238: 
 2239: my $to_remember=-1;
 2240: my %remembered;
 2241: my %accessed;
 2242: my $kicks=0;
 2243: my $hits=0;
 2244: sub make_key {
 2245:     my ($name,$id) = @_;
 2246:     if (length($id) > 65 
 2247: 	&& length(&escape($id)) > 200) {
 2248: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 2249:     }
 2250:     return &escape($name.':'.$id);
 2251: }
 2252: 
 2253: sub devalidate_cache_new {
 2254:     my ($name,$id,$debug) = @_;
 2255:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 2256:     $id=&make_key($name,$id);
 2257:     $memcache->delete($id);
 2258:     delete($remembered{$id});
 2259:     delete($accessed{$id});
 2260: }
 2261: 
 2262: sub is_cached_new {
 2263:     my ($name,$id,$debug) = @_;
 2264:     $id=&make_key($name,$id);
 2265:     if (exists($remembered{$id})) {
 2266: 	if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
 2267: 	$accessed{$id}=[&gettimeofday()];
 2268: 	$hits++;
 2269: 	return ($remembered{$id},1);
 2270:     }
 2271:     my $value = $memcache->get($id);
 2272:     if (!(defined($value))) {
 2273: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 2274: 	return (undef,undef);
 2275:     }
 2276:     if ($value eq '__undef__') {
 2277: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 2278: 	$value=undef;
 2279:     }
 2280:     &make_room($id,$value,$debug);
 2281:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 2282:     return ($value,1);
 2283: }
 2284: 
 2285: sub do_cache_new {
 2286:     my ($name,$id,$value,$time,$debug) = @_;
 2287:     $id=&make_key($name,$id);
 2288:     my $setvalue=$value;
 2289:     if (!defined($setvalue)) {
 2290: 	$setvalue='__undef__';
 2291:     }
 2292:     if (!defined($time) ) {
 2293: 	$time=600;
 2294:     }
 2295:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 2296:     my $result = $memcache->set($id,$setvalue,$time);
 2297:     if (! $result) {
 2298: 	&logthis("caching of id -> $id  failed");
 2299: 	$memcache->disconnect_all();
 2300:     }
 2301:     # need to make a copy of $value
 2302:     &make_room($id,$value,$debug);
 2303:     return $value;
 2304: }
 2305: 
 2306: sub make_room {
 2307:     my ($id,$value,$debug)=@_;
 2308: 
 2309:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
 2310:                                     : $value;
 2311:     if ($to_remember<0) { return; }
 2312:     $accessed{$id}=[&gettimeofday()];
 2313:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 2314:     my $to_kick;
 2315:     my $max_time=0;
 2316:     foreach my $other (keys(%accessed)) {
 2317: 	if (&tv_interval($accessed{$other}) > $max_time) {
 2318: 	    $to_kick=$other;
 2319: 	    $max_time=&tv_interval($accessed{$other});
 2320: 	}
 2321:     }
 2322:     delete($remembered{$to_kick});
 2323:     delete($accessed{$to_kick});
 2324:     $kicks++;
 2325:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 2326:     return;
 2327: }
 2328: 
 2329: sub purge_remembered {
 2330:     #&logthis("Tossing ".scalar(keys(%remembered)));
 2331:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 2332:     undef(%remembered);
 2333:     undef(%accessed);
 2334: }
 2335: # ------------------------------------- Read an entry from a user's environment
 2336: 
 2337: sub userenvironment {
 2338:     my ($udom,$unam,@what)=@_;
 2339:     my $items;
 2340:     foreach my $item (@what) {
 2341:         $items.=&escape($item).'&';
 2342:     }
 2343:     $items=~s/\&$//;
 2344:     my %returnhash=();
 2345:     my $uhome = &homeserver($unam,$udom);
 2346:     unless ($uhome eq 'no_host') {
 2347:         my @answer=split(/\&/, 
 2348:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
 2349:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
 2350:             return %returnhash;
 2351:         }
 2352:         my $i;
 2353:         for ($i=0;$i<=$#what;$i++) {
 2354: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
 2355:         }
 2356:     }
 2357:     return %returnhash;
 2358: }
 2359: 
 2360: # ---------------------------------------------------------- Get a studentphoto
 2361: sub studentphoto {
 2362:     my ($udom,$unam,$ext) = @_;
 2363:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 2364:     if (defined($env{'request.course.id'})) {
 2365:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 2366:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 2367:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 2368:             } else {
 2369:                 my ($result,$perm_reqd)=
 2370: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 2371:                 if ($result eq 'ok') {
 2372:                     if (!($perm_reqd eq 'yes')) {
 2373:                         return(&retrievestudentphoto($udom,$unam,$ext));
 2374:                     }
 2375:                 }
 2376:             }
 2377:         }
 2378:     } else {
 2379:         my ($result,$perm_reqd) = 
 2380: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 2381:         if ($result eq 'ok') {
 2382:             if (!($perm_reqd eq 'yes')) {
 2383:                 return(&retrievestudentphoto($udom,$unam,$ext));
 2384:             }
 2385:         }
 2386:     }
 2387:     return '/adm/lonKaputt/lonlogo_broken.gif';
 2388: }
 2389: 
 2390: sub retrievestudentphoto {
 2391:     my ($udom,$unam,$ext,$type) = @_;
 2392:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 2393:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 2394:     if ($ret eq 'ok') {
 2395:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 2396:         if ($type eq 'thumbnail') {
 2397:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 2398:         }
 2399:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 2400:         return $tokenurl;
 2401:     } else {
 2402:         if ($type eq 'thumbnail') {
 2403:             return '/adm/lonKaputt/genericstudent_tn.gif';
 2404:         } else { 
 2405:             return '/adm/lonKaputt/lonlogo_broken.gif';
 2406:         }
 2407:     }
 2408: }
 2409: 
 2410: # -------------------------------------------------------------------- New chat
 2411: 
 2412: sub chatsend {
 2413:     my ($newentry,$anon,$group)=@_;
 2414:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 2415:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2416:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 2417:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 2418: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 2419: 		   &escape($newentry)).':'.$group,$chome);
 2420: }
 2421: 
 2422: # ------------------------------------------ Find current version of a resource
 2423: 
 2424: sub getversion {
 2425:     my $fname=&clutter(shift);
 2426:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
 2427:     return &currentversion(&filelocation('',$fname));
 2428: }
 2429: 
 2430: sub currentversion {
 2431:     my $fname=shift;
 2432:     my $author=$fname;
 2433:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2434:     my ($udom,$uname)=split(/\//,$author);
 2435:     my $home=&homeserver($uname,$udom);
 2436:     if ($home eq 'no_host') { 
 2437:         return -1; 
 2438:     }
 2439:     my $answer=&reply("currentversion:$fname",$home);
 2440:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 2441: 	return -1;
 2442:     }
 2443:     return $answer;
 2444: }
 2445: 
 2446: #
 2447: # Return special version number of resource if set by override, empty otherwise
 2448: #
 2449: sub usedversion {
 2450:     my $fname=shift;
 2451:     unless ($fname) { $fname=$env{'request.uri'}; }
 2452:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
 2453:     if ($urlversion) { return $urlversion; }
 2454:     return '';
 2455: }
 2456: 
 2457: # ----------------------------- Subscribe to a resource, return URL if possible
 2458: 
 2459: sub subscribe {
 2460:     my $fname=shift;
 2461:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 2462:     $fname=~s/[\n\r]//g;
 2463:     my $author=$fname;
 2464:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2465:     my ($udom,$uname)=split(/\//,$author);
 2466:     my $home=homeserver($uname,$udom);
 2467:     if ($home eq 'no_host') {
 2468:         return 'not_found';
 2469:     }
 2470:     my $answer=reply("sub:$fname",$home);
 2471:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 2472: 	$answer.=' by '.$home;
 2473:     }
 2474:     return $answer;
 2475: }
 2476:     
 2477: # -------------------------------------------------------------- Replicate file
 2478: 
 2479: sub repcopy {
 2480:     my $filename=shift;
 2481:     $filename=~s/\/+/\//g;
 2482:     my $londocroot = $perlvar{'lonDocRoot'};
 2483:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
 2484:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
 2485:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
 2486: 	$filename=~m{^/*(uploaded|editupload)/}) {
 2487: 	return &repcopy_userfile($filename);
 2488:     }
 2489:     $filename=~s/[\n\r]//g;
 2490:     my $transname="$filename.in.transfer";
 2491: # FIXME: this should flock
 2492:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 2493:     my $remoteurl=subscribe($filename);
 2494:     if ($remoteurl =~ /^con_lost by/) {
 2495: 	   &logthis("Subscribe returned $remoteurl: $filename");
 2496:            return 'unavailable';
 2497:     } elsif ($remoteurl eq 'not_found') {
 2498: 	   #&logthis("Subscribe returned not_found: $filename");
 2499: 	   return 'not_found';
 2500:     } elsif ($remoteurl =~ /^rejected by/) {
 2501: 	   &logthis("Subscribe returned $remoteurl: $filename");
 2502:            return 'forbidden';
 2503:     } elsif ($remoteurl eq 'directory') {
 2504:            return 'ok';
 2505:     } else {
 2506:         my $author=$filename;
 2507:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2508:         my ($udom,$uname)=split(/\//,$author);
 2509:         my $home=homeserver($uname,$udom);
 2510:         unless ($home eq $perlvar{'lonHostID'}) {
 2511:            my @parts=split(/\//,$filename);
 2512:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 2513:            if ($path ne "$londocroot/res") {
 2514:                &logthis("Malconfiguration for replication: $filename");
 2515: 	       return 'bad_request';
 2516:            }
 2517:            my $count;
 2518:            for ($count=5;$count<$#parts;$count++) {
 2519:                $path.="/$parts[$count]";
 2520:                if ((-e $path)!=1) {
 2521: 		   mkdir($path,0777);
 2522:                }
 2523:            }
 2524:            my $ua=new LWP::UserAgent;
 2525:            my $request=new HTTP::Request('GET',"$remoteurl");
 2526:            my $response=$ua->request($request,$transname);
 2527:            if ($response->is_error()) {
 2528: 	       unlink($transname);
 2529:                my $message=$response->status_line;
 2530:                &logthis("<font color=\"blue\">WARNING:"
 2531:                        ." LWP get: $message: $filename</font>");
 2532:                return 'unavailable';
 2533:            } else {
 2534: 	       if ($remoteurl!~/\.meta$/) {
 2535:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 2536:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
 2537:                   if ($mresponse->is_error()) {
 2538: 		      unlink($filename.'.meta');
 2539:                       &logthis(
 2540:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 2541:                   }
 2542: 	       }
 2543:                rename($transname,$filename);
 2544:                return 'ok';
 2545:            }
 2546:        }
 2547:     }
 2548: }
 2549: 
 2550: # ------------------------------------------------ Get server side include body
 2551: sub ssi_body {
 2552:     my ($filelink,%form)=@_;
 2553:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 2554:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 2555:     }
 2556:     my $output='';
 2557:     my $response;
 2558:     if ($filelink=~/^https?\:/) {
 2559:        ($output,$response)=&externalssi($filelink);
 2560:     } else {
 2561:        $filelink .= $filelink=~/\?/ ? '&' : '?';
 2562:        $filelink .= 'inhibitmenu=yes';
 2563:        ($output,$response)=&ssi($filelink,%form);
 2564:     }
 2565:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 2566:     $output=~s/^.*?\<body[^\>]*\>//si;
 2567:     $output=~s/\<\/body\s*\>.*?$//si;
 2568:     if (wantarray) {
 2569:         return ($output, $response);
 2570:     } else {
 2571:         return $output;
 2572:     }
 2573: }
 2574: 
 2575: # --------------------------------------------------------- Server Side Include
 2576: 
 2577: sub absolute_url {
 2578:     my ($host_name) = @_;
 2579:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 2580:     if ($host_name eq '') {
 2581: 	$host_name = $ENV{'SERVER_NAME'};
 2582:     }
 2583:     return $protocol.$host_name;
 2584: }
 2585: 
 2586: #
 2587: #   Server side include.
 2588: # Parameters:
 2589: #  fn     Possibly encrypted resource name/id.
 2590: #  form   Hash that describes how the rendering should be done
 2591: #         and other things.
 2592: # Returns:
 2593: #   Scalar context: The content of the response.
 2594: #   Array context:  2 element list of the content and the full response object.
 2595: #     
 2596: sub ssi {
 2597: 
 2598:     my ($fn,%form)=@_;
 2599:     my $ua=new LWP::UserAgent;
 2600:     my $request;
 2601: 
 2602:     $form{'no_update_last_known'}=1;
 2603:     &Apache::lonenc::check_encrypt(\$fn);
 2604:     if (%form) {
 2605:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 2606:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
 2607:     } else {
 2608:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 2609:     }
 2610: 
 2611:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 2612:     my $response= $ua->request($request);
 2613:     my $content = $response->content;
 2614: 
 2615: 
 2616:     if (wantarray) {
 2617: 	return ($content, $response);
 2618:     } else {
 2619: 	return $content;
 2620:     }
 2621: }
 2622: 
 2623: sub externalssi {
 2624:     my ($url)=@_;
 2625:     my $ua=new LWP::UserAgent;
 2626:     my $request=new HTTP::Request('GET',$url);
 2627:     my $response=$ua->request($request);
 2628:     if (wantarray) {
 2629:         return ($response->content, $response);
 2630:     } else {
 2631:         return $response->content;
 2632:     }
 2633: }
 2634: 
 2635: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 2636: 
 2637: sub allowuploaded {
 2638:     my ($srcurl,$url)=@_;
 2639:     $url=&clutter(&declutter($url));
 2640:     my $dir=$url;
 2641:     $dir=~s/\/[^\/]+$//;
 2642:     my %httpref=();
 2643:     my $httpurl=&hreflocation('',$url);
 2644:     $httpref{'httpref.'.$httpurl}=$srcurl;
 2645:     &Apache::lonnet::appenv(\%httpref);
 2646: }
 2647: 
 2648: #
 2649: # Determine if the current user should be able to edit a particular resource,
 2650: # when viewing in course context.
 2651: # (a) When viewing resource used to determine if "Edit" item is included in 
 2652: #     Functions.
 2653: # (b) When displaying folder contents in course editor, used to determine if
 2654: #     "Edit" link will be displayed alongside resource.
 2655: #
 2656: #  input: 3 args -- filename (decluttered), course number and course domain.
 2657: #  output: array of four scalars -- 
 2658: #          $cfile -- url for file editing if editable on current server
 2659: #          $home -- homeserver of resource (i.e., for author if published,
 2660: #                                           or course if uploaded.).
 2661: #          $switchserver --  1 if server switch will be needed.
 2662: #          $uploaded -- 1 if resource is a file uploaded to a course.
 2663: #
 2664: 
 2665: sub can_edit_resource {
 2666:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
 2667:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
 2668: #
 2669: # For aboutme pages user can only edit his/her own.
 2670: #
 2671:     if ($resurl =~ m{^/adm/($match_domain)/($match_username)/aboutme$}) {
 2672:         my ($sdom,$sname) = ($1,$2);
 2673:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
 2674:             $home = $env{'user.home'};
 2675:             $cfile = $resurl;
 2676:             if ($env{'form.forceedit'}) {
 2677:                 $forceview = 1;
 2678:             } else {
 2679:                 $forceedit = 1;
 2680:             }
 2681:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
 2682:         } else {
 2683:             return;
 2684:         }
 2685:     }
 2686: 
 2687:     if ($env{'request.course.id'}) {
 2688:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
 2689:         if ($group ne '') {
 2690: # if this is a group homepage or group bulletin board, check group privs
 2691:             my $allowed = 0;
 2692:             if ($resurl =~ m{^/adm/$cdom/$cnum/$group/smppg$}) {
 2693:                 if ((&Apache::lonnet::allowed('mdg',$env{'request.course.id'}.
 2694:                             ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 2695:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 2696:                     $allowed = 1;
 2697:                 }
 2698:             } elsif ($resurl =~ m{^/adm/$cdom/$cnum/\d+/bulletinboard$}) {
 2699:                 unless ((&allowed(&Apache::lonnet::allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) ||
 2700:                         (&allowed('cgb',$env{'request.course.id'}.$group)) || $crsedit) {
 2701:                     $allowed = 1;
 2702:                 }
 2703:             }
 2704:             if ($allowed) {
 2705:                 $home=&homeserver($cnum,$cdom);
 2706:                 if ($env{'form.forceedit'}) {
 2707:                     $forceview = 1;
 2708:                 } else {
 2709:                     $forceedit = 1;
 2710:                 }
 2711:                 $cfile = $resurl;
 2712:             } else {
 2713:                 return;
 2714:             }
 2715:         } else {
 2716: #
 2717: # No edit allowed where CC has switched to student role.
 2718: #
 2719:             unless ($crsedit) {
 2720:                 return;
 2721:             }
 2722:         }
 2723:     }
 2724: 
 2725:     if ($file ne '') {
 2726:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
 2727:             if (&is_course_upload($file,$cnum,$cdom)) {
 2728:                 $uploaded = 1;
 2729:                 $incourse = 1;
 2730:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
 2731:                     $cfile = &hreflocation('',$file);
 2732:                     $forceedit = 1;
 2733:                 }
 2734:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
 2735:                 $incourse = 1;
 2736:                 if ($env{'form.forceedit'}) {
 2737:                     $forceview = 1;
 2738:                 } else {
 2739:                     $forceedit = 1;
 2740:                 }
 2741:                 $cfile = $resurl;
 2742:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
 2743:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
 2744:                     $incourse = 1;
 2745:                     if ($env{'form.forceedit'}) {
 2746:                         $forceview = 1;
 2747:                     } else {
 2748:                         $forceedit = 1;
 2749:                     }
 2750:                     $cfile = $resurl;
 2751:                 } elsif (($resurl eq '/res/lib/templates/simpleproblem.problem')) {
 2752:                     $incourse = 1;
 2753:                     $cfile = $resurl.'/smpedit';
 2754:                 } elsif ($resurl =~ /ext/) {
 2755:                     $incourse = 1;
 2756:                     # is external
 2757:                 }
 2758:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
 2759:                 my $template = '/res/lib/templates/simpleproblem.problem';
 2760:                 if (&is_on_map($template)) { 
 2761:                     $incourse = 1;
 2762:                     $forceview = 1;
 2763:                     $cfile = $template;
 2764:                 }
 2765:             }
 2766:         }
 2767:         if ($uploaded || $incourse) {
 2768:             $home=&homeserver($cnum,$cdom);
 2769:         } else {
 2770:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
 2771:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
 2772:             # Check that the user has permission to edit this resource
 2773:             my $setpriv = 1;
 2774:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
 2775:             if (defined($cfudom)) {
 2776:                 $home=&homeserver($cfuname,$cfudom);
 2777:                 $cfile=$file;
 2778:             }
 2779:         }
 2780:         if (($cfile ne '') && (!$incourse || $uploaded) && 
 2781:             (($home ne '') && ($home ne 'no_host'))) {
 2782:             my @ids=&current_machine_ids();
 2783:             unless (grep(/^\Q$home\E$/,@ids)) {
 2784:                 $switchserver=1;
 2785:             }
 2786:         }
 2787:     }
 2788:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
 2789: }
 2790: 
 2791: sub is_course_upload {
 2792:     my ($file,$cnum,$cdom) = @_;
 2793:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
 2794:     $uploadpath =~ s{^\/}{};
 2795:     if (($file =~ m{^\Q$uploadpath\E/userfiles/docs/}) ||
 2796:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/docs/})) {
 2797:         return 1;
 2798:     }
 2799:     return;
 2800: }
 2801: 
 2802: sub in_course {
 2803:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
 2804:     if ($hideprivileged) {
 2805:         my $skipuser;
 2806:         if (&privileged($uname,$udom)) {
 2807:             $skipuser = 1;
 2808:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
 2809:             if ($coursehash{'nothideprivileged'}) {
 2810:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 2811:                     my $user;
 2812:                     if ($item =~ /:/) {
 2813:                         $user = $item;
 2814:                     } else {
 2815:                         $user = join(':',split(/[\@]/,$item));
 2816:                     }
 2817:                     if ($user eq $uname.':'.$udom) {
 2818:                         undef($skipuser);
 2819:                         last;
 2820:                     }
 2821:                 }
 2822:             }
 2823:             if ($skipuser) {
 2824:                 return 0;
 2825:             }
 2826:         }
 2827:     }
 2828:     $type ||= 'any';
 2829:     if (!defined($cdom) || !defined($cnum)) {
 2830:         my $cid  = $env{'request.course.id'};
 2831:         $cdom = $env{'course.'.$cid.'.domain'};
 2832:         $cnum = $env{'course.'.$cid.'.num'};
 2833:     }
 2834:     my $typesref;
 2835:     if (($type eq 'any') || ($type eq 'all')) {
 2836:         $typesref = ['active','previous','future'];
 2837:     } elsif ($type eq 'previous' || $type eq 'future') {
 2838:         $typesref = [$type];
 2839:     }
 2840:     my %roles = &get_my_roles($uname,$udom,'userroles',
 2841:                               $typesref,undef,[$cdom]);
 2842:     my ($tmp) = keys(%roles);
 2843:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
 2844:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
 2845:     if (@course_roles > 0) {
 2846:         return 1;
 2847:     }
 2848:     return 0;
 2849: }
 2850: 
 2851: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 2852: # input: action, courseID, current domain, intended
 2853: #        path to file, source of file, instruction to parse file for objects,
 2854: #        ref to hash for embedded objects,
 2855: #        ref to hash for codebase of java objects.
 2856: #        reference to scalar to accommodate mime type determined
 2857: #          from File::MMagic if $parser = parse.
 2858: #
 2859: # output: url to file (if action was uploaddoc), 
 2860: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 2861: #
 2862: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 2863: # course.
 2864: #
 2865: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2866: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 2867: #          course's home server.
 2868: #
 2869: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 2870: #          be copied from $source (current location) to 
 2871: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2872: #         and will then be copied to
 2873: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 2874: #         course's home server.
 2875: #
 2876: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2877: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 2878: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2879: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 2880: #         in course's home server.
 2881: #
 2882: 
 2883: sub process_coursefile {
 2884:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
 2885:         $mimetype)=@_;
 2886:     my $fetchresult;
 2887:     my $home=&homeserver($docuname,$docudom);
 2888:     if ($action eq 'propagate') {
 2889:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2890: 			     $home);
 2891:     } else {
 2892:         my $fpath = '';
 2893:         my $fname = $file;
 2894:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 2895:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 2896:         my $filepath = &build_filepath($fpath);
 2897:         if ($action eq 'copy') {
 2898:             if ($source eq '') {
 2899:                 $fetchresult = 'no source file';
 2900:                 return $fetchresult;
 2901:             } else {
 2902:                 my $destination = $filepath.'/'.$fname;
 2903:                 rename($source,$destination);
 2904:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2905:                                  $home);
 2906:             }
 2907:         } elsif ($action eq 'uploaddoc') {
 2908:             open(my $fh,'>'.$filepath.'/'.$fname);
 2909:             print $fh $env{'form.'.$source};
 2910:             close($fh);
 2911:             if ($parser eq 'parse') {
 2912:                 my $mm = new File::MMagic;
 2913:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
 2914:                 if ($type eq 'text/html') {
 2915:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 2916:                     unless ($parse_result eq 'ok') {
 2917:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 2918:                     }
 2919:                 }
 2920:                 if (ref($mimetype)) {
 2921:                     $$mimetype = $type;
 2922:                 } 
 2923:             }
 2924:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2925:                                  $home);
 2926:             if ($fetchresult eq 'ok') {
 2927:                 return '/uploaded/'.$fpath.'/'.$fname;
 2928:             } else {
 2929:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 2930:                         ' to host '.$home.': '.$fetchresult);
 2931:                 return '/adm/notfound.html';
 2932:             }
 2933:         }
 2934:     }
 2935:     unless ( $fetchresult eq 'ok') {
 2936:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 2937:              ' to host '.$home.': '.$fetchresult);
 2938:     }
 2939:     return $fetchresult;
 2940: }
 2941: 
 2942: sub build_filepath {
 2943:     my ($fpath) = @_;
 2944:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 2945:     unless ($fpath eq '') {
 2946:         my @parts=split('/',$fpath);
 2947:         foreach my $part (@parts) {
 2948:             $filepath.= '/'.$part;
 2949:             if ((-e $filepath)!=1) {
 2950:                 mkdir($filepath,0777);
 2951:             }
 2952:         }
 2953:     }
 2954:     return $filepath;
 2955: }
 2956: 
 2957: sub store_edited_file {
 2958:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 2959:     my $file = $primary_url;
 2960:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 2961:     my $fpath = '';
 2962:     my $fname = $file;
 2963:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 2964:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 2965:     my $filepath = &build_filepath($fpath);
 2966:     open(my $fh,'>'.$filepath.'/'.$fname);
 2967:     print $fh $content;
 2968:     close($fh);
 2969:     my $home=&homeserver($docuname,$docudom);
 2970:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2971: 			  $home);
 2972:     if ($$fetchresult eq 'ok') {
 2973:         return '/uploaded/'.$fpath.'/'.$fname;
 2974:     } else {
 2975:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 2976: 		 ' to host '.$home.': '.$$fetchresult);
 2977:         return '/adm/notfound.html';
 2978:     }
 2979: }
 2980: 
 2981: sub clean_filename {
 2982:     my ($fname,$args)=@_;
 2983: # Replace Windows backslashes by forward slashes
 2984:     $fname=~s/\\/\//g;
 2985:     if (!$args->{'keep_path'}) {
 2986:         # Get rid of everything but the actual filename
 2987: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 2988:     }
 2989: # Replace spaces by underscores
 2990:     $fname=~s/\s+/\_/g;
 2991: # Replace all other weird characters by nothing
 2992:     $fname=~s{[^/\w\.\-]}{}g;
 2993: # Replace all .\d. sequences with _\d. so they no longer look like version
 2994: # numbers
 2995:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 2996:     return $fname;
 2997: }
 2998: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
 2999: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
 3000: # image with the same aspect ratio as the original, but with dimensions which do 
 3001: # not exceed $resizewidth and $resizeheight.
 3002:  
 3003: sub resizeImage {
 3004:     my ($img_path,$resizewidth,$resizeheight) = @_;
 3005:     my $ima = Image::Magick->new;
 3006:     my $resized;
 3007:     if (-e $img_path) {
 3008:         $ima->Read($img_path);
 3009:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
 3010:             my $width = $ima->Get('width');
 3011:             my $height = $ima->Get('height');
 3012:             if ($width > $resizewidth) {
 3013: 	        my $factor = $width/$resizewidth;
 3014:                 my $newheight = $height/$factor;
 3015:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
 3016:                 $resized = 1;
 3017:             }
 3018:         }
 3019:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
 3020:             my $width = $ima->Get('width');
 3021:             my $height = $ima->Get('height');
 3022:             if ($height > $resizeheight) {
 3023:                 my $factor = $height/$resizeheight;
 3024:                 my $newwidth = $width/$factor;
 3025:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
 3026:                 $resized = 1;
 3027:             }
 3028:         }
 3029:         if ($resized) {
 3030:             $ima->Write($img_path);
 3031:         }
 3032:     }
 3033:     return;
 3034: }
 3035: 
 3036: # --------------- Take an uploaded file and put it into the userfiles directory
 3037: # input: $formname - the contents of the file are in $env{"form.$formname"}
 3038: #                    the desired filename is in $env{"form.$formname.filename"}
 3039: #        $context - possible values: coursedoc, existingfile, overwrite, 
 3040: #                                    canceloverwrite, or ''. 
 3041: #                   if 'coursedoc': upload to the current course
 3042: #                   if 'existingfile': write file to tmp/overwrites directory 
 3043: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
 3044: #                   $context is passed as argument to &finishuserfileupload
 3045: #        $subdir - directory in userfile to store the file into
 3046: #        $parser - instruction to parse file for objects ($parser = parse)    
 3047: #        $allfiles - reference to hash for embedded objects
 3048: #        $codebase - reference to hash for codebase of java objects
 3049: #        $desuname - username for permanent storage of uploaded file
 3050: #        $dsetudom - domain for permanaent storage of uploaded file
 3051: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 3052: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 3053: #        $resizewidth - width (pixels) to which to resize uploaded image
 3054: #        $resizeheight - height (pixels) to which to resize uploaded image
 3055: #        $mimetype - reference to scalar to accommodate mime type determined
 3056: #                    from File::MMagic.
 3057: # 
 3058: # output: url of file in userspace, or error: <message> 
 3059: #             or /adm/notfound.html if failure to upload occurse
 3060: 
 3061: sub userfileupload {
 3062:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
 3063:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
 3064:     if (!defined($subdir)) { $subdir='unknown'; }
 3065:     my $fname=$env{'form.'.$formname.'.filename'};
 3066:     $fname=&clean_filename($fname);
 3067:     # See if there is anything left
 3068:     unless ($fname) { return 'error: no uploaded file'; }
 3069:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
 3070:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
 3071:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
 3072:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3073:         my $now = time;
 3074:         my $filepath;
 3075:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
 3076:              $filepath = 'tmp/helprequests/'.$now;
 3077:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
 3078:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 3079:                          '_'.$env{'user.domain'}.'/pending';
 3080:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3081:             my ($docuname,$docudom);
 3082:             if ($destudom) {
 3083:                 $docudom = $destudom;
 3084:             } else {
 3085:                 $docudom = $env{'user.domain'};
 3086:             }
 3087:             if ($destuname) {
 3088:                 $docuname = $destuname;
 3089:             } else {
 3090:                 $docuname = $env{'user.name'};
 3091:             }
 3092:             if (exists($env{'form.group'})) {
 3093:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3094:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3095:             }
 3096:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
 3097:             if ($context eq 'canceloverwrite') {
 3098:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
 3099:                 if (-e  $tempfile) {
 3100:                     my @info = stat($tempfile);
 3101:                     if ($info[9] eq $env{'form.timestamp'}) {
 3102:                         unlink($tempfile);
 3103:                     }
 3104:                 }
 3105:                 return;
 3106:             }
 3107:         }
 3108:         # Create the directory if not present
 3109:         my @parts=split(/\//,$filepath);
 3110:         my $fullpath = $perlvar{'lonDaemons'};
 3111:         for (my $i=0;$i<@parts;$i++) {
 3112:             $fullpath .= '/'.$parts[$i];
 3113:             if ((-e $fullpath)!=1) {
 3114:                 mkdir($fullpath,0777);
 3115:             }
 3116:         }
 3117:         open(my $fh,'>'.$fullpath.'/'.$fname);
 3118:         print $fh $env{'form.'.$formname};
 3119:         close($fh);
 3120:         if ($context eq 'existingfile') {
 3121:             my @info = stat($fullpath.'/'.$fname);
 3122:             return ($fullpath.'/'.$fname,$info[9]);
 3123:         } else {
 3124:             return $fullpath.'/'.$fname;
 3125:         }
 3126:     }
 3127:     if ($subdir eq 'scantron') {
 3128:         $fname = 'scantron_orig_'.$fname;
 3129:     } else {
 3130:         $fname="$subdir/$fname";
 3131:     }
 3132:     if ($context eq 'coursedoc') {
 3133: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3134: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3135:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 3136:             return &finishuserfileupload($docuname,$docudom,
 3137: 					 $formname,$fname,$parser,$allfiles,
 3138: 					 $codebase,$thumbwidth,$thumbheight,
 3139:                                          $resizewidth,$resizeheight,$context,$mimetype);
 3140:         } else {
 3141:             $fname=$env{'form.folder'}.'/'.$fname;
 3142:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 3143: 				       $fname,$formname,$parser,
 3144: 				       $allfiles,$codebase,$mimetype);
 3145:         }
 3146:     } elsif (defined($destuname)) {
 3147:         my $docuname=$destuname;
 3148:         my $docudom=$destudom;
 3149: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 3150: 				     $parser,$allfiles,$codebase,
 3151:                                      $thumbwidth,$thumbheight,
 3152:                                      $resizewidth,$resizeheight,$context,$mimetype);
 3153:     } else {
 3154:         my $docuname=$env{'user.name'};
 3155:         my $docudom=$env{'user.domain'};
 3156:         if (exists($env{'form.group'})) {
 3157:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3158:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3159:         }
 3160: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 3161: 				     $parser,$allfiles,$codebase,
 3162:                                      $thumbwidth,$thumbheight,
 3163:                                      $resizewidth,$resizeheight,$context,$mimetype);
 3164:     }
 3165: }
 3166: 
 3167: sub finishuserfileupload {
 3168:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 3169:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
 3170:     my $path=$docudom.'/'.$docuname.'/';
 3171:     my $filepath=$perlvar{'lonDocRoot'};
 3172:   
 3173:     my ($fnamepath,$file,$fetchthumb);
 3174:     $file=$fname;
 3175:     if ($fname=~m|/|) {
 3176:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 3177: 	$path.=$fnamepath.'/';
 3178:     }
 3179:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 3180:     my $count;
 3181:     for ($count=4;$count<=$#parts;$count++) {
 3182:         $filepath.="/$parts[$count]";
 3183:         if ((-e $filepath)!=1) {
 3184: 	    mkdir($filepath,0777);
 3185:         }
 3186:     }
 3187: 
 3188: # Save the file
 3189:     {
 3190: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
 3191: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 3192: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 3193: 	    return '/adm/notfound.html';
 3194: 	}
 3195:         if ($context eq 'overwrite') {
 3196:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
 3197:             my $target = $filepath.'/'.$file;
 3198:             if (-e $source) {
 3199:                 my @info = stat($source);
 3200:                 if ($info[9] eq $env{'form.timestamp'}) {   
 3201:                     unless (&File::Copy::move($source,$target)) {
 3202:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
 3203:                         return "Moving from $source failed";
 3204:                     }
 3205:                 } else {
 3206:                     return "Temporary file: $source had unexpected date/time for last modification";
 3207:                 }
 3208:             } else {
 3209:                 return "Temporary file: $source missing";
 3210:             }
 3211:         } elsif (!print FH ($env{'form.'.$formname})) {
 3212: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 3213: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 3214: 	    return '/adm/notfound.html';
 3215: 	}
 3216: 	close(FH);
 3217:         if ($resizewidth && $resizeheight) {
 3218:             my $mm = new File::MMagic;
 3219:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
 3220:             if ($mime_type =~ m{^image/}) {
 3221: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
 3222:             }  
 3223: 	}
 3224:     }
 3225:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
 3226:         if (ref($mimetype)) {
 3227:             if ($$mimetype eq '') {
 3228:                 my $mm = new File::MMagic;
 3229:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
 3230:                 $$mimetype = $type;
 3231:             }
 3232:         }
 3233:     }
 3234:     if ($parser eq 'parse') {
 3235:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
 3236:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
 3237:                                                        $allfiles,$codebase);
 3238:             unless ($parse_result eq 'ok') {
 3239:                 &logthis('Failed to parse '.$filepath.$file.
 3240: 	   	         ' for embedded media: '.$parse_result); 
 3241:             }
 3242:         }
 3243:     }
 3244:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 3245:         my $input = $filepath.'/'.$file;
 3246:         my $output = $filepath.'/'.'tn-'.$file;
 3247:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 3248:         system("convert -sample $thumbsize $input $output");
 3249:         if (-e $filepath.'/'.'tn-'.$file) {
 3250:             $fetchthumb  = 1; 
 3251:         }
 3252:     }
 3253:  
 3254: # Notify homeserver to grep it
 3255: #
 3256:     my $docuhome=&homeserver($docuname,$docudom);	
 3257:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 3258:     if ($fetchresult eq 'ok') {
 3259:         if ($fetchthumb) {
 3260:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 3261:             if ($thumbresult ne 'ok') {
 3262:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 3263:                          $docuhome.': '.$thumbresult);
 3264:             }
 3265:         }
 3266: #
 3267: # Return the URL to it
 3268:         return '/uploaded/'.$path.$file;
 3269:     } else {
 3270:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 3271: 		 ': '.$fetchresult);
 3272:         return '/adm/notfound.html';
 3273:     }
 3274: }
 3275: 
 3276: sub extract_embedded_items {
 3277:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 3278:     my @state = ();
 3279:     my (%lastids,%related,%shockwave,%flashvars);
 3280:     my %javafiles = (
 3281:                       codebase => '',
 3282:                       code => '',
 3283:                       archive => ''
 3284:                     );
 3285:     my %mediafiles = (
 3286:                       src => '',
 3287:                       movie => '',
 3288:                      );
 3289:     my $p;
 3290:     if ($content) {
 3291:         $p = HTML::LCParser->new($content);
 3292:     } else {
 3293:         $p = HTML::LCParser->new($fullpath);
 3294:     }
 3295:     while (my $t=$p->get_token()) {
 3296: 	if ($t->[0] eq 'S') {
 3297: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 3298: 	    push(@state, $tagname);
 3299:             if (lc($tagname) eq 'allow') {
 3300:                 &add_filetype($allfiles,$attr->{'src'},'src');
 3301:             }
 3302: 	    if (lc($tagname) eq 'img') {
 3303: 		&add_filetype($allfiles,$attr->{'src'},'src');
 3304: 	    }
 3305: 	    if (lc($tagname) eq 'a') {
 3306: 		&add_filetype($allfiles,$attr->{'href'},'href');
 3307: 	    }
 3308:             if (lc($tagname) eq 'script') {
 3309:                 my $src;
 3310:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 3311:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 3312:                 } else {
 3313:                     if ($attr->{'src'} ne '') {
 3314:                         $src = $attr->{'src'};
 3315:                         &add_filetype($allfiles,$src,'src');
 3316:                     }
 3317:                 }
 3318:                 my $text = $p->get_trimmed_text();
 3319:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
 3320:                     my @swfargs = split(/,/,$1);
 3321:                     foreach my $item (@swfargs) {
 3322:                         $item =~ s/["']//g;
 3323:                         $item =~ s/^\s+//;
 3324:                         $item =~ s/\s+$//;
 3325:                     }
 3326:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
 3327:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
 3328:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
 3329:                         } else {
 3330:                             $related{$swfargs[0]} = [$swfargs[2]];
 3331:                         }
 3332:                     }
 3333:                 }
 3334:             }
 3335:             if (lc($tagname) eq 'link') {
 3336:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 3337:                     &add_filetype($allfiles,$attr->{'href'},'href');
 3338:                 }
 3339:             }
 3340: 	    if (lc($tagname) eq 'object' ||
 3341: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 3342: 		foreach my $item (keys(%javafiles)) {
 3343: 		    $javafiles{$item} = '';
 3344: 		}
 3345:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
 3346:                     $lastids{lc($tagname)} = $attr->{'id'};
 3347:                 }
 3348: 	    }
 3349: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 3350: 		my $name = lc($attr->{'name'});
 3351: 		foreach my $item (keys(%javafiles)) {
 3352: 		    if ($name eq $item) {
 3353: 			$javafiles{$item} = $attr->{'value'};
 3354: 			last;
 3355: 		    }
 3356: 		}
 3357:                 my $pathfrom;
 3358: 		foreach my $item (keys(%mediafiles)) {
 3359: 		    if ($name eq $item) {
 3360:                         $pathfrom = $attr->{'value'};
 3361:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
 3362: 			&add_filetype($allfiles,$pathfrom,$name);
 3363: 			last;
 3364: 		    }
 3365: 		}
 3366:                 if ($name eq 'flashvars') {
 3367:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
 3368:                 }
 3369:                 if ($pathfrom ne '') {
 3370:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
 3371:                                          $pathfrom);
 3372:                 }
 3373: 	    }
 3374: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 3375: 		foreach my $item (keys(%javafiles)) {
 3376: 		    if ($attr->{$item}) {
 3377: 			$javafiles{$item} = $attr->{$item};
 3378: 			last;
 3379: 		    }
 3380: 		}
 3381: 		foreach my $item (keys(%mediafiles)) {
 3382: 		    if ($attr->{$item}) {
 3383: 			&add_filetype($allfiles,$attr->{$item},$item);
 3384: 			last;
 3385: 		    }
 3386: 		}
 3387:                 if (lc($tagname) eq 'embed') {
 3388:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
 3389:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
 3390:                                              $attr->{'src'});
 3391:                     }
 3392:                 }
 3393: 	    }
 3394:             if ($t->[4] =~ m{/>$}) {
 3395:                 pop(@state);  
 3396:             }
 3397: 	} elsif ($t->[0] eq 'E') {
 3398: 	    my ($tagname) = ($t->[1]);
 3399: 	    if ($javafiles{'codebase'} ne '') {
 3400: 		$javafiles{'codebase'} .= '/';
 3401: 	    }  
 3402: 	    if (lc($tagname) eq 'applet' ||
 3403: 		lc($tagname) eq 'object' ||
 3404: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 3405: 		) {
 3406: 		foreach my $item (keys(%javafiles)) {
 3407: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 3408: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 3409: 			&add_filetype($allfiles,$file,$item);
 3410: 		    }
 3411: 		}
 3412: 	    } 
 3413: 	    pop @state;
 3414: 	}
 3415:     }
 3416:     foreach my $id (sort(keys(%flashvars))) {
 3417:         if ($shockwave{$id} ne '') {
 3418:             my @pairs = split(/\&/,$flashvars{$id});
 3419:             foreach my $pair (@pairs) {
 3420:                 my ($key,$value) = split(/\=/,$pair);
 3421:                 if ($key eq 'thumb') {
 3422:                     &add_filetype($allfiles,$value,$key);
 3423:                 } elsif ($key eq 'content') {
 3424:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
 3425:                     my ($ext) = ($value =~ /\.([^.]+)$/);
 3426:                     if ($ext ne '') {
 3427:                         &add_filetype($allfiles,$path.$value,$ext);
 3428:                     }
 3429:                 }
 3430:             }
 3431:         }
 3432:     }
 3433:     return 'ok';
 3434: }
 3435: 
 3436: sub add_filetype {
 3437:     my ($allfiles,$file,$type)=@_;
 3438:     if (exists($allfiles->{$file})) {
 3439: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 3440: 	    push(@{$allfiles->{$file}}, &escape($type));
 3441: 	}
 3442:     } else {
 3443: 	@{$allfiles->{$file}} = (&escape($type));
 3444:     }
 3445: }
 3446: 
 3447: sub embedded_dependency {
 3448:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
 3449:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
 3450:         if (($identifier ne '') &&
 3451:             (ref($related->{$identifier}) eq 'ARRAY') &&
 3452:             ($pathfrom ne '')) {
 3453:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
 3454:             foreach my $dep (@{$related->{$identifier}}) {
 3455:                 &add_filetype($allfiles,$path.$dep,'object');
 3456:             }
 3457:         }
 3458:     }
 3459:     return;
 3460: }
 3461: 
 3462: sub removeuploadedurl {
 3463:     my ($url)=@_;	
 3464:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 3465:     return &removeuserfile($uname,$udom,$fname);
 3466: }
 3467: 
 3468: sub removeuserfile {
 3469:     my ($docuname,$docudom,$fname)=@_;
 3470:     my $home=&homeserver($docuname,$docudom);    
 3471:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 3472:     if ($result eq 'ok') {	
 3473:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 3474:             my $metafile = $fname.'.meta';
 3475:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 3476: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 3477:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 3478:             my $sqlresult = 
 3479:                 &update_portfolio_table($docuname,$docudom,$file,
 3480:                                         'portfolio_metadata',$group,
 3481:                                         'delete');
 3482:         }
 3483:     }
 3484:     return $result;
 3485: }
 3486: 
 3487: sub mkdiruserfile {
 3488:     my ($docuname,$docudom,$dir)=@_;
 3489:     my $home=&homeserver($docuname,$docudom);
 3490:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 3491: }
 3492: 
 3493: sub renameuserfile {
 3494:     my ($docuname,$docudom,$old,$new)=@_;
 3495:     my $home=&homeserver($docuname,$docudom);
 3496:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 3497:                         &escape("$old").':'.&escape("$new"),$home);
 3498:     if ($result eq 'ok') {
 3499:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 3500:             my $oldmeta = $old.'.meta';
 3501:             my $newmeta = $new.'.meta';
 3502:             my $metaresult = 
 3503:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 3504: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 3505:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 3506:             my $sqlresult = 
 3507:                 &update_portfolio_table($docuname,$docudom,$file,
 3508:                                         'portfolio_metadata',$group,
 3509:                                         'delete');
 3510:         }
 3511:     }
 3512:     return $result;
 3513: }
 3514: 
 3515: # ------------------------------------------------------------------------- Log
 3516: 
 3517: sub log {
 3518:     my ($dom,$nam,$hom,$what)=@_;
 3519:     return critical("log:$dom:$nam:$what",$hom);
 3520: }
 3521: 
 3522: # ------------------------------------------------------------------ Course Log
 3523: #
 3524: # This routine flushes several buffers of non-mission-critical nature
 3525: #
 3526: 
 3527: sub flushcourselogs {
 3528:     &logthis('Flushing log buffers');
 3529: #
 3530: # course logs
 3531: # This is a log of all transactions in a course, which can be used
 3532: # for data mining purposes
 3533: #
 3534: # It also collects the courseid database, which lists last transaction
 3535: # times and course titles for all courseids
 3536: #
 3537:     my %courseidbuffer=();
 3538:     foreach my $crsid (keys(%courselogs)) {
 3539:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 3540: 		          &escape($courselogs{$crsid}),
 3541: 		          $coursehombuf{$crsid}) eq 'ok') {
 3542: 	    delete $courselogs{$crsid};
 3543:         } else {
 3544:             &logthis('Failed to flush log buffer for '.$crsid);
 3545:             if (length($courselogs{$crsid})>40000) {
 3546:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 3547:                         " exceeded maximum size, deleting.</font>");
 3548:                delete $courselogs{$crsid};
 3549:             }
 3550:         }
 3551:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 3552:             'description' => $coursedescrbuf{$crsid},
 3553:             'inst_code'    => $courseinstcodebuf{$crsid},
 3554:             'type'        => $coursetypebuf{$crsid},
 3555:             'owner'       => $courseownerbuf{$crsid},
 3556:         };
 3557:     }
 3558: #
 3559: # Write course id database (reverse lookup) to homeserver of courses 
 3560: # Is used in pickcourse
 3561: #
 3562:     foreach my $crs_home (keys(%courseidbuffer)) {
 3563:         my $response = &courseidput(&host_domain($crs_home),
 3564:                                     $courseidbuffer{$crs_home},
 3565:                                     $crs_home,'timeonly');
 3566:     }
 3567: #
 3568: # File accesses
 3569: # Writes to the dynamic metadata of resources to get hit counts, etc.
 3570: #
 3571:     foreach my $entry (keys(%accesshash)) {
 3572:         if ($entry =~ /___count$/) {
 3573:             my ($dom,$name);
 3574:             ($dom,$name,undef)=
 3575: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 3576:             if (! defined($dom) || $dom eq '' || 
 3577:                 ! defined($name) || $name eq '') {
 3578:                 my $cid = $env{'request.course.id'};
 3579:                 $dom  = $env{'request.'.$cid.'.domain'};
 3580:                 $name = $env{'request.'.$cid.'.num'};
 3581:             }
 3582:             my $value = $accesshash{$entry};
 3583:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 3584:             my %temphash=($url => $value);
 3585:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 3586:             if ($result eq 'ok') {
 3587:                 delete $accesshash{$entry};
 3588:             }
 3589:         } else {
 3590:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 3591:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
 3592:             my %temphash=($entry => $accesshash{$entry});
 3593:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 3594:                 delete $accesshash{$entry};
 3595:             }
 3596:         }
 3597:     }
 3598: #
 3599: # Roles
 3600: # Reverse lookup of user roles for course faculty/staff and co-authorship
 3601: #
 3602:     foreach my $entry (keys(%userrolehash)) {
 3603:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 3604: 	    split(/\:/,$entry);
 3605:         if (&Apache::lonnet::put('nohist_userroles',
 3606:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 3607:                 $rudom,$runame) eq 'ok') {
 3608: 	    delete $userrolehash{$entry};
 3609:         }
 3610:     }
 3611: #
 3612: # Reverse lookup of domain roles (dc, ad, li, sc, au)
 3613: #
 3614:     my %domrolebuffer = ();
 3615:     foreach my $entry (keys(%domainrolehash)) {
 3616:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 3617:         if ($domrolebuffer{$rudom}) {
 3618:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 3619:                       '='.&escape($domainrolehash{$entry});
 3620:         } else {
 3621:             $domrolebuffer{$rudom}.=&escape($entry).
 3622:                       '='.&escape($domainrolehash{$entry});
 3623:         }
 3624:         delete $domainrolehash{$entry};
 3625:     }
 3626:     foreach my $dom (keys(%domrolebuffer)) {
 3627: 	my %servers = &get_servers($dom,'library');
 3628: 	foreach my $tryserver (keys(%servers)) {
 3629: 	    unless (&reply('domroleput:'.$dom.':'.
 3630: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
 3631: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 3632: 	    }
 3633:         }
 3634:     }
 3635:     $dumpcount++;
 3636: }
 3637: 
 3638: sub courselog {
 3639:     my $what=shift;
 3640:     $what=time.':'.$what;
 3641:     unless ($env{'request.course.id'}) { return ''; }
 3642:     $coursedombuf{$env{'request.course.id'}}=
 3643:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 3644:     $coursenumbuf{$env{'request.course.id'}}=
 3645:        $env{'course.'.$env{'request.course.id'}.'.num'};
 3646:     $coursehombuf{$env{'request.course.id'}}=
 3647:        $env{'course.'.$env{'request.course.id'}.'.home'};
 3648:     $coursedescrbuf{$env{'request.course.id'}}=
 3649:        $env{'course.'.$env{'request.course.id'}.'.description'};
 3650:     $courseinstcodebuf{$env{'request.course.id'}}=
 3651:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 3652:     $courseownerbuf{$env{'request.course.id'}}=
 3653:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 3654:     $coursetypebuf{$env{'request.course.id'}}=
 3655:        $env{'course.'.$env{'request.course.id'}.'.type'};
 3656:     if (defined $courselogs{$env{'request.course.id'}}) {
 3657: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 3658:     } else {
 3659: 	$courselogs{$env{'request.course.id'}}.=$what;
 3660:     }
 3661:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 3662: 	&flushcourselogs();
 3663:     }
 3664: }
 3665: 
 3666: sub courseacclog {
 3667:     my $fnsymb=shift;
 3668:     unless ($env{'request.course.id'}) { return ''; }
 3669:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 3670:     if ($fnsymb=~/$LONCAPA::assess_re/) {
 3671:         $what.=':POST';
 3672:         # FIXME: Probably ought to escape things....
 3673: 	foreach my $key (keys(%env)) {
 3674:             if ($key=~/^form\.(.*)/) {
 3675:                 my $formitem = $1;
 3676:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 3677:                     $what.=':'.$formitem.'='.$env{$key};
 3678:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 3679:                     $what.=':'.$formitem.'='.$env{$key};
 3680:                 }
 3681:             }
 3682:         }
 3683:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 3684:         # FIXME: We should not be depending on a form parameter that someone
 3685:         # editing lonsearchcat.pm might change in the future.
 3686:         if ($env{'form.phase'} eq 'course_search') {
 3687:             $what.= ':POST';
 3688:             # FIXME: Probably ought to escape things....
 3689:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 3690:                                  'crsdiscuss') {
 3691:                 $what.=':'.$element.'='.$env{'form.'.$element};
 3692:             }
 3693:         }
 3694:     }
 3695:     &courselog($what);
 3696: }
 3697: 
 3698: sub countacc {
 3699:     my $url=&declutter(shift);
 3700:     return if (! defined($url) || $url eq '');
 3701:     unless ($env{'request.course.id'}) { return ''; }
 3702: #
 3703: # Mark that this url was used in this course
 3704: #
 3705:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 3706: #
 3707: # Increase the access count for this resource in this child process
 3708: #
 3709:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 3710:     $accesshash{$key}++;
 3711: }
 3712: 
 3713: sub linklog {
 3714:     my ($from,$to)=@_;
 3715:     $from=&declutter($from);
 3716:     $to=&declutter($to);
 3717:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 3718:     $accesshash{$to.'___'.$from.'___goto'}=1;
 3719: }
 3720: 
 3721: sub statslog {
 3722:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
 3723:     if ($users<2) { return; }
 3724:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
 3725:             'course'       => $env{'request.course.id'},
 3726:             'sections'     => '"all"',
 3727:             'num_students' => $users,
 3728:             'part'         => $part,
 3729:             'symb'         => $symb,
 3730:             'mean_tries'   => $av_attempts,
 3731:             'deg_of_diff'  => $degdiff});
 3732:     foreach my $key (keys(%dynstore)) {
 3733:         $accesshash{$key}=$dynstore{$key};
 3734:     }
 3735: }
 3736:   
 3737: sub userrolelog {
 3738:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 3739:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
 3740:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 3741:        $userrolehash
 3742:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 3743:                     =$tend.':'.$tstart;
 3744:     }
 3745:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
 3746:        $userrolehash
 3747:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 3748:                     =$tend.':'.$tstart;
 3749:     }
 3750:     if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
 3751:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 3752:        $domainrolehash
 3753:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 3754:                     = $tend.':'.$tstart;
 3755:     }
 3756: }
 3757: 
 3758: sub courserolelog {
 3759:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 3760:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 3761:         my $cdom = $1;
 3762:         my $cnum = $2;
 3763:         my $sec = $3;
 3764:         my $namespace = 'rolelog';
 3765:         my %storehash = (
 3766:                            role    => $trole,
 3767:                            start   => $tstart,
 3768:                            end     => $tend,
 3769:                            selfenroll => $selfenroll,
 3770:                            context    => $context,
 3771:                         );
 3772:         if ($trole eq 'gr') {
 3773:             $namespace = 'groupslog';
 3774:             $storehash{'group'} = $sec;
 3775:         } else {
 3776:             $storehash{'section'} = $sec;
 3777:         }
 3778:         &write_log('course',$namespace,\%storehash,$delflag,$username,
 3779:                    $domain,$cnum,$cdom);
 3780:         if (($trole ne 'st') || ($sec ne '')) {
 3781:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 3782:         }
 3783:     }
 3784:     return;
 3785: }
 3786: 
 3787: sub domainrolelog {
 3788:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 3789:     if ($area =~ m{^/($match_domain)/$}) {
 3790:         my $cdom = $1;
 3791:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
 3792:         my $namespace = 'rolelog';
 3793:         my %storehash = (
 3794:                            role    => $trole,
 3795:                            start   => $tstart,
 3796:                            end     => $tend,
 3797:                            context => $context,
 3798:                         );
 3799:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
 3800:                    $domain,$domconfiguser,$cdom);
 3801:     }
 3802:     return;
 3803: 
 3804: }
 3805: 
 3806: sub coauthorrolelog {
 3807:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 3808:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
 3809:         my $audom = $1;
 3810:         my $auname = $2;
 3811:         my $namespace = 'rolelog';
 3812:         my %storehash = (
 3813:                            role    => $trole,
 3814:                            start   => $tstart,
 3815:                            end     => $tend,
 3816:                            context => $context,
 3817:                         );
 3818:         &write_log('author',$namespace,\%storehash,$delflag,$username,
 3819:                    $domain,$auname,$audom);
 3820:     }
 3821:     return;
 3822: }
 3823: 
 3824: sub get_course_adv_roles {
 3825:     my ($cid,$codes) = @_;
 3826:     $cid=$env{'request.course.id'} unless (defined($cid));
 3827:     my %coursehash=&coursedescription($cid);
 3828:     my $crstype = &Apache::loncommon::course_type($cid);
 3829:     my %nothide=();
 3830:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3831:         if ($user !~ /:/) {
 3832: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 3833:         } else {
 3834:             $nothide{$user}=1;
 3835:         }
 3836:     }
 3837:     my %returnhash=();
 3838:     my %dumphash=
 3839:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 3840:     my $now=time;
 3841:     my %privileged;
 3842:     foreach my $entry (keys(%dumphash)) {
 3843: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 3844:         if (($tstart) && ($tstart<0)) { next; }
 3845:         if (($tend) && ($tend<$now)) { next; }
 3846:         if (($tstart) && ($now<$tstart)) { next; }
 3847:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 3848: 	if ($username eq '' || $domain eq '') { next; }
 3849:         unless (ref($privileged{$domain}) eq 'HASH') {
 3850:             my %dompersonnel =
 3851:                 &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
 3852:             $privileged{$domain} = {};
 3853:             foreach my $server (keys(%dompersonnel)) {
 3854:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 3855:                     foreach my $user (keys(%{$dompersonnel{$server}})) {
 3856:                         my ($trole,$uname,$udom) = split(/:/,$user);
 3857:                         $privileged{$udom}{$uname} = 1;
 3858:                     }
 3859:                 }
 3860:             }
 3861:         }
 3862:         if ((exists($privileged{$domain}{$username})) && 
 3863:             (!$nothide{$username.':'.$domain})) { next; }
 3864: 	if ($role eq 'cr') { next; }
 3865:         if ($codes) {
 3866:             if ($section) { $role .= ':'.$section; }
 3867:             if ($returnhash{$role}) {
 3868:                 $returnhash{$role}.=','.$username.':'.$domain;
 3869:             } else {
 3870:                 $returnhash{$role}=$username.':'.$domain;
 3871:             }
 3872:         } else {
 3873:             my $key=&plaintext($role,$crstype);
 3874:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 3875:             if ($returnhash{$key}) {
 3876: 	        $returnhash{$key}.=','.$username.':'.$domain;
 3877:             } else {
 3878:                 $returnhash{$key}=$username.':'.$domain;
 3879:             }
 3880:         }
 3881:     }
 3882:     return %returnhash;
 3883: }
 3884: 
 3885: sub get_my_roles {
 3886:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 3887:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 3888:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 3889:     my (%dumphash,%nothide);
 3890:     if ($context eq 'userroles') {
 3891:         %dumphash = &dump('roles',$udom,$uname);
 3892:     } else {
 3893:         %dumphash=
 3894:             &dump('nohist_userroles',$udom,$uname);
 3895:         if ($hidepriv) {
 3896:             my %coursehash=&coursedescription($udom.'_'.$uname);
 3897:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3898:                 if ($user !~ /:/) {
 3899:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 3900:                 } else {
 3901:                     $nothide{$user} = 1;
 3902:                 }
 3903:             }
 3904:         }
 3905:     }
 3906:     my %returnhash=();
 3907:     my $now=time;
 3908:     my %privileged;
 3909:     foreach my $entry (keys(%dumphash)) {
 3910:         my ($role,$tend,$tstart);
 3911:         if ($context eq 'userroles') {
 3912:             next if ($entry =~ /^rolesdef/);
 3913: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 3914:         } else {
 3915:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 3916:         }
 3917:         if (($tstart) && ($tstart<0)) { next; }
 3918:         my $status = 'active';
 3919:         if (($tend) && ($tend<=$now)) {
 3920:             $status = 'previous';
 3921:         } 
 3922:         if (($tstart) && ($now<$tstart)) {
 3923:             $status = 'future';
 3924:         }
 3925:         if (ref($types) eq 'ARRAY') {
 3926:             if (!grep(/^\Q$status\E$/,@{$types})) {
 3927:                 next;
 3928:             } 
 3929:         } else {
 3930:             if ($status ne 'active') {
 3931:                 next;
 3932:             }
 3933:         }
 3934:         my ($rolecode,$username,$domain,$section,$area);
 3935:         if ($context eq 'userroles') {
 3936:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
 3937:             (undef,$domain,$username,$section) = split(/\//,$area);
 3938:         } else {
 3939:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 3940:         }
 3941:         if (ref($roledoms) eq 'ARRAY') {
 3942:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 3943:                 next;
 3944:             }
 3945:         }
 3946:         if (ref($roles) eq 'ARRAY') {
 3947:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 3948:                 if ($role =~ /^cr\//) {
 3949:                     if (!grep(/^cr$/,@{$roles})) {
 3950:                         next;
 3951:                     }
 3952:                 } elsif ($role =~ /^gr\//) {
 3953:                     if (!grep(/^gr$/,@{$roles})) {
 3954:                         next;
 3955:                     }
 3956:                 } else {
 3957:                     next;
 3958:                 }
 3959:             }
 3960:         }
 3961:         if ($hidepriv) {
 3962:             if ($context eq 'userroles') {
 3963:                 if ((&privileged($username,$domain)) &&
 3964:                     (!$nothide{$username.':'.$domain})) {
 3965:                     next;
 3966:                 }
 3967:             } else {
 3968:                 unless (ref($privileged{$domain}) eq 'HASH') {
 3969:                     my %dompersonnel =
 3970:                         &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
 3971:                     $privileged{$domain} = {};
 3972:                     if (keys(%dompersonnel)) {
 3973:                         foreach my $server (keys(%dompersonnel)) {
 3974:                             if (ref($dompersonnel{$server}) eq 'HASH') {
 3975:                                 foreach my $user (keys(%{$dompersonnel{$server}})) {
 3976:                                     my ($trole,$uname,$udom) = split(/:/,$user);
 3977:                                     $privileged{$udom}{$uname} = $trole;
 3978:                                 }
 3979:                             }
 3980:                         }
 3981:                     }
 3982:                 }
 3983:                 if (exists($privileged{$domain}{$username})) {
 3984:                     if (!$nothide{$username.':'.$domain}) {
 3985:                         next;
 3986:                     }
 3987:                 }
 3988:             }
 3989:         }
 3990:         if ($withsec) {
 3991:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 3992:                 $tstart.':'.$tend;
 3993:         } else {
 3994:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 3995:         }
 3996:     }
 3997:     return %returnhash;
 3998: }
 3999: 
 4000: # ----------------------------------------------------- Frontpage Announcements
 4001: #
 4002: #
 4003: 
 4004: sub postannounce {
 4005:     my ($server,$text)=@_;
 4006:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 4007:     unless ($text=~/\w/) { $text=''; }
 4008:     return &reply('setannounce:'.&escape($text),$server);
 4009: }
 4010: 
 4011: sub getannounce {
 4012: 
 4013:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 4014: 	my $announcement='';
 4015: 	while (my $line = <$fh>) { $announcement .= $line; }
 4016: 	close($fh);
 4017: 	if ($announcement=~/\w/) { 
 4018: 	    return 
 4019:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 4020:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 4021: 	} else {
 4022: 	    return '';
 4023: 	}
 4024:     } else {
 4025: 	return '';
 4026:     }
 4027: }
 4028: 
 4029: # ---------------------------------------------------------- Course ID routines
 4030: # Deal with domain's nohist_courseid.db files
 4031: #
 4032: 
 4033: sub courseidput {
 4034:     my ($domain,$storehash,$coursehome,$caller) = @_;
 4035:     return unless (ref($storehash) eq 'HASH');
 4036:     my $outcome;
 4037:     if ($caller eq 'timeonly') {
 4038:         my $cids = '';
 4039:         foreach my $item (keys(%$storehash)) {
 4040:             $cids.=&escape($item).'&';
 4041:         }
 4042:         $cids=~s/\&$//;
 4043:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 4044:                           $coursehome);       
 4045:     } else {
 4046:         my $items = '';
 4047:         foreach my $item (keys(%$storehash)) {
 4048:             $items.= &escape($item).'='.
 4049:                      &freeze_escape($$storehash{$item}).'&';
 4050:         }
 4051:         $items=~s/\&$//;
 4052:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 4053:                           $coursehome);
 4054:     }
 4055:     if ($outcome eq 'unknown_cmd') {
 4056:         my $what;
 4057:         foreach my $cid (keys(%$storehash)) {
 4058:             $what .= &escape($cid).'=';
 4059:             foreach my $item ('description','inst_code','owner','type') {
 4060:                 $what .= &escape($storehash->{$cid}{$item}).':';
 4061:             }
 4062:             $what =~ s/\:$/&/;
 4063:         }
 4064:         $what =~ s/\&$//;  
 4065:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 4066:     } else {
 4067:         return $outcome;
 4068:     }
 4069: }
 4070: 
 4071: sub courseiddump {
 4072:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 4073:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 4074:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
 4075:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
 4076:     my $as_hash = 1;
 4077:     my %returnhash;
 4078:     if (!$domfilter) { $domfilter=''; }
 4079:     my %libserv = &all_library();
 4080:     foreach my $tryserver (keys(%libserv)) {
 4081:         if ( (  $hostidflag == 1 
 4082: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 4083: 	     || (!defined($hostidflag)) ) {
 4084: 
 4085: 	    if (($domfilter eq '') ||
 4086: 		(&host_domain($tryserver) eq $domfilter)) {
 4087:                 my $rep;
 4088:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
 4089:                     $rep = LONCAPA::Lond::dump_course_id_handler(
 4090:                         join(":", (&host_domain($tryserver), $sincefilter, 
 4091:                                 &escape($descfilter), &escape($instcodefilter), 
 4092:                                 &escape($ownerfilter), &escape($coursefilter),
 4093:                                 &escape($typefilter), &escape($regexp_ok), 
 4094:                                 $as_hash, &escape($selfenrollonly), 
 4095:                                 &escape($catfilter), $showhidden, $caller, 
 4096:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
 4097:                                 &escape($createdbefore), &escape($createdafter), 
 4098:                                 &escape($creationcontext), $domcloner)));
 4099:                 } else {
 4100:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
 4101:                              $sincefilter.':'.&escape($descfilter).':'.
 4102:                              &escape($instcodefilter).':'.&escape($ownerfilter).
 4103:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
 4104:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
 4105:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
 4106:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
 4107:                              &escape($cc_clone).':'.$cloneonly.':'.
 4108:                              &escape($createdbefore).':'.&escape($createdafter).':'.
 4109:                              &escape($creationcontext).':'.$domcloner,
 4110:                              $tryserver);
 4111:                 }
 4112:                      
 4113:                 my @pairs=split(/\&/,$rep);
 4114:                 foreach my $item (@pairs) {
 4115:                     my ($key,$value)=split(/\=/,$item,2);
 4116:                     $key = &unescape($key);
 4117:                     next if ($key =~ /^error: 2 /);
 4118:                     my $result = &thaw_unescape($value);
 4119:                     if (ref($result) eq 'HASH') {
 4120:                         $returnhash{$key}=$result;
 4121:                     } else {
 4122:                         my @responses = split(/:/,$value);
 4123:                         my @items = ('description','inst_code','owner','type');
 4124:                         for (my $i=0; $i<@responses; $i++) {
 4125:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 4126:                         }
 4127:                     }
 4128:                 }
 4129:             }
 4130:         }
 4131:     }
 4132:     return %returnhash;
 4133: }
 4134: 
 4135: sub courselastaccess {
 4136:     my ($cdom,$cnum,$hostidref) = @_;
 4137:     my %returnhash;
 4138:     if ($cdom && $cnum) {
 4139:         my $chome = &homeserver($cnum,$cdom);
 4140:         if ($chome ne 'no_host') {
 4141:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
 4142:             &extract_lastaccess(\%returnhash,$rep);
 4143:         }
 4144:     } else {
 4145:         if (!$cdom) { $cdom=''; }
 4146:         my %libserv = &all_library();
 4147:         foreach my $tryserver (keys(%libserv)) {
 4148:             if (ref($hostidref) eq 'ARRAY') {
 4149:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
 4150:             } 
 4151:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
 4152:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
 4153:                 &extract_lastaccess(\%returnhash,$rep);
 4154:             }
 4155:         }
 4156:     }
 4157:     return %returnhash;
 4158: }
 4159: 
 4160: sub extract_lastaccess {
 4161:     my ($returnhash,$rep) = @_;
 4162:     if (ref($returnhash) eq 'HASH') {
 4163:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
 4164:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
 4165:                  $rep eq '') {
 4166:             my @pairs=split(/\&/,$rep);
 4167:             foreach my $item (@pairs) {
 4168:                 my ($key,$value)=split(/\=/,$item,2);
 4169:                 $key = &unescape($key);
 4170:                 next if ($key =~ /^error: 2 /);
 4171:                 $returnhash->{$key} = &thaw_unescape($value);
 4172:             }
 4173:         }
 4174:     }
 4175:     return;
 4176: }
 4177: 
 4178: # ---------------------------------------------------------- DC e-mail
 4179: 
 4180: sub dcmailput {
 4181:     my ($domain,$msgid,$message,$server)=@_;
 4182:     my $status = &Apache::lonnet::critical(
 4183:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 4184:        &escape($message),$server);
 4185:     return $status;
 4186: }
 4187: 
 4188: sub dcmaildump {
 4189:     my ($dom,$startdate,$enddate,$senders) = @_;
 4190:     my %returnhash=();
 4191: 
 4192:     if (defined(&domain($dom,'primary'))) {
 4193:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 4194:                                                          &escape($enddate).':';
 4195: 	my @esc_senders=map { &escape($_)} @$senders;
 4196: 	$cmd.=&escape(join('&',@esc_senders));
 4197: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 4198:             my ($key,$value) = split(/\=/,$line,2);
 4199:             if (($key) && ($value)) {
 4200:                 $returnhash{&unescape($key)} = &unescape($value);
 4201:             }
 4202:         }
 4203:     }
 4204:     return %returnhash;
 4205: }
 4206: # ---------------------------------------------------------- Domain roles
 4207: 
 4208: sub get_domain_roles {
 4209:     my ($dom,$roles,$startdate,$enddate)=@_;
 4210:     if ((!defined($startdate)) || ($startdate eq '')) {
 4211:         $startdate = '.';
 4212:     }
 4213:     if ((!defined($enddate)) || ($enddate eq '')) {
 4214:         $enddate = '.';
 4215:     }
 4216:     my $rolelist;
 4217:     if (ref($roles) eq 'ARRAY') {
 4218:         $rolelist = join(':',@{$roles});
 4219:     }
 4220:     my %personnel = ();
 4221: 
 4222:     my %servers = &get_servers($dom,'library');
 4223:     foreach my $tryserver (keys(%servers)) {
 4224: 	%{$personnel{$tryserver}}=();
 4225: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 4226: 					    &escape($startdate).':'.
 4227: 					    &escape($enddate).':'.
 4228: 					    &escape($rolelist), $tryserver))) {
 4229: 	    my ($key,$value) = split(/\=/,$line,2);
 4230: 	    if (($key) && ($value)) {
 4231: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 4232: 	    }
 4233: 	}
 4234:     }
 4235:     return %personnel;
 4236: }
 4237: 
 4238: # ----------------------------------------------------------- Interval timing 
 4239: 
 4240: {
 4241: # Caches needed for speedup of navmaps
 4242: # We don't want to cache this for very long at all (5 seconds at most)
 4243: # 
 4244: # The user for whom we cache
 4245: my $cachedkey='';
 4246: # The cached times for this user
 4247: my %cachedtimes=();
 4248: # When this was last done
 4249: my $cachedtime=();
 4250: 
 4251: sub load_all_first_access {
 4252:     my ($uname,$udom)=@_;
 4253:     if (($cachedkey eq $uname.':'.$udom) &&
 4254:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
 4255:         return;
 4256:     }
 4257:     $cachedtime=time;
 4258:     $cachedkey=$uname.':'.$udom;
 4259:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
 4260: }
 4261: 
 4262: sub get_first_access {
 4263:     my ($type,$argsymb,$argmap)=@_;
 4264:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 4265:     if ($argsymb) { $symb=$argsymb; }
 4266:     my ($map,$id,$res)=&decode_symb($symb);
 4267:     if ($argmap) { $map = $argmap; }
 4268:     if ($type eq 'course') {
 4269: 	$res='course';
 4270:     } elsif ($type eq 'map') {
 4271: 	$res=&symbread($map);
 4272:     } else {
 4273: 	$res=$symb;
 4274:     }
 4275:     &load_all_first_access($uname,$udom);
 4276:     return $cachedtimes{"$courseid\0$res"};
 4277: }
 4278: 
 4279: sub set_first_access {
 4280:     my ($type,$interval)=@_;
 4281:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 4282:     my ($map,$id,$res)=&decode_symb($symb);
 4283:     if ($type eq 'course') {
 4284: 	$res='course';
 4285:     } elsif ($type eq 'map') {
 4286: 	$res=&symbread($map);
 4287:     } else {
 4288: 	$res=$symb;
 4289:     }
 4290:     $cachedkey='';
 4291:     my $firstaccess=&get_first_access($type,$symb,$map);
 4292:     if (!$firstaccess) {
 4293:         my $start = time;
 4294: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
 4295:                           $udom,$uname);
 4296:         if ($putres eq 'ok') {
 4297:             &put('timerinterval',{"$courseid\0$res"=>$interval},
 4298:                  $udom,$uname); 
 4299:             &appenv(
 4300:                      {
 4301:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
 4302:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
 4303:                      }
 4304:                   );
 4305:         }
 4306:         return $putres;
 4307:     }
 4308:     return 'already_set';
 4309: }
 4310: }
 4311: # --------------------------------------------- Set Expire Date for Spreadsheet
 4312: 
 4313: sub expirespread {
 4314:     my ($uname,$udom,$stype,$usymb)=@_;
 4315:     my $cid=$env{'request.course.id'}; 
 4316:     if ($cid) {
 4317:        my $now=time;
 4318:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 4319:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 4320:                             $env{'course.'.$cid.'.num'}.
 4321: 	        	    ':nohist_expirationdates:'.
 4322:                             &escape($key).'='.$now,
 4323:                             $env{'course.'.$cid.'.home'})
 4324:     }
 4325:     return 'ok';
 4326: }
 4327: 
 4328: # ----------------------------------------------------- Devalidate Spreadsheets
 4329: 
 4330: sub devalidate {
 4331:     my ($symb,$uname,$udom)=@_;
 4332:     my $cid=$env{'request.course.id'}; 
 4333:     if ($cid) {
 4334:         # delete the stored spreadsheets for
 4335:         # - the student level sheet of this user in course's homespace
 4336:         # - the assessment level sheet for this resource 
 4337:         #   for this user in user's homespace
 4338: 	# - current conditional state info
 4339: 	my $key=$uname.':'.$udom.':';
 4340:         my $status=
 4341: 	    &del('nohist_calculatedsheets',
 4342: 		 [$key.'studentcalc:'],
 4343: 		 $env{'course.'.$cid.'.domain'},
 4344: 		 $env{'course.'.$cid.'.num'})
 4345: 		.' '.
 4346: 	    &del('nohist_calculatedsheets_'.$cid,
 4347: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 4348:         unless ($status eq 'ok ok') {
 4349:            &logthis('Could not devalidate spreadsheet '.
 4350:                     $uname.' at '.$udom.' for '.
 4351: 		    $symb.': '.$status);
 4352:         }
 4353: 	&delenv('user.state.'.$cid);
 4354:     }
 4355: }
 4356: 
 4357: sub get_scalar {
 4358:     my ($string,$end) = @_;
 4359:     my $value;
 4360:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 4361: 	$value = $1;
 4362:     } elsif ($$string =~ s/^([^&]*?)&//) {
 4363: 	$value = $1;
 4364:     }
 4365:     return &unescape($value);
 4366: }
 4367: 
 4368: sub array2str {
 4369:   my (@array) = @_;
 4370:   my $result=&arrayref2str(\@array);
 4371:   $result=~s/^__ARRAY_REF__//;
 4372:   $result=~s/__END_ARRAY_REF__$//;
 4373:   return $result;
 4374: }
 4375: 
 4376: sub arrayref2str {
 4377:   my ($arrayref) = @_;
 4378:   my $result='__ARRAY_REF__';
 4379:   foreach my $elem (@$arrayref) {
 4380:     if(ref($elem) eq 'ARRAY') {
 4381:       $result.=&arrayref2str($elem).'&';
 4382:     } elsif(ref($elem) eq 'HASH') {
 4383:       $result.=&hashref2str($elem).'&';
 4384:     } elsif(ref($elem)) {
 4385:       #print("Got a ref of ".(ref($elem))." skipping.");
 4386:     } else {
 4387:       $result.=&escape($elem).'&';
 4388:     }
 4389:   }
 4390:   $result=~s/\&$//;
 4391:   $result .= '__END_ARRAY_REF__';
 4392:   return $result;
 4393: }
 4394: 
 4395: sub hash2str {
 4396:   my (%hash) = @_;
 4397:   my $result=&hashref2str(\%hash);
 4398:   $result=~s/^__HASH_REF__//;
 4399:   $result=~s/__END_HASH_REF__$//;
 4400:   return $result;
 4401: }
 4402: 
 4403: sub hashref2str {
 4404:   my ($hashref)=@_;
 4405:   my $result='__HASH_REF__';
 4406:   foreach my $key (sort(keys(%$hashref))) {
 4407:     if (ref($key) eq 'ARRAY') {
 4408:       $result.=&arrayref2str($key).'=';
 4409:     } elsif (ref($key) eq 'HASH') {
 4410:       $result.=&hashref2str($key).'=';
 4411:     } elsif (ref($key)) {
 4412:       $result.='=';
 4413:       #print("Got a ref of ".(ref($key))." skipping.");
 4414:     } else {
 4415: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
 4416:     }
 4417: 
 4418:     if(ref($hashref->{$key}) eq 'ARRAY') {
 4419:       $result.=&arrayref2str($hashref->{$key}).'&';
 4420:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 4421:       $result.=&hashref2str($hashref->{$key}).'&';
 4422:     } elsif(ref($hashref->{$key})) {
 4423:        $result.='&';
 4424:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 4425:     } else {
 4426:       $result.=&escape($hashref->{$key}).'&';
 4427:     }
 4428:   }
 4429:   $result=~s/\&$//;
 4430:   $result .= '__END_HASH_REF__';
 4431:   return $result;
 4432: }
 4433: 
 4434: sub str2hash {
 4435:     my ($string)=@_;
 4436:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 4437:     return %$hash;
 4438: }
 4439: 
 4440: sub str2hashref {
 4441:   my ($string) = @_;
 4442: 
 4443:   my %hash;
 4444: 
 4445:   if($string !~ /^__HASH_REF__/) {
 4446:       if (! ($string eq '' || !defined($string))) {
 4447: 	  $hash{'error'}='Not hash reference';
 4448:       }
 4449:       return (\%hash, $string);
 4450:   }
 4451: 
 4452:   $string =~ s/^__HASH_REF__//;
 4453: 
 4454:   while($string !~ /^__END_HASH_REF__/) {
 4455:       #key
 4456:       my $key='';
 4457:       if($string =~ /^__HASH_REF__/) {
 4458:           ($key, $string)=&str2hashref($string);
 4459:           if(defined($key->{'error'})) {
 4460:               $hash{'error'}='Bad data';
 4461:               return (\%hash, $string);
 4462:           }
 4463:       } elsif($string =~ /^__ARRAY_REF__/) {
 4464:           ($key, $string)=&str2arrayref($string);
 4465:           if($key->[0] eq 'Array reference error') {
 4466:               $hash{'error'}='Bad data';
 4467:               return (\%hash, $string);
 4468:           }
 4469:       } else {
 4470:           $string =~ s/^(.*?)=//;
 4471: 	  $key=&unescape($1);
 4472:       }
 4473:       $string =~ s/^=//;
 4474: 
 4475:       #value
 4476:       my $value='';
 4477:       if($string =~ /^__HASH_REF__/) {
 4478:           ($value, $string)=&str2hashref($string);
 4479:           if(defined($value->{'error'})) {
 4480:               $hash{'error'}='Bad data';
 4481:               return (\%hash, $string);
 4482:           }
 4483:       } elsif($string =~ /^__ARRAY_REF__/) {
 4484:           ($value, $string)=&str2arrayref($string);
 4485:           if($value->[0] eq 'Array reference error') {
 4486:               $hash{'error'}='Bad data';
 4487:               return (\%hash, $string);
 4488:           }
 4489:       } else {
 4490: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 4491:       }
 4492:       $string =~ s/^&//;
 4493: 
 4494:       $hash{$key}=$value;
 4495:   }
 4496: 
 4497:   $string =~ s/^__END_HASH_REF__//;
 4498: 
 4499:   return (\%hash, $string);
 4500: }
 4501: 
 4502: sub str2array {
 4503:     my ($string)=@_;
 4504:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 4505:     return @$array;
 4506: }
 4507: 
 4508: sub str2arrayref {
 4509:   my ($string) = @_;
 4510:   my @array;
 4511: 
 4512:   if($string !~ /^__ARRAY_REF__/) {
 4513:       if (! ($string eq '' || !defined($string))) {
 4514: 	  $array[0]='Array reference error';
 4515:       }
 4516:       return (\@array, $string);
 4517:   }
 4518: 
 4519:   $string =~ s/^__ARRAY_REF__//;
 4520: 
 4521:   while($string !~ /^__END_ARRAY_REF__/) {
 4522:       my $value='';
 4523:       if($string =~ /^__HASH_REF__/) {
 4524:           ($value, $string)=&str2hashref($string);
 4525:           if(defined($value->{'error'})) {
 4526:               $array[0] ='Array reference error';
 4527:               return (\@array, $string);
 4528:           }
 4529:       } elsif($string =~ /^__ARRAY_REF__/) {
 4530:           ($value, $string)=&str2arrayref($string);
 4531:           if($value->[0] eq 'Array reference error') {
 4532:               $array[0] ='Array reference error';
 4533:               return (\@array, $string);
 4534:           }
 4535:       } else {
 4536: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 4537:       }
 4538:       $string =~ s/^&//;
 4539: 
 4540:       push(@array, $value);
 4541:   }
 4542: 
 4543:   $string =~ s/^__END_ARRAY_REF__//;
 4544: 
 4545:   return (\@array, $string);
 4546: }
 4547: 
 4548: # -------------------------------------------------------------------Temp Store
 4549: 
 4550: sub tmpreset {
 4551:   my ($symb,$namespace,$domain,$stuname) = @_;
 4552:   if (!$symb) {
 4553:     $symb=&symbread();
 4554:     if (!$symb) { $symb= $env{'request.url'}; }
 4555:   }
 4556:   $symb=escape($symb);
 4557: 
 4558:   if (!$namespace) { $namespace=$env{'request.state'}; }
 4559:   $namespace=~s/\//\_/g;
 4560:   $namespace=~s/\W//g;
 4561: 
 4562:   if (!$domain) { $domain=$env{'user.domain'}; }
 4563:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4564:   if ($domain eq 'public' && $stuname eq 'public') {
 4565:       $stuname=$ENV{'REMOTE_ADDR'};
 4566:   }
 4567:   my $path=LONCAPA::tempdir();
 4568:   my %hash;
 4569:   if (tie(%hash,'GDBM_File',
 4570: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4571: 	  &GDBM_WRCREAT(),0640)) {
 4572:     foreach my $key (keys(%hash)) {
 4573:       if ($key=~ /:$symb/) {
 4574: 	delete($hash{$key});
 4575:       }
 4576:     }
 4577:   }
 4578: }
 4579: 
 4580: sub tmpstore {
 4581:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4582: 
 4583:   if (!$symb) {
 4584:     $symb=&symbread();
 4585:     if (!$symb) { $symb= $env{'request.url'}; }
 4586:   }
 4587:   $symb=escape($symb);
 4588: 
 4589:   if (!$namespace) {
 4590:     # I don't think we would ever want to store this for a course.
 4591:     # it seems this will only be used if we don't have a course.
 4592:     #$namespace=$env{'request.course.id'};
 4593:     #if (!$namespace) {
 4594:       $namespace=$env{'request.state'};
 4595:     #}
 4596:   }
 4597:   $namespace=~s/\//\_/g;
 4598:   $namespace=~s/\W//g;
 4599:   if (!$domain) { $domain=$env{'user.domain'}; }
 4600:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4601:   if ($domain eq 'public' && $stuname eq 'public') {
 4602:       $stuname=$ENV{'REMOTE_ADDR'};
 4603:   }
 4604:   my $now=time;
 4605:   my %hash;
 4606:   my $path=LONCAPA::tempdir();
 4607:   if (tie(%hash,'GDBM_File',
 4608: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4609: 	  &GDBM_WRCREAT(),0640)) {
 4610:     $hash{"version:$symb"}++;
 4611:     my $version=$hash{"version:$symb"};
 4612:     my $allkeys=''; 
 4613:     foreach my $key (keys(%$storehash)) {
 4614:       $allkeys.=$key.':';
 4615:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 4616:     }
 4617:     $hash{"$version:$symb:timestamp"}=$now;
 4618:     $allkeys.='timestamp';
 4619:     $hash{"$version:keys:$symb"}=$allkeys;
 4620:     if (untie(%hash)) {
 4621:       return 'ok';
 4622:     } else {
 4623:       return "error:$!";
 4624:     }
 4625:   } else {
 4626:     return "error:$!";
 4627:   }
 4628: }
 4629: 
 4630: # -----------------------------------------------------------------Temp Restore
 4631: 
 4632: sub tmprestore {
 4633:   my ($symb,$namespace,$domain,$stuname) = @_;
 4634: 
 4635:   if (!$symb) {
 4636:     $symb=&symbread();
 4637:     if (!$symb) { $symb= $env{'request.url'}; }
 4638:   }
 4639:   $symb=escape($symb);
 4640: 
 4641:   if (!$namespace) { $namespace=$env{'request.state'}; }
 4642: 
 4643:   if (!$domain) { $domain=$env{'user.domain'}; }
 4644:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4645:   if ($domain eq 'public' && $stuname eq 'public') {
 4646:       $stuname=$ENV{'REMOTE_ADDR'};
 4647:   }
 4648:   my %returnhash;
 4649:   $namespace=~s/\//\_/g;
 4650:   $namespace=~s/\W//g;
 4651:   my %hash;
 4652:   my $path=LONCAPA::tempdir();
 4653:   if (tie(%hash,'GDBM_File',
 4654: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4655: 	  &GDBM_READER(),0640)) {
 4656:     my $version=$hash{"version:$symb"};
 4657:     $returnhash{'version'}=$version;
 4658:     my $scope;
 4659:     for ($scope=1;$scope<=$version;$scope++) {
 4660:       my $vkeys=$hash{"$scope:keys:$symb"};
 4661:       my @keys=split(/:/,$vkeys);
 4662:       my $key;
 4663:       $returnhash{"$scope:keys"}=$vkeys;
 4664:       foreach $key (@keys) {
 4665: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 4666: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 4667:       }
 4668:     }
 4669:     if (!(untie(%hash))) {
 4670:       return "error:$!";
 4671:     }
 4672:   } else {
 4673:     return "error:$!";
 4674:   }
 4675:   return %returnhash;
 4676: }
 4677: 
 4678: # ----------------------------------------------------------------------- Store
 4679: 
 4680: sub store {
 4681:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4682:     my $home='';
 4683: 
 4684:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4685: 
 4686:     $symb=&symbclean($symb);
 4687:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 4688: 
 4689:     if (!$domain) { $domain=$env{'user.domain'}; }
 4690:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4691: 
 4692:     &devalidate($symb,$stuname,$domain);
 4693: 
 4694:     $symb=escape($symb);
 4695:     if (!$namespace) { 
 4696:        unless ($namespace=$env{'request.course.id'}) { 
 4697:           return ''; 
 4698:        } 
 4699:     }
 4700:     if (!$home) { $home=$env{'user.home'}; }
 4701: 
 4702:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 4703:     $$storehash{'host'}=$perlvar{'lonHostID'};
 4704: 
 4705:     my $namevalue='';
 4706:     foreach my $key (keys(%$storehash)) {
 4707:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4708:     }
 4709:     $namevalue=~s/\&$//;
 4710:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 4711:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 4712: }
 4713: 
 4714: # -------------------------------------------------------------- Critical Store
 4715: 
 4716: sub cstore {
 4717:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4718:     my $home='';
 4719: 
 4720:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4721: 
 4722:     $symb=&symbclean($symb);
 4723:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 4724: 
 4725:     if (!$domain) { $domain=$env{'user.domain'}; }
 4726:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4727: 
 4728:     &devalidate($symb,$stuname,$domain);
 4729: 
 4730:     $symb=escape($symb);
 4731:     if (!$namespace) { 
 4732:        unless ($namespace=$env{'request.course.id'}) { 
 4733:           return ''; 
 4734:        } 
 4735:     }
 4736:     if (!$home) { $home=$env{'user.home'}; }
 4737: 
 4738:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 4739:     $$storehash{'host'}=$perlvar{'lonHostID'};
 4740: 
 4741:     my $namevalue='';
 4742:     foreach my $key (keys(%$storehash)) {
 4743:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4744:     }
 4745:     $namevalue=~s/\&$//;
 4746:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 4747:     return critical
 4748:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 4749: }
 4750: 
 4751: # --------------------------------------------------------------------- Restore
 4752: 
 4753: sub restore {
 4754:     my ($symb,$namespace,$domain,$stuname) = @_;
 4755:     my $home='';
 4756: 
 4757:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4758: 
 4759:     if (!$symb) {
 4760:       unless ($symb=escape(&symbread())) { return ''; }
 4761:     } else {
 4762:       $symb=&escape(&symbclean($symb));
 4763:     }
 4764:     if (!$namespace) { 
 4765:        unless ($namespace=$env{'request.course.id'}) { 
 4766:           return ''; 
 4767:        } 
 4768:     }
 4769:     if (!$domain) { $domain=$env{'user.domain'}; }
 4770:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4771:     if (!$home) { $home=$env{'user.home'}; }
 4772:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 4773: 
 4774:     my %returnhash=();
 4775:     foreach my $line (split(/\&/,$answer)) {
 4776: 	my ($name,$value)=split(/\=/,$line);
 4777:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 4778:     }
 4779:     my $version;
 4780:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 4781:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 4782:           $returnhash{$item}=$returnhash{$version.':'.$item};
 4783:        }
 4784:     }
 4785:     return %returnhash;
 4786: }
 4787: 
 4788: # ---------------------------------------------------------- Course Description
 4789: #
 4790: #  
 4791: 
 4792: sub coursedescription {
 4793:     my ($courseid,$args)=@_;
 4794:     $courseid=~s/^\///;
 4795:     $courseid=~s/\_/\//g;
 4796:     my ($cdomain,$cnum)=split(/\//,$courseid);
 4797:     my $chome=&homeserver($cnum,$cdomain);
 4798:     my $normalid=$cdomain.'_'.$cnum;
 4799:     # need to always cache even if we get errors otherwise we keep 
 4800:     # trying and trying and trying to get the course description.
 4801:     my %envhash=();
 4802:     my %returnhash=();
 4803:     
 4804:     my $expiretime=600;
 4805:     if ($env{'request.course.id'} eq $normalid) {
 4806: 	$expiretime=120;
 4807:     }
 4808: 
 4809:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 4810:     if (!$args->{'freshen_cache'}
 4811: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 4812: 	foreach my $key (keys(%env)) {
 4813: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 4814: 	    my ($setting) = $1;
 4815: 	    $returnhash{$setting} = $env{$key};
 4816: 	}
 4817: 	return %returnhash;
 4818:     }
 4819: 
 4820:     # get the data again
 4821: 
 4822:     if (!$args->{'one_time'}) {
 4823: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 4824:     }
 4825: 
 4826:     if ($chome ne 'no_host') {
 4827:        %returnhash=&dump('environment',$cdomain,$cnum);
 4828:        if (!exists($returnhash{'con_lost'})) {
 4829: 	   my $username = $env{'user.name'}; # Defult username
 4830: 	   if(defined $args->{'user'}) {
 4831: 	       $username = $args->{'user'};
 4832: 	   }
 4833:            $returnhash{'home'}= $chome;
 4834: 	   $returnhash{'domain'} = $cdomain;
 4835: 	   $returnhash{'num'} = $cnum;
 4836:            if (!defined($returnhash{'type'})) {
 4837:                $returnhash{'type'} = 'Course';
 4838:            }
 4839:            while (my ($name,$value) = each %returnhash) {
 4840:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 4841:            }
 4842:            $returnhash{'url'}=&clutter($returnhash{'url'});
 4843:            $returnhash{'fn'}=LONCAPA::tempdir() .
 4844: 	       $username.'_'.$cdomain.'_'.$cnum;
 4845:            $envhash{'course.'.$normalid.'.home'}=$chome;
 4846:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 4847:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 4848:        }
 4849:     }
 4850:     if (!$args->{'one_time'}) {
 4851: 	&appenv(\%envhash);
 4852:     }
 4853:     return %returnhash;
 4854: }
 4855: 
 4856: sub update_released_required {
 4857:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
 4858:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
 4859:         $cid = $env{'request.course.id'};
 4860:         $cdom = $env{'course.'.$cid.'.domain'};
 4861:         $cnum = $env{'course.'.$cid.'.num'};
 4862:         $chome = $env{'course.'.$cid.'.home'};
 4863:     }
 4864:     if ($needsrelease) {
 4865:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
 4866:         my $needsupdate;
 4867:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
 4868:             $needsupdate = 1;
 4869:         } else {
 4870:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
 4871:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
 4872:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
 4873:                 $needsupdate = 1;
 4874:             }
 4875:         }
 4876:         if ($needsupdate) {
 4877:             my %needshash = (
 4878:                              'internal.releaserequired' => $needsrelease,
 4879:                             );
 4880:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
 4881:             if ($putresult eq 'ok') {
 4882:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
 4883:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 4884:                 if (ref($crsinfo{$cid}) eq 'HASH') {
 4885:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
 4886:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
 4887:                 }
 4888:             }
 4889:         }
 4890:     }
 4891:     return;
 4892: }
 4893: 
 4894: # -------------------------------------------------See if a user is privileged
 4895: 
 4896: sub privileged {
 4897:     my ($username,$domain)=@_;
 4898: 
 4899:     my %rolesdump = &dump("roles", $domain, $username) or return 0;
 4900:     my $now = time;
 4901: 
 4902:     for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys %rolesdump}) {
 4903:             my ($trole, $tend, $tstart) = split(/_/, $role);
 4904:             if (($trole eq 'dc') || ($trole eq 'su')) {
 4905:                 return 1 unless ($tend && $tend < $now) 
 4906:                     or ($tstart && $tstart > $now);
 4907:             }
 4908: 	}
 4909: 
 4910:     return 0;
 4911: }
 4912: 
 4913: # -------------------------------------------------------- Get user privileges
 4914: 
 4915: sub rolesinit {
 4916:     my ($domain, $username) = @_;
 4917:     my %userroles = ('user.login.time' => time);
 4918:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
 4919: 
 4920:     # firstaccess and timerinterval are related to timed maps/resources. 
 4921:     # also, blocking can be triggered by an activating timer
 4922:     # it's saved in the user's %env.
 4923:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
 4924:     my %timerinterval = &dump('timerinterval', $domain, $username);
 4925:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
 4926:         %timerintchk, %timerintenv);
 4927: 
 4928:     foreach my $key (keys(%firstaccess)) {
 4929:         my ($cid, $rest) = split(/\0/, $key);
 4930:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
 4931:     }
 4932: 
 4933:     foreach my $key (keys(%timerinterval)) {
 4934:         my ($cid,$rest) = split(/\0/,$key);
 4935:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
 4936:     }
 4937: 
 4938:     my %allroles=();
 4939:     my %allgroups=();
 4940: 
 4941:     for my $area (grep { ! /^rolesdef_/ } keys %rolesdump) {
 4942:         my $role = $rolesdump{$area};
 4943:         $area =~ s/\_\w\w$//;
 4944: 
 4945:         my ($trole, $tend, $tstart, $group_privs);
 4946: 
 4947:         if ($role =~ /^cr/) {
 4948:         # Custom role, defined by a user 
 4949:         # e.g., user.role.cr/msu/smith/mynewrole
 4950:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 4951:                 $trole = $1;
 4952:                 ($tend, $tstart) = split('_', $2);
 4953:             } else {
 4954:                 $trole = $role;
 4955:             }
 4956:         } elsif ($role =~ m|^gr/|) {
 4957:         # Role of member in a group, defined within a course/community
 4958:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
 4959:             ($trole, $tend, $tstart) = split(/_/, $role);
 4960:             next if $tstart eq '-1';
 4961:             ($trole, $group_privs) = split(/\//, $trole);
 4962:             $group_privs = &unescape($group_privs);
 4963:         } else {
 4964:         # Just a normal role, defined in roles.tab
 4965:             ($trole, $tend, $tstart) = split(/_/,$role);
 4966:         }
 4967: 
 4968:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 4969:                  $username);
 4970:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 4971: 
 4972:         # role expired or not available yet?
 4973:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
 4974:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
 4975: 
 4976:         next if $area eq '' or $trole eq '';
 4977: 
 4978:         my $spec = "$trole.$area";
 4979:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
 4980: 
 4981:         if ($trole =~ /^cr\//) {
 4982:         # Custom role, defined by a user
 4983:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 4984:         } elsif ($trole eq 'gr') {
 4985:         # Role of a member in a group, defined within a course/community
 4986:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 4987:             next;
 4988:         } else {
 4989:         # Normal role, defined in roles.tab
 4990:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 4991:         }
 4992: 
 4993:         my $cid = $tdomain.'_'.$trest;
 4994:         unless ($firstaccchk{$cid}) {
 4995:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
 4996:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
 4997:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
 4998:                         $coursetimerstarts{$cid}{$item}; 
 4999:                 }
 5000:             }
 5001:             $firstaccchk{$cid} = 1;
 5002:         }
 5003:         unless ($timerintchk{$cid}) {
 5004:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
 5005:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
 5006:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
 5007:                        $coursetimerintervals{$cid}{$item};
 5008:                 }
 5009:             }
 5010:             $timerintchk{$cid} = 1;
 5011:         }
 5012:     }
 5013: 
 5014:     @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
 5015:         \%allroles, \%allgroups);
 5016:     $env{'user.adv'} = $userroles{'user.adv'};
 5017: 
 5018:     return (\%userroles,\%firstaccenv,\%timerintenv);
 5019: }
 5020: 
 5021: sub set_arearole {
 5022:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
 5023: # log the associated role with the area
 5024:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 5025:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 5026: }
 5027: 
 5028: sub custom_roleprivs {
 5029:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 5030:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 5031:     my $homsvr=homeserver($rauthor,$rdomain);
 5032:     if (&hostname($homsvr) ne '') {
 5033:         my ($rdummy,$roledef)=
 5034:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 5035:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 5036:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 5037:             if (defined($syspriv)) {
 5038:                 if ($trest =~ /^$match_community$/) {
 5039:                     $syspriv =~ s/bre\&S//; 
 5040:                 }
 5041:                 $$allroles{'cm./'}.=':'.$syspriv;
 5042:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 5043:             }
 5044:             if ($tdomain ne '') {
 5045:                 if (defined($dompriv)) {
 5046:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 5047:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 5048:                 }
 5049:                 if (($trest ne '') && (defined($coursepriv))) {
 5050:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 5051:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 5052:                 }
 5053:             }
 5054:         }
 5055:     }
 5056: }
 5057: 
 5058: sub group_roleprivs {
 5059:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 5060:     my $access = 1;
 5061:     my $now = time;
 5062:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 5063:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 5064:     if ($access) {
 5065:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 5066:         $$allgroups{$course}{$group} .=':'.$group_privs;
 5067:     }
 5068: }
 5069: 
 5070: sub standard_roleprivs {
 5071:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 5072:     if (defined($pr{$trole.':s'})) {
 5073:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 5074:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 5075:     }
 5076:     if ($tdomain ne '') {
 5077:         if (defined($pr{$trole.':d'})) {
 5078:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 5079:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 5080:         }
 5081:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 5082:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 5083:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 5084:         }
 5085:     }
 5086: }
 5087: 
 5088: sub set_userprivs {
 5089:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
 5090:     my $author=0;
 5091:     my $adv=0;
 5092:     my %grouproles = ();
 5093:     if (keys(%{$allgroups}) > 0) {
 5094:         my @groupkeys; 
 5095:         foreach my $role (keys(%{$allroles})) {
 5096:             push(@groupkeys,$role);
 5097:         }
 5098:         if (ref($groups_roles) eq 'HASH') {
 5099:             foreach my $key (keys(%{$groups_roles})) {
 5100:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
 5101:                     push(@groupkeys,$key);
 5102:                 }
 5103:             }
 5104:         }
 5105:         if (@groupkeys > 0) {
 5106:             foreach my $role (@groupkeys) {
 5107:                 my ($trole,$area,$sec,$extendedarea);
 5108:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 5109:                     $trole = $1;
 5110:                     $area = $2;
 5111:                     $sec = $3;
 5112:                     $extendedarea = $area.$sec;
 5113:                     if (exists($$allgroups{$area})) {
 5114:                         foreach my $group (keys(%{$$allgroups{$area}})) {
 5115:                             my $spec = $trole.'.'.$extendedarea;
 5116:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
 5117:                                                 $$allgroups{$area}{$group};
 5118:                         }
 5119:                     }
 5120:                 }
 5121:             }
 5122:         }
 5123:     }
 5124:     foreach my $group (keys(%grouproles)) {
 5125:         $$allroles{$group} = $grouproles{$group};
 5126:     }
 5127:     foreach my $role (keys(%{$allroles})) {
 5128:         my %thesepriv;
 5129:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 5130:         foreach my $item (split(/:/,$$allroles{$role})) {
 5131:             if ($item ne '') {
 5132:                 my ($privilege,$restrictions)=split(/&/,$item);
 5133:                 if ($restrictions eq '') {
 5134:                     $thesepriv{$privilege}='F';
 5135:                 } elsif ($thesepriv{$privilege} ne 'F') {
 5136:                     $thesepriv{$privilege}.=$restrictions;
 5137:                 }
 5138:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 5139:             }
 5140:         }
 5141:         my $thesestr='';
 5142:         foreach my $priv (sort(keys(%thesepriv))) {
 5143: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 5144: 	}
 5145:         $userroles->{'user.priv.'.$role} = $thesestr;
 5146:     }
 5147:     return ($author,$adv);
 5148: }
 5149: 
 5150: sub role_status {
 5151:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 5152:     my @pwhere = ();
 5153:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 5154:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
 5155:         unless (!defined($$role) || $$role eq '') {
 5156:             $$where=join('.',@pwhere);
 5157:             $$trolecode=$$role.'.'.$$where;
 5158:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 5159:             $$tstatus='is';
 5160:             if ($$tstart && $$tstart>$update) {
 5161:                 $$tstatus='future';
 5162:                 if ($$tstart<$now) {
 5163:                     if ($$tstart && $$tstart>$refresh) {
 5164:                         if (($$where ne '') && ($$role ne '')) {
 5165:                             my (%allroles,%allgroups,$group_privs,
 5166:                                 %groups_roles,@rolecodes);
 5167:                             my %userroles = (
 5168:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 5169:                             );
 5170:                             @rolecodes = ('cm'); 
 5171:                             my $spec=$$role.'.'.$$where;
 5172:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 5173:                             if ($$role =~ /^cr\//) {
 5174:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 5175:                                 push(@rolecodes,'cr');
 5176:                             } elsif ($$role eq 'gr') {
 5177:                                 push(@rolecodes,$$role);
 5178:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 5179:                                                     $env{'user.name'});
 5180:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
 5181:                                 (undef,my $group_privs) = split(/\//,$trole);
 5182:                                 $group_privs = &unescape($group_privs);
 5183:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 5184:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
 5185:                                 &get_groups_roles($tdomain,$trest,
 5186:                                                   \%course_roles,\@rolecodes,
 5187:                                                   \%groups_roles);
 5188:                             } else {
 5189:                                 push(@rolecodes,$$role);
 5190:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 5191:                             }
 5192:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
 5193:                             &appenv(\%userroles,\@rolecodes);
 5194:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 5195:                         }
 5196:                     }
 5197:                     $$tstatus = 'is';
 5198:                 }
 5199:             }
 5200:             if ($$tend) {
 5201:                 if ($$tend<$update) {
 5202:                     $$tstatus='expired';
 5203:                 } elsif ($$tend<$now) {
 5204:                     $$tstatus='will_not';
 5205:                 }
 5206:             }
 5207:         }
 5208:     }
 5209: }
 5210: 
 5211: sub get_groups_roles {
 5212:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
 5213:     return unless((ref($cdom_courseroles) eq 'HASH') && 
 5214:                   (ref($rolecodes) eq 'ARRAY') && 
 5215:                   (ref($groups_roles) eq 'HASH')); 
 5216:     if (keys(%{$cdom_courseroles}) > 0) {
 5217:         my ($cnum) = ($rest =~ /^($match_courseid)/);
 5218:         if ($cdom ne '' && $cnum ne '') {
 5219:             foreach my $key (keys(%{$cdom_courseroles})) {
 5220:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
 5221:                     my $crsrole = $1;
 5222:                     my $crssec = $2;
 5223:                     if ($crsrole =~ /^cr/) {
 5224:                         unless (grep(/^cr$/,@{$rolecodes})) {
 5225:                             push(@{$rolecodes},'cr');
 5226:                         }
 5227:                     } else {
 5228:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
 5229:                             push(@{$rolecodes},$crsrole);
 5230:                         }
 5231:                     }
 5232:                     my $rolekey = "$crsrole./$cdom/$cnum";
 5233:                     if ($crssec ne '') {
 5234:                         $rolekey .= "/$crssec";
 5235:                     }
 5236:                     $rolekey .= './';
 5237:                     $groups_roles->{$rolekey} = $rolecodes;
 5238:                 }
 5239:             }
 5240:         }
 5241:     }
 5242:     return;
 5243: }
 5244: 
 5245: sub delete_env_groupprivs {
 5246:     my ($where,$courseroles,$possroles) = @_;
 5247:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
 5248:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
 5249:     unless (ref($courseroles->{$udom}) eq 'HASH') {
 5250:         %{$courseroles->{$udom}} =
 5251:             &get_my_roles('','','userroles',['active'],
 5252:                           $possroles,[$udom],1);
 5253:     }
 5254:     if (ref($courseroles->{$udom}) eq 'HASH') {
 5255:         foreach my $item (keys(%{$courseroles->{$udom}})) {
 5256:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
 5257:             my $area = '/'.$cdom.'/'.$cnum;
 5258:             my $privkey = "user.priv.$crsrole.$area";
 5259:             if ($crssec ne '') {
 5260:                 $privkey .= '/'.$crssec;
 5261:             }
 5262:             $privkey .= ".$area/$group";
 5263:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
 5264:         }
 5265:     }
 5266:     return;
 5267: }
 5268: 
 5269: sub check_adhoc_privs {
 5270:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
 5271:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 5272:     my $setprivs;
 5273:     if ($env{$cckey}) {
 5274:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 5275:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 5276:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 5277:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
 5278:             $setprivs = 1;
 5279:         }
 5280:     } else {
 5281:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
 5282:         $setprivs = 1;
 5283:     }
 5284:     return $setprivs;
 5285: }
 5286: 
 5287: sub set_adhoc_privileges {
 5288: # role can be cc or ca
 5289:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
 5290:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 5291:     my $spec = $role.'.'.$area;
 5292:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 5293:                                   $env{'user.name'});
 5294:     my %ccrole = ();
 5295:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
 5296:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
 5297:     &appenv(\%userroles,[$role,'cm']);
 5298:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 5299:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
 5300:         &appenv( {'request.role'        => $spec,
 5301:                   'request.role.domain' => $dcdom,
 5302:                   'request.course.sec'  => ''
 5303:                  }
 5304:                );
 5305:         my $tadv=0;
 5306:         if (&allowed('adv') eq 'F') { $tadv=1; }
 5307:         &appenv({'request.role.adv'    => $tadv});
 5308:     }
 5309: }
 5310: 
 5311: # --------------------------------------------------------------- get interface
 5312: 
 5313: sub get {
 5314:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5315:    my $items='';
 5316:    foreach my $item (@$storearr) {
 5317:        $items.=&escape($item).'&';
 5318:    }
 5319:    $items=~s/\&$//;
 5320:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5321:    if (!$uname) { $uname=$env{'user.name'}; }
 5322:    my $uhome=&homeserver($uname,$udomain);
 5323: 
 5324:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 5325:    my @pairs=split(/\&/,$rep);
 5326:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 5327:      return @pairs;
 5328:    }
 5329:    my %returnhash=();
 5330:    my $i=0;
 5331:    foreach my $item (@$storearr) {
 5332:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 5333:       $i++;
 5334:    }
 5335:    return %returnhash;
 5336: }
 5337: 
 5338: # --------------------------------------------------------------- del interface
 5339: 
 5340: sub del {
 5341:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5342:    my $items='';
 5343:    foreach my $item (@$storearr) {
 5344:        $items.=&escape($item).'&';
 5345:    }
 5346: 
 5347:    $items=~s/\&$//;
 5348:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5349:    if (!$uname) { $uname=$env{'user.name'}; }
 5350:    my $uhome=&homeserver($uname,$udomain);
 5351:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 5352: }
 5353: 
 5354: # -------------------------------------------------------------- dump interface
 5355: 
 5356: sub unserialize {
 5357:     my ($rep, $escapedkeys) = @_;
 5358: 
 5359:     return {} if $rep =~ /^error/;
 5360: 
 5361:     my %returnhash=();
 5362: 	foreach my $item (split /\&/, $rep) {
 5363: 	    my ($key, $value) = split(/=/, $item, 2);
 5364: 	    $key = unescape($key) unless $escapedkeys;
 5365: 	    next if $key =~ /^error: 2 /;
 5366: 	    $returnhash{$key} = Apache::lonnet::thaw_unescape($value);
 5367: 	}
 5368:     #return %returnhash;
 5369:     return \%returnhash;
 5370: }        
 5371: 
 5372: # see Lond::dump_with_regexp
 5373: # if $escapedkeys hash keys won't get unescaped.
 5374: sub dump {
 5375:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
 5376:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5377:     if (!$uname) { $uname=$env{'user.name'}; }
 5378:     my $uhome=&homeserver($uname,$udomain);
 5379: 
 5380:     my $reply;
 5381:     if (grep { $_ eq $uhome } current_machine_ids()) {
 5382:         # user is hosted on this machine
 5383:         $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
 5384:                     $uname, $namespace, $regexp, $range)), $loncaparevs{$uhome});
 5385:         return %{unserialize($reply, $escapedkeys)};
 5386:     }
 5387:     if ($regexp) {
 5388: 	$regexp=&escape($regexp);
 5389:     } else {
 5390: 	$regexp='.';
 5391:     }
 5392:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 5393:     my @pairs=split(/\&/,$rep);
 5394:     my %returnhash=();
 5395:     if (!($rep =~ /^error/ )) {
 5396: 	foreach my $item (@pairs) {
 5397: 	    my ($key,$value)=split(/=/,$item,2);
 5398:         $key = unescape($key) unless $escapedkeys;
 5399:         #$key = &unescape($key);
 5400: 	    next if ($key =~ /^error: 2 /);
 5401: 	    $returnhash{$key}=&thaw_unescape($value);
 5402: 	}
 5403:     }
 5404:     return %returnhash;
 5405: }
 5406: 
 5407: 
 5408: # --------------------------------------------------------- dumpstore interface
 5409: 
 5410: sub dumpstore {
 5411:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 5412:    # same as dump but keys must be escaped. They may contain colon separated
 5413:    # lists of values that may themself contain colons (e.g. symbs).
 5414:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
 5415: }
 5416: 
 5417: # -------------------------------------------------------------- keys interface
 5418: 
 5419: sub getkeys {
 5420:    my ($namespace,$udomain,$uname)=@_;
 5421:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5422:    if (!$uname) { $uname=$env{'user.name'}; }
 5423:    my $uhome=&homeserver($uname,$udomain);
 5424:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 5425:    my @keyarray=();
 5426:    foreach my $key (split(/\&/,$rep)) {
 5427:       next if ($key =~ /^error: 2 /);
 5428:       push(@keyarray,&unescape($key));
 5429:    }
 5430:    return @keyarray;
 5431: }
 5432: 
 5433: # --------------------------------------------------------------- currentdump
 5434: sub currentdump {
 5435:    my ($courseid,$sdom,$sname)=@_;
 5436:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 5437:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 5438:    $sname    = $env{'user.name'}         if (! defined($sname));
 5439:    my $uhome = &homeserver($sname,$sdom);
 5440:    my $rep;
 5441: 
 5442:    if (grep { $_ eq $uhome } current_machine_ids()) {
 5443:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
 5444:                    $courseid)));
 5445:    } else {
 5446:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 5447:    }
 5448: 
 5449:    return if ($rep =~ /^(error:|no_such_host)/);
 5450:    #
 5451:    my %returnhash=();
 5452:    #
 5453:    if ($rep eq "unknown_cmd") { 
 5454:        # an old lond will not know currentdump
 5455:        # Do a dump and make it look like a currentdump
 5456:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 5457:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 5458:        my %hash = @tmp;
 5459:        @tmp=();
 5460:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 5461:    } else {
 5462:        my @pairs=split(/\&/,$rep);
 5463:        foreach my $pair (@pairs) {
 5464:            my ($key,$value)=split(/=/,$pair,2);
 5465:            my ($symb,$param) = split(/:/,$key);
 5466:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 5467:                                                         &thaw_unescape($value);
 5468:        }
 5469:    }
 5470:    return %returnhash;
 5471: }
 5472: 
 5473: sub convert_dump_to_currentdump{
 5474:     my %hash = %{shift()};
 5475:     my %returnhash;
 5476:     # Code ripped from lond, essentially.  The only difference
 5477:     # here is the unescaping done by lonnet::dump().  Conceivably
 5478:     # we might run in to problems with parameter names =~ /^v\./
 5479:     while (my ($key,$value) = each(%hash)) {
 5480:         my ($v,$symb,$param) = split(/:/,$key);
 5481: 	$symb  = &unescape($symb);
 5482: 	$param = &unescape($param);
 5483:         next if ($v eq 'version' || $symb eq 'keys');
 5484:         next if (exists($returnhash{$symb}) &&
 5485:                  exists($returnhash{$symb}->{$param}) &&
 5486:                  $returnhash{$symb}->{'v.'.$param} > $v);
 5487:         $returnhash{$symb}->{$param}=$value;
 5488:         $returnhash{$symb}->{'v.'.$param}=$v;
 5489:     }
 5490:     #
 5491:     # Remove all of the keys in the hashes which keep track of
 5492:     # the version of the parameter.
 5493:     while (my ($symb,$param_hash) = each(%returnhash)) {
 5494:         # use a foreach because we are going to delete from the hash.
 5495:         foreach my $key (keys(%$param_hash)) {
 5496:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 5497:         }
 5498:     }
 5499:     return \%returnhash;
 5500: }
 5501: 
 5502: # ------------------------------------------------------ critical inc interface
 5503: 
 5504: sub cinc {
 5505:     return &inc(@_,'critical');
 5506: }
 5507: 
 5508: # --------------------------------------------------------------- inc interface
 5509: 
 5510: sub inc {
 5511:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 5512:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5513:     if (!$uname) { $uname=$env{'user.name'}; }
 5514:     my $uhome=&homeserver($uname,$udomain);
 5515:     my $items='';
 5516:     if (! ref($store)) {
 5517:         # got a single value, so use that instead
 5518:         $items = &escape($store).'=&';
 5519:     } elsif (ref($store) eq 'SCALAR') {
 5520:         $items = &escape($$store).'=&';        
 5521:     } elsif (ref($store) eq 'ARRAY') {
 5522:         $items = join('=&',map {&escape($_);} @{$store});
 5523:     } elsif (ref($store) eq 'HASH') {
 5524:         while (my($key,$value) = each(%{$store})) {
 5525:             $items.= &escape($key).'='.&escape($value).'&';
 5526:         }
 5527:     }
 5528:     $items=~s/\&$//;
 5529:     if ($critical) {
 5530: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 5531:     } else {
 5532: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 5533:     }
 5534: }
 5535: 
 5536: # --------------------------------------------------------------- put interface
 5537: 
 5538: sub put {
 5539:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5540:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5541:    if (!$uname) { $uname=$env{'user.name'}; }
 5542:    my $uhome=&homeserver($uname,$udomain);
 5543:    my $items='';
 5544:    foreach my $item (keys(%$storehash)) {
 5545:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5546:    }
 5547:    $items=~s/\&$//;
 5548:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 5549: }
 5550: 
 5551: # ------------------------------------------------------------ newput interface
 5552: 
 5553: sub newput {
 5554:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5555:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5556:    if (!$uname) { $uname=$env{'user.name'}; }
 5557:    my $uhome=&homeserver($uname,$udomain);
 5558:    my $items='';
 5559:    foreach my $key (keys(%$storehash)) {
 5560:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 5561:    }
 5562:    $items=~s/\&$//;
 5563:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 5564: }
 5565: 
 5566: # ---------------------------------------------------------  putstore interface
 5567: 
 5568: sub putstore {
 5569:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 5570:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5571:    if (!$uname) { $uname=$env{'user.name'}; }
 5572:    my $uhome=&homeserver($uname,$udomain);
 5573:    my $items='';
 5574:    foreach my $key (keys(%$storehash)) {
 5575:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 5576:    }
 5577:    $items=~s/\&$//;
 5578:    my $esc_symb=&escape($symb);
 5579:    my $esc_v=&escape($version);
 5580:    my $reply =
 5581:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 5582: 	      $uhome);
 5583:    if ($reply eq 'unknown_cmd') {
 5584:        # gfall back to way things use to be done
 5585:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 5586: 			    $uname);
 5587:    }
 5588:    return $reply;
 5589: }
 5590: 
 5591: sub old_putstore {
 5592:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 5593:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5594:     if (!$uname) { $uname=$env{'user.name'}; }
 5595:     my $uhome=&homeserver($uname,$udomain);
 5596:     my %newstorehash;
 5597:     foreach my $item (keys(%$storehash)) {
 5598: 	my $key = $version.':'.&escape($symb).':'.$item;
 5599: 	$newstorehash{$key} = $storehash->{$item};
 5600:     }
 5601:     my $items='';
 5602:     my %allitems = ();
 5603:     foreach my $item (keys(%newstorehash)) {
 5604: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 5605: 	    my $key = $1.':keys:'.$2;
 5606: 	    $allitems{$key} .= $3.':';
 5607: 	}
 5608: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 5609:     }
 5610:     foreach my $item (keys(%allitems)) {
 5611: 	$allitems{$item} =~ s/\:$//;
 5612: 	$items.= $item.'='.$allitems{$item}.'&';
 5613:     }
 5614:     $items=~s/\&$//;
 5615:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 5616: }
 5617: 
 5618: # ------------------------------------------------------ critical put interface
 5619: 
 5620: sub cput {
 5621:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5622:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5623:    if (!$uname) { $uname=$env{'user.name'}; }
 5624:    my $uhome=&homeserver($uname,$udomain);
 5625:    my $items='';
 5626:    foreach my $item (keys(%$storehash)) {
 5627:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5628:    }
 5629:    $items=~s/\&$//;
 5630:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 5631: }
 5632: 
 5633: # -------------------------------------------------------------- eget interface
 5634: 
 5635: sub eget {
 5636:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5637:    my $items='';
 5638:    foreach my $item (@$storearr) {
 5639:        $items.=&escape($item).'&';
 5640:    }
 5641:    $items=~s/\&$//;
 5642:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5643:    if (!$uname) { $uname=$env{'user.name'}; }
 5644:    my $uhome=&homeserver($uname,$udomain);
 5645:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 5646:    my @pairs=split(/\&/,$rep);
 5647:    my %returnhash=();
 5648:    my $i=0;
 5649:    foreach my $item (@$storearr) {
 5650:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 5651:       $i++;
 5652:    }
 5653:    return %returnhash;
 5654: }
 5655: 
 5656: # ------------------------------------------------------------ tmpput interface
 5657: sub tmpput {
 5658:     my ($storehash,$server,$context)=@_;
 5659:     my $items='';
 5660:     foreach my $item (keys(%$storehash)) {
 5661: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5662:     }
 5663:     $items=~s/\&$//;
 5664:     if (defined($context)) {
 5665:         $items .= ':'.&escape($context);
 5666:     }
 5667:     return &reply("tmpput:$items",$server);
 5668: }
 5669: 
 5670: # ------------------------------------------------------------ tmpget interface
 5671: sub tmpget {
 5672:     my ($token,$server)=@_;
 5673:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 5674:     my $rep=&reply("tmpget:$token",$server);
 5675:     my %returnhash;
 5676:     foreach my $item (split(/\&/,$rep)) {
 5677: 	my ($key,$value)=split(/=/,$item);
 5678:         next if ($key =~ /^error: 2 /);
 5679: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 5680:     }
 5681:     return %returnhash;
 5682: }
 5683: 
 5684: # ------------------------------------------------------------ tmpdel interface
 5685: sub tmpdel {
 5686:     my ($token,$server)=@_;
 5687:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 5688:     return &reply("tmpdel:$token",$server);
 5689: }
 5690: 
 5691: # -------------------------------------------------- portfolio access checking
 5692: 
 5693: sub portfolio_access {
 5694:     my ($requrl) = @_;
 5695:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 5696:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
 5697:     if ($result) {
 5698:         my %setters;
 5699:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 5700:             my ($startblock,$endblock) =
 5701:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 5702:             if ($startblock && $endblock) {
 5703:                 return 'B';
 5704:             }
 5705:         } else {
 5706:             my ($startblock,$endblock) =
 5707:                 &Apache::loncommon::blockcheck(\%setters,'port');
 5708:             if ($startblock && $endblock) {
 5709:                 return 'B';
 5710:             }
 5711:         }
 5712:     }
 5713:     if ($result eq 'ok') {
 5714:        return 'F';
 5715:     } elsif ($result =~ /^[^:]+:guest_/) {
 5716:        return 'A';
 5717:     }
 5718:     return '';
 5719: }
 5720: 
 5721: sub get_portfolio_access {
 5722:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
 5723: 
 5724:     if (!ref($access_hash)) {
 5725: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 5726: 	my %access_controls = &get_access_controls($current_perms,$group,
 5727: 						   $file_name);
 5728: 	$access_hash = $access_controls{$file_name};
 5729:     }
 5730: 
 5731:     my ($public,$guest,@domains,@users,@courses,@groups);
 5732:     my $now = time;
 5733:     if (ref($access_hash) eq 'HASH') {
 5734:         foreach my $key (keys(%{$access_hash})) {
 5735:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 5736:             if ($start > $now) {
 5737:                 next;
 5738:             }
 5739:             if ($end && $end<$now) {
 5740:                 next;
 5741:             }
 5742:             if ($scope eq 'public') {
 5743:                 $public = $key;
 5744:                 last;
 5745:             } elsif ($scope eq 'guest') {
 5746:                 $guest = $key;
 5747:             } elsif ($scope eq 'domains') {
 5748:                 push(@domains,$key);
 5749:             } elsif ($scope eq 'users') {
 5750:                 push(@users,$key);
 5751:             } elsif ($scope eq 'course') {
 5752:                 push(@courses,$key);
 5753:             } elsif ($scope eq 'group') {
 5754:                 push(@groups,$key);
 5755:             }
 5756:         }
 5757:         if ($public) {
 5758:             return 'ok';
 5759:         }
 5760:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 5761:             if ($guest) {
 5762:                 return $guest;
 5763:             }
 5764:         } else {
 5765:             if (@domains > 0) {
 5766:                 foreach my $domkey (@domains) {
 5767:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 5768:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 5769:                             return 'ok';
 5770:                         }
 5771:                     }
 5772:                 }
 5773:             }
 5774:             if (@users > 0) {
 5775:                 foreach my $userkey (@users) {
 5776:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 5777:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 5778:                             if (ref($item) eq 'HASH') {
 5779:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 5780:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 5781:                                     return 'ok';
 5782:                                 }
 5783:                             }
 5784:                         }
 5785:                     } 
 5786:                 }
 5787:             }
 5788:             my %roleshash;
 5789:             my @courses_and_groups = @courses;
 5790:             push(@courses_and_groups,@groups); 
 5791:             if (@courses_and_groups > 0) {
 5792:                 my (%allgroups,%allroles); 
 5793:                 my ($start,$end,$role,$sec,$group);
 5794:                 foreach my $envkey (%env) {
 5795:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 5796:                         my $cid = $2.'_'.$3; 
 5797:                         if ($1 eq 'gr') {
 5798:                             $group = $4;
 5799:                             $allgroups{$cid}{$group} = $env{$envkey};
 5800:                         } else {
 5801:                             if ($4 eq '') {
 5802:                                 $sec = 'none';
 5803:                             } else {
 5804:                                 $sec = $4;
 5805:                             }
 5806:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 5807:                         }
 5808:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 5809:                         my $cid = $2.'_'.$3;
 5810:                         if ($4 eq '') {
 5811:                             $sec = 'none';
 5812:                         } else {
 5813:                             $sec = $4;
 5814:                         }
 5815:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 5816:                     }
 5817:                 }
 5818:                 if (keys(%allroles) == 0) {
 5819:                     return;
 5820:                 }
 5821:                 foreach my $key (@courses_and_groups) {
 5822:                     my %content = %{$$access_hash{$key}};
 5823:                     my $cnum = $content{'number'};
 5824:                     my $cdom = $content{'domain'};
 5825:                     my $cid = $cdom.'_'.$cnum;
 5826:                     if (!exists($allroles{$cid})) {
 5827:                         next;
 5828:                     }    
 5829:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 5830:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 5831:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 5832:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 5833:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 5834:                         foreach my $role (keys(%{$allroles{$cid}})) {
 5835:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 5836:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 5837:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 5838:                                         if (grep/^all$/,@sections) {
 5839:                                             return 'ok';
 5840:                                         } else {
 5841:                                             if (grep/^$sec$/,@sections) {
 5842:                                                 return 'ok';
 5843:                                             }
 5844:                                         }
 5845:                                     }
 5846:                                 }
 5847:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 5848:                                     if (grep/^none$/,@groups) {
 5849:                                         return 'ok';
 5850:                                     }
 5851:                                 } else {
 5852:                                     if (grep/^all$/,@groups) {
 5853:                                         return 'ok';
 5854:                                     } 
 5855:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 5856:                                         if (grep/^$group$/,@groups) {
 5857:                                             return 'ok';
 5858:                                         }
 5859:                                     }
 5860:                                 } 
 5861:                             }
 5862:                         }
 5863:                     }
 5864:                 }
 5865:             }
 5866:             if ($guest) {
 5867:                 return $guest;
 5868:             }
 5869:         }
 5870:     }
 5871:     return;
 5872: }
 5873: 
 5874: sub course_group_datechecker {
 5875:     my ($dates,$now,$status) = @_;
 5876:     my ($start,$end) = split(/\./,$dates);
 5877:     if (!$start && !$end) {
 5878:         return 'ok';
 5879:     }
 5880:     if (grep/^active$/,@{$status}) {
 5881:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 5882:             return 'ok';
 5883:         }
 5884:     }
 5885:     if (grep/^previous$/,@{$status}) {
 5886:         if ($end > $now ) {
 5887:             return 'ok';
 5888:         }
 5889:     }
 5890:     if (grep/^future$/,@{$status}) {
 5891:         if ($start > $now) {
 5892:             return 'ok';
 5893:         }
 5894:     }
 5895:     return; 
 5896: }
 5897: 
 5898: sub parse_portfolio_url {
 5899:     my ($url) = @_;
 5900: 
 5901:     my ($type,$udom,$unum,$group,$file_name);
 5902:     
 5903:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 5904: 	$type = 1;
 5905:         $udom = $1;
 5906:         $unum = $2;
 5907:         $file_name = $3;
 5908:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 5909: 	$type = 2;
 5910:         $udom = $1;
 5911:         $unum = $2;
 5912:         $group = $3;
 5913:         $file_name = $3.'/'.$4;
 5914:     }
 5915:     if (wantarray) {
 5916: 	return ($type,$udom,$unum,$file_name,$group);
 5917:     }
 5918:     return $type;
 5919: }
 5920: 
 5921: sub is_portfolio_url {
 5922:     my ($url) = @_;
 5923:     return scalar(&parse_portfolio_url($url));
 5924: }
 5925: 
 5926: sub is_portfolio_file {
 5927:     my ($file) = @_;
 5928:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 5929:         return 1;
 5930:     }
 5931:     return;
 5932: }
 5933: 
 5934: sub usertools_access {
 5935:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
 5936:     my ($access,%tools);
 5937:     if ($context eq '') {
 5938:         $context = 'tools';
 5939:     }
 5940:     if ($context eq 'requestcourses') {
 5941:         %tools = (
 5942:                       official   => 1,
 5943:                       unofficial => 1,
 5944:                       community  => 1,
 5945:                  );
 5946:     } elsif ($context eq 'requestauthor') {
 5947:         %tools = (
 5948:                       requestauthor => 1,
 5949:                  );
 5950:     } else {
 5951:         %tools = (
 5952:                       aboutme   => 1,
 5953:                       blog      => 1,
 5954:                       webdav    => 1,
 5955:                       portfolio => 1,
 5956:                  );
 5957:     }
 5958:     return if (!defined($tools{$tool}));
 5959: 
 5960:     if ((!defined($udom)) || (!defined($uname))) {
 5961:         $udom = $env{'user.domain'};
 5962:         $uname = $env{'user.name'};
 5963:     }
 5964: 
 5965:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 5966:         if ($action ne 'reload') {
 5967:             if ($context eq 'requestcourses') {
 5968:                 return $env{'environment.canrequest.'.$tool};
 5969:             } elsif ($context eq 'requestauthor') {
 5970:                 return $env{'environment.canrequest.author'};
 5971:             } else {
 5972:                 return $env{'environment.availabletools.'.$tool};
 5973:             }
 5974:         }
 5975:     }
 5976: 
 5977:     my ($toolstatus,$inststatus,$envkey);
 5978:     if ($context eq 'requestauthor') {
 5979:         $envkey = $context; 
 5980:     } else {
 5981:         $envkey = $context.'.'.$tool;
 5982:     }
 5983: 
 5984:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 5985:          ($action ne 'reload')) {
 5986:         $toolstatus = $env{'environment.'.$envkey};
 5987:         $inststatus = $env{'environment.inststatus'};
 5988:     } else {
 5989:         if (ref($userenvref) eq 'HASH') {
 5990:             $toolstatus = $userenvref->{$envkey};
 5991:             $inststatus = $userenvref->{'inststatus'};
 5992:         } else {
 5993:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
 5994:             $toolstatus = $userenv{$envkey};
 5995:             $inststatus = $userenv{'inststatus'};
 5996:         }
 5997:     }
 5998: 
 5999:     if ($toolstatus ne '') {
 6000:         if ($toolstatus) {
 6001:             $access = 1;
 6002:         } else {
 6003:             $access = 0;
 6004:         }
 6005:         return $access;
 6006:     }
 6007: 
 6008:     my ($is_adv,%domdef);
 6009:     if (ref($is_advref) eq 'HASH') {
 6010:         $is_adv = $is_advref->{'is_adv'};
 6011:     } else {
 6012:         $is_adv = &is_advanced_user($udom,$uname);
 6013:     }
 6014:     if (ref($domdefref) eq 'HASH') {
 6015:         %domdef = %{$domdefref};
 6016:     } else {
 6017:         %domdef = &get_domain_defaults($udom);
 6018:     }
 6019:     if (ref($domdef{$tool}) eq 'HASH') {
 6020:         if ($is_adv) {
 6021:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 6022:                 if ($domdef{$tool}{'_LC_adv'}) { 
 6023:                     $access = 1;
 6024:                 } else {
 6025:                     $access = 0;
 6026:                 }
 6027:                 return $access;
 6028:             }
 6029:         }
 6030:         if ($inststatus ne '') {
 6031:             my ($hasaccess,$hasnoaccess);
 6032:             foreach my $affiliation (split(/:/,$inststatus)) {
 6033:                 if ($domdef{$tool}{$affiliation} ne '') { 
 6034:                     if ($domdef{$tool}{$affiliation}) {
 6035:                         $hasaccess = 1;
 6036:                     } else {
 6037:                         $hasnoaccess = 1;
 6038:                     }
 6039:                 }
 6040:             }
 6041:             if ($hasaccess || $hasnoaccess) {
 6042:                 if ($hasaccess) {
 6043:                     $access = 1;
 6044:                 } elsif ($hasnoaccess) {
 6045:                     $access = 0; 
 6046:                 }
 6047:                 return $access;
 6048:             }
 6049:         } else {
 6050:             if ($domdef{$tool}{'default'} ne '') {
 6051:                 if ($domdef{$tool}{'default'}) {
 6052:                     $access = 1;
 6053:                 } elsif ($domdef{$tool}{'default'} == 0) {
 6054:                     $access = 0;
 6055:                 }
 6056:                 return $access;
 6057:             }
 6058:         }
 6059:     } else {
 6060:         if (($context eq 'tools') && ($tool ne 'webdav')) {
 6061:             $access = 1;
 6062:         } else {
 6063:             $access = 0;
 6064:         }
 6065:         return $access;
 6066:     }
 6067: }
 6068: 
 6069: sub is_course_owner {
 6070:     my ($cdom,$cnum,$udom,$uname) = @_;
 6071:     if (($udom eq '') || ($uname eq '')) {
 6072:         $udom = $env{'user.domain'};
 6073:         $uname = $env{'user.name'};
 6074:     }
 6075:     unless (($udom eq '') || ($uname eq '')) {
 6076:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
 6077:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
 6078:                 return 1;
 6079:             } else {
 6080:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
 6081:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
 6082:                     return 1;
 6083:                 }
 6084:             }
 6085:         }
 6086:     }
 6087:     return;
 6088: }
 6089: 
 6090: sub is_advanced_user {
 6091:     my ($udom,$uname) = @_;
 6092:     if ($udom ne '' && $uname ne '') {
 6093:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 6094:             if (wantarray) {
 6095:                 return ($env{'user.adv'},$env{'user.author'});
 6096:             } else {
 6097:                 return $env{'user.adv'};
 6098:             }
 6099:         }
 6100:     }
 6101:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 6102:     my %allroles;
 6103:     my ($is_adv,$is_author);
 6104:     foreach my $role (keys(%roleshash)) {
 6105:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 6106:         my $area = '/'.$tdomain.'/'.$trest;
 6107:         if ($sec ne '') {
 6108:             $area .= '/'.$sec;
 6109:         }
 6110:         if (($area ne '') && ($trole ne '')) {
 6111:             my $spec=$trole.'.'.$area;
 6112:             if ($trole =~ /^cr\//) {
 6113:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 6114:             } elsif ($trole ne 'gr') {
 6115:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 6116:             }
 6117:             if ($trole eq 'au') {
 6118:                 $is_author = 1;
 6119:             }
 6120:         }
 6121:     }
 6122:     foreach my $role (keys(%allroles)) {
 6123:         last if ($is_adv);
 6124:         foreach my $item (split(/:/,$allroles{$role})) {
 6125:             if ($item ne '') {
 6126:                 my ($privilege,$restrictions)=split(/&/,$item);
 6127:                 if ($privilege eq 'adv') {
 6128:                     $is_adv = 1;
 6129:                     last;
 6130:                 }
 6131:             }
 6132:         }
 6133:     }
 6134:     if (wantarray) {
 6135:         return ($is_adv,$is_author);
 6136:     }
 6137:     return $is_adv;
 6138: }
 6139: 
 6140: sub check_can_request {
 6141:     my ($dom,$can_request,$request_domains) = @_;
 6142:     my $canreq = 0;
 6143:     my ($types,$typename) = &Apache::loncommon::course_types();
 6144:     my @options = ('approval','validate','autolimit');
 6145:     my $optregex = join('|',@options);
 6146:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
 6147:         foreach my $type (@{$types}) {
 6148:             if (&usertools_access($env{'user.name'},
 6149:                                   $env{'user.domain'},
 6150:                                   $type,undef,'requestcourses')) {
 6151:                 $canreq ++;
 6152:                 if (ref($request_domains) eq 'HASH') {
 6153:                     push(@{$request_domains->{$type}},$env{'user.domain'});
 6154:                 }
 6155:                 if ($dom eq $env{'user.domain'}) {
 6156:                     $can_request->{$type} = 1;
 6157:                 }
 6158:             }
 6159:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
 6160:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
 6161:                 if (@curr > 0) {
 6162:                     foreach my $item (@curr) {
 6163:                         if (ref($request_domains) eq 'HASH') {
 6164:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
 6165:                             if ($otherdom ne '') {
 6166:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
 6167:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
 6168:                                         push(@{$request_domains->{$type}},$otherdom);
 6169:                                     }
 6170:                                 } else {
 6171:                                     push(@{$request_domains->{$type}},$otherdom);
 6172:                                 }
 6173:                             }
 6174:                         }
 6175:                     }
 6176:                     unless($dom eq $env{'user.domain'}) {
 6177:                         $canreq ++;
 6178:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
 6179:                             $can_request->{$type} = 1;
 6180:                         }
 6181:                     }
 6182:                 }
 6183:             }
 6184:         }
 6185:     }
 6186:     return $canreq;
 6187: }
 6188: 
 6189: # ---------------------------------------------- Custom access rule evaluation
 6190: 
 6191: sub customaccess {
 6192:     my ($priv,$uri)=@_;
 6193:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 6194:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 6195:     $udom = &LONCAPA::clean_domain($udom);
 6196:     $ucrs = &LONCAPA::clean_username($ucrs);
 6197:     my $access=0;
 6198:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 6199: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 6200: 	if ($type eq 'user') {
 6201: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 6202: 		my ($tdom,$tuname)=split(m{/},$scope);
 6203: 		if ($tdom) {
 6204: 		    if ($tdom ne $env{'user.domain'}) { next; }
 6205: 		}
 6206: 		if ($tuname) {
 6207: 		    if ($tuname ne $env{'user.name'}) { next; }
 6208: 		}
 6209: 		$access=($effect eq 'allow');
 6210: 		last;
 6211: 	    }
 6212: 	} else {
 6213: 	    if ($role) {
 6214: 		if ($role ne $urole) { next; }
 6215: 	    }
 6216: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 6217: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 6218: 		if ($tdom) {
 6219: 		    if ($tdom ne $udom) { next; }
 6220: 		}
 6221: 		if ($tcrs) {
 6222: 		    if ($tcrs ne $ucrs) { next; }
 6223: 		}
 6224: 		if ($tsec) {
 6225: 		    if ($tsec ne $usec) { next; }
 6226: 		}
 6227: 		$access=($effect eq 'allow');
 6228: 		last;
 6229: 	    }
 6230: 	    if ($realm eq '' && $role eq '') {
 6231: 		$access=($effect eq 'allow');
 6232: 	    }
 6233: 	}
 6234:     }
 6235:     return $access;
 6236: }
 6237: 
 6238: # ------------------------------------------------- Check for a user privilege
 6239: 
 6240: sub allowed {
 6241:     my ($priv,$uri,$symb,$role)=@_;
 6242:     my $ver_orguri=$uri;
 6243:     $uri=&deversion($uri);
 6244:     my $orguri=$uri;
 6245:     $uri=&declutter($uri);
 6246: 
 6247:     if ($priv eq 'evb') {
 6248: # Evade communication block restrictions for specified role in a course
 6249:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 6250:             return $1;
 6251:         } else {
 6252:             return;
 6253:         }
 6254:     }
 6255: 
 6256:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 6257: # Free bre access to adm and meta resources
 6258:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
 6259: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 6260: 	&& ($priv eq 'bre')) {
 6261: 	return 'F';
 6262:     }
 6263: 
 6264: # Free bre access to user's own portfolio contents
 6265:     my ($space,$domain,$name,@dir)=split('/',$uri);
 6266:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 6267: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 6268:         my %setters;
 6269:         my ($startblock,$endblock) = 
 6270:             &Apache::loncommon::blockcheck(\%setters,'port');
 6271:         if ($startblock && $endblock) {
 6272:             return 'B';
 6273:         } else {
 6274:             return 'F';
 6275:         }
 6276:     }
 6277: 
 6278: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 6279:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 6280:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 6281:         if (exists($env{'request.course.id'})) {
 6282:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6283:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 6284:             if (($domain eq $cdom) && ($name eq $cnum)) {
 6285:                 my $courseprivid=$env{'request.course.id'};
 6286:                 $courseprivid=~s/\_/\//;
 6287:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 6288:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 6289:                     return $1; 
 6290:                 } else {
 6291:                     if ($env{'request.course.sec'}) {
 6292:                         $courseprivid.='/'.$env{'request.course.sec'};
 6293:                     }
 6294:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 6295:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 6296:                         return $2;
 6297:                     }
 6298:                 }
 6299:             }
 6300:         }
 6301:     }
 6302: 
 6303: # Free bre to public access
 6304: 
 6305:     if ($priv eq 'bre') {
 6306:         my $copyright=&metadata($uri,'copyright');
 6307: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 6308:            return 'F'; 
 6309:         }
 6310:         if ($copyright eq 'priv') {
 6311:             $uri=~/([^\/]+)\/([^\/]+)\//;
 6312: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 6313: 		return '';
 6314:             }
 6315:         }
 6316:         if ($copyright eq 'domain') {
 6317:             $uri=~/([^\/]+)\/([^\/]+)\//;
 6318: 	    unless (($env{'user.domain'} eq $1) ||
 6319:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 6320: 		return '';
 6321:             }
 6322:         }
 6323:         if ($env{'request.role'}=~ /li\.\//) {
 6324:             # Library role, so allow browsing of resources in this domain.
 6325:             return 'F';
 6326:         }
 6327:         if ($copyright eq 'custom') {
 6328: 	    unless (&customaccess($priv,$uri)) { return ''; }
 6329:         }
 6330:     }
 6331:     # Domain coordinator is trying to create a course
 6332:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 6333:         # uri is the requested domain in this case.
 6334:         # comparison to 'request.role.domain' shows if the user has selected
 6335:         # a role of dc for the domain in question.
 6336:         return 'F' if ($uri eq $env{'request.role.domain'});
 6337:     }
 6338: 
 6339:     my $thisallowed='';
 6340:     my $statecond=0;
 6341:     my $courseprivid='';
 6342: 
 6343:     my $ownaccess;
 6344:     # Community Coordinator or Assistant Co-author browsing resource space.
 6345:     if (($priv eq 'bro') && ($env{'user.author'})) {
 6346:         if ($uri eq '') {
 6347:             $ownaccess = 1;
 6348:         } else {
 6349:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
 6350:                 my $udom = $env{'user.domain'};
 6351:                 my $uname = $env{'user.name'};
 6352:                 if ($uri =~ m{^\Q$udom\E/?$}) {
 6353:                     $ownaccess = 1;
 6354:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
 6355:                     unless ($uri =~ m{\.\./}) {
 6356:                         $ownaccess = 1;
 6357:                     }
 6358:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
 6359:                     my $now = time;
 6360:                     if ($uri =~ m{^([^/]+)/?$}) {
 6361:                         my $adom = $1;
 6362:                         foreach my $key (keys(%env)) {
 6363:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
 6364:                                 my ($start,$end) = split('.',$env{$key});
 6365:                                 if (($now >= $start) && (!$end || $end < $now)) {
 6366:                                     $ownaccess = 1;
 6367:                                     last;
 6368:                                 }
 6369:                             }
 6370:                         }
 6371:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
 6372:                         my $adom = $1;
 6373:                         my $aname = $2;
 6374:                         foreach my $role ('ca','aa') { 
 6375:                             if ($env{"user.role.$role./$adom/$aname"}) {
 6376:                                 my ($start,$end) =
 6377:                                     split('.',$env{"user.role.$role./$adom/$aname"});
 6378:                                 if (($now >= $start) && (!$end || $end < $now)) {
 6379:                                     $ownaccess = 1;
 6380:                                     last;
 6381:                                 }
 6382:                             }
 6383:                         }
 6384:                     }
 6385:                 }
 6386:             }
 6387:         }
 6388:     }
 6389: 
 6390: # Course
 6391: 
 6392:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 6393:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6394:             $thisallowed.=$1;
 6395:         }
 6396:     }
 6397: 
 6398: # Domain
 6399: 
 6400:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 6401:        =~/\Q$priv\E\&([^\:]*)/) {
 6402:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6403:             $thisallowed.=$1;
 6404:         }
 6405:     }
 6406: 
 6407: # User who is not author or co-author might still be able to edit
 6408: # resource of an author in the domain (e.g., if Domain Coordinator).
 6409:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
 6410:         (&allowed('mdc',$env{'request.course.id'}))) {
 6411:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
 6412:             $thisallowed.=$1;
 6413:         }
 6414:     }
 6415: 
 6416: # Course: uri itself is a course
 6417:     my $courseuri=$uri;
 6418:     $courseuri=~s/\_(\d)/\/$1/;
 6419:     $courseuri=~s/^([^\/])/\/$1/;
 6420: 
 6421:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 6422:        =~/\Q$priv\E\&([^\:]*)/) {
 6423:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6424:             $thisallowed.=$1;
 6425:         }
 6426:     }
 6427: 
 6428: # URI is an uploaded document for this course, default permissions don't matter
 6429: # not allowing 'edit' access (editupload) to uploaded course docs
 6430:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 6431: 	$thisallowed='';
 6432:         my ($match)=&is_on_map($uri);
 6433:         if ($match) {
 6434:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 6435:                   =~/\Q$priv\E\&([^\:]*)/) {
 6436:                 my @blockers = &has_comm_blocking($priv,$symb,$uri);
 6437:                 if (@blockers > 0) {
 6438:                     $thisallowed = 'B';
 6439:                 } else {
 6440:                     $thisallowed.=$1;
 6441:                 }
 6442:             }
 6443:         } else {
 6444:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 6445:             if ($refuri) {
 6446:                 if ($refuri =~ m|^/adm/|) {
 6447:                     $thisallowed='F';
 6448:                 } else {
 6449:                     $refuri=&declutter($refuri);
 6450:                     my ($match) = &is_on_map($refuri);
 6451:                     if ($match) {
 6452:                         my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 6453:                         if (@blockers > 0) {
 6454:                             $thisallowed = 'B';
 6455:                         } else {
 6456:                             $thisallowed='F';
 6457:                         }
 6458:                     }
 6459:                 }
 6460:             }
 6461:         }
 6462:     }
 6463: 
 6464:     if ($priv eq 'bre'
 6465: 	&& $thisallowed ne 'F' 
 6466: 	&& $thisallowed ne '2'
 6467: 	&& &is_portfolio_url($uri)) {
 6468: 	$thisallowed = &portfolio_access($uri);
 6469:     }
 6470:     
 6471: # Full access at system, domain or course-wide level? Exit.
 6472:     if ($thisallowed=~/F/) {
 6473: 	return 'F';
 6474:     }
 6475: 
 6476: # If this is generating or modifying users, exit with special codes
 6477: 
 6478:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 6479: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 6480: 	    my ($audom,$auname)=split('/',$uri);
 6481: # no author name given, so this just checks on the general right to make a co-author in this domain
 6482: 	    unless ($auname) { return $thisallowed; }
 6483: # an author name is given, so we are about to actually make a co-author for a certain account
 6484: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 6485: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 6486: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 6487: 	}
 6488: 	return $thisallowed;
 6489:     }
 6490: #
 6491: # Gathered so far: system, domain and course wide privileges
 6492: #
 6493: # Course: See if uri or referer is an individual resource that is part of 
 6494: # the course
 6495: 
 6496:     if ($env{'request.course.id'}) {
 6497: 
 6498:        $courseprivid=$env{'request.course.id'};
 6499:        if ($env{'request.course.sec'}) {
 6500:           $courseprivid.='/'.$env{'request.course.sec'};
 6501:        }
 6502:        $courseprivid=~s/\_/\//;
 6503:        my $checkreferer=1;
 6504:        my ($match,$cond)=&is_on_map($uri);
 6505:        if ($match) {
 6506:            $statecond=$cond;
 6507:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 6508:                =~/\Q$priv\E\&([^\:]*)/) {
 6509:                my $value = $1;
 6510:                if ($priv eq 'bre') {
 6511:                    my @blockers = &has_comm_blocking($priv,$symb,$uri);
 6512:                    if (@blockers > 0) {
 6513:                        $thisallowed = 'B';
 6514:                    } else {
 6515:                        $thisallowed.=$value;
 6516:                    }
 6517:                } else {
 6518:                    $thisallowed.=$value;
 6519:                }
 6520:                $checkreferer=0;
 6521:            }
 6522:        }
 6523:        
 6524:        if ($checkreferer) {
 6525: 	  my $refuri=$env{'httpref.'.$orguri};
 6526:             unless ($refuri) {
 6527:                 foreach my $key (keys(%env)) {
 6528: 		    if ($key=~/^httpref\..*\*/) {
 6529: 			my $pattern=$key;
 6530:                         $pattern=~s/^httpref\.\/res\///;
 6531:                         $pattern=~s/\*/\[\^\/\]\+/g;
 6532:                         $pattern=~s/\//\\\//g;
 6533:                         if ($orguri=~/$pattern/) {
 6534: 			    $refuri=$env{$key};
 6535:                         }
 6536:                     }
 6537:                 }
 6538:             }
 6539: 
 6540:          if ($refuri) { 
 6541: 	  $refuri=&declutter($refuri);
 6542:           my ($match,$cond)=&is_on_map($refuri);
 6543:             if ($match) {
 6544:               my $refstatecond=$cond;
 6545:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 6546:                   =~/\Q$priv\E\&([^\:]*)/) {
 6547:                   my $value = $1;
 6548:                   if ($priv eq 'bre') {
 6549:                       my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 6550:                       if (@blockers > 0) {
 6551:                           $thisallowed = 'B';
 6552:                       } else {
 6553:                           $thisallowed.=$value;
 6554:                       }
 6555:                   } else {
 6556:                       $thisallowed.=$value;
 6557:                   }
 6558:                   $uri=$refuri;
 6559:                   $statecond=$refstatecond;
 6560:               }
 6561:           }
 6562:         }
 6563:        }
 6564:    }
 6565: 
 6566: #
 6567: # Gathered now: all privileges that could apply, and condition number
 6568: # 
 6569: #
 6570: # Full or no access?
 6571: #
 6572: 
 6573:     if ($thisallowed=~/F/) {
 6574: 	return 'F';
 6575:     }
 6576: 
 6577:     unless ($thisallowed) {
 6578:         return '';
 6579:     }
 6580: 
 6581: # Restrictions exist, deal with them
 6582: #
 6583: #   C:according to course preferences
 6584: #   R:according to resource settings
 6585: #   L:unless locked
 6586: #   X:according to user session state
 6587: #
 6588: 
 6589: # Possibly locked functionality, check all courses
 6590: # Locks might take effect only after 10 minutes cache expiration for other
 6591: # courses, and 2 minutes for current course
 6592: 
 6593:     my $envkey;
 6594:     if ($thisallowed=~/L/) {
 6595:         foreach $envkey (keys(%env)) {
 6596:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 6597:                my $courseid=$2;
 6598:                my $roleid=$1.'.'.$2;
 6599:                $courseid=~s/^\///;
 6600:                my $expiretime=600;
 6601:                if ($env{'request.role'} eq $roleid) {
 6602: 		  $expiretime=120;
 6603:                }
 6604: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 6605:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 6606:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 6607: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 6608:                }
 6609:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 6610:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 6611: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 6612:                        &log($env{'user.domain'},$env{'user.name'},
 6613:                             $env{'user.home'},
 6614:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 6615:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 6616:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 6617: 		       return '';
 6618:                    }
 6619:                }
 6620:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 6621:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 6622: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 6623:                        &log($env{'user.domain'},$env{'user.name'},
 6624:                             $env{'user.home'},
 6625:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 6626:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 6627:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 6628: 		       return '';
 6629:                    }
 6630:                }
 6631: 	   }
 6632:        }
 6633:     }
 6634:    
 6635: #
 6636: # Rest of the restrictions depend on selected course
 6637: #
 6638: 
 6639:     unless ($env{'request.course.id'}) {
 6640: 	if ($thisallowed eq 'A') {
 6641: 	    return 'A';
 6642:         } elsif ($thisallowed eq 'B') {
 6643:             return 'B';
 6644: 	} else {
 6645: 	    return '1';
 6646: 	}
 6647:     }
 6648: 
 6649: #
 6650: # Now user is definitely in a course
 6651: #
 6652: 
 6653: 
 6654: # Course preferences
 6655: 
 6656:    if ($thisallowed=~/C/) {
 6657:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 6658:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 6659:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 6660: 	   =~/\Q$rolecode\E/) {
 6661: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 6662: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 6663: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 6664: 			$env{'request.course.id'});
 6665: 	   }
 6666:            return '';
 6667:        }
 6668: 
 6669:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 6670: 	   =~/\Q$unamedom\E/) {
 6671: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 6672: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 6673: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 6674: 			$env{'request.course.id'});
 6675: 	   }
 6676:            return '';
 6677:        }
 6678:    }
 6679: 
 6680: # Resource preferences
 6681: 
 6682:    if ($thisallowed=~/R/) {
 6683:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 6684:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 6685: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 6686: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 6687: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 6688: 	   }
 6689: 	   return '';
 6690:        }
 6691:    }
 6692: 
 6693: # Restricted by state or randomout?
 6694: 
 6695:    if ($thisallowed=~/X/) {
 6696:       if ($env{'acc.randomout'}) {
 6697: 	 if (!$symb) { $symb=&symbread($uri,1); }
 6698:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 6699:             return ''; 
 6700:          }
 6701:       }
 6702:       if (&condval($statecond)) {
 6703: 	 return '2';
 6704:       } else {
 6705:          return '';
 6706:       }
 6707:    }
 6708: 
 6709:     if ($thisallowed eq 'A') {
 6710: 	return 'A';
 6711:     } elsif ($thisallowed eq 'B') {
 6712:         return 'B';
 6713:     }
 6714:    return 'F';
 6715: }
 6716: 
 6717: # ------------------------------------------- Check construction space access
 6718: 
 6719: sub constructaccess {
 6720:     my ($url,$setpriv)=@_;
 6721: 
 6722: # We do not allow editing of previous versions of files
 6723:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
 6724: 
 6725: # Get username and domain from URL
 6726:     my ($ownername,$ownerdomain,$ownerhome);
 6727: 
 6728:     ($ownerdomain,$ownername) =
 6729:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)/});
 6730: 
 6731: # The URL does not really point to any authorspace, forget it
 6732:     unless (($ownername) && ($ownerdomain)) { return ''; }
 6733: 
 6734: # Now we need to see if the user has access to the authorspace of
 6735: # $ownername at $ownerdomain
 6736: 
 6737:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
 6738: # Real author for this?
 6739:        $ownerhome = $env{'user.home'};
 6740:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
 6741:           return ($ownername,$ownerdomain,$ownerhome);
 6742:        }
 6743:     } else {
 6744: # Co-author for this?
 6745:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
 6746:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
 6747:             $ownerhome = &homeserver($ownername,$ownerdomain);
 6748:             return ($ownername,$ownerdomain,$ownerhome);
 6749:         }
 6750:     }
 6751: 
 6752: # We don't have any access right now. If we are not possibly going to do anything about this,
 6753: # we might as well leave
 6754:    unless ($setpriv) { return ''; }
 6755: 
 6756: # Backdoor access?
 6757:     my $allowed=&allowed('eco',$ownerdomain);
 6758: # Nope
 6759:     unless ($allowed) { return ''; }
 6760: # Looks like we may have access, but could be locked by the owner of the construction space
 6761:     if ($allowed eq 'U') {
 6762:         my %blocked=&get('environment',['domcoord.author'],
 6763:                          $ownerdomain,$ownername);
 6764: # Is blocked by owner
 6765:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
 6766:     }
 6767:     if (($allowed eq 'F') || ($allowed eq 'U')) {
 6768: # Grant temporary access
 6769:         my $then=$env{'user.login.time'};
 6770:         my $update==$env{'user.update.time'};
 6771:         if (!$update) { $update = $then; }
 6772:         my $refresh=$env{'user.refresh.time'};
 6773:         if (!$refresh) { $refresh = $update; }
 6774:         my $now = time;
 6775:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
 6776:                            $now,'ca','constructaccess');
 6777:         $ownerhome = &homeserver($ownername,$ownerdomain);
 6778:         return($ownername,$ownerdomain,$ownerhome);
 6779:     }
 6780: # No business here
 6781:     return '';
 6782: }
 6783: 
 6784: sub get_comm_blocks {
 6785:     my ($cdom,$cnum) = @_;
 6786:     if ($cdom eq '' || $cnum eq '') {
 6787:         return unless ($env{'request.course.id'});
 6788:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 6789:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6790:     }
 6791:     my %commblocks;
 6792:     my $hashid=$cdom.'_'.$cnum;
 6793:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
 6794:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
 6795:         %commblocks = %{$blocksref};
 6796:     } else {
 6797:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
 6798:         my $cachetime = 600;
 6799:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
 6800:     }
 6801:     return %commblocks;
 6802: }
 6803: 
 6804: sub has_comm_blocking {
 6805:     my ($priv,$symb,$uri,$blocks) = @_;
 6806:     return unless ($env{'request.course.id'});
 6807:     return unless ($priv eq 'bre');
 6808:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 6809:     my %commblocks;
 6810:     if (ref($blocks) eq 'HASH') {
 6811:         %commblocks = %{$blocks};
 6812:     } else {
 6813:         %commblocks = &get_comm_blocks();
 6814:     }
 6815:     return unless (keys(%commblocks) > 0);
 6816:     if (!$symb) { $symb=&symbread($uri,1); }
 6817:     my ($map,$resid,undef)=&decode_symb($symb);
 6818:     my %tocheck = (
 6819:                     maps      => $map,
 6820:                     resources => $symb,
 6821:                   );
 6822:     my @blockers;
 6823:     my $now = time;
 6824:     my $navmap = Apache::lonnavmaps::navmap->new();
 6825:     foreach my $block (keys(%commblocks)) {
 6826:         if ($block =~ /^(\d+)____(\d+)$/) {
 6827:             my ($start,$end) = ($1,$2);
 6828:             if ($start <= $now && $end >= $now) {
 6829:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 6830:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 6831:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 6832:                             if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
 6833:                                 unless (grep(/^\Q$block\E$/,@blockers)) {
 6834:                                     push(@blockers,$block);
 6835:                                 }
 6836:                             }
 6837:                         }
 6838:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 6839:                             if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
 6840:                                 unless (grep(/^\Q$block\E$/,@blockers)) {  
 6841:                                     push(@blockers,$block);
 6842:                                 }
 6843:                             }
 6844:                         }
 6845:                     }
 6846:                 }
 6847:             }
 6848:         } elsif ($block =~ /^firstaccess____(.+)$/) {
 6849:             my $item = $1;
 6850:             my @to_test;
 6851:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 6852:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 6853:                     my $check_interval;
 6854:                     if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
 6855:                         my @interval;
 6856:                         my $type = 'map';
 6857:                         if ($item eq 'course') {
 6858:                             $type = 'course';
 6859:                             @interval=&EXT("resource.0.interval");
 6860:                         } else {
 6861:                             if ($item =~ /___\d+___/) {
 6862:                                 $type = 'resource';
 6863:                                 @interval=&EXT("resource.0.interval",$item);
 6864:                                 if (ref($navmap)) {                        
 6865:                                     my $res = $navmap->getBySymb($item); 
 6866:                                     push(@to_test,$res);
 6867:                                 }
 6868:                             } else {
 6869:                                 my $mapsymb = &symbread($item,1);
 6870:                                 if ($mapsymb) {
 6871:                                     if (ref($navmap)) {
 6872:                                         my $mapres = $navmap->getBySymb($mapsymb);
 6873:                                         @to_test = $mapres->retrieveResources($mapres,undef,0,1);
 6874:                                         foreach my $res (@to_test) {
 6875:                                             my $symb = $res->symb();
 6876:                                             next if ($symb eq $mapsymb);
 6877:                                             if ($symb ne '') {
 6878:                                                 @interval=&EXT("resource.0.interval",$symb);
 6879:                                                 last;
 6880:                                             }
 6881:                                         }
 6882:                                     }
 6883:                                 }
 6884:                             }
 6885:                         }
 6886:                         if ($interval[0] =~ /\d+/) {
 6887:                             my $first_access;
 6888:                             if ($type eq 'resource') {
 6889:                                 $first_access=&get_first_access($interval[1],$item);
 6890:                             } elsif ($type eq 'map') {
 6891:                                 $first_access=&get_first_access($interval[1],undef,$item);
 6892:                             } else {
 6893:                                 $first_access=&get_first_access($interval[1]);
 6894:                             }
 6895:                             if ($first_access) {
 6896:                                 my $timesup = $first_access+$interval[0];
 6897:                                 if ($timesup > $now) {
 6898:                                     foreach my $res (@to_test) {
 6899:                                         if ($res->is_problem()) {
 6900:                                             if ($res->completable()) {
 6901:                                                 unless (grep(/^\Q$block\E$/,@blockers)) {
 6902:                                                     push(@blockers,$block);
 6903:                                                 }
 6904:                                                 last;
 6905:                                             }
 6906:                                         }
 6907:                                     }
 6908:                                 }
 6909:                             }
 6910:                         }
 6911:                     }
 6912:                 }
 6913:             }
 6914:         }
 6915:     }
 6916:     return @blockers;
 6917: }
 6918: 
 6919: sub check_docs_block {
 6920:     my ($docsblock,$tocheck) =@_;
 6921:     if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
 6922:         return;
 6923:     }
 6924:     if (ref($docsblock->{'maps'}) eq 'HASH') {
 6925:         if ($tocheck->{'maps'}) {
 6926:             if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
 6927:                 return 1;
 6928:             }
 6929:         }
 6930:     }
 6931:     if (ref($docsblock->{'resources'}) eq 'HASH') {
 6932:         if ($tocheck->{'resources'}) {
 6933:             if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
 6934:                 return 1;
 6935:             }
 6936:         }
 6937:     }
 6938:     return;
 6939: }
 6940: 
 6941: #
 6942: #   Removes the versino from a URI and
 6943: #   splits it in to its filename and path to the filename.
 6944: #   Seems like File::Basename could have done this more clearly.
 6945: #   Parameters:
 6946: #      $uri   - input URI
 6947: #   Returns:
 6948: #     Two element list consisting of 
 6949: #     $pathname  - the URI up to and excluding the trailing /
 6950: #     $filename  - The part of the URI following the last /
 6951: #  NOTE:
 6952: #    Another realization of this is simply:
 6953: #    use File::Basename;
 6954: #    ...
 6955: #    $uri = shift;
 6956: #    $filename = basename($uri);
 6957: #    $path     = dirname($uri);
 6958: #    return ($filename, $path);
 6959: #
 6960: #     The implementation below is probably faster however.
 6961: #
 6962: sub split_uri_for_cond {
 6963:     my $uri=&deversion(&declutter(shift));
 6964:     my @uriparts=split(/\//,$uri);
 6965:     my $filename=pop(@uriparts);
 6966:     my $pathname=join('/',@uriparts);
 6967:     return ($pathname,$filename);
 6968: }
 6969: # --------------------------------------------------- Is a resource on the map?
 6970: 
 6971: sub is_on_map {
 6972:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 6973:     #Trying to find the conditional for the file
 6974:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 6975: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 6976:     if ($match) {
 6977: 	return (1,$1);
 6978:     } else {
 6979: 	return (0,0);
 6980:     }
 6981: }
 6982: 
 6983: # --------------------------------------------------------- Get symb from alias
 6984: 
 6985: sub get_symb_from_alias {
 6986:     my $symb=shift;
 6987:     my ($map,$resid,$url)=&decode_symb($symb);
 6988: # Already is a symb
 6989:     if ($url) { return $symb; }
 6990: # Must be an alias
 6991:     my $aliassymb='';
 6992:     my %bighash;
 6993:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6994:                             &GDBM_READER(),0640)) {
 6995:         my $rid=$bighash{'mapalias_'.$symb};
 6996: 	if ($rid) {
 6997: 	    my ($mapid,$resid)=split(/\./,$rid);
 6998: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 6999: 				    $resid,$bighash{'src_'.$rid});
 7000: 	}
 7001:         untie %bighash;
 7002:     }
 7003:     return $aliassymb;
 7004: }
 7005: 
 7006: # ----------------------------------------------------------------- Define Role
 7007: 
 7008: sub definerole {
 7009:   if (allowed('mcr','/')) {
 7010:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 7011:     foreach my $role (split(':',$sysrole)) {
 7012: 	my ($crole,$cqual)=split(/\&/,$role);
 7013:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 7014:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 7015: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 7016:                return "refused:s:$crole&$cqual"; 
 7017:             }
 7018:         }
 7019:     }
 7020:     foreach my $role (split(':',$domrole)) {
 7021: 	my ($crole,$cqual)=split(/\&/,$role);
 7022:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 7023:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 7024: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 7025:                return "refused:d:$crole&$cqual"; 
 7026:             }
 7027:         }
 7028:     }
 7029:     foreach my $role (split(':',$courole)) {
 7030: 	my ($crole,$cqual)=split(/\&/,$role);
 7031:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 7032:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 7033: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 7034:                return "refused:c:$crole&$cqual"; 
 7035:             }
 7036:         }
 7037:     }
 7038:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 7039:                 "$env{'user.domain'}:$env{'user.name'}:".
 7040: 	        "rolesdef_$rolename=".
 7041:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 7042:     return reply($command,$env{'user.home'});
 7043:   } else {
 7044:     return 'refused';
 7045:   }
 7046: }
 7047: 
 7048: # ---------------- Make a metadata query against the network of library servers
 7049: 
 7050: sub metadata_query {
 7051:     my ($query,$custom,$customshow,$server_array)=@_;
 7052:     my %rhash;
 7053:     my %libserv = &all_library();
 7054:     my @server_list = (defined($server_array) ? @$server_array
 7055:                                               : keys(%libserv) );
 7056:     for my $server (@server_list) {
 7057: 	unless ($custom or $customshow) {
 7058: 	    my $reply=&reply("querysend:".&escape($query),$server);
 7059: 	    $rhash{$server}=$reply;
 7060: 	}
 7061: 	else {
 7062: 	    my $reply=&reply("querysend:".&escape($query).':'.
 7063: 			     &escape($custom).':'.&escape($customshow),
 7064: 			     $server);
 7065: 	    $rhash{$server}=$reply;
 7066: 	}
 7067:     }
 7068:     return \%rhash;
 7069: }
 7070: 
 7071: # ----------------------------------------- Send log queries and wait for reply
 7072: 
 7073: sub log_query {
 7074:     my ($uname,$udom,$query,%filters)=@_;
 7075:     my $uhome=&homeserver($uname,$udom);
 7076:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 7077:     my $uhost=&hostname($uhome);
 7078:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 7079:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 7080:                        $uhome);
 7081:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 7082:     return get_query_reply($queryid);
 7083: }
 7084: 
 7085: # -------------------------- Update MySQL table for portfolio file
 7086: 
 7087: sub update_portfolio_table {
 7088:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 7089:     if ($group ne '') {
 7090:         $file_name =~s /^\Q$group\E//;
 7091:     }
 7092:     my $homeserver = &homeserver($uname,$udom);
 7093:     my $queryid=
 7094:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 7095:                ':'.&escape($file_name).':'.$action,$homeserver);
 7096:     my $reply = &get_query_reply($queryid);
 7097:     return $reply;
 7098: }
 7099: 
 7100: # -------------------------- Update MySQL allusers table
 7101: 
 7102: sub update_allusers_table {
 7103:     my ($uname,$udom,$names) = @_;
 7104:     my $homeserver = &homeserver($uname,$udom);
 7105:     my $queryid=
 7106:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 7107:                'lastname='.&escape($names->{'lastname'}).'%%'.
 7108:                'firstname='.&escape($names->{'firstname'}).'%%'.
 7109:                'middlename='.&escape($names->{'middlename'}).'%%'.
 7110:                'generation='.&escape($names->{'generation'}).'%%'.
 7111:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 7112:                'id='.&escape($names->{'id'}),$homeserver);
 7113:     return;
 7114: }
 7115: 
 7116: # ------- Request retrieval of institutional classlists for course(s)
 7117: 
 7118: sub fetch_enrollment_query {
 7119:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 7120:     my $homeserver;
 7121:     my $maxtries = 1;
 7122:     if ($context eq 'automated') {
 7123:         $homeserver = $perlvar{'lonHostID'};
 7124:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 7125:     } else {
 7126:         $homeserver = &homeserver($cnum,$dom);
 7127:     }
 7128:     my $host=&hostname($homeserver);
 7129:     my $cmd = '';
 7130:     foreach my $affiliate (keys(%{$affiliatesref})) {
 7131:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 7132:     }
 7133:     $cmd =~ s/%%$//;
 7134:     $cmd = &escape($cmd);
 7135:     my $query = 'fetchenrollment';
 7136:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 7137:     unless ($queryid=~/^\Q$host\E\_/) { 
 7138:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 7139:         return 'error: '.$queryid;
 7140:     }
 7141:     my $reply = &get_query_reply($queryid);
 7142:     my $tries = 1;
 7143:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 7144:         $reply = &get_query_reply($queryid);
 7145:         $tries ++;
 7146:     }
 7147:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 7148:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 7149:     } else {
 7150:         my @responses = split(/:/,$reply);
 7151:         if ($homeserver eq $perlvar{'lonHostID'}) {
 7152:             foreach my $line (@responses) {
 7153:                 my ($key,$value) = split(/=/,$line,2);
 7154:                 $$replyref{$key} = $value;
 7155:             }
 7156:         } else {
 7157:             my $pathname = LONCAPA::tempdir();
 7158:             foreach my $line (@responses) {
 7159:                 my ($key,$value) = split(/=/,$line);
 7160:                 $$replyref{$key} = $value;
 7161:                 if ($value > 0) {
 7162:                     foreach my $item (@{$$affiliatesref{$key}}) {
 7163:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 7164:                         my $destname = $pathname.'/'.$filename;
 7165:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 7166:                         if ($xml_classlist =~ /^error/) {
 7167:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 7168:                         } else {
 7169:                             if ( open(FILE,">$destname") ) {
 7170:                                 print FILE &unescape($xml_classlist);
 7171:                                 close(FILE);
 7172:                             } else {
 7173:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 7174:                             }
 7175:                         }
 7176:                     }
 7177:                 }
 7178:             }
 7179:         }
 7180:         return 'ok';
 7181:     }
 7182:     return 'error';
 7183: }
 7184: 
 7185: sub get_query_reply {
 7186:     my $queryid=shift;
 7187:     my $replyfile=LONCAPA::tempdir().$queryid;
 7188:     my $reply='';
 7189:     for (1..100) {
 7190: 	sleep 2;
 7191:         if (-e $replyfile.'.end') {
 7192: 	    if (open(my $fh,$replyfile)) {
 7193: 		$reply = join('',<$fh>);
 7194: 		close($fh);
 7195: 	   } else { return 'error: reply_file_error'; }
 7196:            return &unescape($reply);
 7197: 	}
 7198:     }
 7199:     return 'timeout:'.$queryid;
 7200: }
 7201: 
 7202: sub courselog_query {
 7203: #
 7204: # possible filters:
 7205: # url: url or symb
 7206: # username
 7207: # domain
 7208: # action: view, submit, grade
 7209: # start: timestamp
 7210: # end: timestamp
 7211: #
 7212:     my (%filters)=@_;
 7213:     unless ($env{'request.course.id'}) { return 'no_course'; }
 7214:     if ($filters{'url'}) {
 7215: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 7216:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 7217:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 7218:     }
 7219:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7220:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7221:     return &log_query($cname,$cdom,'courselog',%filters);
 7222: }
 7223: 
 7224: sub userlog_query {
 7225: #
 7226: # possible filters:
 7227: # action: log check role
 7228: # start: timestamp
 7229: # end: timestamp
 7230: #
 7231:     my ($uname,$udom,%filters)=@_;
 7232:     return &log_query($uname,$udom,'userlog',%filters);
 7233: }
 7234: 
 7235: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 7236: 
 7237: sub auto_run {
 7238:     my ($cnum,$cdom) = @_;
 7239:     my $response = 0;
 7240:     my $settings;
 7241:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 7242:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 7243:         $settings = $domconfig{'autoenroll'};
 7244:         if ($settings->{'run'} eq '1') {
 7245:             $response = 1;
 7246:         }
 7247:     } else {
 7248:         my $homeserver;
 7249:         if (&is_course($cdom,$cnum)) {
 7250:             $homeserver = &homeserver($cnum,$cdom);
 7251:         } else {
 7252:             $homeserver = &domain($cdom,'primary');
 7253:         }
 7254:         if ($homeserver ne 'no_host') {
 7255:             $response = &reply('autorun:'.$cdom,$homeserver);
 7256:         }
 7257:     }
 7258:     return $response;
 7259: }
 7260: 
 7261: sub auto_get_sections {
 7262:     my ($cnum,$cdom,$inst_coursecode) = @_;
 7263:     my $homeserver;
 7264:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
 7265:         $homeserver = &homeserver($cnum,$cdom);
 7266:     }
 7267:     if (!defined($homeserver)) { 
 7268:         if ($cdom =~ /^$match_domain$/) {
 7269:             $homeserver = &domain($cdom,'primary');
 7270:         }
 7271:     }
 7272:     my @secs;
 7273:     if (defined($homeserver)) {
 7274:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 7275:         unless ($response eq 'refused') {
 7276:             @secs = split(/:/,$response);
 7277:         }
 7278:     }
 7279:     return @secs;
 7280: }
 7281: 
 7282: sub auto_new_course {
 7283:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
 7284:     my $homeserver = &homeserver($cnum,$cdom);
 7285:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
 7286:     return $response;
 7287: }
 7288: 
 7289: sub auto_validate_courseID {
 7290:     my ($cnum,$cdom,$inst_course_id) = @_;
 7291:     my $homeserver = &homeserver($cnum,$cdom);
 7292:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 7293:     return $response;
 7294: }
 7295: 
 7296: sub auto_validate_instcode {
 7297:     my ($cnum,$cdom,$instcode,$owner) = @_;
 7298:     my ($homeserver,$response);
 7299:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 7300:         $homeserver = &homeserver($cnum,$cdom);
 7301:     }
 7302:     if (!defined($homeserver)) {
 7303:         if ($cdom =~ /^$match_domain$/) {
 7304:             $homeserver = &domain($cdom,'primary');
 7305:         }
 7306:     }
 7307:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
 7308:                         &escape($instcode).':'.&escape($owner),$homeserver));
 7309:     my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
 7310:     return ($outcome,$description);
 7311: }
 7312: 
 7313: sub auto_create_password {
 7314:     my ($cnum,$cdom,$authparam,$udom) = @_;
 7315:     my ($homeserver,$response);
 7316:     my $create_passwd = 0;
 7317:     my $authchk = '';
 7318:     if ($udom =~ /^$match_domain$/) {
 7319:         $homeserver = &domain($udom,'primary');
 7320:     }
 7321:     if ($homeserver eq '') {
 7322:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 7323:             $homeserver = &homeserver($cnum,$cdom);
 7324:         }
 7325:     }
 7326:     if ($homeserver eq '') {
 7327:         $authchk = 'nodomain';
 7328:     } else {
 7329:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 7330:         if ($response eq 'refused') {
 7331:             $authchk = 'refused';
 7332:         } else {
 7333:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 7334:         }
 7335:     }
 7336:     return ($authparam,$create_passwd,$authchk);
 7337: }
 7338: 
 7339: sub auto_photo_permission {
 7340:     my ($cnum,$cdom,$students) = @_;
 7341:     my $homeserver = &homeserver($cnum,$cdom);
 7342:     my ($outcome,$perm_reqd,$conditions) = 
 7343: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 7344:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 7345: 	return (undef,undef);
 7346:     }
 7347:     return ($outcome,$perm_reqd,$conditions);
 7348: }
 7349: 
 7350: sub auto_checkphotos {
 7351:     my ($uname,$udom,$pid) = @_;
 7352:     my $homeserver = &homeserver($uname,$udom);
 7353:     my ($result,$resulttype);
 7354:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 7355: 				   &escape($uname).':'.&escape($pid),
 7356: 				   $homeserver));
 7357:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 7358: 	return (undef,undef);
 7359:     }
 7360:     if ($outcome) {
 7361:         ($result,$resulttype) = split(/:/,$outcome);
 7362:     } 
 7363:     return ($result,$resulttype);
 7364: }
 7365: 
 7366: sub auto_photochoice {
 7367:     my ($cnum,$cdom) = @_;
 7368:     my $homeserver = &homeserver($cnum,$cdom);
 7369:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 7370: 						       &escape($cdom),
 7371: 						       $homeserver)));
 7372:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 7373: 	return (undef,undef);
 7374:     }
 7375:     return ($update,$comment);
 7376: }
 7377: 
 7378: sub auto_photoupdate {
 7379:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 7380:     my $homeserver = &homeserver($cnum,$dom);
 7381:     my $host=&hostname($homeserver);
 7382:     my $cmd = '';
 7383:     my $maxtries = 1;
 7384:     foreach my $affiliate (keys(%{$affiliatesref})) {
 7385:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 7386:     }
 7387:     $cmd =~ s/%%$//;
 7388:     $cmd = &escape($cmd);
 7389:     my $query = 'institutionalphotos';
 7390:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 7391:     unless ($queryid=~/^\Q$host\E\_/) {
 7392:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 7393:         return 'error: '.$queryid;
 7394:     }
 7395:     my $reply = &get_query_reply($queryid);
 7396:     my $tries = 1;
 7397:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 7398:         $reply = &get_query_reply($queryid);
 7399:         $tries ++;
 7400:     }
 7401:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 7402:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 7403:     } else {
 7404:         my @responses = split(/:/,$reply);
 7405:         my $outcome = shift(@responses); 
 7406:         foreach my $item (@responses) {
 7407:             my ($key,$value) = split(/=/,$item);
 7408:             $$photo{$key} = $value;
 7409:         }
 7410:         return $outcome;
 7411:     }
 7412:     return 'error';
 7413: }
 7414: 
 7415: sub auto_instcode_format {
 7416:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 7417: 	$cat_order) = @_;
 7418:     my $courses = '';
 7419:     my @homeservers;
 7420:     if ($caller eq 'global') {
 7421: 	my %servers = &get_servers($codedom,'library');
 7422: 	foreach my $tryserver (keys(%servers)) {
 7423: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7424: 		push(@homeservers,$tryserver);
 7425: 	    }
 7426:         }
 7427:     } elsif ($caller eq 'requests') {
 7428:         if ($codedom =~ /^$match_domain$/) {
 7429:             my $chome = &domain($codedom,'primary');
 7430:             unless ($chome eq 'no_host') {
 7431:                 push(@homeservers,$chome);
 7432:             }
 7433:         }
 7434:     } else {
 7435:         push(@homeservers,&homeserver($caller,$codedom));
 7436:     }
 7437:     foreach my $code (keys(%{$instcodes})) {
 7438:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 7439:     }
 7440:     chop($courses);
 7441:     my $ok_response = 0;
 7442:     my $response;
 7443:     while (@homeservers > 0 && $ok_response == 0) {
 7444:         my $server = shift(@homeservers); 
 7445:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 7446:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 7447:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 7448: 		split(/:/,$response);
 7449:             %{$codes} = (%{$codes},&str2hash($codes_str));
 7450:             push(@{$codetitles},&str2array($codetitles_str));
 7451:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 7452:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 7453:             $ok_response = 1;
 7454:         }
 7455:     }
 7456:     if ($ok_response) {
 7457:         return 'ok';
 7458:     } else {
 7459:         return $response;
 7460:     }
 7461: }
 7462: 
 7463: sub auto_instcode_defaults {
 7464:     my ($domain,$returnhash,$code_order) = @_;
 7465:     my @homeservers;
 7466: 
 7467:     my %servers = &get_servers($domain,'library');
 7468:     foreach my $tryserver (keys(%servers)) {
 7469: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7470: 	    push(@homeservers,$tryserver);
 7471: 	}
 7472:     }
 7473: 
 7474:     my $response;
 7475:     foreach my $server (@homeservers) {
 7476:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 7477:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 7478: 	
 7479: 	foreach my $pair (split(/\&/,$response)) {
 7480: 	    my ($name,$value)=split(/\=/,$pair);
 7481: 	    if ($name eq 'code_order') {
 7482: 		@{$code_order} = split(/\&/,&unescape($value));
 7483: 	    } else {
 7484: 		$returnhash->{&unescape($name)}=&unescape($value);
 7485: 	    }
 7486: 	}
 7487: 	return 'ok';
 7488:     }
 7489: 
 7490:     return $response;
 7491: }
 7492: 
 7493: sub auto_possible_instcodes {
 7494:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
 7495:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
 7496:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 7497:         return;
 7498:     }
 7499:     my (@homeservers,$uhome);
 7500:     if (defined(&domain($domain,'primary'))) {
 7501:         $uhome=&domain($domain,'primary');
 7502:         push(@homeservers,&domain($domain,'primary'));
 7503:     } else {
 7504:         my %servers = &get_servers($domain,'library');
 7505:         foreach my $tryserver (keys(%servers)) {
 7506:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7507:                 push(@homeservers,$tryserver);
 7508:             }
 7509:         }
 7510:     }
 7511:     my $response;
 7512:     foreach my $server (@homeservers) {
 7513:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
 7514:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 7515:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
 7516:             split(':',$response);
 7517:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
 7518:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
 7519:         foreach my $item (split('&',$cat_title)) {   
 7520:             my ($name,$value)=split('=',$item);
 7521:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
 7522:         }
 7523:         foreach my $item (split('&',$cat_order)) {
 7524:             my ($name,$value)=split('=',$item);
 7525:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
 7526:         }
 7527:         return 'ok';
 7528:     }
 7529:     return $response;
 7530: }
 7531: 
 7532: sub auto_courserequest_checks {
 7533:     my ($dom) = @_;
 7534:     my ($homeserver,%validations);
 7535:     if ($dom =~ /^$match_domain$/) {
 7536:         $homeserver = &domain($dom,'primary');
 7537:     }
 7538:     unless ($homeserver eq 'no_host') {
 7539:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
 7540:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 7541:             my @items = split(/&/,$response);
 7542:             foreach my $item (@items) {
 7543:                 my ($key,$value) = split('=',$item);
 7544:                 $validations{&unescape($key)} = &thaw_unescape($value);
 7545:             }
 7546:         }
 7547:     }
 7548:     return %validations; 
 7549: }
 7550: 
 7551: sub auto_courserequest_validation {
 7552:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
 7553:     my ($homeserver,$response);
 7554:     if ($dom =~ /^$match_domain$/) {
 7555:         $homeserver = &domain($dom,'primary');
 7556:     }
 7557:     unless ($homeserver eq 'no_host') {  
 7558:           
 7559:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
 7560:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
 7561:                                     ':'.&escape($instcode).':'.&escape($instseclist),
 7562:                                     $homeserver));
 7563:     }
 7564:     return $response;
 7565: }
 7566: 
 7567: sub auto_validate_class_sec {
 7568:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 7569:     my $homeserver = &homeserver($cnum,$cdom);
 7570:     my $ownerlist;
 7571:     if (ref($owners) eq 'ARRAY') {
 7572:         $ownerlist = join(',',@{$owners});
 7573:     } else {
 7574:         $ownerlist = $owners;
 7575:     }
 7576:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 7577:                         &escape($ownerlist).':'.$cdom,$homeserver);
 7578:     return $response;
 7579: }
 7580: 
 7581: # ------------------------------------------------------- Course Group routines
 7582: 
 7583: sub get_coursegroups {
 7584:     my ($cdom,$cnum,$group,$namespace) = @_;
 7585:     return(&dump($namespace,$cdom,$cnum,$group));
 7586: }
 7587: 
 7588: sub modify_coursegroup {
 7589:     my ($cdom,$cnum,$groupsettings) = @_;
 7590:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 7591: }
 7592: 
 7593: sub toggle_coursegroup_status {
 7594:     my ($cdom,$cnum,$group,$action) = @_;
 7595:     my ($from_namespace,$to_namespace);
 7596:     if ($action eq 'delete') {
 7597:         $from_namespace = 'coursegroups';
 7598:         $to_namespace = 'deleted_groups';
 7599:     } else {
 7600:         $from_namespace = 'deleted_groups';
 7601:         $to_namespace = 'coursegroups';
 7602:     }
 7603:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 7604:     if (my $tmp = &error(%curr_group)) {
 7605:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 7606:         return ('read error',$tmp);
 7607:     } else {
 7608:         my %savedsettings = %curr_group; 
 7609:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 7610:         my $deloutcome;
 7611:         if ($result eq 'ok') {
 7612:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 7613:         } else {
 7614:             return ('write error',$result);
 7615:         }
 7616:         if ($deloutcome eq 'ok') {
 7617:             return 'ok';
 7618:         } else {
 7619:             return ('delete error',$deloutcome);
 7620:         }
 7621:     }
 7622: }
 7623: 
 7624: sub modify_group_roles {
 7625:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 7626:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 7627:     my $role = 'gr/'.&escape($userprivs);
 7628:     my ($uname,$udom) = split(/:/,$user);
 7629:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 7630:     if ($result eq 'ok') {
 7631:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 7632:     }
 7633:     return $result;
 7634: }
 7635: 
 7636: sub modify_coursegroup_membership {
 7637:     my ($cdom,$cnum,$membership) = @_;
 7638:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 7639:     return $result;
 7640: }
 7641: 
 7642: sub get_active_groups {
 7643:     my ($udom,$uname,$cdom,$cnum) = @_;
 7644:     my $now = time;
 7645:     my %groups = ();
 7646:     foreach my $key (keys(%env)) {
 7647:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 7648:             my ($start,$end) = split(/\./,$env{$key});
 7649:             if (($end!=0) && ($end<$now)) { next; }
 7650:             if (($start!=0) && ($start>$now)) { next; }
 7651:             if ($1 eq $cdom && $2 eq $cnum) {
 7652:                 $groups{$3} = $env{$key} ;
 7653:             }
 7654:         }
 7655:     }
 7656:     return %groups;
 7657: }
 7658: 
 7659: sub get_group_membership {
 7660:     my ($cdom,$cnum,$group) = @_;
 7661:     return(&dump('groupmembership',$cdom,$cnum,$group));
 7662: }
 7663: 
 7664: sub get_users_groups {
 7665:     my ($udom,$uname,$courseid) = @_;
 7666:     my @usersgroups;
 7667:     my $cachetime=1800;
 7668: 
 7669:     my $hashid="$udom:$uname:$courseid";
 7670:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 7671:     if (defined($cached)) {
 7672:         @usersgroups = split(/:/,$grouplist);
 7673:     } else {  
 7674:         $grouplist = '';
 7675:         my $courseurl = &courseid_to_courseurl($courseid);
 7676:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 7677:         my $access_end = $env{'course.'.$courseid.
 7678:                               '.default_enrollment_end_date'};
 7679:         my $now = time;
 7680:         foreach my $key (keys(%roleshash)) {
 7681:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 7682:                 my $group = $1;
 7683:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 7684:                     my $start = $2;
 7685:                     my $end = $1;
 7686:                     if ($start == -1) { next; } # deleted from group
 7687:                     if (($start!=0) && ($start>$now)) { next; }
 7688:                     if (($end!=0) && ($end<$now)) {
 7689:                         if ($access_end && $access_end < $now) {
 7690:                             if ($access_end - $end < 86400) {
 7691:                                 push(@usersgroups,$group);
 7692:                             }
 7693:                         }
 7694:                         next;
 7695:                     }
 7696:                     push(@usersgroups,$group);
 7697:                 }
 7698:             }
 7699:         }
 7700:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 7701:         $grouplist = join(':',@usersgroups);
 7702:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 7703:     }
 7704:     return @usersgroups;
 7705: }
 7706: 
 7707: sub devalidate_getgroups_cache {
 7708:     my ($udom,$uname,$cdom,$cnum)=@_;
 7709:     my $courseid = $cdom.'_'.$cnum;
 7710: 
 7711:     my $hashid="$udom:$uname:$courseid";
 7712:     &devalidate_cache_new('getgroups',$hashid);
 7713: }
 7714: 
 7715: # ------------------------------------------------------------------ Plain Text
 7716: 
 7717: sub plaintext {
 7718:     my ($short,$type,$cid,$forcedefault) = @_;
 7719:     if ($short =~ m{^cr/}) {
 7720: 	return (split('/',$short))[-1];
 7721:     }
 7722:     if (!defined($cid)) {
 7723:         $cid = $env{'request.course.id'};
 7724:     }
 7725:     my %rolenames = (
 7726:                       Course    => 'std',
 7727:                       Community => 'alt1',
 7728:                     );
 7729:     if ($cid ne '') {
 7730:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
 7731:             unless ($forcedefault) {
 7732:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
 7733:                 &Apache::lonlocal::mt_escape(\$roletext);
 7734:                 return &Apache::lonlocal::mt($roletext);
 7735:             }
 7736:         }
 7737:     }
 7738:     if ((defined($type)) && (defined($rolenames{$type})) &&
 7739:         (defined($rolenames{$type})) && 
 7740:         (defined($prp{$short}{$rolenames{$type}}))) {
 7741:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 7742:     } elsif ($cid ne '') {
 7743:         my $crstype = $env{'course.'.$cid.'.type'};
 7744:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
 7745:             (defined($prp{$short}{$rolenames{$crstype}}))) {
 7746:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
 7747:         }
 7748:     }
 7749:     return &Apache::lonlocal::mt($prp{$short}{'std'});
 7750: }
 7751: 
 7752: # ----------------------------------------------------------------- Assign Role
 7753: 
 7754: sub assignrole {
 7755:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
 7756:         $context)=@_;
 7757:     my $mrole;
 7758:     if ($role =~ /^cr\//) {
 7759:         my $cwosec=$url;
 7760:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 7761: 	unless (&allowed('ccr',$cwosec)) {
 7762:            my $refused = 1;
 7763:            if ($context eq 'requestcourses') {
 7764:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 7765:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
 7766:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
 7767:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 7768:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 7769:                            if ($crsenv{'internal.courseowner'} eq
 7770:                                $env{'user.name'}.':'.$env{'user.domain'}) {
 7771:                                $refused = '';
 7772:                            }
 7773:                        }
 7774:                    }
 7775:                }
 7776:            }
 7777:            if ($refused) {
 7778:                &logthis('Refused custom assignrole: '.
 7779:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
 7780:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
 7781:                return 'refused';
 7782:            }
 7783:         }
 7784:         $mrole='cr';
 7785:     } elsif ($role =~ /^gr\//) {
 7786:         my $cwogrp=$url;
 7787:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 7788:         unless (&allowed('mdg',$cwogrp)) {
 7789:             &logthis('Refused group assignrole: '.
 7790:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 7791:                     $env{'user.name'}.' at '.$env{'user.domain'});
 7792:             return 'refused';
 7793:         }
 7794:         $mrole='gr';
 7795:     } else {
 7796:         my $cwosec=$url;
 7797:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 7798:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 7799:             my $refused;
 7800:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 7801:                 if (!(&allowed('c'.$role,$url))) {
 7802:                     $refused = 1;
 7803:                 }
 7804:             } else {
 7805:                 $refused = 1;
 7806:             }
 7807:             if ($refused) {
 7808:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 7809:                 if (!$selfenroll && $context eq 'course') {
 7810:                     my %crsenv;
 7811:                     if ($role eq 'cc' || $role eq 'co') {
 7812:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 7813:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
 7814:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
 7815:                                 if ($crsenv{'internal.courseowner'} eq 
 7816:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 7817:                                     $refused = '';
 7818:                                 }
 7819:                             }
 7820:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
 7821:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
 7822:                                 if ($crsenv{'internal.courseowner'} eq 
 7823:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 7824:                                     $refused = '';
 7825:                                 }
 7826:                             }
 7827:                         }
 7828:                     }
 7829:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 7830:                     $refused = '';
 7831:                 } elsif ($context eq 'requestcourses') {
 7832:                     my @possroles = ('st','ta','ep','in','cc','co');
 7833:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
 7834:                         my $wrongcc;
 7835:                         if ($cnum =~ /^$match_community$/) {
 7836:                             $wrongcc = 1 if ($role eq 'cc');
 7837:                         } else {
 7838:                             $wrongcc = 1 if ($role eq 'co');
 7839:                         }
 7840:                         unless ($wrongcc) {
 7841:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 7842:                             if ($crsenv{'internal.courseowner'} eq 
 7843:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
 7844:                                 $refused = '';
 7845:                             }
 7846:                         }
 7847:                     }
 7848:                 } elsif ($context eq 'requestauthor') {
 7849:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
 7850:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
 7851:                         if ($env{'environment.requestauthor'} eq 'automatic') {
 7852:                             $refused = '';
 7853:                         } else {
 7854:                             my %domdefaults = &get_domain_defaults($udom);
 7855:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
 7856:                                 my $checkbystatus;
 7857:                                 if ($env{'user.adv'}) { 
 7858:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
 7859:                                     if ($disposition eq 'automatic') {
 7860:                                         $refused = '';
 7861:                                     } elsif ($disposition eq '') {
 7862:                                         $checkbystatus = 1;
 7863:                                     } 
 7864:                                 } else {
 7865:                                     $checkbystatus = 1;
 7866:                                 }
 7867:                                 if ($checkbystatus) {
 7868:                                     if ($env{'environment.inststatus'}) {
 7869:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
 7870:                                         foreach my $type (@inststatuses) {
 7871:                                             if (($type ne '') &&
 7872:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
 7873:                                                 $refused = '';
 7874:                                             }
 7875:                                         }
 7876:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
 7877:                                         $refused = '';
 7878:                                     }
 7879:                                 }
 7880:                             }
 7881:                         }
 7882:                     }
 7883:                 }
 7884:                 if ($refused) {
 7885:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 7886:                              ' '.$role.' '.$end.' '.$start.' by '.
 7887: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
 7888:                     return 'refused';
 7889:                 }
 7890:             }
 7891:         } elsif ($role eq 'au') {
 7892:             if ($url ne '/'.$udom.'/') {
 7893:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
 7894:                          ' to assign author role for '.$uname.':'.$udom.
 7895:                          ' in domain: '.$url.' refused (wrong domain).');
 7896:                 return 'refused';
 7897:             }
 7898:         }
 7899:         $mrole=$role;
 7900:     }
 7901:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 7902:                 "$udom:$uname:$url".'_'."$mrole=$role";
 7903:     if ($end) { $command.='_'.$end; }
 7904:     if ($start) {
 7905: 	if ($end) { 
 7906:            $command.='_'.$start; 
 7907:         } else {
 7908:            $command.='_0_'.$start;
 7909:         }
 7910:     }
 7911:     my $origstart = $start;
 7912:     my $origend = $end;
 7913:     my $delflag;
 7914: # actually delete
 7915:     if ($deleteflag) {
 7916: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 7917: # modify command to delete the role
 7918:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 7919:                 "$udom:$uname:$url".'_'."$mrole";
 7920: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 7921: # set start and finish to negative values for userrolelog
 7922:            $start=-1;
 7923:            $end=-1;
 7924:            $delflag = 1;
 7925:         }
 7926:     }
 7927: # send command
 7928:     my $answer=&reply($command,&homeserver($uname,$udom));
 7929: # log new user role if status is ok
 7930:     if ($answer eq 'ok') {
 7931: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 7932: # for course roles, perform group memberships changes triggered by role change.
 7933:         unless ($role =~ /^gr/) {
 7934:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 7935:                                              $origstart,$selfenroll,$context);
 7936:         }
 7937:         if (($role eq 'cc') || ($role eq 'in') ||
 7938:             ($role eq 'ep') || ($role eq 'ad') ||
 7939:             ($role eq 'ta') || ($role eq 'st') ||
 7940:             ($role=~/^cr/) || ($role eq 'gr') ||
 7941:             ($role eq 'co')) {
 7942:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 7943:                            $selfenroll,$context);
 7944:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
 7945:                  ($role eq 'au') || ($role eq 'dc')) {
 7946:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 7947:                            $context);
 7948:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
 7949:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 7950:                              $context); 
 7951:         }
 7952:         if ($role eq 'cc') {
 7953:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
 7954:         }
 7955:     }
 7956:     return $answer;
 7957: }
 7958: 
 7959: sub autoupdate_coowners {
 7960:     my ($url,$end,$start,$uname,$udom) = @_;
 7961:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
 7962:     if (($cdom ne '') && ($cnum ne '')) {
 7963:         my $now = time;
 7964:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
 7965:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
 7966:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
 7967:             my $instcode = $coursehash{'internal.coursecode'};
 7968:             if ($instcode ne '') {
 7969:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
 7970:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
 7971:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
 7972:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
 7973:                         if ($result eq 'valid') {
 7974:                             if ($coursehash{'internal.co-owners'}) {
 7975:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 7976:                                     push(@newcoowners,$coowner);
 7977:                                 }
 7978:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
 7979:                                     push(@newcoowners,$uname.':'.$udom);
 7980:                                 }
 7981:                                 @newcoowners = sort(@newcoowners);
 7982:                             } else {
 7983:                                 push(@newcoowners,$uname.':'.$udom);
 7984:                             }
 7985:                         } else {
 7986:                             if ($coursehash{'internal.co-owners'}) {
 7987:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 7988:                                     unless ($coowner eq $uname.':'.$udom) {
 7989:                                         push(@newcoowners,$coowner);
 7990:                                     }
 7991:                                 }
 7992:                                 unless (@newcoowners > 0) {
 7993:                                     $delcoowners = 1;
 7994:                                     $coowners = '';
 7995:                                 }
 7996:                             }
 7997:                         }
 7998:                         if (@newcoowners || $delcoowners) {
 7999:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
 8000:                                             $delcoowners,@newcoowners);
 8001:                         }
 8002:                     }
 8003:                 }
 8004:             }
 8005:         }
 8006:     }
 8007: }
 8008: 
 8009: sub store_coowners {
 8010:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
 8011:     my $cid = $cdom.'_'.$cnum;
 8012:     my ($coowners,$delresult,$putresult);
 8013:     if (@newcoowners) {
 8014:         $coowners = join(',',@newcoowners);
 8015:         my %coownershash = (
 8016:                             'internal.co-owners' => $coowners,
 8017:                            );
 8018:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
 8019:         if ($putresult eq 'ok') {
 8020:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
 8021:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
 8022:             }
 8023:         }
 8024:     }
 8025:     if ($delcoowners) {
 8026:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
 8027:         if ($delresult eq 'ok') {
 8028:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
 8029:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
 8030:             }
 8031:         }
 8032:     }
 8033:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
 8034:         my %crsinfo =
 8035:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 8036:         if (ref($crsinfo{$cid}) eq 'HASH') {
 8037:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
 8038:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
 8039:         }
 8040:     }
 8041: }
 8042: 
 8043: # -------------------------------------------------- Modify user authentication
 8044: # Overrides without validation
 8045: 
 8046: sub modifyuserauth {
 8047:     my ($udom,$uname,$umode,$upass)=@_;
 8048:     my $uhome=&homeserver($uname,$udom);
 8049:     unless (&allowed('mau',$udom)) { return 'refused'; }
 8050:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 8051:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 8052:              ' in domain '.$env{'request.role.domain'});  
 8053:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 8054: 		     &escape($upass),$uhome);
 8055:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 8056:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 8057:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 8058:     &log($udom,,$uname,$uhome,
 8059:         'Authentication changed by '.$env{'user.domain'}.', '.
 8060:                                      $env{'user.name'}.', '.$umode.
 8061:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 8062:     unless ($reply eq 'ok') {
 8063:         &logthis('Authentication mode error: '.$reply);
 8064: 	return 'error: '.$reply;
 8065:     }   
 8066:     return 'ok';
 8067: }
 8068: 
 8069: # --------------------------------------------------------------- Modify a user
 8070: 
 8071: sub modifyuser {
 8072:     my ($udom,    $uname, $uid,
 8073:         $umode,   $upass, $first,
 8074:         $middle,  $last,  $gene,
 8075:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
 8076:     $udom= &LONCAPA::clean_domain($udom);
 8077:     $uname=&LONCAPA::clean_username($uname);
 8078:     my $showcandelete = 'none';
 8079:     if (ref($candelete) eq 'ARRAY') {
 8080:         if (@{$candelete} > 0) {
 8081:             $showcandelete = join(', ',@{$candelete});
 8082:         }
 8083:     }
 8084:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 8085:              $umode.', '.$first.', '.$middle.', '.
 8086: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
 8087:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 8088:                                      ' desiredhome not specified'). 
 8089:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 8090:              ' in domain '.$env{'request.role.domain'});
 8091:     my $uhome=&homeserver($uname,$udom,'true');
 8092:     my $newuser;
 8093:     if ($uhome eq 'no_host') {
 8094:         $newuser = 1;
 8095:     }
 8096: # ----------------------------------------------------------------- Create User
 8097:     if (($uhome eq 'no_host') && 
 8098: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 8099:         my $unhome='';
 8100:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 8101:             $unhome = $desiredhome;
 8102: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 8103: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 8104:         } else { # load balancing routine for determining $unhome
 8105:             my $loadm=10000000;
 8106: 	    my %servers = &get_servers($udom,'library');
 8107: 	    foreach my $tryserver (keys(%servers)) {
 8108: 		my $answer=reply('load',$tryserver);
 8109: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 8110: 		    $loadm=$answer;
 8111: 		    $unhome=$tryserver;
 8112: 		}
 8113: 	    }
 8114:         }
 8115:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 8116: 	    return 'error: unable to find a home server for '.$uname.
 8117:                    ' in domain '.$udom;
 8118:         }
 8119:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 8120:                          &escape($upass),$unhome);
 8121: 	unless ($reply eq 'ok') {
 8122:             return 'error: '.$reply;
 8123:         }   
 8124:         $uhome=&homeserver($uname,$udom,'true');
 8125:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 8126: 	    return 'error: unable verify users home machine.';
 8127:         }
 8128:     }   # End of creation of new user
 8129: # ---------------------------------------------------------------------- Add ID
 8130:     if ($uid) {
 8131:        $uid=~tr/A-Z/a-z/;
 8132:        my %uidhash=&idrget($udom,$uname);
 8133:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 8134:          && (!$forceid)) {
 8135: 	  unless ($uid eq $uidhash{$uname}) {
 8136: 	      return 'error: user id "'.$uid.'" does not match '.
 8137:                   'current user id "'.$uidhash{$uname}.'".';
 8138:           }
 8139:        } else {
 8140: 	  &idput($udom,($uname => $uid));
 8141:        }
 8142:     }
 8143: # -------------------------------------------------------------- Add names, etc
 8144:     my @tmp=&get('environment',
 8145: 		   ['firstname','middlename','lastname','generation','id',
 8146:                     'permanentemail','inststatus'],
 8147: 		   $udom,$uname);
 8148:     my (%names,%oldnames);
 8149:     if ($tmp[0] =~ m/^error:.*/) { 
 8150:         %names=(); 
 8151:     } else {
 8152:         %names = @tmp;
 8153:         %oldnames = %names;
 8154:     }
 8155: #
 8156: # If name, email and/or uid are blank (e.g., because an uploaded file
 8157: # of users did not contain them), do not overwrite existing values
 8158: # unless field is in $candelete array ref.  
 8159: #
 8160: 
 8161:     my @fields = ('firstname','middlename','lastname','generation',
 8162:                   'permanentemail','id');
 8163:     my %newvalues;
 8164:     if (ref($candelete) eq 'ARRAY') {
 8165:         foreach my $field (@fields) {
 8166:             if (grep(/^\Q$field\E$/,@{$candelete})) {
 8167:                 if ($field eq 'firstname') {
 8168:                     $names{$field} = $first;
 8169:                 } elsif ($field eq 'middlename') {
 8170:                     $names{$field} = $middle;
 8171:                 } elsif ($field eq 'lastname') {
 8172:                     $names{$field} = $last;
 8173:                 } elsif ($field eq 'generation') { 
 8174:                     $names{$field} = $gene;
 8175:                 } elsif ($field eq 'permanentemail') {
 8176:                     $names{$field} = $email;
 8177:                 } elsif ($field eq 'id') {
 8178:                     $names{$field}  = $uid;
 8179:                 }
 8180:             }
 8181:         }
 8182:     }
 8183:     if ($first)  { $names{'firstname'}  = $first; }
 8184:     if (defined($middle)) { $names{'middlename'} = $middle; }
 8185:     if ($last)   { $names{'lastname'}   = $last; }
 8186:     if (defined($gene))   { $names{'generation'} = $gene; }
 8187:     if ($email) {
 8188:        $email=~s/[^\w\@\.\-\,]//gs;
 8189:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
 8190:     }
 8191:     if ($uid) { $names{'id'}  = $uid; }
 8192:     if (defined($inststatus)) {
 8193:         $names{'inststatus'} = '';
 8194:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
 8195:         if (ref($usertypes) eq 'HASH') {
 8196:             my @okstatuses; 
 8197:             foreach my $item (split(/:/,$inststatus)) {
 8198:                 if (defined($usertypes->{$item})) {
 8199:                     push(@okstatuses,$item);  
 8200:                 }
 8201:             }
 8202:             if (@okstatuses) {
 8203:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
 8204:             }
 8205:         }
 8206:     }
 8207:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
 8208:                  $umode.', '.$first.', '.$middle.', '.
 8209:                  $last.', '.$gene.', '.$email.', '.$inststatus;
 8210:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
 8211:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
 8212:     } else {
 8213:         $logmsg .= ' during self creation';
 8214:     }
 8215:     my $changed;
 8216:     if ($newuser) {
 8217:         $changed = 1;
 8218:     } else {
 8219:         foreach my $field (@fields) {
 8220:             if ($names{$field} ne $oldnames{$field}) {
 8221:                 $changed = 1;
 8222:                 last;
 8223:             }
 8224:         }
 8225:     }
 8226:     unless ($changed) {
 8227:         $logmsg = 'No changes in user information needed for: '.$logmsg;
 8228:         &logthis($logmsg);
 8229:         return 'ok';
 8230:     }
 8231:     my $reply = &put('environment', \%names, $udom,$uname);
 8232:     if ($reply ne 'ok') { 
 8233:         return 'error: '.$reply;
 8234:     }
 8235:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
 8236:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
 8237:     }
 8238:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
 8239:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 8240:     $logmsg = 'Success modifying user '.$logmsg;
 8241:     &logthis($logmsg);
 8242:     return 'ok';
 8243: }
 8244: 
 8245: # -------------------------------------------------------------- Modify student
 8246: 
 8247: sub modifystudent {
 8248:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 8249:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
 8250:         $selfenroll,$context,$inststatus)=@_;
 8251:     if (!$cid) {
 8252: 	unless ($cid=$env{'request.course.id'}) {
 8253: 	    return 'not_in_class';
 8254: 	}
 8255:     }
 8256: # --------------------------------------------------------------- Make the user
 8257:     my $reply=&modifyuser
 8258: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 8259:          $desiredhome,$email,$inststatus);
 8260:     unless ($reply eq 'ok') { return $reply; }
 8261:     # This will cause &modify_student_enrollment to get the uid from the
 8262:     # students environment
 8263:     $uid = undef if (!$forceid);
 8264:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 8265: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
 8266:     return $reply;
 8267: }
 8268: 
 8269: sub modify_student_enrollment {
 8270:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
 8271:     my ($cdom,$cnum,$chome);
 8272:     if (!$cid) {
 8273: 	unless ($cid=$env{'request.course.id'}) {
 8274: 	    return 'not_in_class';
 8275: 	}
 8276: 	$cdom=$env{'course.'.$cid.'.domain'};
 8277: 	$cnum=$env{'course.'.$cid.'.num'};
 8278:     } else {
 8279: 	($cdom,$cnum)=split(/_/,$cid);
 8280:     }
 8281:     $chome=$env{'course.'.$cid.'.home'};
 8282:     if (!$chome) {
 8283: 	$chome=&homeserver($cnum,$cdom);
 8284:     }
 8285:     if (!$chome) { return 'unknown_course'; }
 8286:     # Make sure the user exists
 8287:     my $uhome=&homeserver($uname,$udom);
 8288:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 8289: 	return 'error: no such user';
 8290:     }
 8291:     # Get student data if we were not given enough information
 8292:     if (!defined($first)  || $first  eq '' || 
 8293:         !defined($last)   || $last   eq '' || 
 8294:         !defined($uid)    || $uid    eq '' || 
 8295:         !defined($middle) || $middle eq '' || 
 8296:         !defined($gene)   || $gene   eq '') {
 8297:         # They did not supply us with enough data to enroll the student, so
 8298:         # we need to pick up more information.
 8299:         my %tmp = &get('environment',
 8300:                        ['firstname','middlename','lastname', 'generation','id']
 8301:                        ,$udom,$uname);
 8302: 
 8303:         #foreach my $key (keys(%tmp)) {
 8304:         #    &logthis("key $key = ".$tmp{$key});
 8305:         #}
 8306:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 8307:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 8308:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 8309:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 8310:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 8311:     }
 8312:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 8313:     my $user = "$uname:$udom";
 8314:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
 8315:     my $reply=cput('classlist',
 8316: 		   {$user => 
 8317: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
 8318: 		   $cdom,$cnum);
 8319:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
 8320:         &devalidate_getsection_cache($udom,$uname,$cid);
 8321:     } else { 
 8322: 	return 'error: '.$reply;
 8323:     }
 8324:     # Add student role to user
 8325:     my $uurl='/'.$cid;
 8326:     $uurl=~s/\_/\//g;
 8327:     if ($usec) {
 8328: 	$uurl.='/'.$usec;
 8329:     }
 8330:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
 8331:                              $selfenroll,$context);
 8332:     if ($result ne 'ok') {
 8333:         if ($old_entry{$user} ne '') {
 8334:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
 8335:         } else {
 8336:             $reply = &del('classlist',[$user],$cdom,$cnum);
 8337:         }
 8338:     }
 8339:     return $result; 
 8340: }
 8341: 
 8342: sub format_name {
 8343:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 8344:     my $name;
 8345:     if ($first ne 'lastname') {
 8346: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 8347:     } else {
 8348: 	if ($lastname=~/\S/) {
 8349: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 8350: 	    $name=~s/\s+,/,/;
 8351: 	} else {
 8352: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 8353: 	}
 8354:     }
 8355:     $name=~s/^\s+//;
 8356:     $name=~s/\s+$//;
 8357:     $name=~s/\s+/ /g;
 8358:     return $name;
 8359: }
 8360: 
 8361: # ------------------------------------------------- Write to course preferences
 8362: 
 8363: sub writecoursepref {
 8364:     my ($courseid,%prefs)=@_;
 8365:     $courseid=~s/^\///;
 8366:     $courseid=~s/\_/\//g;
 8367:     my ($cdomain,$cnum)=split(/\//,$courseid);
 8368:     my $chome=homeserver($cnum,$cdomain);
 8369:     if (($chome eq '') || ($chome eq 'no_host')) { 
 8370: 	return 'error: no such course';
 8371:     }
 8372:     my $cstring='';
 8373:     foreach my $pref (keys(%prefs)) {
 8374: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 8375:     }
 8376:     $cstring=~s/\&$//;
 8377:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 8378: }
 8379: 
 8380: # ---------------------------------------------------------- Make/modify course
 8381: 
 8382: sub createcourse {
 8383:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 8384:         $course_owner,$crstype,$cnum,$context,$category)=@_;
 8385:     $url=&declutter($url);
 8386:     my $cid='';
 8387:     if ($context eq 'requestcourses') {
 8388:         my $can_create = 0;
 8389:         my ($ownername,$ownerdom) = split(':',$course_owner);
 8390:         if ($udom eq $ownerdom) {
 8391:             if (&usertools_access($ownername,$ownerdom,$category,undef,
 8392:                                   $context)) {
 8393:                 $can_create = 1;
 8394:             }
 8395:         } else {
 8396:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
 8397:                                            $category);
 8398:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
 8399:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
 8400:                 if (@curr > 0) {
 8401:                     my @options = qw(approval validate autolimit);
 8402:                     my $optregex = join('|',@options);
 8403:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
 8404:                         $can_create = 1;
 8405:                     }
 8406:                 }
 8407:             }
 8408:         }
 8409:         if ($can_create) {
 8410:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
 8411:                 unless (&allowed('ccc',$udom)) {
 8412:                     return 'refused'; 
 8413:                 }
 8414:             }
 8415:         } else {
 8416:             return 'refused';
 8417:         }
 8418:     } elsif (!&allowed('ccc',$udom)) {
 8419:         return 'refused';
 8420:     }
 8421: # --------------------------------------------------------------- Get Unique ID
 8422:     my $uname;
 8423:     if ($cnum =~ /^$match_courseid$/) {
 8424:         my $chome=&homeserver($cnum,$udom,'true');
 8425:         if (($chome eq '') || ($chome eq 'no_host')) {
 8426:             $uname = $cnum;
 8427:         } else {
 8428:             $uname = &generate_coursenum($udom,$crstype);
 8429:         }
 8430:     } else {
 8431:         $uname = &generate_coursenum($udom,$crstype);
 8432:     }
 8433:     return $uname if ($uname =~ /^error/);
 8434: # -------------------------------------------------- Check supplied server name
 8435:     if (!defined($course_server)) {
 8436:         if (defined(&domain($udom,'primary'))) {
 8437:             $course_server = &domain($udom,'primary');
 8438:         } else {
 8439:             $course_server = $env{'user.home'}; 
 8440:         }
 8441:     }
 8442:     my %host_servers =
 8443:         &Apache::lonnet::get_servers($udom,'library');
 8444:     unless ($host_servers{$course_server}) {
 8445:         return 'error: invalid home server for course: '.$course_server;
 8446:     }
 8447: # ------------------------------------------------------------- Make the course
 8448:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 8449:                       $course_server);
 8450:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 8451:     my $uhome=&homeserver($uname,$udom,'true');
 8452:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 8453: 	return 'error: no such course';
 8454:     }
 8455: # ----------------------------------------------------------------- Course made
 8456: # log existence
 8457:     my $now = time;
 8458:     my $newcourse = {
 8459:                     $udom.'_'.$uname => {
 8460:                                      description => $description,
 8461:                                      inst_code   => $inst_code,
 8462:                                      owner       => $course_owner,
 8463:                                      type        => $crstype,
 8464:                                      creator     => $env{'user.name'}.':'.
 8465:                                                     $env{'user.domain'},
 8466:                                      created     => $now,
 8467:                                      context     => $context,
 8468:                                                 },
 8469:                     };
 8470:     &courseidput($udom,$newcourse,$uhome,'notime');
 8471: # set toplevel url
 8472:     my $topurl=$url;
 8473:     unless ($nonstandard) {
 8474: # ------------------------------------------ For standard courses, make top url
 8475:         my $mapurl=&clutter($url);
 8476:         if ($mapurl eq '/res/') { $mapurl=''; }
 8477:         $env{'form.initmap'}=(<<ENDINITMAP);
 8478: <map>
 8479: <resource id="1" type="start"></resource>
 8480: <resource id="2" src="$mapurl"></resource>
 8481: <resource id="3" type="finish"></resource>
 8482: <link index="1" from="1" to="2"></link>
 8483: <link index="2" from="2" to="3"></link>
 8484: </map>
 8485: ENDINITMAP
 8486:         $topurl=&declutter(
 8487:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 8488:                           );
 8489:     }
 8490: # ----------------------------------------------------------- Write preferences
 8491:     &writecoursepref($udom.'_'.$uname,
 8492:                      ('description'              => $description,
 8493:                       'url'                      => $topurl,
 8494:                       'internal.creator'         => $env{'user.name'}.':'.
 8495:                                                     $env{'user.domain'},
 8496:                       'internal.created'         => $now,
 8497:                       'internal.creationcontext' => $context)
 8498:                     );
 8499:     return '/'.$udom.'/'.$uname;
 8500: }
 8501: 
 8502: # ------------------------------------------------------------------- Create ID
 8503: sub generate_coursenum {
 8504:     my ($udom,$crstype) = @_;
 8505:     my $domdesc = &domain($udom);
 8506:     return 'error: invalid domain' if ($domdesc eq '');
 8507:     my $first;
 8508:     if ($crstype eq 'Community') {
 8509:         $first = '0';
 8510:     } else {
 8511:         $first = int(1+rand(9)); 
 8512:     } 
 8513:     my $uname=$first.
 8514:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 8515:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
 8516:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 8517: # ----------------------------------------------- Make sure that does not exist
 8518:     my $uhome=&homeserver($uname,$udom,'true');
 8519:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
 8520:         if ($crstype eq 'Community') {
 8521:             $first = '0';
 8522:         } else {
 8523:             $first = int(1+rand(9));
 8524:         }
 8525:         $uname=$first.
 8526:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 8527:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
 8528:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 8529:         $uhome=&homeserver($uname,$udom,'true');
 8530:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
 8531:             return 'error: unable to generate unique course-ID';
 8532:         }
 8533:     }
 8534:     return $uname;
 8535: }
 8536: 
 8537: sub is_course {
 8538:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
 8539:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
 8540: 
 8541:     return unless $cdom and $cnum;
 8542: 
 8543:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
 8544:         '.');
 8545: 
 8546:     return unless exists($courses{$cdom.'_'.$cnum});
 8547:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
 8548: }
 8549: 
 8550: sub store_userdata {
 8551:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
 8552:     my $result;
 8553:     if ($datakey ne '') {
 8554:         if (ref($storehash) eq 'HASH') {
 8555:             if ($udom eq '' || $uname eq '') {
 8556:                 $udom = $env{'user.domain'};
 8557:                 $uname = $env{'user.name'};
 8558:             }
 8559:             my $uhome=&homeserver($uname,$udom);
 8560:             if (($uhome eq '') || ($uhome eq 'no_host')) {
 8561:                 $result = 'error: no_host';
 8562:             } else {
 8563:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
 8564:                 $storehash->{'host'} = $perlvar{'lonHostID'};
 8565: 
 8566:                 my $namevalue='';
 8567:                 foreach my $key (keys(%{$storehash})) {
 8568:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 8569:                 }
 8570:                 $namevalue=~s/\&$//;
 8571:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
 8572:                                   $namevalue,$uhome);
 8573:             }
 8574:         } else {
 8575:             $result = 'error: data to store was not a hash reference'; 
 8576:         }
 8577:     } else {
 8578:         $result= 'error: invalid requestkey'; 
 8579:     }
 8580:     return $result;
 8581: }
 8582: 
 8583: # ---------------------------------------------------------- Assign Custom Role
 8584: 
 8585: sub assigncustomrole {
 8586:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
 8587:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 8588:                        $end,$start,$deleteflag,$selfenroll,$context);
 8589: }
 8590: 
 8591: # ----------------------------------------------------------------- Revoke Role
 8592: 
 8593: sub revokerole {
 8594:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
 8595:     my $now=time;
 8596:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
 8597: }
 8598: 
 8599: # ---------------------------------------------------------- Revoke Custom Role
 8600: 
 8601: sub revokecustomrole {
 8602:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
 8603:     my $now=time;
 8604:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 8605:            $deleteflag,$selfenroll,$context);
 8606: }
 8607: 
 8608: # ------------------------------------------------------------ Disk usage
 8609: sub diskusage {
 8610:     my ($udom,$uname,$directorypath,$getpropath)=@_;
 8611:     $directorypath =~ s/\/$//;
 8612:     my $listing=&reply('du2:'.&escape($directorypath).':'
 8613:                        .&escape($getpropath).':'.&escape($uname).':'
 8614:                        .&escape($udom),homeserver($uname,$udom));
 8615:     if ($listing eq 'unknown_cmd') {
 8616:         if ($getpropath) {
 8617:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
 8618:         }
 8619:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
 8620:     }
 8621:     return $listing;
 8622: }
 8623: 
 8624: sub is_locked {
 8625:     my ($file_name, $domain, $user, $which) = @_;
 8626:     my @check;
 8627:     my $is_locked;
 8628:     push (@check,$file_name);
 8629:     my %locked = &get('file_permissions',\@check,
 8630: 		      $env{'user.domain'},$env{'user.name'});
 8631:     my ($tmp)=keys(%locked);
 8632:     if ($tmp=~/^error:/) { undef(%locked); }
 8633:     
 8634:     if (ref($locked{$file_name}) eq 'ARRAY') {
 8635:         $is_locked = 'false';
 8636:         foreach my $entry (@{$locked{$file_name}}) {
 8637:            if (ref($entry) eq 'ARRAY') {
 8638:                $is_locked = 'true';
 8639:                if (ref($which) eq 'ARRAY') {
 8640:                    push(@{$which},$entry);
 8641:                } else {
 8642:                    last;
 8643:                }
 8644:            }
 8645:        }
 8646:     } else {
 8647:         $is_locked = 'false';
 8648:     }
 8649:     return $is_locked;
 8650: }
 8651: 
 8652: sub declutter_portfile {
 8653:     my ($file) = @_;
 8654:     $file =~ s{^(/portfolio/|portfolio/)}{/};
 8655:     return $file;
 8656: }
 8657: 
 8658: # ------------------------------------------------------------- Mark as Read Only
 8659: 
 8660: sub mark_as_readonly {
 8661:     my ($domain,$user,$files,$what) = @_;
 8662:     my %current_permissions = &dump('file_permissions',$domain,$user);
 8663:     my ($tmp)=keys(%current_permissions);
 8664:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 8665:     foreach my $file (@{$files}) {
 8666: 	$file = &declutter_portfile($file);
 8667:         push(@{$current_permissions{$file}},$what);
 8668:     }
 8669:     &put('file_permissions',\%current_permissions,$domain,$user);
 8670:     return;
 8671: }
 8672: 
 8673: # ------------------------------------------------------------Save Selected Files
 8674: 
 8675: sub save_selected_files {
 8676:     my ($user, $path, @files) = @_;
 8677:     my $filename = $user."savedfiles";
 8678:     my @other_files = &files_not_in_path($user, $path);
 8679:     open (OUT, '>'.$tmpdir.$filename);
 8680:     foreach my $file (@files) {
 8681:         print (OUT $env{'form.currentpath'}.$file."\n");
 8682:     }
 8683:     foreach my $file (@other_files) {
 8684:         print (OUT $file."\n");
 8685:     }
 8686:     close (OUT);
 8687:     return 'ok';
 8688: }
 8689: 
 8690: sub clear_selected_files {
 8691:     my ($user) = @_;
 8692:     my $filename = $user."savedfiles";
 8693:     open (OUT, '>'.LONCAPA::tempdir().$filename);
 8694:     print (OUT undef);
 8695:     close (OUT);
 8696:     return ("ok");    
 8697: }
 8698: 
 8699: sub files_in_path {
 8700:     my ($user, $path) = @_;
 8701:     my $filename = $user."savedfiles";
 8702:     my %return_files;
 8703:     open (IN, '<'.LONCAPA::tempdir().$filename);
 8704:     while (my $line_in = <IN>) {
 8705:         chomp ($line_in);
 8706:         my @paths_and_file = split (m!/!, $line_in);
 8707:         my $file_part = pop (@paths_and_file);
 8708:         my $path_part = join ('/', @paths_and_file);
 8709:         $path_part.='/';
 8710:         my $path_and_file = $path_part.$file_part;
 8711:         if ($path_part eq $path) {
 8712:             $return_files{$file_part}= 'selected';
 8713:         }
 8714:     }
 8715:     close (IN);
 8716:     return (\%return_files);
 8717: }
 8718: 
 8719: # called in portfolio select mode, to show files selected NOT in current directory
 8720: sub files_not_in_path {
 8721:     my ($user, $path) = @_;
 8722:     my $filename = $user."savedfiles";
 8723:     my @return_files;
 8724:     my $path_part;
 8725:     open(IN, '<'.LONCAPA::.$filename);
 8726:     while (my $line = <IN>) {
 8727:         #ok, I know it's clunky, but I want it to work
 8728:         my @paths_and_file = split(m|/|, $line);
 8729:         my $file_part = pop(@paths_and_file);
 8730:         chomp($file_part);
 8731:         my $path_part = join('/', @paths_and_file);
 8732:         $path_part .= '/';
 8733:         my $path_and_file = $path_part.$file_part;
 8734:         if ($path_part ne $path) {
 8735:             push(@return_files, ($path_and_file));
 8736:         }
 8737:     }
 8738:     close(OUT);
 8739:     return (@return_files);
 8740: }
 8741: 
 8742: #----------------------------------------------Get portfolio file permissions
 8743: 
 8744: sub get_portfile_permissions {
 8745:     my ($domain,$user) = @_;
 8746:     my %current_permissions = &dump('file_permissions',$domain,$user);
 8747:     my ($tmp)=keys(%current_permissions);
 8748:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 8749:     return \%current_permissions;
 8750: }
 8751: 
 8752: #---------------------------------------------Get portfolio file access controls
 8753: 
 8754: sub get_access_controls {
 8755:     my ($current_permissions,$group,$file) = @_;
 8756:     my %access;
 8757:     my $real_file = $file;
 8758:     $file =~ s/\.meta$//;
 8759:     if (defined($file)) {
 8760:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
 8761:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
 8762:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
 8763:             }
 8764:         }
 8765:     } else {
 8766:         foreach my $key (keys(%{$current_permissions})) {
 8767:             if ($key =~ /\0accesscontrol$/) {
 8768:                 if (defined($group)) {
 8769:                     if ($key !~ m-^\Q$group\E/-) {
 8770:                         next;
 8771:                     }
 8772:                 }
 8773:                 my ($fullpath) = split(/\0/,$key);
 8774:                 if (ref($$current_permissions{$key}) eq 'HASH') {
 8775:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
 8776:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
 8777:                     }
 8778:                 }
 8779:             }
 8780:         }
 8781:     }
 8782:     return %access;
 8783: }
 8784: 
 8785: sub modify_access_controls {
 8786:     my ($file_name,$changes,$domain,$user)=@_;
 8787:     my ($outcome,$deloutcome);
 8788:     my %store_permissions;
 8789:     my %new_values;
 8790:     my %new_control;
 8791:     my %translation;
 8792:     my @deletions = ();
 8793:     my $now = time;
 8794:     if (exists($$changes{'activate'})) {
 8795:         if (ref($$changes{'activate'}) eq 'HASH') {
 8796:             my @newitems = sort(keys(%{$$changes{'activate'}}));
 8797:             my $numnew = scalar(@newitems);
 8798:             for (my $i=0; $i<$numnew; $i++) {
 8799:                 my $newkey = $newitems[$i];
 8800:                 my $newid = &Apache::loncommon::get_cgi_id();
 8801:                 if ($newkey =~ /^\d+:/) { 
 8802:                     $newkey =~ s/^(\d+)/$newid/;
 8803:                     $translation{$1} = $newid;
 8804:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
 8805:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
 8806:                     $translation{$1} = $newid;
 8807:                 }
 8808:                 $new_values{$file_name."\0".$newkey} = 
 8809:                                           $$changes{'activate'}{$newitems[$i]};
 8810:                 $new_control{$newkey} = $now;
 8811:             }
 8812:         }
 8813:     }
 8814:     my %todelete;
 8815:     my %changed_items;
 8816:     foreach my $action ('delete','update') {
 8817:         if (exists($$changes{$action})) {
 8818:             if (ref($$changes{$action}) eq 'HASH') {
 8819:                 foreach my $key (keys(%{$$changes{$action}})) {
 8820:                     my ($itemnum) = ($key =~ /^([^:]+):/);
 8821:                     if ($action eq 'delete') { 
 8822:                         $todelete{$itemnum} = 1;
 8823:                     } else {
 8824:                         $changed_items{$itemnum} = $key;
 8825:                     }
 8826:                 }
 8827:             }
 8828:         }
 8829:     }
 8830:     # get lock on access controls for file.
 8831:     my $lockhash = {
 8832:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
 8833:                                                        ':'.$env{'user.domain'},
 8834:                    }; 
 8835:     my $tries = 0;
 8836:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 8837:    
 8838:     while (($gotlock ne 'ok') && $tries <3) {
 8839:         $tries ++;
 8840:         sleep 1;
 8841:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 8842:     }
 8843:     if ($gotlock eq 'ok') {
 8844:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
 8845:         my ($tmp)=keys(%curr_permissions);
 8846:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
 8847:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
 8848:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
 8849:             if (ref($curr_controls) eq 'HASH') {
 8850:                 foreach my $control_item (keys(%{$curr_controls})) {
 8851:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
 8852:                     if (defined($todelete{$itemnum})) {
 8853:                         push(@deletions,$file_name."\0".$control_item);
 8854:                     } else {
 8855:                         if (defined($changed_items{$itemnum})) {
 8856:                             $new_control{$changed_items{$itemnum}} = $now;
 8857:                             push(@deletions,$file_name."\0".$control_item);
 8858:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
 8859:                         } else {
 8860:                             $new_control{$control_item} = $$curr_controls{$control_item};
 8861:                         }
 8862:                     }
 8863:                 }
 8864:             }
 8865:         }
 8866:         my ($group);
 8867:         if (&is_course($domain,$user)) {
 8868:             ($group,my $file) = split(/\//,$file_name,2);
 8869:         }
 8870:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
 8871:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
 8872:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
 8873:         #  remove lock
 8874:         my @del_lock = ($file_name."\0".'locked_access_records');
 8875:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
 8876:         my $sqlresult =
 8877:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
 8878:                                     $group);
 8879:     } else {
 8880:         $outcome = "error: could not obtain lockfile\n";  
 8881:     }
 8882:     return ($outcome,$deloutcome,\%new_values,\%translation);
 8883: }
 8884: 
 8885: sub make_public_indefinitely {
 8886:     my ($requrl) = @_;
 8887:     my $now = time;
 8888:     my $action = 'activate';
 8889:     my $aclnum = 0;
 8890:     if (&is_portfolio_url($requrl)) {
 8891:         my (undef,$udom,$unum,$file_name,$group) =
 8892:             &parse_portfolio_url($requrl);
 8893:         my $current_perms = &get_portfile_permissions($udom,$unum);
 8894:         my %access_controls = &get_access_controls($current_perms,
 8895:                                                    $group,$file_name);
 8896:         foreach my $key (keys(%{$access_controls{$file_name}})) {
 8897:             my ($num,$scope,$end,$start) = 
 8898:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 8899:             if ($scope eq 'public') {
 8900:                 if ($start <= $now && $end == 0) {
 8901:                     $action = 'none';
 8902:                 } else {
 8903:                     $action = 'update';
 8904:                     $aclnum = $num;
 8905:                 }
 8906:                 last;
 8907:             }
 8908:         }
 8909:         if ($action eq 'none') {
 8910:              return 'ok';
 8911:         } else {
 8912:             my %changes;
 8913:             my $newend = 0;
 8914:             my $newstart = $now;
 8915:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
 8916:             $changes{$action}{$newkey} = {
 8917:                 type => 'public',
 8918:                 time => {
 8919:                     start => $newstart,
 8920:                     end   => $newend,
 8921:                 },
 8922:             };
 8923:             my ($outcome,$deloutcome,$new_values,$translation) =
 8924:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
 8925:             return $outcome;
 8926:         }
 8927:     } else {
 8928:         return 'invalid';
 8929:     }
 8930: }
 8931: 
 8932: #------------------------------------------------------Get Marked as Read Only
 8933: 
 8934: sub get_marked_as_readonly {
 8935:     my ($domain,$user,$what,$group) = @_;
 8936:     my $current_permissions = &get_portfile_permissions($domain,$user);
 8937:     my @readonly_files;
 8938:     my $cmp1=$what;
 8939:     if (ref($what)) { $cmp1=join('',@{$what}) };
 8940:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 8941:         if (defined($group)) {
 8942:             if ($file_name !~ m-^\Q$group\E/-) {
 8943:                 next;
 8944:             }
 8945:         }
 8946:         if (ref($value) eq "ARRAY"){
 8947:             foreach my $stored_what (@{$value}) {
 8948:                 my $cmp2=$stored_what;
 8949:                 if (ref($stored_what) eq 'ARRAY') {
 8950:                     $cmp2=join('',@{$stored_what});
 8951:                 }
 8952:                 if ($cmp1 eq $cmp2) {
 8953:                     push(@readonly_files, $file_name);
 8954:                     last;
 8955:                 } elsif (!defined($what)) {
 8956:                     push(@readonly_files, $file_name);
 8957:                     last;
 8958:                 }
 8959:             }
 8960:         }
 8961:     }
 8962:     return @readonly_files;
 8963: }
 8964: #-----------------------------------------------------------Get Marked as Read Only Hash
 8965: 
 8966: sub get_marked_as_readonly_hash {
 8967:     my ($current_permissions,$group,$what) = @_;
 8968:     my %readonly_files;
 8969:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 8970:         if (defined($group)) {
 8971:             if ($file_name !~ m-^\Q$group\E/-) {
 8972:                 next;
 8973:             }
 8974:         }
 8975:         if (ref($value) eq "ARRAY"){
 8976:             foreach my $stored_what (@{$value}) {
 8977:                 if (ref($stored_what) eq 'ARRAY') {
 8978:                     foreach my $lock_descriptor(@{$stored_what}) {
 8979:                         if ($lock_descriptor eq 'graded') {
 8980:                             $readonly_files{$file_name} = 'graded';
 8981:                         } elsif ($lock_descriptor eq 'handback') {
 8982:                             $readonly_files{$file_name} = 'handback';
 8983:                         } else {
 8984:                             if (!exists($readonly_files{$file_name})) {
 8985:                                 $readonly_files{$file_name} = 'locked';
 8986:                             }
 8987:                         }
 8988:                     }
 8989:                 } 
 8990:             }
 8991:         } 
 8992:     }
 8993:     return %readonly_files;
 8994: }
 8995: # ------------------------------------------------------------ Unmark as Read Only
 8996: 
 8997: sub unmark_as_readonly {
 8998:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
 8999:     # for portfolio submissions, $what contains [$symb,$crsid] 
 9000:     my ($domain,$user,$what,$file_name,$group) = @_;
 9001:     $file_name = &declutter_portfile($file_name);
 9002:     my $symb_crs = $what;
 9003:     if (ref($what)) { $symb_crs=join('',@$what); }
 9004:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
 9005:     my ($tmp)=keys(%current_permissions);
 9006:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 9007:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
 9008:     foreach my $file (@readonly_files) {
 9009: 	my $clean_file = &declutter_portfile($file);
 9010: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
 9011: 	my $current_locks = $current_permissions{$file};
 9012:         my @new_locks;
 9013:         my @del_keys;
 9014:         if (ref($current_locks) eq "ARRAY"){
 9015:             foreach my $locker (@{$current_locks}) {
 9016:                 my $compare=$locker;
 9017:                 if (ref($locker) eq 'ARRAY') {
 9018:                     $compare=join('',@{$locker});
 9019:                     if ($compare ne $symb_crs) {
 9020:                         push(@new_locks, $locker);
 9021:                     }
 9022:                 }
 9023:             }
 9024:             if (scalar(@new_locks) > 0) {
 9025:                 $current_permissions{$file} = \@new_locks;
 9026:             } else {
 9027:                 push(@del_keys, $file);
 9028:                 &del('file_permissions',\@del_keys, $domain, $user);
 9029:                 delete($current_permissions{$file});
 9030:             }
 9031:         }
 9032:     }
 9033:     &put('file_permissions',\%current_permissions,$domain,$user);
 9034:     return;
 9035: }
 9036: 
 9037: # ------------------------------------------------------------ Directory lister
 9038: 
 9039: sub dirlist {
 9040:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
 9041:     $uri=~s/^\///;
 9042:     $uri=~s/\/$//;
 9043:     my ($udom, $uname);
 9044:     if ($getuserdir) {
 9045:         $udom = $userdomain;
 9046:         $uname = $username;
 9047:     } else {
 9048:         (undef,$udom,$uname)=split(/\//,$uri);
 9049:         if(defined($userdomain)) {
 9050:             $udom = $userdomain;
 9051:         }
 9052:         if(defined($username)) {
 9053:             $uname = $username;
 9054:         }
 9055:     }
 9056:     my ($dirRoot,$listing,@listing_results);
 9057: 
 9058:     $dirRoot = $perlvar{'lonDocRoot'};
 9059:     if (defined($getpropath)) {
 9060:         $dirRoot = &propath($udom,$uname);
 9061:         $dirRoot =~ s/\/$//;
 9062:     } elsif (defined($getuserdir)) {
 9063:         my $subdir=$uname.'__';
 9064:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 9065:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
 9066:                    ."/$udom/$subdir/$uname";
 9067:     } elsif (defined($alternateRoot)) {
 9068:         $dirRoot = $alternateRoot;
 9069:     }
 9070: 
 9071:     if($udom) {
 9072:         if($uname) {
 9073:             my $uhome = &homeserver($uname,$udom);
 9074:             if ($uhome eq 'no_host') {
 9075:                 return ([],'no_host');
 9076:             }
 9077:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
 9078:                               .$getuserdir.':'.&escape($dirRoot)
 9079:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
 9080:             if ($listing eq 'unknown_cmd') {
 9081:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
 9082:             } else {
 9083:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 9084:             }
 9085:             if ($listing eq 'unknown_cmd') {
 9086:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
 9087:                 @listing_results = split(/:/,$listing);
 9088:             } else {
 9089:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 9090:             }
 9091:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
 9092:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
 9093:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
 9094:                 return ([],$listing);
 9095:             } else {
 9096:                 return (\@listing_results);
 9097:             }
 9098:         } elsif(!$alternateRoot) {
 9099:             my (%allusers,%listerror);
 9100: 	    my %servers = &get_servers($udom,'library');
 9101:  	    foreach my $tryserver (keys(%servers)) {
 9102:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
 9103:                                   &escape($udom),$tryserver);
 9104:                 if ($listing eq 'unknown_cmd') {
 9105: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
 9106: 				      $udom, $tryserver);
 9107:                 } else {
 9108:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
 9109:                 }
 9110: 		if ($listing eq 'unknown_cmd') {
 9111: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 9112: 				      $udom, $tryserver);
 9113: 		    @listing_results = split(/:/,$listing);
 9114: 		} else {
 9115: 		    @listing_results =
 9116: 			map { &unescape($_); } split(/:/,$listing);
 9117: 		}
 9118:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
 9119:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
 9120:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
 9121:                     $listerror{$tryserver} = $listing;
 9122:                 } else {
 9123: 		    foreach my $line (@listing_results) {
 9124: 			my ($entry) = split(/&/,$line,2);
 9125: 			$allusers{$entry} = 1;
 9126: 		    }
 9127: 		}
 9128:             }
 9129:             my @alluserslist=();
 9130:             foreach my $user (sort(keys(%allusers))) {
 9131:                 push(@alluserslist,$user.'&user');
 9132:             }
 9133:             return (\@alluserslist);
 9134:         } else {
 9135:             return ([],'missing username');
 9136:         }
 9137:     } elsif(!defined($getpropath)) {
 9138:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
 9139:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
 9140:         return (\@all_domains);
 9141:     } else {
 9142:         return ([],'missing domain');
 9143:     }
 9144: }
 9145: 
 9146: # --------------------------------------------- GetFileTimestamp
 9147: # This function utilizes dirlist and returns the date stamp for
 9148: # when it was last modified.  It will also return an error of -1
 9149: # if an error occurs
 9150: 
 9151: sub GetFileTimestamp {
 9152:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
 9153:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
 9154:     $studentName   = &LONCAPA::clean_username($studentName);
 9155:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
 9156:                                     undef,$getuserdir);
 9157:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
 9158:         return -1;
 9159:     }
 9160:     if (ref($fileref) eq 'ARRAY') {
 9161:         my @stats = split('&',$fileref->[0]);
 9162:         # @stats contains first the filename, then the stat output
 9163:         return $stats[10]; # so this is 10 instead of 9.
 9164:     } else {
 9165:         return -1;
 9166:     }
 9167: }
 9168: 
 9169: sub stat_file {
 9170:     my ($uri) = @_;
 9171:     $uri = &clutter_with_no_wrapper($uri);
 9172: 
 9173:     my ($udom,$uname,$file);
 9174:     if ($uri =~ m-^/(uploaded|editupload)/-) {
 9175: 	($udom,$uname,$file) =
 9176: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
 9177: 	$file = 'userfiles/'.$file;
 9178:     }
 9179:     if ($uri =~ m-^/res/-) {
 9180: 	($udom,$uname) = 
 9181: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
 9182: 	$file = $uri;
 9183:     }
 9184: 
 9185:     if (!$udom || !$uname || !$file) {
 9186: 	# unable to handle the uri
 9187: 	return ();
 9188:     }
 9189:     my $getpropath;
 9190:     if ($file =~ /^userfiles\//) {
 9191:         $getpropath = 1;
 9192:     }
 9193:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
 9194:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
 9195:         return ();
 9196:     } else {
 9197:         if (ref($listref) eq 'ARRAY') {
 9198:             my @stats = split('&',$listref->[0]);
 9199: 	    shift(@stats); #filename is first
 9200: 	    return @stats;
 9201:         }
 9202:     }
 9203:     return ();
 9204: }
 9205: 
 9206: # -------------------------------------------------------- Value of a Condition
 9207: 
 9208: # gets the value of a specific preevaluated condition
 9209: #    stored in the string  $env{user.state.<cid>}
 9210: # or looks up a condition reference in the bighash and if if hasn't
 9211: # already been evaluated recurses into docondval to get the value of
 9212: # the condition, then memoizing it to 
 9213: #   $env{user.state.<cid>.<condition>}
 9214: sub directcondval {
 9215:     my $number=shift;
 9216:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
 9217: 	&Apache::lonuserstate::evalstate();
 9218:     }
 9219:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
 9220: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
 9221:     } elsif ($number =~ /^_/) {
 9222: 	my $sub_condition;
 9223: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 9224: 		&GDBM_READER(),0640)) {
 9225: 	    $sub_condition=$bighash{'conditions'.$number};
 9226: 	    untie(%bighash);
 9227: 	}
 9228: 	my $value = &docondval($sub_condition);
 9229: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
 9230: 	return $value;
 9231:     }
 9232:     if ($env{'user.state.'.$env{'request.course.id'}}) {
 9233:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
 9234:     } else {
 9235:        return 2;
 9236:     }
 9237: }
 9238: 
 9239: # get the collection of conditions for this resource
 9240: sub condval {
 9241:     my $condidx=shift;
 9242:     my $allpathcond='';
 9243:     foreach my $cond (split(/\|/,$condidx)) {
 9244: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
 9245: 	    $allpathcond.=
 9246: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
 9247: 	}
 9248:     }
 9249:     $allpathcond=~s/\|$//;
 9250:     return &docondval($allpathcond);
 9251: }
 9252: 
 9253: #evaluates an expression of conditions
 9254: sub docondval {
 9255:     my ($allpathcond) = @_;
 9256:     my $result=0;
 9257:     if ($env{'request.course.id'}
 9258: 	&& defined($allpathcond)) {
 9259: 	my $operand='|';
 9260: 	my @stack;
 9261: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
 9262: 	    if ($chunk eq '(') {
 9263: 		push @stack,($operand,$result);
 9264: 	    } elsif ($chunk eq ')') {
 9265: 		my $before=pop @stack;
 9266: 		if (pop @stack eq '&') {
 9267: 		    $result=$result>$before?$before:$result;
 9268: 		} else {
 9269: 		    $result=$result>$before?$result:$before;
 9270: 		}
 9271: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
 9272: 		$operand=$chunk;
 9273: 	    } else {
 9274: 		my $new=directcondval($chunk);
 9275: 		if ($operand eq '&') {
 9276: 		    $result=$result>$new?$new:$result;
 9277: 		} else {
 9278: 		    $result=$result>$new?$result:$new;
 9279: 		}
 9280: 	    }
 9281: 	}
 9282:     }
 9283:     return $result;
 9284: }
 9285: 
 9286: # ---------------------------------------------------- Devalidate courseresdata
 9287: 
 9288: sub devalidatecourseresdata {
 9289:     my ($coursenum,$coursedomain)=@_;
 9290:     my $hashid=$coursenum.':'.$coursedomain;
 9291:     &devalidate_cache_new('courseres',$hashid);
 9292: }
 9293: 
 9294: 
 9295: # --------------------------------------------------- Course Resourcedata Query
 9296: #
 9297: #  Parameters:
 9298: #      $coursenum    - Number of the course.
 9299: #      $coursedomain - Domain at which the course was created.
 9300: #  Returns:
 9301: #     A hash of the course parameters along (I think) with timestamps
 9302: #     and version info.
 9303: 
 9304: sub get_courseresdata {
 9305:     my ($coursenum,$coursedomain)=@_;
 9306:     my $coursehom=&homeserver($coursenum,$coursedomain);
 9307:     my $hashid=$coursenum.':'.$coursedomain;
 9308:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
 9309:     my %dumpreply;
 9310:     unless (defined($cached)) {
 9311: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 9312: 	$result=\%dumpreply;
 9313: 	my ($tmp) = keys(%dumpreply);
 9314: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 9315: 	    &do_cache_new('courseres',$hashid,$result,600);
 9316: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 9317: 	    return $tmp;
 9318: 	} elsif ($tmp =~ /^(error)/) {
 9319: 	    $result=undef;
 9320: 	    &do_cache_new('courseres',$hashid,$result,600);
 9321: 	}
 9322:     }
 9323:     return $result;
 9324: }
 9325: 
 9326: sub devalidateuserresdata {
 9327:     my ($uname,$udom)=@_;
 9328:     my $hashid="$udom:$uname";
 9329:     &devalidate_cache_new('userres',$hashid);
 9330: }
 9331: 
 9332: sub get_userresdata {
 9333:     my ($uname,$udom)=@_;
 9334:     #most student don\'t have any data set, check if there is some data
 9335:     if (&EXT_cache_status($udom,$uname)) { return undef; }
 9336: 
 9337:     my $hashid="$udom:$uname";
 9338:     my ($result,$cached)=&is_cached_new('userres',$hashid);
 9339:     if (!defined($cached)) {
 9340: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
 9341: 	$result=\%resourcedata;
 9342: 	&do_cache_new('userres',$hashid,$result,600);
 9343:     }
 9344:     my ($tmp)=keys(%$result);
 9345:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
 9346: 	return $result;
 9347:     }
 9348:     #error 2 occurs when the .db doesn't exist
 9349:     if ($tmp!~/error: 2 /) {
 9350: 	&logthis("<font color=\"blue\">WARNING:".
 9351: 		 " Trying to get resource data for ".
 9352: 		 $uname." at ".$udom.": ".
 9353: 		 $tmp."</font>");
 9354:     } elsif ($tmp=~/error: 2 /) {
 9355: 	#&EXT_cache_set($udom,$uname);
 9356: 	&do_cache_new('userres',$hashid,undef,600);
 9357: 	undef($tmp); # not really an error so don't send it back
 9358:     }
 9359:     return $tmp;
 9360: }
 9361: #----------------------------------------------- resdata - return resource data
 9362: #  Purpose:
 9363: #    Return resource data for either users or for a course.
 9364: #  Parameters:
 9365: #     $name      - Course/user name.
 9366: #     $domain    - Name of the domain the user/course is registered on.
 9367: #     $type      - Type of thing $name is (must be 'course' or 'user'
 9368: #     @which     - Array of names of resources desired.
 9369: #  Returns:
 9370: #     The value of the first reasource in @which that is found in the
 9371: #     resource hash.
 9372: #  Exceptional Conditions:
 9373: #     If the $type passed in is not valid (not the string 'course' or 
 9374: #     'user', an undefined  reference is returned.
 9375: #     If none of the resources are found, an undef is returned
 9376: sub resdata {
 9377:     my ($name,$domain,$type,@which)=@_;
 9378:     my $result;
 9379:     if ($type eq 'course') {
 9380: 	$result=&get_courseresdata($name,$domain);
 9381:     } elsif ($type eq 'user') {
 9382: 	$result=&get_userresdata($name,$domain);
 9383:     }
 9384:     if (!ref($result)) { return $result; }    
 9385:     foreach my $item (@which) {
 9386: 	if (defined($result->{$item->[0]})) {
 9387: 	    return [$result->{$item->[0]},$item->[1]];
 9388: 	}
 9389:     }
 9390:     return undef;
 9391: }
 9392: 
 9393: #
 9394: # EXT resource caching routines
 9395: #
 9396: 
 9397: sub clear_EXT_cache_status {
 9398:     &delenv('cache.EXT.');
 9399: }
 9400: 
 9401: sub EXT_cache_status {
 9402:     my ($target_domain,$target_user) = @_;
 9403:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 9404:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
 9405:         # We know already the user has no data
 9406:         return 1;
 9407:     } else {
 9408:         return 0;
 9409:     }
 9410: }
 9411: 
 9412: sub EXT_cache_set {
 9413:     my ($target_domain,$target_user) = @_;
 9414:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 9415:     #&appenv({$cachename => time});
 9416: }
 9417: 
 9418: # --------------------------------------------------------- Value of a Variable
 9419: sub EXT {
 9420: 
 9421:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
 9422:     unless ($varname) { return ''; }
 9423:     #get real user name/domain, courseid and symb
 9424:     my $courseid;
 9425:     my $publicuser;
 9426:     if ($symbparm) {
 9427: 	$symbparm=&get_symb_from_alias($symbparm);
 9428:     }
 9429:     if (!($uname && $udom)) {
 9430:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
 9431:       if (!$symbparm) {	$symbparm=$cursymb; }
 9432:     } else {
 9433: 	$courseid=$env{'request.course.id'};
 9434:     }
 9435:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 9436:     my $rest;
 9437:     if (defined($therest[0])) {
 9438:        $rest=join('.',@therest);
 9439:     } else {
 9440:        $rest='';
 9441:     }
 9442: 
 9443:     my $qualifierrest=$qualifier;
 9444:     if ($rest) { $qualifierrest.='.'.$rest; }
 9445:     my $spacequalifierrest=$space;
 9446:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 9447:     if ($realm eq 'user') {
 9448: # --------------------------------------------------------------- user.resource
 9449: 	if ($space eq 'resource') {
 9450: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
 9451: 		  || defined($Apache::lonhomework::parsing_a_task))
 9452: 		 &&
 9453: 		 ($symbparm eq &symbread()) ) {	
 9454: 		# if we are in the middle of processing the resource the
 9455: 		# get the value we are planning on committing
 9456:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
 9457:                     return $Apache::lonhomework::results{$qualifierrest};
 9458:                 } else {
 9459:                     return $Apache::lonhomework::history{$qualifierrest};
 9460:                 }
 9461: 	    } else {
 9462: 		my %restored;
 9463: 		if ($publicuser || $env{'request.state'} eq 'construct') {
 9464: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
 9465: 		} else {
 9466: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
 9467: 		}
 9468: 		return $restored{$qualifierrest};
 9469: 	    }
 9470: # ----------------------------------------------------------------- user.access
 9471:         } elsif ($space eq 'access') {
 9472: 	    # FIXME - not supporting calls for a specific user
 9473:             return &allowed($qualifier,$rest);
 9474: # ------------------------------------------ user.preferences, user.environment
 9475:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 9476: 	    if (($uname eq $env{'user.name'}) &&
 9477: 		($udom eq $env{'user.domain'})) {
 9478: 		return $env{join('.',('environment',$qualifierrest))};
 9479: 	    } else {
 9480: 		my %returnhash;
 9481: 		if (!$publicuser) {
 9482: 		    %returnhash=&userenvironment($udom,$uname,
 9483: 						 $qualifierrest);
 9484: 		}
 9485: 		return $returnhash{$qualifierrest};
 9486: 	    }
 9487: # ----------------------------------------------------------------- user.course
 9488:         } elsif ($space eq 'course') {
 9489: 	    # FIXME - not supporting calls for a specific user
 9490:             return $env{join('.',('request.course',$qualifier))};
 9491: # ------------------------------------------------------------------- user.role
 9492:         } elsif ($space eq 'role') {
 9493: 	    # FIXME - not supporting calls for a specific user
 9494:             my ($role,$where)=split(/\./,$env{'request.role'});
 9495:             if ($qualifier eq 'value') {
 9496: 		return $role;
 9497:             } elsif ($qualifier eq 'extent') {
 9498:                 return $where;
 9499:             }
 9500: # ----------------------------------------------------------------- user.domain
 9501:         } elsif ($space eq 'domain') {
 9502:             return $udom;
 9503: # ------------------------------------------------------------------- user.name
 9504:         } elsif ($space eq 'name') {
 9505:             return $uname;
 9506: # ---------------------------------------------------- Any other user namespace
 9507:         } else {
 9508: 	    my %reply;
 9509: 	    if (!$publicuser) {
 9510: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
 9511: 	    }
 9512: 	    return $reply{$qualifierrest};
 9513:         }
 9514:     } elsif ($realm eq 'query') {
 9515: # ---------------------------------------------- pull stuff out of query string
 9516:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 9517: 						[$spacequalifierrest]);
 9518: 	return $env{'form.'.$spacequalifierrest}; 
 9519:    } elsif ($realm eq 'request') {
 9520: # ------------------------------------------------------------- request.browser
 9521:         if ($space eq 'browser') {
 9522:             return $env{'browser.'.$qualifier};
 9523: # ------------------------------------------------------------ request.filename
 9524:         } else {
 9525:             return $env{'request.'.$spacequalifierrest};
 9526:         }
 9527:     } elsif ($realm eq 'course') {
 9528: # ---------------------------------------------------------- course.description
 9529:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
 9530:     } elsif ($realm eq 'resource') {
 9531: 
 9532: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
 9533: 	    if (!$symbparm) { $symbparm=&symbread(); }
 9534: 	}
 9535: 
 9536: 	if ($space eq 'title') {
 9537: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
 9538: 	    return &gettitle($symbparm);
 9539: 	}
 9540: 	
 9541: 	if ($space eq 'map') {
 9542: 	    my ($map) = &decode_symb($symbparm);
 9543: 	    return &symbread($map);
 9544: 	}
 9545: 	if ($space eq 'filename') {
 9546: 	    if ($symbparm) {
 9547: 		return &clutter((&decode_symb($symbparm))[2]);
 9548: 	    }
 9549: 	    return &hreflocation('',$env{'request.filename'});
 9550: 	}
 9551: 
 9552: 	my ($section, $group, @groups);
 9553: 	my ($courselevelm,$courselevel);
 9554: 	if ($symbparm && defined($courseid) && 
 9555: 	    $courseid eq $env{'request.course.id'}) {
 9556: 
 9557: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
 9558: 
 9559: # ----------------------------------------------------- Cascading lookup scheme
 9560: 	    my $symbp=$symbparm;
 9561: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
 9562: 
 9563: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
 9564: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
 9565: 
 9566: 	    if (($env{'user.name'} eq $uname) &&
 9567: 		($env{'user.domain'} eq $udom)) {
 9568: 		$section=$env{'request.course.sec'};
 9569:                 @groups = split(/:/,$env{'request.course.groups'});  
 9570:                 @groups=&sort_course_groups($courseid,@groups); 
 9571: 	    } else {
 9572: 		if (! defined($usection)) {
 9573: 		    $section=&getsection($udom,$uname,$courseid);
 9574: 		} else {
 9575: 		    $section = $usection;
 9576: 		}
 9577:                 @groups = &get_users_groups($udom,$uname,$courseid);
 9578: 	    }
 9579: 
 9580: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
 9581: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
 9582: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
 9583: 
 9584: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
 9585: 	    my $courselevelr=$courseid.'.'.$symbparm;
 9586: 	    $courselevelm=$courseid.'.'.$mapparm;
 9587: 
 9588: # ----------------------------------------------------------- first, check user
 9589: 
 9590: 	    my $userreply=&resdata($uname,$udom,'user',
 9591: 				       ([$courselevelr,'resource'],
 9592: 					[$courselevelm,'map'     ],
 9593: 					[$courselevel, 'course'  ]));
 9594: 	    if (defined($userreply)) { return &get_reply($userreply); }
 9595: 
 9596: # ------------------------------------------------ second, check some of course
 9597:             my $coursereply;
 9598:             if (@groups > 0) {
 9599:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
 9600:                                        $mapparm,$spacequalifierrest);
 9601:                 if (defined($coursereply)) { return &get_reply($coursereply); }
 9602:             }
 9603: 
 9604: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 9605: 				  $env{'course.'.$courseid.'.domain'},
 9606: 				  'course',
 9607: 				  ([$seclevelr,   'resource'],
 9608: 				   [$seclevelm,   'map'     ],
 9609: 				   [$seclevel,    'course'  ],
 9610: 				   [$courselevelr,'resource']));
 9611: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 9612: 
 9613: # ------------------------------------------------------ third, check map parms
 9614: 	    my %parmhash=();
 9615: 	    my $thisparm='';
 9616: 	    if (tie(%parmhash,'GDBM_File',
 9617: 		    $env{'request.course.fn'}.'_parms.db',
 9618: 		    &GDBM_READER(),0640)) {
 9619: 		$thisparm=$parmhash{$symbparm};
 9620: 		untie(%parmhash);
 9621: 	    }
 9622: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
 9623: 	}
 9624: # ------------------------------------------ fourth, look in resource metadata
 9625: 
 9626: 	$spacequalifierrest=~s/\./\_/;
 9627: 	my $filename;
 9628: 	if (!$symbparm) { $symbparm=&symbread(); }
 9629: 	if ($symbparm) {
 9630: 	    $filename=(&decode_symb($symbparm))[2];
 9631: 	} else {
 9632: 	    $filename=$env{'request.filename'};
 9633: 	}
 9634: 	my $metadata=&metadata($filename,$spacequalifierrest);
 9635: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 9636: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
 9637: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 9638: 
 9639: # ---------------------------------------------- fourth, look in rest of course
 9640: 	if ($symbparm && defined($courseid) && 
 9641: 	    $courseid eq $env{'request.course.id'}) {
 9642: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 9643: 				     $env{'course.'.$courseid.'.domain'},
 9644: 				     'course',
 9645: 				     ([$courselevelm,'map'   ],
 9646: 				      [$courselevel, 'course']));
 9647: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 9648: 	}
 9649: # ------------------------------------------------------------------ Cascade up
 9650: 	unless ($space eq '0') {
 9651: 	    my @parts=split(/_/,$space);
 9652: 	    my $id=pop(@parts);
 9653: 	    my $part=join('_',@parts);
 9654: 	    if ($part eq '') { $part='0'; }
 9655: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
 9656: 				 $symbparm,$udom,$uname,$section,1);
 9657: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
 9658: 	}
 9659: 	if ($recurse) { return undef; }
 9660: 	my $pack_def=&packages_tab_default($filename,$varname);
 9661: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
 9662: # ---------------------------------------------------- Any other user namespace
 9663:     } elsif ($realm eq 'environment') {
 9664: # ----------------------------------------------------------------- environment
 9665: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
 9666: 	    return $env{'environment.'.$spacequalifierrest};
 9667: 	} else {
 9668: 	    if ($uname eq 'anonymous' && $udom eq '') {
 9669: 		return '';
 9670: 	    }
 9671: 	    my %returnhash=&userenvironment($udom,$uname,
 9672: 					    $spacequalifierrest);
 9673: 	    return $returnhash{$spacequalifierrest};
 9674: 	}
 9675:     } elsif ($realm eq 'system') {
 9676: # ----------------------------------------------------------------- system.time
 9677: 	if ($space eq 'time') {
 9678: 	    return time;
 9679:         }
 9680:     } elsif ($realm eq 'server') {
 9681: # ----------------------------------------------------------------- system.time
 9682: 	if ($space eq 'name') {
 9683: 	    return $ENV{'SERVER_NAME'};
 9684:         }
 9685:     }
 9686:     return '';
 9687: }
 9688: 
 9689: sub get_reply {
 9690:     my ($reply_value) = @_;
 9691:     if (ref($reply_value) eq 'ARRAY') {
 9692:         if (wantarray) {
 9693: 	    return @$reply_value;
 9694:         }
 9695:         return $reply_value->[0];
 9696:     } else {
 9697:         return $reply_value;
 9698:     }
 9699: }
 9700: 
 9701: sub check_group_parms {
 9702:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
 9703:     my @groupitems = ();
 9704:     my $resultitem;
 9705:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
 9706:     foreach my $group (@{$groups}) {
 9707:         foreach my $level (@levels) {
 9708:              my $item = $courseid.'.['.$group.'].'.$level->[0];
 9709:              push(@groupitems,[$item,$level->[1]]);
 9710:         }
 9711:     }
 9712:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
 9713:                             $env{'course.'.$courseid.'.domain'},
 9714:                                      'course',@groupitems);
 9715:     return $coursereply;
 9716: }
 9717: 
 9718: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
 9719:     my ($courseid,@groups) = @_;
 9720:     @groups = sort(@groups);
 9721:     return @groups;
 9722: }
 9723: 
 9724: sub packages_tab_default {
 9725:     my ($uri,$varname)=@_;
 9726:     my (undef,$part,$name)=split(/\./,$varname);
 9727: 
 9728:     my (@extension,@specifics,$do_default);
 9729:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
 9730: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
 9731: 	if ($pack_type eq 'default') {
 9732: 	    $do_default=1;
 9733: 	} elsif ($pack_type eq 'extension') {
 9734: 	    push(@extension,[$package,$pack_type,$pack_part]);
 9735: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
 9736: 	    # only look at packages defaults for packages that this id is
 9737: 	    push(@specifics,[$package,$pack_type,$pack_part]);
 9738: 	}
 9739:     }
 9740:     # first look for a package that matches the requested part id
 9741:     foreach my $package (@specifics) {
 9742: 	my (undef,$pack_type,$pack_part)=@{$package};
 9743: 	next if ($pack_part ne $part);
 9744: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 9745: 	    return $packagetab{"$pack_type&$name&default"};
 9746: 	}
 9747:     }
 9748:     # look for any possible matching non extension_ package
 9749:     foreach my $package (@specifics) {
 9750: 	my (undef,$pack_type,$pack_part)=@{$package};
 9751: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 9752: 	    return $packagetab{"$pack_type&$name&default"};
 9753: 	}
 9754: 	if ($pack_type eq 'part') { $pack_part='0'; }
 9755: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
 9756: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
 9757: 	}
 9758:     }
 9759:     # look for any posible extension_ match
 9760:     foreach my $package (@extension) {
 9761: 	my ($package,$pack_type)=@{$package};
 9762: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 9763: 	    return $packagetab{"$pack_type&$name&default"};
 9764: 	}
 9765: 	if (defined($packagetab{$package."&$name&default"})) {
 9766: 	    return $packagetab{$package."&$name&default"};
 9767: 	}
 9768:     }
 9769:     # look for a global default setting
 9770:     if ($do_default && defined($packagetab{"default&$name&default"})) {
 9771: 	return $packagetab{"default&$name&default"};
 9772:     }
 9773:     return undef;
 9774: }
 9775: 
 9776: sub add_prefix_and_part {
 9777:     my ($prefix,$part)=@_;
 9778:     my $keyroot;
 9779:     if (defined($prefix) && $prefix !~ /^__/) {
 9780: 	# prefix that has a part already
 9781: 	$keyroot=$prefix;
 9782:     } elsif (defined($prefix)) {
 9783: 	# prefix that is missing a part
 9784: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
 9785:     } else {
 9786: 	# no prefix at all
 9787: 	if (defined($part)) { $keyroot='_'.$part; }
 9788:     }
 9789:     return $keyroot;
 9790: }
 9791: 
 9792: # ---------------------------------------------------------------- Get metadata
 9793: 
 9794: my %metaentry;
 9795: my %importedpartids;
 9796: sub metadata {
 9797:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
 9798:     $uri=&declutter($uri);
 9799:     # if it is a non metadata possible uri return quickly
 9800:     if (($uri eq '') || 
 9801: 	(($uri =~ m|^/*adm/|) && 
 9802: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
 9803:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
 9804: 	return undef;
 9805:     }
 9806:     if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) 
 9807: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
 9808: 	return undef;
 9809:     }
 9810:     my $filename=$uri;
 9811:     $uri=~s/\.meta$//;
 9812: #
 9813: # Is the metadata already cached?
 9814: # Look at timestamp of caching
 9815: # Everything is cached by the main uri, libraries are never directly cached
 9816: #
 9817:     if (!defined($liburi)) {
 9818: 	my ($result,$cached)=&is_cached_new('meta',$uri);
 9819: 	if (defined($cached)) { return $result->{':'.$what}; }
 9820:     }
 9821:     {
 9822: # Imported parts would go here
 9823:         my %importedids=();
 9824:         my @origfileimportpartids=();
 9825:         my $importedparts=0;
 9826: #
 9827: # Is this a recursive call for a library?
 9828: #
 9829: #	if (! exists($metacache{$uri})) {
 9830: #	    $metacache{$uri}={};
 9831: #	}
 9832: 	my $cachetime = 60*60;
 9833:         if ($liburi) {
 9834: 	    $liburi=&declutter($liburi);
 9835:             $filename=$liburi;
 9836:         } else {
 9837: 	    &devalidate_cache_new('meta',$uri);
 9838: 	    undef(%metaentry);
 9839: 	}
 9840:         my %metathesekeys=();
 9841:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
 9842: 	my $metastring;
 9843: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
 9844: 	    my $which = &hreflocation('','/'.($liburi || $uri));
 9845: 	    $metastring = 
 9846: 		&Apache::lonnet::ssi_body($which,
 9847: 					  ('grade_target' => 'meta'));
 9848: 	    $cachetime = 1; # only want this cached in the child not long term
 9849: 	} elsif (($uri !~ m -^(editupload)/-) && 
 9850:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
 9851: 	    my $file=&filelocation('',&clutter($filename));
 9852: 	    #push(@{$metaentry{$uri.'.file'}},$file);
 9853: 	    $metastring=&getfile($file);
 9854: 	}
 9855:         my $parser=HTML::LCParser->new(\$metastring);
 9856:         my $token;
 9857:         undef %metathesekeys;
 9858:         while ($token=$parser->get_token) {
 9859: 	    if ($token->[0] eq 'S') {
 9860: 		if (defined($token->[2]->{'package'})) {
 9861: #
 9862: # This is a package - get package info
 9863: #
 9864: 		    my $package=$token->[2]->{'package'};
 9865: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 9866: 		    if (defined($token->[2]->{'id'})) { 
 9867: 			$keyroot.='_'.$token->[2]->{'id'}; 
 9868: 		    }
 9869: 		    if ($metaentry{':packages'}) {
 9870: 			$metaentry{':packages'}.=','.$package.$keyroot;
 9871: 		    } else {
 9872: 			$metaentry{':packages'}=$package.$keyroot;
 9873: 		    }
 9874: 		    foreach my $pack_entry (keys(%packagetab)) {
 9875: 			my $part=$keyroot;
 9876: 			$part=~s/^\_//;
 9877: 			if ($pack_entry=~/^\Q$package\E\&/ || 
 9878: 			    $pack_entry=~/^\Q$package\E_0\&/) {
 9879: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
 9880: 			    # ignore package.tab specified default values
 9881:                             # here &package_tab_default() will fetch those
 9882: 			    if ($subp eq 'default') { next; }
 9883: 			    my $value=$packagetab{$pack_entry};
 9884: 			    my $unikey;
 9885: 			    if ($pack =~ /_0$/) {
 9886: 				$unikey='parameter_0_'.$name;
 9887: 				$part=0;
 9888: 			    } else {
 9889: 				$unikey='parameter'.$keyroot.'_'.$name;
 9890: 			    }
 9891: 			    if ($subp eq 'display') {
 9892: 				$value.=' [Part: '.$part.']';
 9893: 			    }
 9894: 			    $metaentry{':'.$unikey.'.part'}=$part;
 9895: 			    $metathesekeys{$unikey}=1;
 9896: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 9897: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
 9898: 			    }
 9899: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
 9900: 				$metaentry{':'.$unikey}=
 9901: 				    $metaentry{':'.$unikey.'.default'};
 9902: 			    }
 9903: 			}
 9904: 		    }
 9905: 		} else {
 9906: #
 9907: # This is not a package - some other kind of start tag
 9908: #
 9909: 		    my $entry=$token->[1];
 9910: 		    my $unikey='';
 9911: 
 9912: 		    if ($entry eq 'import') {
 9913: #
 9914: # Importing a library here
 9915: #
 9916:                         my $location=$parser->get_text('/import');
 9917:                         my $dir=$filename;
 9918:                         $dir=~s|[^/]*$||;
 9919:                         $location=&filelocation($dir,$location);
 9920:                        
 9921:                         my $importmode=$token->[2]->{'importmode'};
 9922:                         if ($importmode eq 'problem') {
 9923: # Import as problem/response
 9924:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 9925:                         } elsif ($importmode eq 'part') {
 9926: # Import as part(s)
 9927:                            $importedparts=1;
 9928: # We need to get the original file and the imported file to get the part order correct
 9929: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
 9930: # Load and inspect original file
 9931:                            if ($#origfileimportpartids<0) {
 9932:                               undef(%importedpartids);
 9933:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
 9934:                               my $origfile=&getfile($origfilelocation);
 9935:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
 9936:                            }
 9937: 
 9938: # Load and inspect imported file
 9939:                            my $impfile=&getfile($location);
 9940:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
 9941:                            if ($#impfilepartids>=0) {
 9942: # This problem had parts
 9943:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
 9944:                            } else {
 9945: # Importing by turning a single problem into a problem part
 9946: # It gets the import-tags ID as part-ID
 9947:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
 9948:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
 9949:                            }
 9950:                         } else {
 9951: # Normal import
 9952:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 9953:                            if (defined($token->[2]->{'id'})) {
 9954:                               $unikey.='_'.$token->[2]->{'id'};
 9955:                            }
 9956:                         }
 9957: 
 9958: 			if ($depthcount<20) {
 9959: 			    my $metadata = 
 9960: 				&metadata($uri,'keys', $location,$unikey,
 9961: 					  $depthcount+1);
 9962: 			    foreach my $meta (split(',',$metadata)) {
 9963: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
 9964: 				$metathesekeys{$meta}=1;
 9965: 			    }
 9966: 			
 9967:                         }
 9968: 		    } else {
 9969: #
 9970: # Not importing, some other kind of non-package, non-library start tag
 9971: # 
 9972:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
 9973:                         if (defined($token->[2]->{'id'})) {
 9974:                             $unikey.='_'.$token->[2]->{'id'};
 9975:                         }
 9976: 			if (defined($token->[2]->{'name'})) { 
 9977: 			    $unikey.='_'.$token->[2]->{'name'}; 
 9978: 			}
 9979: 			$metathesekeys{$unikey}=1;
 9980: 			foreach my $param (@{$token->[3]}) {
 9981: 			    $metaentry{':'.$unikey.'.'.$param} =
 9982: 				$token->[2]->{$param};
 9983: 			}
 9984: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
 9985: 			my $default=$metaentry{':'.$unikey.'.default'};
 9986: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
 9987: 		 # only ws inside the tag, and not in default, so use default
 9988: 		 # as value
 9989: 			    $metaentry{':'.$unikey}=$default;
 9990: 			} elsif ( $internaltext =~ /\S/ ) {
 9991: 		  # something interesting inside the tag
 9992: 			    $metaentry{':'.$unikey}=$internaltext;
 9993: 			} else {
 9994: 		  # no interesting values, don't set a default
 9995: 			}
 9996: # end of not-a-package not-a-library import
 9997: 		    }
 9998: # end of not-a-package start tag
 9999: 		}
10000: # the next is the end of "start tag"
10001: 	    }
10002: 	}
10003: 	my ($extension) = ($uri =~ /\.(\w+)$/);
10004: 	$extension = lc($extension);
10005: 	if ($extension eq 'htm') { $extension='html'; }
10006: 
10007: 	foreach my $key (keys(%packagetab)) {
10008: 	    #no specific packages #how's our extension
10009: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
10010: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
10011: 					 \%metathesekeys);
10012: 	}
10013: 
10014: 	if (!exists($metaentry{':packages'})
10015: 	    || $packagetab{"import_defaults&extension_$extension"}) {
10016: 	    foreach my $key (keys(%packagetab)) {
10017: 		#no specific packages well let's get default then
10018: 		if ($key!~/^default&/) { next; }
10019: 		&metadata_create_package_def($uri,$key,'default',
10020: 					     \%metathesekeys);
10021: 	    }
10022: 	}
10023: # are there custom rights to evaluate
10024: 	if ($metaentry{':copyright'} eq 'custom') {
10025: 
10026:     #
10027:     # Importing a rights file here
10028:     #
10029: 	    unless ($depthcount) {
10030: 		my $location=$metaentry{':customdistributionfile'};
10031: 		my $dir=$filename;
10032: 		$dir=~s|[^/]*$||;
10033: 		$location=&filelocation($dir,$location);
10034: 		my $rights_metadata =
10035: 		    &metadata($uri,'keys',$location,'_rights',
10036: 			      $depthcount+1);
10037: 		foreach my $rights (split(',',$rights_metadata)) {
10038: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
10039: 		    $metathesekeys{$rights}=1;
10040: 		}
10041: 	    }
10042: 	}
10043: 	# uniqifiy package listing
10044: 	my %seen;
10045: 	my @uniq_packages =
10046: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
10047: 	$metaentry{':packages'} = join(',',@uniq_packages);
10048: 
10049:         if ($importedparts) {
10050: # We had imported parts and need to rebuild partorder
10051:            $metaentry{':partorder'}='';
10052:            $metathesekeys{'partorder'}=1;
10053:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
10054:                if ($origfileimportpartids[$index] eq 'part') {
10055: # original part, part of the problem
10056:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
10057:                } else {
10058: # we have imported parts at this position
10059:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
10060:                }
10061:            }
10062:            $metaentry{':partorder'}=~s/^\,//;
10063:         }
10064: 
10065: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
10066: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
10067: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
10068: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
10069: # this is the end of "was not already recently cached
10070:     }
10071:     return $metaentry{':'.$what};
10072: }
10073: 
10074: sub metadata_create_package_def {
10075:     my ($uri,$key,$package,$metathesekeys)=@_;
10076:     my ($pack,$name,$subp)=split(/\&/,$key);
10077:     if ($subp eq 'default') { next; }
10078:     
10079:     if (defined($metaentry{':packages'})) {
10080: 	$metaentry{':packages'}.=','.$package;
10081:     } else {
10082: 	$metaentry{':packages'}=$package;
10083:     }
10084:     my $value=$packagetab{$key};
10085:     my $unikey;
10086:     $unikey='parameter_0_'.$name;
10087:     $metaentry{':'.$unikey.'.part'}=0;
10088:     $$metathesekeys{$unikey}=1;
10089:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10090: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
10091:     }
10092:     if (defined($metaentry{':'.$unikey.'.default'})) {
10093: 	$metaentry{':'.$unikey}=
10094: 	    $metaentry{':'.$unikey.'.default'};
10095:     }
10096: }
10097: 
10098: sub metadata_generate_part0 {
10099:     my ($metadata,$metacache,$uri) = @_;
10100:     my %allnames;
10101:     foreach my $metakey (keys(%$metadata)) {
10102: 	if ($metakey=~/^parameter\_(.*)/) {
10103: 	  my $part=$$metacache{':'.$metakey.'.part'};
10104: 	  my $name=$$metacache{':'.$metakey.'.name'};
10105: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
10106: 	    $allnames{$name}=$part;
10107: 	  }
10108: 	}
10109:     }
10110:     foreach my $name (keys(%allnames)) {
10111:       $$metadata{"parameter_0_$name"}=1;
10112:       my $key=":parameter_0_$name";
10113:       $$metacache{"$key.part"}='0';
10114:       $$metacache{"$key.name"}=$name;
10115:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
10116: 					   $allnames{$name}.'_'.$name.
10117: 					   '.type'};
10118:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
10119: 			     '.display'};
10120:       my $expr='[Part: '.$allnames{$name}.']';
10121:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
10122:       $$metacache{"$key.display"}=$olddis;
10123:     }
10124: }
10125: 
10126: # ------------------------------------------------------ Devalidate title cache
10127: 
10128: sub devalidate_title_cache {
10129:     my ($url)=@_;
10130:     if (!$env{'request.course.id'}) { return; }
10131:     my $symb=&symbread($url);
10132:     if (!$symb) { return; }
10133:     my $key=$env{'request.course.id'}."\0".$symb;
10134:     &devalidate_cache_new('title',$key);
10135: }
10136: 
10137: # ------------------------------------------------- Get the title of a course
10138: 
10139: sub current_course_title {
10140:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
10141: }
10142: # ------------------------------------------------- Get the title of a resource
10143: 
10144: sub gettitle {
10145:     my $urlsymb=shift;
10146:     my $symb=&symbread($urlsymb);
10147:     if ($symb) {
10148: 	my $key=$env{'request.course.id'}."\0".$symb;
10149: 	my ($result,$cached)=&is_cached_new('title',$key);
10150: 	if (defined($cached)) { 
10151: 	    return $result;
10152: 	}
10153: 	my ($map,$resid,$url)=&decode_symb($symb);
10154: 	my $title='';
10155: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
10156: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
10157: 	} else {
10158: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10159: 		    &GDBM_READER(),0640)) {
10160: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
10161: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
10162: 		untie(%bighash);
10163: 	    }
10164: 	}
10165: 	$title=~s/\&colon\;/\:/gs;
10166: 	if ($title) {
10167: # Remember both $symb and $title for dynamic metadata
10168:             $accesshash{$symb.'___crstitle'}=$title;
10169:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
10170: # Cache this title and then return it
10171: 	    return &do_cache_new('title',$key,$title,600);
10172: 	}
10173: 	$urlsymb=$url;
10174:     }
10175:     my $title=&metadata($urlsymb,'title');
10176:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
10177:     return $title;
10178: }
10179: 
10180: sub get_slot {
10181:     my ($which,$cnum,$cdom)=@_;
10182:     if (!$cnum || !$cdom) {
10183: 	(undef,my $courseid)=&whichuser();
10184: 	$cdom=$env{'course.'.$courseid.'.domain'};
10185: 	$cnum=$env{'course.'.$courseid.'.num'};
10186:     }
10187:     my $key=join("\0",'slots',$cdom,$cnum,$which);
10188:     my %slotinfo;
10189:     if (exists($remembered{$key})) {
10190: 	$slotinfo{$which} = $remembered{$key};
10191:     } else {
10192: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
10193: 	&Apache::lonhomework::showhash(%slotinfo);
10194: 	my ($tmp)=keys(%slotinfo);
10195: 	if ($tmp=~/^error:/) { return (); }
10196: 	$remembered{$key} = $slotinfo{$which};
10197:     }
10198:     if (ref($slotinfo{$which}) eq 'HASH') {
10199: 	return %{$slotinfo{$which}};
10200:     }
10201:     return $slotinfo{$which};
10202: }
10203: 
10204: sub get_reservable_slots {
10205:     my ($cnum,$cdom,$uname,$udom) = @_;
10206:     my $now = time;
10207:     my $reservable_info;
10208:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
10209:     if (exists($remembered{$key})) {
10210:         $reservable_info = $remembered{$key};
10211:     } else {
10212:         my %resv;
10213:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
10214:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
10215:         $reservable_info = \%resv;
10216:         $remembered{$key} = $reservable_info;
10217:     }
10218:     return $reservable_info;
10219: }
10220: 
10221: sub get_course_slots {
10222:     my ($cnum,$cdom) = @_;
10223:     my $hashid=$cnum.':'.$cdom;
10224:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
10225:     if (defined($cached)) {
10226:         if (ref($result) eq 'HASH') {
10227:             return %{$result};
10228:         }
10229:     } else {
10230:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
10231:         my ($tmp) = keys(%slots);
10232:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
10233:             &Apache::lonnet::do_cache_new('allslots',$hashid,\%slots,600);
10234:             return %slots;
10235:         }
10236:     }
10237:     return;
10238: }
10239: 
10240: sub devalidate_slots_cache {
10241:     my ($cnum,$cdom)=@_;
10242:     my $hashid=$cnum.':'.$cdom;
10243:     &devalidate_cache_new('allslots',$hashid);
10244: }
10245: 
10246: sub get_coursechange {
10247:     my ($cdom,$cnum) = @_;
10248:     if ($cdom eq '' || $cnum eq '') {
10249:         return unless ($env{'request.course.id'});
10250:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10251:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10252:     }
10253:     my $hashid=$cdom.'_'.$cnum;
10254:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
10255:     if ((defined($cached)) && ($change ne '')) {
10256:         return $change;
10257:     } else {
10258:         my %crshash;
10259:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
10260:         if ($crshash{'internal.contentchange'} eq '') {
10261:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
10262:             if ($change eq '') {
10263:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
10264:                 $change = $crshash{'internal.created'};
10265:             }
10266:         } else {
10267:             $change = $crshash{'internal.contentchange'};
10268:         }
10269:         my $cachetime = 600;
10270:         &do_cache_new('crschange',$hashid,$change,$cachetime);
10271:     }
10272:     return $change;
10273: }
10274: 
10275: sub devalidate_coursechange_cache {
10276:     my ($cnum,$cdom)=@_;
10277:     my $hashid=$cnum.':'.$cdom;
10278:     &devalidate_cache_new('crschange',$hashid);
10279: }
10280: 
10281: # ------------------------------------------------- Update symbolic store links
10282: 
10283: sub symblist {
10284:     my ($mapname,%newhash)=@_;
10285:     $mapname=&deversion(&declutter($mapname));
10286:     my %hash;
10287:     if (($env{'request.course.fn'}) && (%newhash)) {
10288:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
10289:                       &GDBM_WRCREAT(),0640)) {
10290: 	    foreach my $url (keys(%newhash)) {
10291: 		next if ($url eq 'last_known'
10292: 			 && $env{'form.no_update_last_known'});
10293: 		$hash{declutter($url)}=&encode_symb($mapname,
10294: 						    $newhash{$url}->[1],
10295: 						    $newhash{$url}->[0]);
10296:             }
10297:             if (untie(%hash)) {
10298: 		return 'ok';
10299:             }
10300:         }
10301:     }
10302:     return 'error';
10303: }
10304: 
10305: # --------------------------------------------------------------- Verify a symb
10306: 
10307: sub symbverify {
10308:     my ($symb,$thisurl,$encstate)=@_;
10309:     my $thisfn=$thisurl;
10310:     $thisfn=&declutter($thisfn);
10311: # direct jump to resource in page or to a sequence - will construct own symbs
10312:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
10313: # check URL part
10314:     my ($map,$resid,$url)=&decode_symb($symb);
10315: 
10316:     unless ($url eq $thisfn) { return 0; }
10317: 
10318:     $symb=&symbclean($symb);
10319:     $thisurl=&deversion($thisurl);
10320:     $thisfn=&deversion($thisfn);
10321: 
10322:     my %bighash;
10323:     my $okay=0;
10324: 
10325:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10326:                             &GDBM_READER(),0640)) {
10327:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
10328:             $thisurl =~ s/\?.+$//;
10329:         }
10330:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
10331:         unless ($ids) {
10332:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
10333:             $ids=$bighash{$idkey};
10334:         }
10335:         if ($ids) {
10336: # ------------------------------------------------------------------- Has ID(s)
10337: 	    foreach my $id (split(/\,/,$ids)) {
10338: 	       my ($mapid,$resid)=split(/\./,$id);
10339:                if ($thisfn =~ m{^/adm/wrapper/ext/}) {
10340:                    $symb =~ s/\?.+$//;
10341:                }
10342:                if (
10343:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
10344:    eq $symb) {
10345:                    if (ref($encstate)) {
10346:                        $$encstate = $bighash{'encrypted_'.$id};
10347:                    }
10348: 		   if (($env{'request.role.adv'}) ||
10349: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
10350:                        ($thisurl eq '/adm/navmaps')) {
10351: 		       $okay=1;
10352: 		   }
10353: 	       }
10354: 	   }
10355:         }
10356: 	untie(%bighash);
10357:     }
10358:     return $okay;
10359: }
10360: 
10361: # --------------------------------------------------------------- Clean-up symb
10362: 
10363: sub symbclean {
10364:     my $symb=shift;
10365:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
10366: # remove version from map
10367:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
10368: 
10369: # remove version from URL
10370:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
10371: 
10372: # remove wrapper
10373: 
10374:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
10375:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
10376:     return $symb;
10377: }
10378: 
10379: # ---------------------------------------------- Split symb to find map and url
10380: 
10381: sub encode_symb {
10382:     my ($map,$resid,$url)=@_;
10383:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
10384: }
10385: 
10386: sub decode_symb {
10387:     my $symb=shift;
10388:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
10389:     my ($map,$resid,$url)=split(/___/,$symb);
10390:     return (&fixversion($map),$resid,&fixversion($url));
10391: }
10392: 
10393: sub fixversion {
10394:     my $fn=shift;
10395:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
10396:     my %bighash;
10397:     my $uri=&clutter($fn);
10398:     my $key=$env{'request.course.id'}.'_'.$uri;
10399: # is this cached?
10400:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
10401:     if (defined($cached)) { return $result; }
10402: # unfortunately not cached, or expired
10403:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10404: 	    &GDBM_READER(),0640)) {
10405:  	if ($bighash{'version_'.$uri}) {
10406:  	    my $version=$bighash{'version_'.$uri};
10407:  	    unless (($version eq 'mostrecent') || 
10408: 		    ($version==&getversion($uri))) {
10409:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
10410:  	    }
10411:  	}
10412:  	untie %bighash;
10413:     }
10414:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
10415: }
10416: 
10417: sub deversion {
10418:     my $url=shift;
10419:     $url=~s/\.\d+\.(\w+)$/\.$1/;
10420:     return $url;
10421: }
10422: 
10423: # ------------------------------------------------------ Return symb list entry
10424: 
10425: sub symbread {
10426:     my ($thisfn,$donotrecurse)=@_;
10427:     my $cache_str='request.symbread.cached.'.$thisfn;
10428:     if (defined($env{$cache_str})) {
10429:         if (($thisfn) || ($env{$cache_str} ne '')) {
10430:             return $env{$cache_str};
10431:         }
10432:     }
10433: # no filename provided? try from environment
10434:     unless ($thisfn) {
10435:         if ($env{'request.symb'}) {
10436: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
10437: 	}
10438: 	$thisfn=$env{'request.filename'};
10439:     }
10440:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
10441: # is that filename actually a symb? Verify, clean, and return
10442:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
10443: 	if (&symbverify($thisfn,$1)) {
10444: 	    return $env{$cache_str}=&symbclean($thisfn);
10445: 	}
10446:     }
10447:     $thisfn=declutter($thisfn);
10448:     my %hash;
10449:     my %bighash;
10450:     my $syval='';
10451:     if (($env{'request.course.fn'}) && ($thisfn)) {
10452:         my $targetfn = $thisfn;
10453:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
10454:             $targetfn = 'adm/wrapper/'.$thisfn;
10455:         }
10456: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
10457: 	    $targetfn=$1;
10458: 	}
10459:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
10460:                       &GDBM_READER(),0640)) {
10461: 	    $syval=$hash{$targetfn};
10462:             untie(%hash);
10463:         }
10464: # ---------------------------------------------------------- There was an entry
10465:         if ($syval) {
10466: 	    #unless ($syval=~/\_\d+$/) {
10467: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
10468: 		    #&appenv({'request.ambiguous' => $thisfn});
10469: 		    #return $env{$cache_str}='';
10470: 		#}    
10471: 		#$syval.=$1;
10472: 	    #}
10473:         } else {
10474: # ------------------------------------------------------- Was not in symb table
10475:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10476:                             &GDBM_READER(),0640)) {
10477: # ---------------------------------------------- Get ID(s) for current resource
10478:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
10479:               unless ($ids) { 
10480:                  $ids=$bighash{'ids_/'.$thisfn};
10481:               }
10482:               unless ($ids) {
10483: # alias?
10484: 		  $ids=$bighash{'mapalias_'.$thisfn};
10485:               }
10486:               if ($ids) {
10487: # ------------------------------------------------------------------- Has ID(s)
10488:                  my @possibilities=split(/\,/,$ids);
10489:                  if ($#possibilities==0) {
10490: # ----------------------------------------------- There is only one possibility
10491: 		     my ($mapid,$resid)=split(/\./,$ids);
10492: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
10493: 						    $resid,$thisfn);
10494:                  } elsif (!$donotrecurse) {
10495: # ------------------------------------------ There is more than one possibility
10496:                      my $realpossible=0;
10497:                      foreach my $id (@possibilities) {
10498: 			 my $file=$bighash{'src_'.$id};
10499:                          if (&allowed('bre',$file)) {
10500:          		    my ($mapid,$resid)=split(/\./,$id);
10501:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
10502: 				$realpossible++;
10503:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
10504: 						    $resid,$thisfn);
10505:                             }
10506: 			 }
10507:                      }
10508: 		     if ($realpossible!=1) { $syval=''; }
10509:                  } else {
10510:                      $syval='';
10511:                  }
10512: 	      }
10513:               untie(%bighash)
10514:            }
10515:         }
10516:         if ($syval) {
10517: 	    return $env{$cache_str}=$syval;
10518:         }
10519:     }
10520:     &appenv({'request.ambiguous' => $thisfn});
10521:     return $env{$cache_str}='';
10522: }
10523: 
10524: # ---------------------------------------------------------- Return random seed
10525: 
10526: sub numval {
10527:     my $txt=shift;
10528:     $txt=~tr/A-J/0-9/;
10529:     $txt=~tr/a-j/0-9/;
10530:     $txt=~tr/K-T/0-9/;
10531:     $txt=~tr/k-t/0-9/;
10532:     $txt=~tr/U-Z/0-5/;
10533:     $txt=~tr/u-z/0-5/;
10534:     $txt=~s/\D//g;
10535:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
10536:     return int($txt);
10537: }
10538: 
10539: sub numval2 {
10540:     my $txt=shift;
10541:     $txt=~tr/A-J/0-9/;
10542:     $txt=~tr/a-j/0-9/;
10543:     $txt=~tr/K-T/0-9/;
10544:     $txt=~tr/k-t/0-9/;
10545:     $txt=~tr/U-Z/0-5/;
10546:     $txt=~tr/u-z/0-5/;
10547:     $txt=~s/\D//g;
10548:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10549:     my $total;
10550:     foreach my $val (@txts) { $total+=$val; }
10551:     if ($_64bit) { if ($total > 2**32) { return -1; } }
10552:     return int($total);
10553: }
10554: 
10555: sub numval3 {
10556:     use integer;
10557:     my $txt=shift;
10558:     $txt=~tr/A-J/0-9/;
10559:     $txt=~tr/a-j/0-9/;
10560:     $txt=~tr/K-T/0-9/;
10561:     $txt=~tr/k-t/0-9/;
10562:     $txt=~tr/U-Z/0-5/;
10563:     $txt=~tr/u-z/0-5/;
10564:     $txt=~s/\D//g;
10565:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10566:     my $total;
10567:     foreach my $val (@txts) { $total+=$val; }
10568:     if ($_64bit) { $total=(($total<<32)>>32); }
10569:     return $total;
10570: }
10571: 
10572: sub digest {
10573:     my ($data)=@_;
10574:     my $digest=&Digest::MD5::md5($data);
10575:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
10576:     my ($e,$f);
10577:     {
10578:         use integer;
10579:         $e=($a+$b);
10580:         $f=($c+$d);
10581:         if ($_64bit) {
10582:             $e=(($e<<32)>>32);
10583:             $f=(($f<<32)>>32);
10584:         }
10585:     }
10586:     if (wantarray) {
10587: 	return ($e,$f);
10588:     } else {
10589: 	my $g;
10590: 	{
10591: 	    use integer;
10592: 	    $g=($e+$f);
10593: 	    if ($_64bit) {
10594: 		$g=(($g<<32)>>32);
10595: 	    }
10596: 	}
10597: 	return $g;
10598:     }
10599: }
10600: 
10601: sub latest_rnd_algorithm_id {
10602:     return '64bit5';
10603: }
10604: 
10605: sub get_rand_alg {
10606:     my ($courseid)=@_;
10607:     if (!$courseid) { $courseid=(&whichuser())[1]; }
10608:     if ($courseid) {
10609: 	return $env{"course.$courseid.rndseed"};
10610:     }
10611:     return &latest_rnd_algorithm_id();
10612: }
10613: 
10614: sub validCODE {
10615:     my ($CODE)=@_;
10616:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
10617:     return 0;
10618: }
10619: 
10620: sub getCODE {
10621:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
10622:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
10623: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
10624: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
10625: 	return $Apache::lonhomework::history{'resource.CODE'};
10626:     }
10627:     return undef;
10628: }
10629: #
10630: #  Determines the random seed for a specific context:
10631: #
10632: # parameters:
10633: #   symb      - in course context the symb for the seed.
10634: #   course_id - The course id of the form domain_coursenum.
10635: #   domain    - Domain for the user.
10636: #   course    - Course for the user.
10637: #   cenv      - environment of the course.
10638: #
10639: # NOTE:
10640: #   All parameters are picked out of the environment if missing
10641: #   or not defined.
10642: #   If a symb cannot be determined the current time is used instead.
10643: #
10644: #  For a given well defined symb, courside, domain, username,
10645: #  and course environment, the seed is reproducible.
10646: #
10647: sub rndseed {
10648:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
10649:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
10650:     if (!defined($symb)) {
10651: 	unless ($symb=$wsymb) { return time; }
10652:     }
10653:     if (!defined $courseid) { 
10654: 	$courseid=$wcourseid; 
10655:     }
10656:     if (!defined $domain) { $domain=$wdomain; }
10657:     if (!defined $username) { $username=$wusername }
10658: 
10659:     my $which;
10660:     if (defined($cenv->{'rndseed'})) {
10661: 	$which = $cenv->{'rndseed'};
10662:     } else {
10663: 	$which =&get_rand_alg($courseid);
10664:     }
10665:     if (defined(&getCODE())) {
10666: 
10667: 	if ($which eq '64bit5') {
10668: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
10669: 	} elsif ($which eq '64bit4') {
10670: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
10671: 	} else {
10672: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
10673: 	}
10674:     } elsif ($which eq '64bit5') {
10675: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
10676:     } elsif ($which eq '64bit4') {
10677: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
10678:     } elsif ($which eq '64bit3') {
10679: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
10680:     } elsif ($which eq '64bit2') {
10681: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
10682:     } elsif ($which eq '64bit') {
10683: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
10684:     }
10685:     return &rndseed_32bit($symb,$courseid,$domain,$username);
10686: }
10687: 
10688: sub rndseed_32bit {
10689:     my ($symb,$courseid,$domain,$username)=@_;
10690:     {
10691: 	use integer;
10692: 	my $symbchck=unpack("%32C*",$symb) << 27;
10693: 	my $symbseed=numval($symb) << 22;
10694: 	my $namechck=unpack("%32C*",$username) << 17;
10695: 	my $nameseed=numval($username) << 12;
10696: 	my $domainseed=unpack("%32C*",$domain) << 7;
10697: 	my $courseseed=unpack("%32C*",$courseid);
10698: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
10699: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10700: 	#&logthis("rndseed :$num:$symb");
10701: 	if ($_64bit) { $num=(($num<<32)>>32); }
10702: 	return $num;
10703:     }
10704: }
10705: 
10706: sub rndseed_64bit {
10707:     my ($symb,$courseid,$domain,$username)=@_;
10708:     {
10709: 	use integer;
10710: 	my $symbchck=unpack("%32S*",$symb) << 21;
10711: 	my $symbseed=numval($symb) << 10;
10712: 	my $namechck=unpack("%32S*",$username);
10713: 	
10714: 	my $nameseed=numval($username) << 21;
10715: 	my $domainseed=unpack("%32S*",$domain) << 10;
10716: 	my $courseseed=unpack("%32S*",$courseid);
10717: 	
10718: 	my $num1=$symbchck+$symbseed+$namechck;
10719: 	my $num2=$nameseed+$domainseed+$courseseed;
10720: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10721: 	#&logthis("rndseed :$num:$symb");
10722: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
10723: 	return "$num1,$num2";
10724:     }
10725: }
10726: 
10727: sub rndseed_64bit2 {
10728:     my ($symb,$courseid,$domain,$username)=@_;
10729:     {
10730: 	use integer;
10731: 	# strings need to be an even # of cahracters long, it it is odd the
10732:         # last characters gets thrown away
10733: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
10734: 	my $symbseed=numval($symb) << 10;
10735: 	my $namechck=unpack("%32S*",$username.' ');
10736: 	
10737: 	my $nameseed=numval($username) << 21;
10738: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
10739: 	my $courseseed=unpack("%32S*",$courseid.' ');
10740: 	
10741: 	my $num1=$symbchck+$symbseed+$namechck;
10742: 	my $num2=$nameseed+$domainseed+$courseseed;
10743: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10744: 	#&logthis("rndseed :$num:$symb");
10745: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
10746: 	return "$num1,$num2";
10747:     }
10748: }
10749: 
10750: sub rndseed_64bit3 {
10751:     my ($symb,$courseid,$domain,$username)=@_;
10752:     {
10753: 	use integer;
10754: 	# strings need to be an even # of cahracters long, it it is odd the
10755:         # last characters gets thrown away
10756: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
10757: 	my $symbseed=numval2($symb) << 10;
10758: 	my $namechck=unpack("%32S*",$username.' ');
10759: 	
10760: 	my $nameseed=numval2($username) << 21;
10761: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
10762: 	my $courseseed=unpack("%32S*",$courseid.' ');
10763: 	
10764: 	my $num1=$symbchck+$symbseed+$namechck;
10765: 	my $num2=$nameseed+$domainseed+$courseseed;
10766: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10767: 	#&logthis("rndseed :$num1:$num2:$_64bit");
10768: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
10769: 	
10770: 	return "$num1:$num2";
10771:     }
10772: }
10773: 
10774: sub rndseed_64bit4 {
10775:     my ($symb,$courseid,$domain,$username)=@_;
10776:     {
10777: 	use integer;
10778: 	# strings need to be an even # of cahracters long, it it is odd the
10779:         # last characters gets thrown away
10780: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
10781: 	my $symbseed=numval3($symb) << 10;
10782: 	my $namechck=unpack("%32S*",$username.' ');
10783: 	
10784: 	my $nameseed=numval3($username) << 21;
10785: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
10786: 	my $courseseed=unpack("%32S*",$courseid.' ');
10787: 	
10788: 	my $num1=$symbchck+$symbseed+$namechck;
10789: 	my $num2=$nameseed+$domainseed+$courseseed;
10790: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10791: 	#&logthis("rndseed :$num1:$num2:$_64bit");
10792: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
10793: 	
10794: 	return "$num1:$num2";
10795:     }
10796: }
10797: 
10798: sub rndseed_64bit5 {
10799:     my ($symb,$courseid,$domain,$username)=@_;
10800:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
10801:     return "$num1:$num2";
10802: }
10803: 
10804: sub rndseed_CODE_64bit {
10805:     my ($symb,$courseid,$domain,$username)=@_;
10806:     {
10807: 	use integer;
10808: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
10809: 	my $symbseed=numval2($symb);
10810: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
10811: 	my $CODEseed=numval(&getCODE());
10812: 	my $courseseed=unpack("%32S*",$courseid.' ');
10813: 	my $num1=$symbseed+$CODEchck;
10814: 	my $num2=$CODEseed+$courseseed+$symbchck;
10815: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
10816: 	#&logthis("rndseed :$num1:$num2:$symb");
10817: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
10818: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
10819: 	return "$num1:$num2";
10820:     }
10821: }
10822: 
10823: sub rndseed_CODE_64bit4 {
10824:     my ($symb,$courseid,$domain,$username)=@_;
10825:     {
10826: 	use integer;
10827: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
10828: 	my $symbseed=numval3($symb);
10829: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
10830: 	my $CODEseed=numval3(&getCODE());
10831: 	my $courseseed=unpack("%32S*",$courseid.' ');
10832: 	my $num1=$symbseed+$CODEchck;
10833: 	my $num2=$CODEseed+$courseseed+$symbchck;
10834: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
10835: 	#&logthis("rndseed :$num1:$num2:$symb");
10836: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
10837: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
10838: 	return "$num1:$num2";
10839:     }
10840: }
10841: 
10842: sub rndseed_CODE_64bit5 {
10843:     my ($symb,$courseid,$domain,$username)=@_;
10844:     my $code = &getCODE();
10845:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
10846:     return "$num1:$num2";
10847: }
10848: 
10849: sub setup_random_from_rndseed {
10850:     my ($rndseed)=@_;
10851:     if ($rndseed =~/([,:])/) {
10852: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
10853: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
10854:     } else {
10855: 	&Math::Random::random_set_seed_from_phrase($rndseed);
10856:     }
10857: }
10858: 
10859: sub latest_receipt_algorithm_id {
10860:     return 'receipt3';
10861: }
10862: 
10863: sub recunique {
10864:     my $fucourseid=shift;
10865:     my $unique;
10866:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
10867: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
10868: 	$unique=$env{"course.$fucourseid.internal.encseed"};
10869:     } else {
10870: 	$unique=$perlvar{'lonReceipt'};
10871:     }
10872:     return unpack("%32C*",$unique);
10873: }
10874: 
10875: sub recprefix {
10876:     my $fucourseid=shift;
10877:     my $prefix;
10878:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
10879: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
10880: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
10881:     } else {
10882: 	$prefix=$perlvar{'lonHostID'};
10883:     }
10884:     return unpack("%32C*",$prefix);
10885: }
10886: 
10887: sub ireceipt {
10888:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
10889: 
10890:     my $return =&recprefix($fucourseid).'-';
10891: 
10892:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
10893: 	$env{'request.state'} eq 'construct') {
10894: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
10895: 	return $return;
10896:     }
10897: 
10898:     my $cuname=unpack("%32C*",$funame);
10899:     my $cudom=unpack("%32C*",$fudom);
10900:     my $cucourseid=unpack("%32C*",$fucourseid);
10901:     my $cusymb=unpack("%32C*",$fusymb);
10902:     my $cunique=&recunique($fucourseid);
10903:     my $cpart=unpack("%32S*",$part);
10904:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
10905: 
10906: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
10907: 			       
10908: 	$return.= ($cunique%$cuname+
10909: 		   $cunique%$cudom+
10910: 		   $cusymb%$cuname+
10911: 		   $cusymb%$cudom+
10912: 		   $cucourseid%$cuname+
10913: 		   $cucourseid%$cudom+
10914: 		   $cpart%$cuname+
10915: 		   $cpart%$cudom);
10916:     } else {
10917: 	$return.= ($cunique%$cuname+
10918: 		   $cunique%$cudom+
10919: 		   $cusymb%$cuname+
10920: 		   $cusymb%$cudom+
10921: 		   $cucourseid%$cuname+
10922: 		   $cucourseid%$cudom);
10923:     }
10924:     return $return;
10925: }
10926: 
10927: sub receipt {
10928:     my ($part)=@_;
10929:     my ($symb,$courseid,$domain,$name) = &whichuser();
10930:     return &ireceipt($name,$domain,$courseid,$symb,$part);
10931: }
10932: 
10933: sub whichuser {
10934:     my ($passedsymb)=@_;
10935:     my ($symb,$courseid,$domain,$name,$publicuser);
10936:     if (defined($env{'form.grade_symb'})) {
10937: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
10938: 	my $allowed=&allowed('vgr',$tmp_courseid);
10939: 	if (!$allowed &&
10940: 	    exists($env{'request.course.sec'}) &&
10941: 	    $env{'request.course.sec'} !~ /^\s*$/) {
10942: 	    $allowed=&allowed('vgr',$tmp_courseid.
10943: 			      '/'.$env{'request.course.sec'});
10944: 	}
10945: 	if ($allowed) {
10946: 	    ($symb)=&get_env_multiple('form.grade_symb');
10947: 	    $courseid=$tmp_courseid;
10948: 	    ($domain)=&get_env_multiple('form.grade_domain');
10949: 	    ($name)=&get_env_multiple('form.grade_username');
10950: 	    return ($symb,$courseid,$domain,$name,$publicuser);
10951: 	}
10952:     }
10953:     if (!$passedsymb) {
10954: 	$symb=&symbread();
10955:     } else {
10956: 	$symb=$passedsymb;
10957:     }
10958:     $courseid=$env{'request.course.id'};
10959:     $domain=$env{'user.domain'};
10960:     $name=$env{'user.name'};
10961:     if ($name eq 'public' && $domain eq 'public') {
10962: 	if (!defined($env{'form.username'})) {
10963: 	    $env{'form.username'}.=time.rand(10000000);
10964: 	}
10965: 	$name.=$env{'form.username'};
10966:     }
10967:     return ($symb,$courseid,$domain,$name,$publicuser);
10968: 
10969: }
10970: 
10971: # ------------------------------------------------------------ Serves up a file
10972: # returns either the contents of the file or 
10973: # -1 if the file doesn't exist
10974: #
10975: # if the target is a file that was uploaded via DOCS, 
10976: # a check will be made to see if a current copy exists on the local server,
10977: # if it does this will be served, otherwise a copy will be retrieved from
10978: # the home server for the course and stored in /home/httpd/html/userfiles on
10979: # the local server.   
10980: 
10981: sub getfile {
10982:     my ($file) = @_;
10983:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
10984:     &repcopy($file);
10985:     return &readfile($file);
10986: }
10987: 
10988: sub repcopy_userfile {
10989:     my ($file)=@_;
10990:     my $londocroot = $perlvar{'lonDocRoot'};
10991:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
10992:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
10993:     my ($cdom,$cnum,$filename) = 
10994: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
10995:     my $uri="/uploaded/$cdom/$cnum/$filename";
10996:     if (-e "$file") {
10997: # we already have a local copy, check it out
10998: 	my @fileinfo = stat($file);
10999: 	my $rtncode;
11000: 	my $info;
11001: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
11002: 	if ($lwpresp ne 'ok') {
11003: # there is no such file anymore, even though we had a local copy
11004: 	    if ($rtncode eq '404') {
11005: 		unlink($file);
11006: 	    }
11007: 	    return -1;
11008: 	}
11009: 	if ($info < $fileinfo[9]) {
11010: # nice, the file we have is up-to-date, just say okay
11011: 	    return 'ok';
11012: 	} else {
11013: # the file is outdated, get rid of it
11014: 	    unlink($file);
11015: 	}
11016:     }
11017: # one way or the other, at this point, we don't have the file
11018: # construct the correct path for the file
11019:     my @parts = ($cdom,$cnum); 
11020:     if ($filename =~ m|^(.+)/[^/]+$|) {
11021: 	push @parts, split(/\//,$1);
11022:     }
11023:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
11024:     foreach my $part (@parts) {
11025: 	$path .= '/'.$part;
11026: 	if (!-e $path) {
11027: 	    mkdir($path,0770);
11028: 	}
11029:     }
11030: # now the path exists for sure
11031: # get a user agent
11032:     my $ua=new LWP::UserAgent;
11033:     my $transferfile=$file.'.in.transfer';
11034: # FIXME: this should flock
11035:     if (-e $transferfile) { return 'ok'; }
11036:     my $request;
11037:     $uri=~s/^\///;
11038:     my $homeserver = &homeserver($cnum,$cdom);
11039:     my $protocol = $protocol{$homeserver};
11040:     $protocol = 'http' if ($protocol ne 'https');
11041:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
11042:     my $response=$ua->request($request,$transferfile);
11043: # did it work?
11044:     if ($response->is_error()) {
11045: 	unlink($transferfile);
11046: 	&logthis("Userfile repcopy failed for $uri");
11047: 	return -1;
11048:     }
11049: # worked, rename the transfer file
11050:     rename($transferfile,$file);
11051:     return 'ok';
11052: }
11053: 
11054: sub tokenwrapper {
11055:     my $uri=shift;
11056:     $uri=~s|^https?\://([^/]+)||;
11057:     $uri=~s|^/||;
11058:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
11059:     my $token=$1;
11060:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
11061:     if ($udom && $uname && $file) {
11062: 	$file=~s|(\?\.*)*$||;
11063:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
11064:         my $homeserver = &homeserver($uname,$udom);
11065:         my $protocol = $protocol{$homeserver};
11066:         $protocol = 'http' if ($protocol ne 'https');
11067:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
11068:                (($uri=~/\?/)?'&':'?').'token='.$token.
11069:                                '&tokenissued='.$perlvar{'lonHostID'};
11070:     } else {
11071:         return '/adm/notfound.html';
11072:     }
11073: }
11074: 
11075: # call with reqtype HEAD: get last modification time
11076: # call with reqtype GET: get the file contents
11077: # Do not call this with reqtype GET for large files! It loads everything into memory
11078: #
11079: sub getuploaded {
11080:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
11081:     $uri=~s/^\///;
11082:     my $homeserver = &homeserver($cnum,$cdom);
11083:     my $protocol = $protocol{$homeserver};
11084:     $protocol = 'http' if ($protocol ne 'https');
11085:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
11086:     my $ua=new LWP::UserAgent;
11087:     my $request=new HTTP::Request($reqtype,$uri);
11088:     my $response=$ua->request($request);
11089:     $$rtncode = $response->code;
11090:     if (! $response->is_success()) {
11091: 	return 'failed';
11092:     }      
11093:     if ($reqtype eq 'HEAD') {
11094: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
11095:     } elsif ($reqtype eq 'GET') {
11096: 	$$info = $response->content;
11097:     }
11098:     return 'ok';
11099: }
11100: 
11101: sub readfile {
11102:     my $file = shift;
11103:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
11104:     my $fh;
11105:     open($fh,"<$file");
11106:     my $a='';
11107:     while (my $line = <$fh>) { $a .= $line; }
11108:     return $a;
11109: }
11110: 
11111: sub filelocation {
11112:     my ($dir,$file) = @_;
11113:     my $location;
11114:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
11115: 
11116:     if ($file =~ m-^/adm/-) {
11117: 	$file=~s-^/adm/wrapper/-/-;
11118: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
11119:     }
11120: 
11121:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
11122:         $location = $file;
11123:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
11124:         my ($udom,$uname,$filename)=
11125:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
11126:         my $home=&homeserver($uname,$udom);
11127:         my $is_me=0;
11128:         my @ids=&current_machine_ids();
11129:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
11130:         if ($is_me) {
11131:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
11132:         } else {
11133:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
11134:   	      $udom.'/'.$uname.'/'.$filename;
11135:         }
11136:     } elsif ($file =~ m-^/adm/-) {
11137: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
11138:     } else {
11139:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
11140:         $file=~s:^/(res|priv)/:/:;
11141:         my $space=$1;
11142:         if ( !( $file =~ m:^/:) ) {
11143:             $location = $dir. '/'.$file;
11144:         } else {
11145:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
11146:         }
11147:     }
11148:     $location=~s://+:/:g; # remove duplicate /
11149:     while ($location=~m{/\.\./}) {
11150: 	if ($location =~ m{/[^/]+/\.\./}) {
11151: 	    $location=~ s{/[^/]+/\.\./}{/}g;
11152: 	} else {
11153: 	    $location=~ s{/\.\./}{/}g;
11154: 	}
11155:     } #remove dir/..
11156:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
11157:     return $location;
11158: }
11159: 
11160: sub hreflocation {
11161:     my ($dir,$file)=@_;
11162:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
11163: 	$file=filelocation($dir,$file);
11164:     } elsif ($file=~m-^/adm/-) {
11165: 	$file=~s-^/adm/wrapper/-/-;
11166: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
11167:     }
11168:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
11169: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
11170:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
11171: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
11172: 	        {/uploaded/$1/$2/}x;
11173:     }
11174:     if ($file=~ m{^/userfiles/}) {
11175: 	$file =~ s{^/userfiles/}{/uploaded/};
11176:     }
11177:     return $file;
11178: }
11179: 
11180: 
11181: 
11182: 
11183: 
11184: sub current_machine_domains {
11185:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
11186: }
11187: 
11188: sub machine_domains {
11189:     my ($hostname) = @_;
11190:     my @domains;
11191:     my %hostname = &all_hostnames();
11192:     while( my($id, $name) = each(%hostname)) {
11193: #	&logthis("-$id-$name-$hostname-");
11194: 	if ($hostname eq $name) {
11195: 	    push(@domains,&host_domain($id));
11196: 	}
11197:     }
11198:     return @domains;
11199: }
11200: 
11201: sub current_machine_ids {
11202:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
11203: }
11204: 
11205: sub machine_ids {
11206:     my ($hostname) = @_;
11207:     $hostname ||= &hostname($perlvar{'lonHostID'});
11208:     my @ids;
11209:     my %name_to_host = &all_names();
11210:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
11211: 	return @{ $name_to_host{$hostname} };
11212:     }
11213:     return;
11214: }
11215: 
11216: sub additional_machine_domains {
11217:     my @domains;
11218:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
11219:     while( my $line = <$fh>) {
11220:         $line =~ s/\s//g;
11221:         push(@domains,$line);
11222:     }
11223:     return @domains;
11224: }
11225: 
11226: sub default_login_domain {
11227:     my $domain = $perlvar{'lonDefDomain'};
11228:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
11229:     foreach my $posdom (&current_machine_domains(),
11230:                         &additional_machine_domains()) {
11231:         if (lc($posdom) eq lc($testdomain)) {
11232:             $domain=$posdom;
11233:             last;
11234:         }
11235:     }
11236:     return $domain;
11237: }
11238: 
11239: # ------------------------------------------------------------- Declutters URLs
11240: 
11241: sub declutter {
11242:     my $thisfn=shift;
11243:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
11244:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
11245:     $thisfn=~s/^\///;
11246:     $thisfn=~s|^adm/wrapper/||;
11247:     $thisfn=~s|^adm/coursedocs/showdoc/||;
11248:     $thisfn=~s/^res\///;
11249:     $thisfn=~s/^priv\///;
11250:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
11251:         $thisfn=~s/\?.+$//;
11252:     }
11253:     return $thisfn;
11254: }
11255: 
11256: # ------------------------------------------------------------- Clutter up URLs
11257: 
11258: sub clutter {
11259:     my $thisfn='/'.&declutter(shift);
11260:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
11261: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
11262:        $thisfn='/res'.$thisfn; 
11263:     }
11264:     if ($thisfn !~m|^/adm|) {
11265: 	if ($thisfn =~ m|^/ext/|) {
11266: 	    $thisfn='/adm/wrapper'.$thisfn;
11267: 	} else {
11268: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
11269: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
11270: 	    if ($embstyle eq 'ssi'
11271: 		|| ($embstyle eq 'hdn')
11272: 		|| ($embstyle eq 'rat')
11273: 		|| ($embstyle eq 'prv')
11274: 		|| ($embstyle eq 'ign')) {
11275: 		#do nothing with these
11276: 	    } elsif (($embstyle eq 'img') 
11277: 		|| ($embstyle eq 'emb')
11278: 		|| ($embstyle eq 'wrp')) {
11279: 		$thisfn='/adm/wrapper'.$thisfn;
11280: 	    } elsif ($embstyle eq 'unk'
11281: 		     && $thisfn!~/\.(sequence|page)$/) {
11282: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
11283: 	    } else {
11284: #		&logthis("Got a blank emb style");
11285: 	    }
11286: 	}
11287:     }
11288:     return $thisfn;
11289: }
11290: 
11291: sub clutter_with_no_wrapper {
11292:     my $uri = &clutter(shift);
11293:     if ($uri =~ m-^/adm/-) {
11294: 	$uri =~ s-^/adm/wrapper/-/-;
11295: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
11296:     }
11297:     return $uri;
11298: }
11299: 
11300: sub freeze_escape {
11301:     my ($value)=@_;
11302:     if (ref($value)) {
11303: 	$value=&nfreeze($value);
11304: 	return '__FROZEN__'.&escape($value);
11305:     }
11306:     return &escape($value);
11307: }
11308: 
11309: 
11310: sub thaw_unescape {
11311:     my ($value)=@_;
11312:     if ($value =~ /^__FROZEN__/) {
11313: 	substr($value,0,10,undef);
11314: 	$value=&unescape($value);
11315: 	return &thaw($value);
11316:     }
11317:     return &unescape($value);
11318: }
11319: 
11320: sub correct_line_ends {
11321:     my ($result)=@_;
11322:     $$result =~s/\r\n/\n/mg;
11323:     $$result =~s/\r/\n/mg;
11324: }
11325: # ================================================================ Main Program
11326: 
11327: sub goodbye {
11328:    &logthis("Starting Shut down");
11329: #not converted to using infrastruture and probably shouldn't be
11330:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
11331: #converted
11332: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
11333:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
11334: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
11335: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
11336: #1.1 only
11337: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
11338: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
11339: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
11340: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
11341:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
11342:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
11343:    &logthis(sprintf("%-20s is %s",'hits',$hits));
11344:    &flushcourselogs();
11345:    &logthis("Shutting down");
11346: }
11347: 
11348: sub get_dns {
11349:     my ($url,$func,$ignore_cache) = @_;
11350:     if (!$ignore_cache) {
11351: 	my ($content,$cached)=
11352: 	    &Apache::lonnet::is_cached_new('dns',$url);
11353: 	if ($cached) {
11354: 	    &$func($content);
11355: 	    return;
11356: 	}
11357:     }
11358: 
11359:     my %alldns;
11360:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11361:     foreach my $dns (<$config>) {
11362: 	next if ($dns !~ /^\^(\S*)/x);
11363:         my $line = $1;
11364:         my ($host,$protocol) = split(/:/,$line);
11365:         if ($protocol ne 'https') {
11366:             $protocol = 'http';
11367:         }
11368: 	$alldns{$host} = $protocol;
11369:     }
11370:     while (%alldns) {
11371: 	my ($dns) = keys(%alldns);
11372: 	my $ua=new LWP::UserAgent;
11373:         $ua->timeout(30);
11374: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
11375: 	my $response=$ua->request($request);
11376:         delete($alldns{$dns});
11377: 	next if ($response->is_error());
11378: 	my @content = split("\n",$response->content);
11379: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
11380: 	&$func(\@content);
11381: 	return;
11382:     }
11383:     close($config);
11384:     my $which = (split('/',$url))[3];
11385:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
11386:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
11387:     my @content = <$config>;
11388:     &$func(\@content);
11389:     return;
11390: }
11391: # ------------------------------------------------------------ Read domain file
11392: {
11393:     my $loaded;
11394:     my %domain;
11395: 
11396:     sub parse_domain_tab {
11397: 	my ($lines) = @_;
11398: 	foreach my $line (@$lines) {
11399: 	    next if ($line =~ /^(\#|\s*$ )/x);
11400: 
11401: 	    chomp($line);
11402: 	    my ($name,@elements) = split(/:/,$line,9);
11403: 	    my %this_domain;
11404: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
11405: 			       'lang_def', 'city', 'longi', 'lati',
11406: 			       'primary') {
11407: 		$this_domain{$field} = shift(@elements);
11408: 	    }
11409: 	    $domain{$name} = \%this_domain;
11410: 	}
11411:     }
11412: 
11413:     sub reset_domain_info {
11414: 	undef($loaded);
11415: 	undef(%domain);
11416:     }
11417: 
11418:     sub load_domain_tab {
11419: 	my ($ignore_cache) = @_;
11420: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
11421: 	my $fh;
11422: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
11423: 	    my @lines = <$fh>;
11424: 	    &parse_domain_tab(\@lines);
11425: 	}
11426: 	close($fh);
11427: 	$loaded = 1;
11428:     }
11429: 
11430:     sub domain {
11431: 	&load_domain_tab() if (!$loaded);
11432: 
11433: 	my ($name,$what) = @_;
11434: 	return if ( !exists($domain{$name}) );
11435: 
11436: 	if (!$what) {
11437: 	    return $domain{$name}{'description'};
11438: 	}
11439: 	return $domain{$name}{$what};
11440:     }
11441: 
11442:     sub domain_info {
11443:         &load_domain_tab() if (!$loaded);
11444:         return %domain;
11445:     }
11446: 
11447: }
11448: 
11449: 
11450: # ------------------------------------------------------------- Read hosts file
11451: {
11452:     my %hostname;
11453:     my %hostdom;
11454:     my %libserv;
11455:     my $loaded;
11456:     my %name_to_host;
11457:     my %internetdom;
11458:     my %LC_dns_serv;
11459: 
11460:     sub parse_hosts_tab {
11461: 	my ($file) = @_;
11462: 	foreach my $configline (@$file) {
11463: 	    next if ($configline =~ /^(\#|\s*$ )/x);
11464:             chomp($configline);
11465: 	    if ($configline =~ /^\^/) {
11466:                 if ($configline =~ /^\^([\w.\-]+)/) {
11467:                     $LC_dns_serv{$1} = 1;
11468:                 }
11469:                 next;
11470:             }
11471: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
11472: 	    $name=~s/\s//g;
11473: 	    if ($id && $domain && $role && $name) {
11474: 		$hostname{$id}=$name;
11475: 		push(@{$name_to_host{$name}}, $id);
11476: 		$hostdom{$id}=$domain;
11477: 		if ($role eq 'library') { $libserv{$id}=$name; }
11478:                 if (defined($protocol)) {
11479:                     if ($protocol eq 'https') {
11480:                         $protocol{$id} = $protocol;
11481:                     } else {
11482:                         $protocol{$id} = 'http'; 
11483:                     }
11484:                 } else {
11485:                     $protocol{$id} = 'http';
11486:                 }
11487:                 if (defined($intdom)) {
11488:                     $internetdom{$id} = $intdom;
11489:                 }
11490: 	    }
11491: 	}
11492:     }
11493:     
11494:     sub reset_hosts_info {
11495: 	&purge_remembered();
11496: 	&reset_domain_info();
11497: 	&reset_hosts_ip_info();
11498: 	undef(%name_to_host);
11499: 	undef(%hostname);
11500: 	undef(%hostdom);
11501: 	undef(%libserv);
11502: 	undef($loaded);
11503:     }
11504: 
11505:     sub load_hosts_tab {
11506: 	my ($ignore_cache) = @_;
11507: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
11508: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11509: 	my @config = <$config>;
11510: 	&parse_hosts_tab(\@config);
11511: 	close($config);
11512: 	$loaded=1;
11513:     }
11514: 
11515:     sub hostname {
11516: 	&load_hosts_tab() if (!$loaded);
11517: 
11518: 	my ($lonid) = @_;
11519: 	return $hostname{$lonid};
11520:     }
11521: 
11522:     sub all_hostnames {
11523: 	&load_hosts_tab() if (!$loaded);
11524: 
11525: 	return %hostname;
11526:     }
11527: 
11528:     sub all_names {
11529: 	&load_hosts_tab() if (!$loaded);
11530: 
11531: 	return %name_to_host;
11532:     }
11533: 
11534:     sub all_host_domain {
11535:         &load_hosts_tab() if (!$loaded);
11536:         return %hostdom;
11537:     }
11538: 
11539:     sub is_library {
11540: 	&load_hosts_tab() if (!$loaded);
11541: 
11542: 	return exists($libserv{$_[0]});
11543:     }
11544: 
11545:     sub all_library {
11546: 	&load_hosts_tab() if (!$loaded);
11547: 
11548: 	return %libserv;
11549:     }
11550: 
11551:     sub unique_library {
11552: 	#2x reverse removes all hostnames that appear more than once
11553:         my %unique = reverse &all_library();
11554:         return reverse %unique;
11555:     }
11556: 
11557:     sub get_servers {
11558: 	&load_hosts_tab() if (!$loaded);
11559: 
11560: 	my ($domain,$type) = @_;
11561: 	my %possible_hosts = ($type eq 'library') ? %libserv
11562: 	                                          : %hostname;
11563: 	my %result;
11564: 	if (ref($domain) eq 'ARRAY') {
11565: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
11566: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
11567: 		    $result{$host} = $hostname;
11568: 		}
11569: 	    }
11570: 	} else {
11571: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
11572: 		if ($hostdom{$host} eq $domain) {
11573: 		    $result{$host} = $hostname;
11574: 		}
11575: 	    }
11576: 	}
11577: 	return %result;
11578:     }
11579: 
11580:     sub get_unique_servers {
11581:         my %unique = reverse &get_servers(@_);
11582: 	return reverse %unique;
11583:     }
11584: 
11585:     sub host_domain {
11586: 	&load_hosts_tab() if (!$loaded);
11587: 
11588: 	my ($lonid) = @_;
11589: 	return $hostdom{$lonid};
11590:     }
11591: 
11592:     sub all_domains {
11593: 	&load_hosts_tab() if (!$loaded);
11594: 
11595: 	my %seen;
11596: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
11597: 	return @uniq;
11598:     }
11599: 
11600:     sub internet_dom {
11601:         &load_hosts_tab() if (!$loaded);
11602: 
11603:         my ($lonid) = @_;
11604:         return $internetdom{$lonid};
11605:     }
11606: 
11607:     sub is_LC_dns {
11608:         &load_hosts_tab() if (!$loaded);
11609: 
11610:         my ($hostname) = @_;
11611:         return exists($LC_dns_serv{$hostname});
11612:     }
11613: 
11614: }
11615: 
11616: { 
11617:     my %iphost;
11618:     my %name_to_ip;
11619:     my %lonid_to_ip;
11620: 
11621:     sub get_hosts_from_ip {
11622: 	my ($ip) = @_;
11623: 	my %iphosts = &get_iphost();
11624: 	if (ref($iphosts{$ip})) {
11625: 	    return @{$iphosts{$ip}};
11626: 	}
11627: 	return;
11628:     }
11629:     
11630:     sub reset_hosts_ip_info {
11631: 	undef(%iphost);
11632: 	undef(%name_to_ip);
11633: 	undef(%lonid_to_ip);
11634:     }
11635: 
11636:     sub get_host_ip {
11637: 	my ($lonid) = @_;
11638: 	if (exists($lonid_to_ip{$lonid})) {
11639: 	    return $lonid_to_ip{$lonid};
11640: 	}
11641: 	my $name=&hostname($lonid);
11642:    	my $ip = gethostbyname($name);
11643: 	return if (!$ip || length($ip) ne 4);
11644: 	$ip=inet_ntoa($ip);
11645: 	$name_to_ip{$name}   = $ip;
11646: 	$lonid_to_ip{$lonid} = $ip;
11647: 	return $ip;
11648:     }
11649:     
11650:     sub get_iphost {
11651: 	my ($ignore_cache) = @_;
11652: 
11653: 	if (!$ignore_cache) {
11654: 	    if (%iphost) {
11655: 		return %iphost;
11656: 	    }
11657: 	    my ($ip_info,$cached)=
11658: 		&Apache::lonnet::is_cached_new('iphost','iphost');
11659: 	    if ($cached) {
11660: 		%iphost      = %{$ip_info->[0]};
11661: 		%name_to_ip  = %{$ip_info->[1]};
11662: 		%lonid_to_ip = %{$ip_info->[2]};
11663: 		return %iphost;
11664: 	    }
11665: 	}
11666: 
11667: 	# get yesterday's info for fallback
11668: 	my %old_name_to_ip;
11669: 	my ($ip_info,$cached)=
11670: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
11671: 	if ($cached) {
11672: 	    %old_name_to_ip = %{$ip_info->[1]};
11673: 	}
11674: 
11675: 	my %name_to_host = &all_names();
11676: 	foreach my $name (keys(%name_to_host)) {
11677: 	    my $ip;
11678: 	    if (!exists($name_to_ip{$name})) {
11679: 		$ip = gethostbyname($name);
11680: 		if (!$ip || length($ip) ne 4) {
11681: 		    if (defined($old_name_to_ip{$name})) {
11682: 			$ip = $old_name_to_ip{$name};
11683: 			&logthis("Can't find $name defaulting to old $ip");
11684: 		    } else {
11685: 			&logthis("Name $name no IP found");
11686: 			next;
11687: 		    }
11688: 		} else {
11689: 		    $ip=inet_ntoa($ip);
11690: 		}
11691: 		$name_to_ip{$name} = $ip;
11692: 	    } else {
11693: 		$ip = $name_to_ip{$name};
11694: 	    }
11695: 	    foreach my $id (@{ $name_to_host{$name} }) {
11696: 		$lonid_to_ip{$id} = $ip;
11697: 	    }
11698: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
11699: 	}
11700: 	&Apache::lonnet::do_cache_new('iphost','iphost',
11701: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
11702: 				      48*60*60);
11703: 
11704: 	return %iphost;
11705:     }
11706: 
11707:     #
11708:     #  Given a DNS returns the loncapa host name for that DNS 
11709:     # 
11710:     sub host_from_dns {
11711:         my ($dns) = @_;
11712:         my @hosts;
11713:         my $ip;
11714: 
11715:         if (exists($name_to_ip{$dns})) {
11716:             $ip = $name_to_ip{$dns};
11717:         }
11718:         if (!$ip) {
11719:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
11720:             if (length($ip) == 4) { 
11721: 	        $ip   = &IO::Socket::inet_ntoa($ip);
11722:             }
11723:         }
11724:         if ($ip) {
11725: 	    @hosts = get_hosts_from_ip($ip);
11726: 	    return $hosts[0];
11727:         }
11728:         return undef;
11729:     }
11730: 
11731:     sub get_internet_names {
11732:         my ($lonid) = @_;
11733:         return if ($lonid eq '');
11734:         my ($idnref,$cached)=
11735:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
11736:         if ($cached) {
11737:             return $idnref;
11738:         }
11739:         my $ip = &get_host_ip($lonid);
11740:         my @hosts = &get_hosts_from_ip($ip);
11741:         my %iphost = &get_iphost();
11742:         my (@idns,%seen);
11743:         foreach my $id (@hosts) {
11744:             my $dom = &host_domain($id);
11745:             my $prim_id = &domain($dom,'primary');
11746:             my $prim_ip = &get_host_ip($prim_id);
11747:             next if ($seen{$prim_ip});
11748:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
11749:                 foreach my $id (@{$iphost{$prim_ip}}) {
11750:                     my $intdom = &internet_dom($id);
11751:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
11752:                         push(@idns,$intdom);
11753:                     }
11754:                 }
11755:             }
11756:             $seen{$prim_ip} = 1;
11757:         }
11758:         return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
11759:     }
11760: 
11761: }
11762: 
11763: sub all_loncaparevs {
11764:     return qw(1.1 1.2 1.3 2.0 2.1 2.2 2.3 2.4 2.5 2.6 2.7 2.8 2.9 2.10);
11765: }
11766: 
11767: BEGIN {
11768: 
11769: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
11770:     unless ($readit) {
11771: {
11772:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
11773:     %perlvar = (%perlvar,%{$configvars});
11774: }
11775: 
11776: 
11777: # ------------------------------------------------------ Read spare server file
11778: {
11779:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
11780: 
11781:     while (my $configline=<$config>) {
11782:        chomp($configline);
11783:        if ($configline) {
11784: 	   my ($host,$type) = split(':',$configline,2);
11785: 	   if (!defined($type) || $type eq '') { $type = 'default' };
11786: 	   push(@{ $spareid{$type} }, $host);
11787:        }
11788:     }
11789:     close($config);
11790: }
11791: # ------------------------------------------------------------ Read permissions
11792: {
11793:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
11794: 
11795:     while (my $configline=<$config>) {
11796: 	chomp($configline);
11797: 	if ($configline) {
11798: 	    my ($role,$perm)=split(/ /,$configline);
11799: 	    if ($perm ne '') { $pr{$role}=$perm; }
11800: 	}
11801:     }
11802:     close($config);
11803: }
11804: 
11805: # -------------------------------------------- Read plain texts for permissions
11806: {
11807:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
11808: 
11809:     while (my $configline=<$config>) {
11810: 	chomp($configline);
11811: 	if ($configline) {
11812: 	    my ($short,@plain)=split(/:/,$configline);
11813:             %{$prp{$short}} = ();
11814: 	    if (@plain > 0) {
11815:                 $prp{$short}{'std'} = $plain[0];
11816:                 for (my $i=1; $i<@plain; $i++) {
11817:                     $prp{$short}{'alt'.$i} = $plain[$i];  
11818:                 }
11819:             }
11820: 	}
11821:     }
11822:     close($config);
11823: }
11824: 
11825: # ---------------------------------------------------------- Read package table
11826: {
11827:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
11828: 
11829:     while (my $configline=<$config>) {
11830: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
11831: 	chomp($configline);
11832: 	my ($short,$plain)=split(/:/,$configline);
11833: 	my ($pack,$name)=split(/\&/,$short);
11834: 	if ($plain ne '') {
11835: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
11836: 	    $packagetab{$short}=$plain; 
11837: 	}
11838:     }
11839:     close($config);
11840: }
11841: 
11842: # ---------------------------------------------------------- Read loncaparev table
11843: {
11844:     if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
11845:         if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
11846:             while (my $configline=<$config>) {
11847:                 chomp($configline);
11848:                 my ($hostid,$loncaparev)=split(/:/,$configline);
11849:                 $loncaparevs{$hostid}=$loncaparev;
11850:             }
11851:             close($config);
11852:         }
11853:     }
11854: }
11855: 
11856: # ---------------------------------------------------------- Read serverhostID table
11857: {
11858:     if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
11859:         if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
11860:             while (my $configline=<$config>) {
11861:                 chomp($configline);
11862:                 my ($name,$id)=split(/:/,$configline);
11863:                 $serverhomeIDs{$name}=$id;
11864:             }
11865:             close($config);
11866:         }
11867:     }
11868: }
11869: 
11870: {
11871:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
11872:     if (-e $file) {
11873:         my $parser = HTML::LCParser->new($file);
11874:         while (my $token = $parser->get_token()) {
11875:             if ($token->[0] eq 'S') {
11876:                 my $item = $token->[1];
11877:                 my $name = $token->[2]{'name'};
11878:                 my $value = $token->[2]{'value'};
11879:                 if ($item ne '' && $name ne '' && $value ne '') {
11880:                     my $release = $parser->get_text();
11881:                     $release =~ s/(^\s*|\s*$ )//gx;
11882:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
11883:                 }
11884:             }
11885:         }
11886:     }
11887: }
11888: 
11889: # ---------------------------------------------------------- Read managers table
11890: {
11891:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
11892:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
11893:             while (my $configline=<$config>) {
11894:                 chomp($configline);
11895:                 next if ($configline =~ /^\#/);
11896:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
11897:                     $managerstab{$configline} = 1;
11898:                 }
11899:             }
11900:             close($config);
11901:         }
11902:     }
11903: }
11904: 
11905: # ------------- set up temporary directory
11906: {
11907:     $tmpdir = LONCAPA::tempdir();
11908: 
11909: }
11910: 
11911: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
11912: 				'compress_threshold'=> 20_000,
11913:  			        });
11914: 
11915: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
11916: $dumpcount=0;
11917: $locknum=0;
11918: 
11919: &logtouch();
11920: &logthis('<font color="yellow">INFO: Read configuration</font>');
11921: $readit=1;
11922:     {
11923: 	use integer;
11924: 	my $test=(2**32)+1;
11925: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
11926: 	&logthis(" Detected 64bit platform ($_64bit)");
11927:     }
11928: }
11929: }
11930: 
11931: 1;
11932: __END__
11933: 
11934: =pod
11935: 
11936: =head1 NAME
11937: 
11938: Apache::lonnet - Subroutines to ask questions about things in the network.
11939: 
11940: =head1 SYNOPSIS
11941: 
11942: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
11943: 
11944:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
11945: 
11946: Common parameters:
11947: 
11948: =over 4
11949: 
11950: =item *
11951: 
11952: $uname : an internal username (if $cname expecting a course Id specifically)
11953: 
11954: =item *
11955: 
11956: $udom : a domain (if $cdom expecting a course's domain specifically)
11957: 
11958: =item *
11959: 
11960: $symb : a resource instance identifier
11961: 
11962: =item *
11963: 
11964: $namespace : the name of a .db file that contains the data needed or
11965: being set.
11966: 
11967: =back
11968: 
11969: =head1 OVERVIEW
11970: 
11971: lonnet provides subroutines which interact with the
11972: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
11973: about classes, users, and resources.
11974: 
11975: For many of these objects you can also use this to store data about
11976: them or modify them in various ways.
11977: 
11978: =head2 Symbs
11979: 
11980: To identify a specific instance of a resource, LON-CAPA uses symbols
11981: or "symbs"X<symb>. These identifiers are built from the URL of the
11982: map, the resource number of the resource in the map, and the URL of
11983: the resource itself. The latter is somewhat redundant, but might help
11984: if maps change.
11985: 
11986: An example is
11987: 
11988:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
11989: 
11990: The respective map entry is
11991: 
11992:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
11993:   title="Problem 2">
11994:  </resource>
11995: 
11996: Symbs are used by the random number generator, as well as to store and
11997: restore data specific to a certain instance of for example a problem.
11998: 
11999: =head2 Storing And Retrieving Data
12000: 
12001: X<store()>X<cstore()>X<restore()>Three of the most important functions
12002: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
12003: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
12004: is is the non-critical message twin of cstore. These functions are for
12005: handlers to store a perl hash to a user's permanent data space in an
12006: easy manner, and to retrieve it again on another call. It is expected
12007: that a handler would use this once at the beginning to retrieve data,
12008: and then again once at the end to send only the new data back.
12009: 
12010: The data is stored in the user's data directory on the user's
12011: homeserver under the ID of the course.
12012: 
12013: The hash that is returned by restore will have all of the previous
12014: value for all of the elements of the hash.
12015: 
12016: Example:
12017: 
12018:  #creating a hash
12019:  my %hash;
12020:  $hash{'foo'}='bar';
12021: 
12022:  #storing it
12023:  &Apache::lonnet::cstore(\%hash);
12024: 
12025:  #changing a value
12026:  $hash{'foo'}='notbar';
12027: 
12028:  #adding a new value
12029:  $hash{'bar'}='foo';
12030:  &Apache::lonnet::cstore(\%hash);
12031: 
12032:  #retrieving the hash
12033:  my %history=&Apache::lonnet::restore();
12034: 
12035:  #print the hash
12036:  foreach my $key (sort(keys(%history))) {
12037:    print("\%history{$key} = $history{$key}");
12038:  }
12039: 
12040: Will print out:
12041: 
12042:  %history{1:foo} = bar
12043:  %history{1:keys} = foo:timestamp
12044:  %history{1:timestamp} = 990455579
12045:  %history{2:bar} = foo
12046:  %history{2:foo} = notbar
12047:  %history{2:keys} = foo:bar:timestamp
12048:  %history{2:timestamp} = 990455580
12049:  %history{bar} = foo
12050:  %history{foo} = notbar
12051:  %history{timestamp} = 990455580
12052:  %history{version} = 2
12053: 
12054: Note that the special hash entries C<keys>, C<version> and
12055: C<timestamp> were added to the hash. C<version> will be equal to the
12056: total number of versions of the data that have been stored. The
12057: C<timestamp> attribute will be the UNIX time the hash was
12058: stored. C<keys> is available in every historical section to list which
12059: keys were added or changed at a specific historical revision of a
12060: hash.
12061: 
12062: B<Warning>: do not store the hash that restore returns directly. This
12063: will cause a mess since it will restore the historical keys as if the
12064: were new keys. I.E. 1:foo will become 1:1:foo etc.
12065: 
12066: Calling convention:
12067: 
12068:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
12069:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
12070: 
12071: For more detailed information, see lonnet specific documentation.
12072: 
12073: =head1 RETURN MESSAGES
12074: 
12075: =over 4
12076: 
12077: =item * B<con_lost>: unable to contact remote host
12078: 
12079: =item * B<con_delayed>: unable to contact remote host, message will be delivered
12080: when the connection is brought back up
12081: 
12082: =item * B<con_failed>: unable to contact remote host and unable to save message
12083: for later delivery
12084: 
12085: =item * B<error:>: an error a occurred, a description of the error follows the :
12086: 
12087: =item * B<no_such_host>: unable to fund a host associated with the user/domain
12088: that was requested
12089: 
12090: =back
12091: 
12092: =head1 PUBLIC SUBROUTINES
12093: 
12094: =head2 Session Environment Functions
12095: 
12096: =over 4
12097: 
12098: =item * 
12099: X<appenv()>
12100: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
12101: the user envirnoment file, and will be restored for each access this
12102: user makes during this session, also modifies the %env for the current
12103: process. Optional rolesarrayref - if defined contains a reference to an array
12104: of roles which are exempt from the restriction on modifying user.role entries 
12105: in the user's environment.db and in %env.    
12106: 
12107: =item *
12108: X<delenv()>
12109: B<delenv($delthis,$regexp)>: removes all items from the session
12110: environment file that begin with $delthis. If the 
12111: optional second arg - $regexp - is true, $delthis is treated as a 
12112: regular expression, otherwise \Q$delthis\E is used. 
12113: The values are also deleted from the current processes %env.
12114: 
12115: =item * get_env_multiple($name) 
12116: 
12117: gets $name from the %env hash, it seemlessly handles the cases where multiple
12118: values may be defined and end up as an array ref.
12119: 
12120: returns an array of values
12121: 
12122: =back
12123: 
12124: =head2 User Information
12125: 
12126: =over 4
12127: 
12128: =item *
12129: X<queryauthenticate()>
12130: B<queryauthenticate($uname,$udom)>: try to determine user's current 
12131: authentication scheme
12132: 
12133: =item *
12134: X<authenticate()>
12135: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
12136: authenticate user from domain's lib servers (first use the current
12137: one). C<$upass> should be the users password.
12138: $checkdefauth is optional (value is 1 if a check should be made to
12139:    authenticate user using default authentication method, and allow
12140:    account creation if username does not have account in the domain).
12141: $clientcancheckhost is optional (value is 1 if checking whether the
12142:    server can host will occur on the client side in lonauth.pm).   
12143: 
12144: =item *
12145: X<homeserver()>
12146: B<homeserver($uname,$udom)>: find the server which has
12147: the user's directory and files (there must be only one), this caches
12148: the answer, and also caches if there is a borken connection.
12149: 
12150: =item *
12151: X<idget()>
12152: B<idget($udom,@ids)>: find the usernames behind a list of IDs
12153: (IDs are a unique resource in a domain, there must be only 1 ID per
12154: username, and only 1 username per ID in a specific domain) (returns
12155: hash: id=>name,id=>name)
12156: 
12157: =item *
12158: X<idrget()>
12159: B<idrget($udom,@unames)>: find the IDs behind a list of
12160: usernames (returns hash: name=>id,name=>id)
12161: 
12162: =item *
12163: X<idput()>
12164: B<idput($udom,%ids)>: store away a list of names and associated IDs
12165: 
12166: =item *
12167: X<rolesinit()>
12168: B<rolesinit($udom,$username)>: get user privileges.
12169: returns user role, first access and timer interval hashes
12170: 
12171: =item *
12172: X<privileged()>
12173: B<privileged($username,$domain)>: returns a true if user has a
12174: privileged and active role (i.e. su or dc), false otherwise.
12175: 
12176: =item *
12177: X<getsection()>
12178: B<getsection($udom,$uname,$cname)>: finds the section of student in the
12179: course $cname, return section name/number or '' for "not in course"
12180: and '-1' for "no section"
12181: 
12182: =item *
12183: X<userenvironment()>
12184: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
12185: passed in @what from the requested user's environment, returns a hash
12186: 
12187: =item * 
12188: X<userlog_query()>
12189: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
12190: activity.log file. %filters defines filters applied when parsing the
12191: log file. These can be start or end timestamps, or the type of action
12192: - log to look for Login or Logout events, check for Checkin or
12193: Checkout, role for role selection. The response is in the form
12194: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
12195: escaped strings of the action recorded in the activity.log file.
12196: 
12197: =back
12198: 
12199: =head2 User Roles
12200: 
12201: =over 4
12202: 
12203: =item *
12204: 
12205: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
12206:  F: full access
12207:  U,I,K: authentication modes (cxx only)
12208:  '': forbidden
12209:  1: user needs to choose course
12210:  2: browse allowed
12211:  A: passphrase authentication needed
12212: 
12213: =item *
12214: 
12215: constructaccess($url,$setpriv) : check for access to construction space URL
12216: 
12217: See if the owner domain and name in the URL match those in the
12218: expected environment.  If so, return three element list
12219: ($ownername,$ownerdomain,$ownerhome).
12220: 
12221: Otherwise return the null string.
12222: 
12223: If second argument 'setpriv' is true, it assigns the privileges,
12224: and returns the same three element list, unless the owner has
12225: blocked "ad hoc" Domain Coordinator access to the Author Space,
12226: in which case the null string is returned.
12227: 
12228: =item *
12229: 
12230: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
12231: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
12232: and course level
12233: 
12234: =item *
12235: 
12236: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
12237: (rolesplain.tab); plain text explanation of a user role term.
12238: $type is Course (default) or Community.
12239: If $forcedefault evaluates to true, text returned will be default 
12240: text for $type. Otherwise, if this is a course, the text returned 
12241: will be a custom name for the role (if defined in the course's 
12242: environment).  If no custom name is defined the default is returned.
12243:    
12244: =item *
12245: 
12246: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
12247: All arguments are optional. Returns a hash of a roles, either for
12248: co-author/assistant author roles for a user's Construction Space
12249: (default), or if $context is 'userroles', roles for the user himself,
12250: In the hash, keys are set to colon-separated $uname,$udom,$role, and
12251: (optionally) if $withsec is true, a fourth colon-separated item - $section.
12252: For each key, value is set to colon-separated start and end times for
12253: the role.  If no username and domain are specified, will default to
12254: current user/domain. Types, roles, and roledoms are references to arrays
12255: of role statuses (active, future or previous), roles 
12256: (e.g., cc,in, st etc.) and domains of the roles which can be used
12257: to restrict the list of roles reported. If no array ref is 
12258: provided for types, will default to return only active roles.
12259: 
12260: =item *
12261: 
12262: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
12263: user: $uname:$udom has a role in the course: $cdom_$cnum. Additional
12264: optional arguments are: $type (if role checking is to be restricted to
12265: certain user status types -- previous (expired roles), active (currently
12266: available roles) or future (roles available in the future), and
12267: $hideprivileged -- if true will not report course roles for users who
12268: have active Domain Coordinator or Super User roles.
12269: 
12270: =back
12271: 
12272: =head2 User Modification
12273: 
12274: =over 4
12275: 
12276: =item *
12277: 
12278: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
12279: user for the level given by URL.  Optional start and end dates (leave empty
12280: string or zero for "no date")
12281: 
12282: =item *
12283: 
12284: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
12285: change a users, password, possible return values are: ok,
12286: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
12287: refused
12288: 
12289: =item *
12290: 
12291: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
12292: 
12293: =item *
12294: 
12295: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
12296:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
12297: 
12298: will update user information (firstname,middlename,lastname,generation,
12299: permanentemail), and if forceid is true, student/employee ID also.
12300: A user's institutional affiliation(s) can also be updated.
12301: User information fields will not be overwritten with empty entries 
12302: unless the field is included in the $candelete array reference.
12303: This array is included when a single user is modified via "Manage Users",
12304: or when Autoupdate.pl is run by cron in a domain.
12305: 
12306: =item *
12307: 
12308: modifystudent
12309: 
12310: modify a student's enrollment and identification information.
12311: The course id is resolved based on the current users environment.  
12312: This means the envoking user must be a course coordinator or otherwise
12313: associated with a course.
12314: 
12315: This call is essentially a wrapper for lonnet::modifyuser and
12316: lonnet::modify_student_enrollment
12317: 
12318: Inputs: 
12319: 
12320: =over 4
12321: 
12322: =item B<$udom> Student's loncapa domain
12323: 
12324: =item B<$uname> Student's loncapa login name
12325: 
12326: =item B<$uid> Student/Employee ID
12327: 
12328: =item B<$umode> Student's authentication mode
12329: 
12330: =item B<$upass> Student's password
12331: 
12332: =item B<$first> Student's first name
12333: 
12334: =item B<$middle> Student's middle name
12335: 
12336: =item B<$last> Student's last name
12337: 
12338: =item B<$gene> Student's generation
12339: 
12340: =item B<$usec> Student's section in course
12341: 
12342: =item B<$end> Unix time of the roles expiration
12343: 
12344: =item B<$start> Unix time of the roles start date
12345: 
12346: =item B<$forceid> If defined, allow $uid to be changed
12347: 
12348: =item B<$desiredhome> server to use as home server for student
12349: 
12350: =item B<$email> Student's permanent e-mail address
12351: 
12352: =item B<$type> Type of enrollment (auto or manual)
12353: 
12354: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
12355: 
12356: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
12357: 
12358: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
12359: 
12360: =item B<$context> role change context (shown in User Management Logs display in a course)
12361: 
12362: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
12363: 
12364: =back
12365: 
12366: =item *
12367: 
12368: modify_student_enrollment
12369: 
12370: Change a students enrollment status in a class.  The environment variable
12371: 'role.request.course' must be defined for this function to proceed.
12372: 
12373: Inputs:
12374: 
12375: =over 4
12376: 
12377: =item $udom, students domain
12378: 
12379: =item $uname, students name
12380: 
12381: =item $uid, students user id
12382: 
12383: =item $first, students first name
12384: 
12385: =item $middle
12386: 
12387: =item $last
12388: 
12389: =item $gene
12390: 
12391: =item $usec
12392: 
12393: =item $end
12394: 
12395: =item $start
12396: 
12397: =item $type
12398: 
12399: =item $locktype
12400: 
12401: =item $cid
12402: 
12403: =item $selfenroll
12404: 
12405: =item $context
12406: 
12407: =back
12408: 
12409: 
12410: =item *
12411: 
12412: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
12413: custom role; give a custom role to a user for the level given by URL.  Specify
12414: name and domain of role author, and role name
12415: 
12416: =item *
12417: 
12418: revokerole($udom,$uname,$url,$role) : revoke a role for url
12419: 
12420: =item *
12421: 
12422: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
12423: 
12424: =back
12425: 
12426: =head2 Course Infomation
12427: 
12428: =over 4
12429: 
12430: =item *
12431: 
12432: coursedescription($courseid,$options) : returns a hash of information about the
12433: specified course id, including all environment settings for the
12434: course, the description of the course will be in the hash under the
12435: key 'description'
12436: 
12437: $options is an optional parameter that if supplied is a hash reference that controls
12438: what how this function works.  It has the following key/values:
12439: 
12440: =over 4
12441: 
12442: =item freshen_cache
12443: 
12444: If defined, and the environment cache for the course is valid, it is 
12445: returned in the returned hash.
12446: 
12447: =item one_time
12448: 
12449: If defined, the last cache time is set to _now_
12450: 
12451: =item user
12452: 
12453: If defined, the supplied username is used instead of the current user.
12454: 
12455: 
12456: =back
12457: 
12458: =item *
12459: 
12460: resdata($name,$domain,$type,@which) : request for current parameter
12461: setting for a specific $type, where $type is either 'course' or 'user',
12462: @what should be a list of parameters to ask about. This routine caches
12463: answers for 5 minutes.
12464: 
12465: =item *
12466: 
12467: get_courseresdata($courseid, $domain) : dump the entire course resource
12468: data base, returning a hash that is keyed by the resource name and has
12469: values that are the resource value.  I believe that the timestamps and
12470: versions are also returned.
12471: 
12472: =back
12473: 
12474: =head2 Course Modification
12475: 
12476: =over 4
12477: 
12478: =item *
12479: 
12480: writecoursepref($courseid,%prefs) : write preferences (environment
12481: database) for a course
12482: 
12483: =item *
12484: 
12485: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
12486: 
12487: =item *
12488: 
12489: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
12490: 
12491: =item *
12492: 
12493: is_course($courseid), is_course($cdom, $cnum)
12494: 
12495: Accepts either a combined $courseid (in the form of domain_courseid) or the
12496: two component version $cdom, $cnum. It checks if the specified course exists.
12497: 
12498: Returns:
12499:     undef if the course doesn't exist, otherwise
12500:     in scalar context the combined courseid.
12501:     in list context the two components of the course identifier, domain and 
12502:     courseid.    
12503: 
12504: =back
12505: 
12506: =head2 Resource Subroutines
12507: 
12508: =over 4
12509: 
12510: =item *
12511: 
12512: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
12513: 
12514: =item *
12515: 
12516: repcopy($filename) : subscribes to the requested file, and attempts to
12517: replicate from the owning library server, Might return
12518: 'unavailable', 'not_found', 'forbidden', 'ok', or
12519: 'bad_request', also attempts to grab the metadata for the
12520: resource. Expects the local filesystem pathname
12521: (/home/httpd/html/res/....)
12522: 
12523: =back
12524: 
12525: =head2 Resource Information
12526: 
12527: =over 4
12528: 
12529: =item *
12530: 
12531: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
12532: a vairety of different possible values, $varname should be a request
12533: string, and the other parameters can be used to specify who and what
12534: one is asking about.
12535: 
12536: Possible values for $varname are environment.lastname (or other item
12537: from the envirnment hash), user.name (or someother aspect about the
12538: user), resource.0.maxtries (or some other part and parameter of a
12539: resource)
12540: 
12541: =item *
12542: 
12543: directcondval($number) : get current value of a condition; reads from a state
12544: string
12545: 
12546: =item *
12547: 
12548: condval($condidx) : value of condition index based on state
12549: 
12550: =item *
12551: 
12552: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
12553: resource's metadata, $what should be either a specific key, or either
12554: 'keys' (to get a list of possible keys) or 'packages' to get a list of
12555: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
12556: 
12557: this function automatically caches all requests
12558: 
12559: =item *
12560: 
12561: metadata_query($query,$custom,$customshow) : make a metadata query against the
12562: network of library servers; returns file handle of where SQL and regex results
12563: will be stored for query
12564: 
12565: =item *
12566: 
12567: symbread($filename) : return symbolic list entry (filename argument optional);
12568: returns the data handle
12569: 
12570: =item *
12571: 
12572: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
12573: and is a possible symb for the URL in $thisfn, and if is an encrypted
12574: resource that the user accessed using /enc/ returns a 1 on success, 0
12575: on failure, user must be in a course, as it assumes the existence of
12576: the course initial hash, and uses $env('request.course.id'}.  The third
12577: arg is an optional reference to a scalar.  If this arg is passed in the 
12578: call to symbverify, it will be set to 1 if the symb has been set to be 
12579: encrypted; otherwise it will be null.  
12580: 
12581: =item *
12582: 
12583: symbclean($symb) : removes versions numbers from a symb, returns the
12584: cleaned symb
12585: 
12586: =item *
12587: 
12588: is_on_map($uri) : checks if the $uri is somewhere on the current
12589: course map, user must be in a course for it to work.
12590: 
12591: =item *
12592: 
12593: numval($salt) : return random seed value (addend for rndseed)
12594: 
12595: =item *
12596: 
12597: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
12598: a random seed, all arguments are optional, if they aren't sent it uses the
12599: environment to derive them. Note: if symb isn't sent and it can't get one
12600: from &symbread it will use the current time as its return value
12601: 
12602: =item *
12603: 
12604: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
12605: unfakeable, receipt
12606: 
12607: =item *
12608: 
12609: receipt() : API to ireceipt working off of env values; given out to users
12610: 
12611: =item *
12612: 
12613: countacc($url) : count the number of accesses to a given URL
12614: 
12615: =item *
12616: 
12617: 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
12618: 
12619: =item *
12620: 
12621: 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)
12622: 
12623: =item *
12624: 
12625: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
12626: 
12627: =item *
12628: 
12629: devalidate($symb) : devalidate temporary spreadsheet calculations,
12630: forcing spreadsheet to reevaluate the resource scores next time.
12631: 
12632: =item * 
12633: 
12634: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group)
12635: 
12636: Determine if the current user should be able to edit a particular resource,
12637: when viewing in course context.
12638: (a) When viewing resource used to determine if "Edit" item is included in
12639:      Functions.
12640: (b) When displaying folder contents in course editor, used to determine if
12641:     "Edit" link will be displayed alongside resource.
12642: 
12643:  input: 3 args -- filename (decluttered), course number and course domain.
12644:  output: array of four scalars --
12645:          $cfile -- url for file editing if editable on current server
12646:          $home -- homeserver of resource (i.e., for author if published,
12647:                                           or course if uploaded.).
12648:          $switchserver --  1 if server switch will be needed.
12649:          $uploaded -- 1 if resource is a file uploaded to a course.
12650: 
12651: =item *
12652: 
12653: is_course_upload($file,$cnum,$cdom)
12654: 
12655: Used in course context to determine if current file was uploaded to 
12656: the course (i.e., would be found in /userfiles/docs on the course's 
12657: homeserver.
12658: 
12659:   input: 3 args -- filename (decluttered), course number and course domain.
12660:   output: boolean -- 1 if file was uploaded.
12661: 
12662: =back
12663: 
12664: =head2 Storing/Retreiving Data
12665: 
12666: =over 4
12667: 
12668: =item *
12669: 
12670: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
12671: for this url; hashref needs to be given and should be a \%hashname; the
12672: remaining args aren't required and if they aren't passed or are '' they will
12673: be derived from the env
12674: 
12675: =item *
12676: 
12677: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
12678: uses critical subroutine
12679: 
12680: =item *
12681: 
12682: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
12683: all args are optional
12684: 
12685: =item *
12686: 
12687: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
12688: dumps the complete (or key matching regexp) namespace into a hash
12689: ($udom, $uname, $regexp, $range are optional) for a namespace that is
12690: normally &store()ed into
12691: 
12692: $range should be either an integer '100' (give me the first 100
12693:                                            matching records)
12694:               or be  two integers sperated by a - with no spaces
12695:                  '30-50' (give me the 30th through the 50th matching
12696:                           records)
12697: 
12698: 
12699: =item *
12700: 
12701: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
12702: replaces a &store() version of data with a replacement set of data
12703: for a particular resource in a namespace passed in the $storehash hash 
12704: reference
12705: 
12706: =item *
12707: 
12708: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
12709: works very similar to store/cstore, but all data is stored in a
12710: temporary location and can be reset using tmpreset, $storehash should
12711: be a hash reference, returns nothing on success
12712: 
12713: =item *
12714: 
12715: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
12716: similar to restore, but all data is stored in a temporary location and
12717: can be reset using tmpreset. Returns a hash of values on success,
12718: error string otherwise.
12719: 
12720: =item *
12721: 
12722: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
12723: deltes all keys for $symb form the temporary storage hash.
12724: 
12725: =item *
12726: 
12727: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
12728: reference filled in from namesp ($udom and $uname are optional)
12729: 
12730: =item *
12731: 
12732: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
12733: namesp ($udom and $uname are optional)
12734: 
12735: =item *
12736: 
12737: dump($namespace,$udom,$uname,$regexp,$range) : 
12738: dumps the complete (or key matching regexp) namespace into a hash
12739: ($udom, $uname, $regexp, $range are optional)
12740: 
12741: $range should be either an integer '100' (give me the first 100
12742:                                            matching records)
12743:               or be  two integers sperated by a - with no spaces
12744:                  '30-50' (give me the 30th through the 50th matching
12745:                           records)
12746: =item *
12747: 
12748: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
12749: $store can be a scalar, an array reference, or if the amount to be 
12750: incremented is > 1, a hash reference.
12751: 
12752: ($udom and $uname are optional)
12753: 
12754: =item *
12755: 
12756: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
12757: ($udom and $uname are optional)
12758: 
12759: =item *
12760: 
12761: cput($namespace,$storehash,$udom,$uname) : critical put
12762: ($udom and $uname are optional)
12763: 
12764: =item *
12765: 
12766: newput($namespace,$storehash,$udom,$uname) :
12767: 
12768: Attempts to store the items in the $storehash, but only if they don't
12769: currently exist, if this succeeds you can be certain that you have 
12770: successfully created a new key value pair in the $namespace db.
12771: 
12772: 
12773: Args:
12774:  $namespace: name of database to store values to
12775:  $storehash: hashref to store to the db
12776:  $udom: (optional) domain of user containing the db
12777:  $uname: (optional) name of user caontaining the db
12778: 
12779: Returns:
12780:  'ok' -> succeeded in storing all keys of $storehash
12781:  'key_exists: <key>' -> failed to anything out of $storehash, as at
12782:                         least <key> already existed in the db (other
12783:                         requested keys may also already exist)
12784:  'error: <msg>' -> unable to tie the DB or other error occurred
12785:  'con_lost' -> unable to contact request server
12786:  'refused' -> action was not allowed by remote machine
12787: 
12788: 
12789: =item *
12790: 
12791: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
12792: reference filled in from namesp (encrypts the return communication)
12793: ($udom and $uname are optional)
12794: 
12795: =item *
12796: 
12797: log($udom,$name,$home,$message) : write to permanent log for user; use
12798: critical subroutine
12799: 
12800: =item *
12801: 
12802: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
12803: array reference filled in from namespace found in domain level on either
12804: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
12805: 
12806: =item *
12807: 
12808: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
12809: domain level either on specified domain server ($uhome) or primary domain 
12810: server ($udom and $uhome are optional)
12811: 
12812: =item * 
12813: 
12814: get_domain_defaults($target_domain) : returns hash with defaults for
12815: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
12816: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
12817: or localauth), initial password or a kerberos realm, language (e.g., en-us).
12818: Values are retrieved from cache (if current), or from domain's configuration.db
12819: (if available), or lastly from values in lonTabs/dns_domain,tab, 
12820: or lonTabs/domain.tab. 
12821: 
12822: %domdefaults = &get_auth_defaults($target_domain);
12823: 
12824: =back
12825: 
12826: =head2 Network Status Functions
12827: 
12828: =over 4
12829: 
12830: =item *
12831: 
12832: dirlist() : return directory list based on URI (first arg).
12833: 
12834: Inputs: 1 required, 5 optional.
12835: 
12836: =over
12837: 
12838: =item 
12839: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
12840: 
12841: =item
12842: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
12843: 
12844: =item
12845: $username -  username of user/course to be listed. Extracted from $uri if absent. 
12846: 
12847: =item
12848: $getpropath - boolean: 1 if prepend path using &propath(). 
12849: 
12850: =item
12851: $getuserdir - boolean: 1 if prepend path for "userfiles".
12852: 
12853: =item 
12854: $alternateRoot - path to prepend in place of path from $uri.
12855: 
12856: =back
12857: 
12858: Returns: Array of up to two items.
12859: 
12860: =over
12861: 
12862: a reference to an array of files/subdirectories
12863: 
12864: =over
12865: 
12866: Each element in the array of files/subdirectories is a & separated list of
12867: item name and the result of running stat on the item.  If dirlist was requested
12868: for a file instead of a directory, the item name will be ''. For a directory 
12869: listing, if the item is a metadata file, the element will end &N&M 
12870: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
12871: default copyright set (1).  
12872: 
12873: =back
12874: 
12875: a scalar containing error condition (if encountered).
12876: 
12877: =over
12878: 
12879: =item 
12880: no_host (no homeserver identified for $username:$domain).
12881: 
12882: =item 
12883: no_such_host (server contacted for listing not identified as valid host).
12884: 
12885: =item 
12886: con_lost (connection to remote server failed).
12887: 
12888: =item 
12889: refused (invalid $username:$domain received on lond side).
12890: 
12891: =item 
12892: no_such_dir (directory at specified path on lond side does not exist). 
12893: 
12894: =item 
12895: empty (directory at specified path on lond side is empty).
12896: 
12897: =over
12898: 
12899: This is currently not encountered because the &ls3, &ls2, 
12900: &ls (_handler) routines on the lond side do not filter out
12901: . and .. from a directory listing. 
12902: 
12903: =back
12904: 
12905: =back
12906: 
12907: =back
12908: 
12909: =item *
12910: 
12911: spareserver() : find server with least workload from spare.tab
12912: 
12913: 
12914: =item *
12915: 
12916: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
12917: if there is no corresponding loncapa host.
12918: 
12919: =back
12920: 
12921: 
12922: =head2 Apache Request
12923: 
12924: =over 4
12925: 
12926: =item *
12927: 
12928: ssi($url,%hash) : server side include, does a complete request cycle on url to
12929: localhost, posts hash
12930: 
12931: =back
12932: 
12933: =head2 Data to String to Data
12934: 
12935: =over 4
12936: 
12937: =item *
12938: 
12939: hash2str(%hash) : convert a hash into a string complete with escaping and '='
12940: and '&' separators, supports elements that are arrayrefs and hashrefs
12941: 
12942: =item *
12943: 
12944: hashref2str($hashref) : convert a hashref into a string complete with
12945: escaping and '=' and '&' separators, supports elements that are
12946: arrayrefs and hashrefs
12947: 
12948: =item *
12949: 
12950: arrayref2str($arrayref) : convert an arrayref into a string complete
12951: with escaping and '&' separators, supports elements that are arrayrefs
12952: and hashrefs
12953: 
12954: =item *
12955: 
12956: str2hash($string) : convert string to hash using unescaping and
12957: splitting on '=' and '&', supports elements that are arrayrefs and
12958: hashrefs
12959: 
12960: =item *
12961: 
12962: str2array($string) : convert string to hash using unescaping and
12963: splitting on '&', supports elements that are arrayrefs and hashrefs
12964: 
12965: =back
12966: 
12967: =head2 Logging Routines
12968: 
12969: 
12970: These routines allow one to make log messages in the lonnet.log and
12971: lonnet.perm logfiles.
12972: 
12973: =over 4
12974: 
12975: =item *
12976: 
12977: logtouch() : make sure the logfile, lonnet.log, exists
12978: 
12979: =item *
12980: 
12981: logthis() : append message to the normal lonnet.log file, it gets
12982: preiodically rolled over and deleted.
12983: 
12984: =item *
12985: 
12986: logperm() : append a permanent message to lonnet.perm.log, this log
12987: file never gets deleted by any automated portion of the system, only
12988: messages of critical importance should go in here.
12989: 
12990: 
12991: =back
12992: 
12993: =head2 General File Helper Routines
12994: 
12995: =over 4
12996: 
12997: =item *
12998: 
12999: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
13000: (a) files in /uploaded
13001:   (i) If a local copy of the file exists - 
13002:       compares modification date of local copy with last-modified date for 
13003:       definitive version stored on home server for course. If local copy is 
13004:       stale, requests a new version from the home server and stores it. 
13005:       If the original has been removed from the home server, then local copy 
13006:       is unlinked.
13007:   (ii) If local copy does not exist -
13008:       requests the file from the home server and stores it. 
13009:   
13010:   If $caller is 'uploadrep':  
13011:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
13012:     for request for files originally uploaded via DOCS. 
13013:      - returns 'ok' if fresh local copy now available, -1 otherwise.
13014:   
13015:   Otherwise:
13016:      This indicates a call from the content generation phase of the request.
13017:      -  returns the entire contents of the file or -1.
13018:      
13019: (b) files in /res
13020:    - returns the entire contents of a file or -1; 
13021:    it properly subscribes to and replicates the file if neccessary.
13022: 
13023: 
13024: =item *
13025: 
13026: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
13027:                   reference
13028: 
13029: returns either a stat() list of data about the file or an empty list
13030: if the file doesn't exist or couldn't find out about it (connection
13031: problems or user unknown)
13032: 
13033: =item *
13034: 
13035: filelocation($dir,$file) : returns file system location of a file
13036: based on URI; meant to be "fairly clean" absolute reference, $dir is a
13037: directory that relative $file lookups are to looked in ($dir of /a/dir
13038: and a file of ../bob will become /a/bob)
13039: 
13040: =item *
13041: 
13042: hreflocation($dir,$file) : returns file system location or a URL; same as
13043: filelocation except for hrefs
13044: 
13045: =item *
13046: 
13047: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
13048: 
13049: =back
13050: 
13051: =head2 Usererfile file routines (/uploaded*)
13052: 
13053: =over 4
13054: 
13055: =item *
13056: 
13057: userfileupload(): main rotine for putting a file in a user or course's
13058:                   filespace, arguments are,
13059: 
13060:  formname - required - this is the name of the element in $env where the
13061:            filename, and the contents of the file to create/modifed exist
13062:            the filename is in $env{'form.'.$formname.'.filename'} and the
13063:            contents of the file is located in $env{'form.'.$formname}
13064:  context - if coursedoc, store the file in the course of the active role
13065:              of the current user; 
13066:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
13067:            if 'canceloverwrite': delete file in tmp/overwrites directory
13068:  subdir - required - subdirectory to put the file in under ../userfiles/
13069:          if undefined, it will be placed in "unknown"
13070: 
13071:  (This routine calls clean_filename() to remove any dangerous
13072:  characters from the filename, and then calls finuserfileupload() to
13073:  complete the transaction)
13074: 
13075:  returns either the url of the uploaded file (/uploaded/....) if successful
13076:  and /adm/notfound.html if unsuccessful
13077: 
13078: =item *
13079: 
13080: clean_filename(): routine for cleaing a filename up for storage in
13081:                  userfile space, argument is:
13082: 
13083:  filename - proposed filename
13084: 
13085: returns: the new clean filename
13086: 
13087: =item *
13088: 
13089: finishuserfileupload(): routine that creates and sends the file to
13090: userspace, probably shouldn't be called directly
13091: 
13092:   docuname: username or courseid of destination for the file
13093:   docudom: domain of user/course of destination for the file
13094:   formname: same as for userfileupload()
13095:   fname: filename (including subdirectories) for the file
13096:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
13097:   allfiles: reference to hash used to store objects found by parser
13098:   codebase: reference to hash used for codebases of java objects found by parser
13099:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
13100:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
13101:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
13102:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
13103:   context: if 'overwrite', will move the uploaded file from its temporary location to
13104:             userfiles to facilitate overwriting a previously uploaded file with same name.
13105:   mimetype: reference to scalar to accommodate mime type determined
13106:             from File::MMagic if $parser = parse.
13107: 
13108:  returns either the url of the uploaded file (/uploaded/....) if successful
13109:  and /adm/notfound.html if unsuccessful (or an error message if context 
13110:  was 'overwrite').
13111:  
13112: 
13113: =item *
13114: 
13115: renameuserfile(): renames an existing userfile to a new name
13116: 
13117:   Args:
13118:    docuname: username or courseid of destination for the file
13119:    docudom: domain of user/course of destination for the file
13120:    old: current file name (including any subdirs under userfiles)
13121:    new: desired file name (including any subdirs under userfiles)
13122: 
13123: =item *
13124: 
13125: mkdiruserfile(): creates a directory is a userfiles dir
13126: 
13127:   Args:
13128:    docuname: username or courseid of destination for the file
13129:    docudom: domain of user/course of destination for the file
13130:    dir: dir to create (including any subdirs under userfiles)
13131: 
13132: =item *
13133: 
13134: removeuserfile(): removes a file that exists in userfiles
13135: 
13136:   Args:
13137:    docuname: username or courseid of destination for the file
13138:    docudom: domain of user/course of destination for the file
13139:    fname: filname to delete (including any subdirs under userfiles)
13140: 
13141: =item *
13142: 
13143: removeuploadedurl(): convience function for removeuserfile()
13144: 
13145:   Args:
13146:    url:  a full /uploaded/... url to delete
13147: 
13148: =item * 
13149: 
13150: get_portfile_permissions():
13151:   Args:
13152:     domain: domain of user or course contain the portfolio files
13153:     user: name of user or num of course contain the portfolio files
13154:   Returns:
13155:     hashref of a dump of the proper file_permissions.db
13156:    
13157: 
13158: =item * 
13159: 
13160: get_access_controls():
13161: 
13162: Args:
13163:   current_permissions: the hash ref returned from get_portfile_permissions()
13164:   group: (optional) the group you want the files associated with
13165:   file: (optional) the file you want access info on
13166: 
13167: Returns:
13168:     a hash (keys are file names) of hashes containing
13169:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
13170:         values are XML containing access control settings (see below) 
13171: 
13172: Internal notes:
13173: 
13174:  access controls are stored in file_permissions.db as key=value pairs.
13175:     key -> path to file/file_name\0uniqueID:scope_end_start
13176:         where scope -> public,guest,course,group,domains or users.
13177:               end -> UNIX time for end of access (0 -> no end date)
13178:               start -> UNIX time for start of access
13179: 
13180:     value -> XML description of access control
13181:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
13182:             <start></start>
13183:             <end></end>
13184: 
13185:             <password></password>  for scope type = guest
13186: 
13187:             <domain></domain>     for scope type = course or group
13188:             <number></number>
13189:             <roles id="">
13190:              <role></role>
13191:              <access></access>
13192:              <section></section>
13193:              <group></group>
13194:             </roles>
13195: 
13196:             <dom></dom>         for scope type = domains
13197: 
13198:             <users>             for scope type = users
13199:              <user>
13200:               <uname></uname>
13201:               <udom></udom>
13202:              </user>
13203:             </users>
13204:            </scope> 
13205:               
13206:  Access data is also aggregated for each file in an additional key=value pair:
13207:  key -> path to file/file_name\0accesscontrol 
13208:  value -> reference to hash
13209:           hash contains key = value pairs
13210:           where key = uniqueID:scope_end_start
13211:                 value = UNIX time record was last updated
13212: 
13213:           Used to improve speed of look-ups of access controls for each file.  
13214:  
13215:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
13216: 
13217: modify_access_controls():
13218: 
13219: Modifies access controls for a portfolio file
13220: Args
13221: 1. file name
13222: 2. reference to hash of required changes,
13223: 3. domain
13224: 4. username
13225:   where domain,username are the domain of the portfolio owner 
13226:   (either a user or a course) 
13227: 
13228: Returns:
13229: 1. result of additions or updates ('ok' or 'error', with error message). 
13230: 2. result of deletions ('ok' or 'error', with error message).
13231: 3. reference to hash of any new or updated access controls.
13232: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
13233:    key = integer (inbound ID)
13234:    value = uniqueID  
13235: 
13236: =back
13237: 
13238: =head2 HTTP Helper Routines
13239: 
13240: =over 4
13241: 
13242: =item *
13243: 
13244: escape() : unpack non-word characters into CGI-compatible hex codes
13245: 
13246: =item *
13247: 
13248: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
13249: 
13250: =back
13251: 
13252: =head1 PRIVATE SUBROUTINES
13253: 
13254: =head2 Underlying communication routines (Shouldn't call)
13255: 
13256: =over 4
13257: 
13258: =item *
13259: 
13260: subreply() : tries to pass a message to lonc, returns con_lost if incapable
13261: 
13262: =item *
13263: 
13264: reply() : uses subreply to send a message to remote machine, logs all failures
13265: 
13266: =item *
13267: 
13268: critical() : passes a critical message to another server; if cannot
13269: get through then place message in connection buffer directory and
13270: returns con_delayed, if incapable of saving message, returns
13271: con_failed
13272: 
13273: =item *
13274: 
13275: reconlonc() : tries to reconnect lonc client processes.
13276: 
13277: =back
13278: 
13279: =head2 Resource Access Logging
13280: 
13281: =over 4
13282: 
13283: =item *
13284: 
13285: flushcourselogs() : flush (save) buffer logs and access logs
13286: 
13287: =item *
13288: 
13289: courselog($what) : save message for course in hash
13290: 
13291: =item *
13292: 
13293: courseacclog($what) : save message for course using &courselog().  Perform
13294: special processing for specific resource types (problems, exams, quizzes, etc).
13295: 
13296: =item *
13297: 
13298: goodbye() : flush course logs and log shutting down; it is called in srm.conf
13299: as a PerlChildExitHandler
13300: 
13301: =back
13302: 
13303: =head2 Other
13304: 
13305: =over 4
13306: 
13307: =item *
13308: 
13309: symblist($mapname,%newhash) : update symbolic storage links
13310: 
13311: =back
13312: 
13313: =cut
13314: 

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