File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1301: download - view: text, annotated - select for diffs
Wed Mar 2 14:14:14 2016 UTC (8 years, 3 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Bug 4373. Ability to set map-level parameters which apply recursively
  to subfolders.

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1301 2016/03/02 14:14:14 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( sleep 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 = 20;     # 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,$cachekeys) = @_;
  360:     my $items;
  361:     return unless (ref($cachekeys) eq 'ARRAY');
  362:     my $cachestr = join('&',@{$cachekeys});
  363:     my $response = &reply('devalidatecache:'.&escape($cachestr),$lonhost);
  364:     return $response;
  365: }
  366: 
  367: # -------------------------------------------------- Non-critical communication
  368: sub subreply {
  369:     my ($cmd,$server)=@_;
  370:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
  371:     #
  372:     #  With loncnew process trimming, there's a timing hole between lonc server
  373:     #  process exit and the master server picking up the listen on the AF_UNIX
  374:     #  socket.  In that time interval, a lock file will exist:
  375: 
  376:     my $lockfile=$peerfile.".lock";
  377:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
  378: 	sleep(0.1);
  379:     }
  380:     # At this point, either a loncnew parent is listening or an old lonc
  381:     # or loncnew child is listening so we can connect or everything's dead.
  382:     #
  383:     #   We'll give the connection a few tries before abandoning it.  If
  384:     #   connection is not possible, we'll con_lost back to the client.
  385:     #   
  386:     my $client;
  387:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
  388: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  389: 				      Type    => SOCK_STREAM,
  390: 				      Timeout => 10);
  391: 	if ($client) {
  392: 	    last;		# Connected!
  393: 	} else {
  394: 	    &create_connection(&hostname($server),$server);
  395: 	}
  396:         sleep(0.1);	# Try again later if failed connection.
  397:     }
  398:     my $answer;
  399:     if ($client) {
  400: 	print $client "sethost:$server:$cmd\n";
  401: 	$answer=<$client>;
  402: 	if (!$answer) { $answer="con_lost"; }
  403: 	chomp($answer);
  404:     } else {
  405: 	$answer = 'con_lost';	# Failed connection.
  406:     }
  407:     return $answer;
  408: }
  409: 
  410: sub reply {
  411:     my ($cmd,$server)=@_;
  412:     unless (defined(&hostname($server))) { return 'no_such_host'; }
  413:     my $answer=subreply($cmd,$server);
  414:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
  415:        &logthis("<font color=\"blue\">WARNING:".
  416:                 " $cmd to $server returned $answer</font>");
  417:     }
  418:     return $answer;
  419: }
  420: 
  421: # ----------------------------------------------------------- Send USR1 to lonc
  422: 
  423: sub reconlonc {
  424:     my ($lonid) = @_;
  425:     if ($lonid) {
  426:         my $hostname = &hostname($lonid);
  427: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
  428: 	if ($hostname && -e $peerfile) {
  429: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
  430: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
  431: 					     Type    => SOCK_STREAM,
  432: 					     Timeout => 10);
  433: 	    if ($client) {
  434: 		print $client ("reset_retries\n");
  435: 		my $answer=<$client>;
  436: 		#reset just this one.
  437: 	    }
  438: 	}
  439: 	return;
  440:     }
  441: 
  442:     &logthis("Trying to reconnect lonc");
  443:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  444:     if (open(my $fh,"<$loncfile")) {
  445: 	my $loncpid=<$fh>;
  446:         chomp($loncpid);
  447:         if (kill 0 => $loncpid) {
  448: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  449:             kill USR1 => $loncpid;
  450:             sleep 1;
  451:         } else {
  452: 	    &logthis(
  453:                "<font color=\"blue\">WARNING:".
  454:                " lonc at pid $loncpid not responding, giving up</font>");
  455:         }
  456:     } else {
  457: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
  458:     }
  459: }
  460: 
  461: # ------------------------------------------------------ Critical communication
  462: 
  463: sub critical {
  464:     my ($cmd,$server)=@_;
  465:     unless (&hostname($server)) {
  466:         &logthis("<font color=\"blue\">WARNING:".
  467:                " Critical message to unknown server ($server)</font>");
  468:         return 'no_such_host';
  469:     }
  470:     my $answer=reply($cmd,$server);
  471:     if ($answer eq 'con_lost') {
  472: 	&reconlonc($server);
  473: 	my $answer=reply($cmd,$server);
  474:         if ($answer eq 'con_lost') {
  475:             my $now=time;
  476:             my $middlename=$cmd;
  477:             $middlename=substr($middlename,0,16);
  478:             $middlename=~s/\W//g;
  479:             my $dfilename=
  480:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
  481:             $dumpcount++;
  482:             {
  483: 		my $dfh;
  484: 		if (open($dfh,">$dfilename")) {
  485: 		    print $dfh "$cmd\n"; 
  486: 		    close($dfh);
  487: 		}
  488:             }
  489:             sleep 1;
  490:             my $wcmd='';
  491:             {
  492: 		my $dfh;
  493: 		if (open($dfh,"<$dfilename")) {
  494: 		    $wcmd=<$dfh>; 
  495: 		    close($dfh);
  496: 		}
  497:             }
  498:             chomp($wcmd);
  499:             if ($wcmd eq $cmd) {
  500: 		&logthis("<font color=\"blue\">WARNING: ".
  501:                          "Connection buffer $dfilename: $cmd</font>");
  502:                 &logperm("D:$server:$cmd");
  503: 	        return 'con_delayed';
  504:             } else {
  505:                 &logthis("<font color=\"red\">CRITICAL:"
  506:                         ." Critical connection failed: $server $cmd</font>");
  507:                 &logperm("F:$server:$cmd");
  508:                 return 'con_failed';
  509:             }
  510:         }
  511:     }
  512:     return $answer;
  513: }
  514: 
  515: # ------------------------------------------- check if return value is an error
  516: 
  517: sub error {
  518:     my ($result) = @_;
  519:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
  520: 	if ($2 == 2) { return undef; }
  521: 	return $1;
  522:     }
  523:     return undef;
  524: }
  525: 
  526: sub convert_and_load_session_env {
  527:     my ($lonidsdir,$handle)=@_;
  528:     my @profile;
  529:     {
  530: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  531: 	if (!$opened) {
  532: 	    return 0;
  533: 	}
  534: 	flock($idf,LOCK_SH);
  535: 	@profile=<$idf>;
  536: 	close($idf);
  537:     }
  538:     my %temp_env;
  539:     foreach my $line (@profile) {
  540: 	if ($line !~ m/=/) {
  541: 	    return 0;
  542: 	}
  543: 	chomp($line);
  544: 	my ($envname,$envvalue)=split(/=/,$line,2);
  545: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
  546:     }
  547:     unlink("$lonidsdir/$handle.id");
  548:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
  549: 	    0640)) {
  550: 	%disk_env = %temp_env;
  551: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
  552: 	untie(%disk_env);
  553:     }
  554:     return 1;
  555: }
  556: 
  557: # ------------------------------------------- Transfer profile into environment
  558: my $env_loaded;
  559: sub transfer_profile_to_env {
  560:     my ($lonidsdir,$handle,$force_transfer) = @_;
  561:     if (!$force_transfer && $env_loaded) { return; } 
  562: 
  563:     if (!defined($lonidsdir)) {
  564: 	$lonidsdir = $perlvar{'lonIDsDir'};
  565:     }
  566:     if (!defined($handle)) {
  567:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
  568:     }
  569: 
  570:     my $convert;
  571:     {
  572:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  573: 	if (!$opened) {
  574: 	    return;
  575: 	}
  576: 	flock($idf,LOCK_SH);
  577: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  578: 		&GDBM_READER(),0640)) {
  579: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
  580: 	    untie(%disk_env);
  581: 	} else {
  582: 	    $convert = 1;
  583: 	}
  584:     }
  585:     if ($convert) {
  586: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
  587: 	    &logthis("Failed to load session, or convert session.");
  588: 	}
  589:     }
  590: 
  591:     my %remove;
  592:     while ( my $envname = each(%env) ) {
  593:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  594:             if ($time < time-300) {
  595:                 $remove{$key}++;
  596:             }
  597:         }
  598:     }
  599: 
  600:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  601:     $env_loaded=1;
  602:     foreach my $expired_key (keys(%remove)) {
  603:         &delenv($expired_key);
  604:     }
  605: }
  606: 
  607: # ---------------------------------------------------- Check for valid session 
  608: sub check_for_valid_session {
  609:     my ($r,$name,$userhashref) = @_;
  610:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
  611:     if ($name eq '') {
  612:         $name = 'lonID';
  613:     }
  614:     my $lonid=$cookies{$name};
  615:     return undef if (!$lonid);
  616: 
  617:     my $handle=&LONCAPA::clean_handle($lonid->value);
  618:     my $lonidsdir;
  619:     if ($name eq 'lonDAV') {
  620:         $lonidsdir=$r->dir_config('lonDAVsessDir');
  621:     } else {
  622:         $lonidsdir=$r->dir_config('lonIDsDir');
  623:     }
  624:     return undef if (!-e "$lonidsdir/$handle.id");
  625: 
  626:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  627:     return undef if (!$opened);
  628: 
  629:     flock($idf,LOCK_SH);
  630:     my %disk_env;
  631:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  632: 	    &GDBM_READER(),0640)) {
  633: 	return undef;	
  634:     }
  635: 
  636:     if (!defined($disk_env{'user.name'})
  637: 	|| !defined($disk_env{'user.domain'})) {
  638: 	return undef;
  639:     }
  640: 
  641:     if (ref($userhashref) eq 'HASH') {
  642:         $userhashref->{'name'} = $disk_env{'user.name'};
  643:         $userhashref->{'domain'} = $disk_env{'user.domain'};
  644:     }
  645: 
  646:     return $handle;
  647: }
  648: 
  649: sub timed_flock {
  650:     my ($file,$lock_type) = @_;
  651:     my $failed=0;
  652:     eval {
  653: 	local $SIG{__DIE__}='DEFAULT';
  654: 	local $SIG{ALRM}=sub {
  655: 	    $failed=1;
  656: 	    die("failed lock");
  657: 	};
  658: 	alarm(13);
  659: 	flock($file,$lock_type);
  660: 	alarm(0);
  661:     };
  662:     if ($failed) {
  663: 	return undef;
  664:     } else {
  665: 	return 1;
  666:     }
  667: }
  668: 
  669: # ---------------------------------------------------------- Append Environment
  670: 
  671: sub appenv {
  672:     my ($newenv,$roles) = @_;
  673:     if (ref($newenv) eq 'HASH') {
  674:         foreach my $key (keys(%{$newenv})) {
  675:             my $refused = 0;
  676: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
  677:                 $refused = 1;
  678:                 if (ref($roles) eq 'ARRAY') {
  679:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
  680:                     if (grep(/^\Q$role\E$/,@{$roles})) {
  681:                         $refused = 0;
  682:                     }
  683:                 }
  684:             }
  685:             if ($refused) {
  686:                 &logthis("<font color=\"blue\">WARNING: ".
  687:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
  688:                          .'</font>');
  689: 	        delete($newenv->{$key});
  690:             } else {
  691:                 $env{$key}=$newenv->{$key};
  692:             }
  693:         }
  694:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
  695:         if ($opened
  696: 	    && &timed_flock($env_file,LOCK_EX)
  697: 	    &&
  698: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  699: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  700: 	    while (my ($key,$value) = each(%{$newenv})) {
  701: 	        $disk_env{$key} = $value;
  702: 	    }
  703: 	    untie(%disk_env);
  704:         }
  705:     }
  706:     return 'ok';
  707: }
  708: # ----------------------------------------------------- Delete from Environment
  709: 
  710: sub delenv {
  711:     my ($delthis,$regexp,$roles) = @_;
  712:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
  713:         my $refused = 1;
  714:         if (ref($roles) eq 'ARRAY') {
  715:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
  716:             if (grep(/^\Q$role\E$/,@{$roles})) {
  717:                 $refused = 0;
  718:             }
  719:         }
  720:         if ($refused) {
  721:             &logthis("<font color=\"blue\">WARNING: ".
  722:                      "Attempt to delete from environment ".$delthis);
  723:             return 'error';
  724:         }
  725:     }
  726:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
  727:     if ($opened
  728: 	&& &timed_flock($env_file,LOCK_EX)
  729: 	&&
  730: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  731: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  732: 	foreach my $key (keys(%disk_env)) {
  733: 	    if ($regexp) {
  734:                 if ($key=~/^$delthis/) {
  735:                     delete($env{$key});
  736:                     delete($disk_env{$key});
  737:                 } 
  738:             } else {
  739:                 if ($key=~/^\Q$delthis\E/) {
  740: 		    delete($env{$key});
  741: 		    delete($disk_env{$key});
  742: 	        }
  743:             }
  744: 	}
  745: 	untie(%disk_env);
  746:     }
  747:     return 'ok';
  748: }
  749: 
  750: sub get_env_multiple {
  751:     my ($name) = @_;
  752:     my @values;
  753:     if (defined($env{$name})) {
  754:         # exists is it an array
  755:         if (ref($env{$name})) {
  756:             @values=@{ $env{$name} };
  757:         } else {
  758:             $values[0]=$env{$name};
  759:         }
  760:     }
  761:     return(@values);
  762: }
  763: 
  764: # ------------------------------------------------------------------- Locking
  765: 
  766: sub set_lock {
  767:     my ($text)=@_;
  768:     $locknum++;
  769:     my $id=$$.'-'.$locknum;
  770:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
  771:              'session.lock.'.$id => $text});
  772:     return $id;
  773: }
  774: 
  775: sub get_locks {
  776:     my $num=0;
  777:     my %texts=();
  778:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  779:        if ($lock=~/\w/) {
  780:           $num++;
  781:           $texts{$lock}=$env{'session.lock.'.$lock};
  782:        }
  783:    }
  784:    return ($num,%texts);
  785: }
  786: 
  787: sub remove_lock {
  788:     my ($id)=@_;
  789:     my $newlocks='';
  790:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  791:        if (($lock=~/\w/) && ($lock ne $id)) {
  792:           $newlocks.=','.$lock;
  793:        }
  794:     }
  795:     &appenv({'session.locks' => $newlocks});
  796:     &delenv('session.lock.'.$id);
  797: }
  798: 
  799: sub remove_all_locks {
  800:     my $activelocks=$env{'session.locks'};
  801:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  802:        if ($lock=~/\w/) {
  803:           &remove_lock($lock);
  804:        }
  805:     }
  806: }
  807: 
  808: 
  809: # ------------------------------------------ Find out current server userload
  810: sub userload {
  811:     my $numusers=0;
  812:     {
  813: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  814: 	my $filename;
  815: 	my $curtime=time;
  816: 	while ($filename=readdir(LONIDS)) {
  817: 	    next if ($filename eq '.' || $filename eq '..');
  818: 	    next if ($filename =~ /publicuser_\d+\.id/);
  819: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  820: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  821: 	}
  822: 	closedir(LONIDS);
  823:     }
  824:     my $userloadpercent=0;
  825:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  826:     if ($maxuserload) {
  827: 	$userloadpercent=100*$numusers/$maxuserload;
  828:     }
  829:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  830:     return $userloadpercent;
  831: }
  832: 
  833: # ------------------------------ Find server with least workload from spare.tab
  834: 
  835: sub spareserver {
  836:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
  837:     my $spare_server;
  838:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  839:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
  840:                                                      :  $userloadpercent;
  841:     my ($uint_dom,$remotesessions);
  842:     if (($udom ne '') && (&domain($udom) ne '')) {
  843:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
  844:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
  845:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
  846:         $remotesessions = $udomdefaults{'remotesessions'};
  847:     }
  848:     my $spareshash = &this_host_spares($udom);
  849:     if (ref($spareshash) eq 'HASH') {
  850:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
  851:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
  852:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
  853:                                              $try_server));
  854: 	        ($spare_server, $lowest_load) =
  855: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
  856:             }
  857:         }
  858: 
  859:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
  860: 
  861:         if (!$found_server) {
  862:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
  863: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
  864:                     next unless (&spare_can_host($udom,$uint_dom,
  865:                                                  $remotesessions,$try_server));
  866: 	            ($spare_server, $lowest_load) =
  867: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
  868:                 }
  869: 	    }
  870:         }
  871:     }
  872: 
  873:     if (!$want_server_name) {
  874:         my $protocol = 'http';
  875:         if ($protocol{$spare_server} eq 'https') {
  876:             $protocol = $protocol{$spare_server};
  877:         }
  878:         if (defined($spare_server)) {
  879:             my $hostname = &hostname($spare_server);
  880:             if (defined($hostname)) {
  881: 	        $spare_server = $protocol.'://'.$hostname;
  882:             }
  883:         }
  884:     }
  885:     return $spare_server;
  886: }
  887: 
  888: sub compare_server_load {
  889:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
  890: 
  891:     if ($required) {
  892:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
  893:         my $remoterev = &get_server_loncaparev(undef,$try_server);
  894:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
  895:         if (($major eq '' && $minor eq '') ||
  896:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
  897:             return ($spare_server,$lowest_load);
  898:         }
  899:     }
  900: 
  901:     my $loadans     = &reply('load',    $try_server);
  902:     my $userloadans = &reply('userload',$try_server);
  903: 
  904:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
  905: 	return ($spare_server, $lowest_load); #didn't get a number from the server
  906:     }
  907: 
  908:     my $load;
  909:     if ($loadans =~ /\d/) {
  910: 	if ($userloadans =~ /\d/) {
  911: 	    #both are numbers, pick the bigger one
  912: 	    $load = ($loadans > $userloadans) ? $loadans 
  913: 		                              : $userloadans;
  914: 	} else {
  915: 	    $load = $loadans;
  916: 	}
  917:     } else {
  918: 	$load = $userloadans;
  919:     }
  920: 
  921:     if (($load =~ /\d/) && ($load < $lowest_load)) {
  922: 	$spare_server = $try_server;
  923: 	$lowest_load  = $load;
  924:     }
  925:     return ($spare_server,$lowest_load);
  926: }
  927: 
  928: # --------------------------- ask offload servers if user already has a session
  929: sub find_existing_session {
  930:     my ($udom,$uname) = @_;
  931:     my $spareshash = &this_host_spares($udom);
  932:     if (ref($spareshash) eq 'HASH') {
  933:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
  934:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
  935:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
  936:             }
  937:         }
  938:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
  939:             foreach my $try_server (@{ $spareshash->{'default'} }) {
  940:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
  941:             }
  942:         }
  943:     }
  944:     return;
  945: }
  946: 
  947: # -------------------------------- ask if server already has a session for user
  948: sub has_user_session {
  949:     my ($lonid,$udom,$uname) = @_;
  950:     my $result = &reply(join(':','userhassession',
  951: 			     map {&escape($_)} ($udom,$uname)),$lonid);
  952:     return 1 if ($result eq 'ok');
  953: 
  954:     return 0;
  955: }
  956: 
  957: # --------- determine least loaded server in a user's domain which allows login
  958: 
  959: sub choose_server {
  960:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
  961:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
  962:     my %servers = &get_servers($udom);
  963:     my $lowest_load = 30000;
  964:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
  965:     if ($skiploadbal) {
  966:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
  967:         unless (defined($cached)) {
  968:             my $cachetime = 60*60*24;
  969:             my %domconfig =
  970:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
  971:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
  972:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
  973:                                            $cachetime);
  974:             }
  975:         }
  976:     }
  977:     foreach my $lonhost (keys(%servers)) {
  978:         if ($skiploadbal) {
  979:             if (ref($balancers) eq 'HASH') {
  980:                 next if (exists($balancers->{$lonhost}));
  981:             }
  982:         }   
  983:         my $loginvia;
  984:         if ($checkloginvia) {
  985:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
  986:             if ($loginvia) {
  987:                 my ($server,$path) = split(/:/,$loginvia);
  988:                 ($login_host, $lowest_load) =
  989:                     &compare_server_load($server, $login_host, $lowest_load, $required);
  990:                 if ($login_host eq $server) {
  991:                     $portal_path = $path;
  992:                     $isredirect = 1;
  993:                 }
  994:             } else {
  995:                 ($login_host, $lowest_load) =
  996:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
  997:                 if ($login_host eq $lonhost) {
  998:                     $portal_path = '';
  999:                     $isredirect = ''; 
 1000:                 }
 1001:             }
 1002:         } else {
 1003:             ($login_host, $lowest_load) =
 1004:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
 1005:         }
 1006:     }
 1007:     if ($login_host ne '') {
 1008:         $hostname = &hostname($login_host);
 1009:     }
 1010:     return ($login_host,$hostname,$portal_path,$isredirect);
 1011: }
 1012: 
 1013: # --------------------------------------------- Try to change a user's password
 1014: 
 1015: sub changepass {
 1016:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
 1017:     $currentpass = &escape($currentpass);
 1018:     $newpass     = &escape($newpass);
 1019:     my $lonhost = $perlvar{'lonHostID'};
 1020:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
 1021: 		       $server);
 1022:     if (! $answer) {
 1023: 	&logthis("No reply on password change request to $server ".
 1024: 		 "by $uname in domain $udom.");
 1025:     } elsif ($answer =~ "^ok") {
 1026:         &logthis("$uname in $udom successfully changed their password ".
 1027: 		 "on $server.");
 1028:     } elsif ($answer =~ "^pwchange_failure") {
 1029: 	&logthis("$uname in $udom was unable to change their password ".
 1030: 		 "on $server.  The action was blocked by either lcpasswd ".
 1031: 		 "or pwchange");
 1032:     } elsif ($answer =~ "^non_authorized") {
 1033:         &logthis("$uname in $udom did not get their password correct when ".
 1034: 		 "attempting to change it on $server.");
 1035:     } elsif ($answer =~ "^auth_mode_error") {
 1036:         &logthis("$uname in $udom attempted to change their password despite ".
 1037: 		 "not being locally or internally authenticated on $server.");
 1038:     } elsif ($answer =~ "^unknown_user") {
 1039:         &logthis("$uname in $udom attempted to change their password ".
 1040: 		 "on $server but were unable to because $server is not ".
 1041: 		 "their home server.");
 1042:     } elsif ($answer =~ "^refused") {
 1043: 	&logthis("$server refused to change $uname in $udom password because ".
 1044: 		 "it was sent an unencrypted request to change the password.");
 1045:     } elsif ($answer =~ "invalid_client") {
 1046:         &logthis("$server refused to change $uname in $udom password because ".
 1047:                  "it was a reset by e-mail originating from an invalid server.");
 1048:     }
 1049:     return $answer;
 1050: }
 1051: 
 1052: # ----------------------- Try to determine user's current authentication scheme
 1053: 
 1054: sub queryauthenticate {
 1055:     my ($uname,$udom)=@_;
 1056:     my $uhome=&homeserver($uname,$udom);
 1057:     if (!$uhome) {
 1058: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
 1059: 	return 'no_host';
 1060:     }
 1061:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
 1062:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
 1063: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1064:     }
 1065:     return $answer;
 1066: }
 1067: 
 1068: # --------- Try to authenticate user from domain's lib servers (first this one)
 1069: 
 1070: sub authenticate {
 1071:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
 1072:     $upass=&escape($upass);
 1073:     $uname= &LONCAPA::clean_username($uname);
 1074:     my $uhome=&homeserver($uname,$udom,1);
 1075:     my $newhome;
 1076:     if ((!$uhome) || ($uhome eq 'no_host')) {
 1077: # Maybe the machine was offline and only re-appeared again recently?
 1078:         &reconlonc();
 1079: # One more
 1080: 	$uhome=&homeserver($uname,$udom,1);
 1081:         if (($uhome eq 'no_host') && $checkdefauth) {
 1082:             if (defined(&domain($udom,'primary'))) {
 1083:                 $newhome=&domain($udom,'primary');
 1084:             }
 1085:             if ($newhome ne '') {
 1086:                 $uhome = $newhome;
 1087:             }
 1088:         }
 1089: 	if ((!$uhome) || ($uhome eq 'no_host')) {
 1090: 	    &logthis("User $uname at $udom is unknown in authenticate");
 1091: 	    return 'no_host';
 1092:         }
 1093:     }
 1094:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
 1095:     if ($answer eq 'authorized') {
 1096:         if ($newhome) {
 1097:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
 1098:             return 'no_account_on_host'; 
 1099:         } else {
 1100:             &logthis("User $uname at $udom authorized by $uhome");
 1101:             return $uhome;
 1102:         }
 1103:     }
 1104:     if ($answer eq 'non_authorized') {
 1105: 	&logthis("User $uname at $udom rejected by $uhome");
 1106: 	return 'no_host'; 
 1107:     }
 1108:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1109:     return 'no_host';
 1110: }
 1111: 
 1112: sub can_host_session {
 1113:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
 1114:     my $canhost = 1;
 1115:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
 1116:     if (ref($remotesessions) eq 'HASH') {
 1117:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
 1118:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
 1119:                 $canhost = 0;
 1120:             } else {
 1121:                 $canhost = 1;
 1122:             }
 1123:         }
 1124:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
 1125:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
 1126:                 $canhost = 1;
 1127:             } else {
 1128:                 $canhost = 0;
 1129:             }
 1130:         }
 1131:         if ($canhost) {
 1132:             if ($remotesessions->{'version'} ne '') {
 1133:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
 1134:                 if ($reqmajor ne '' && $reqminor ne '') {
 1135:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
 1136:                         my $major = $1;
 1137:                         my $minor = $2;
 1138:                         if (($major < $reqmajor ) ||
 1139:                             (($major == $reqmajor) && ($minor < $reqminor))) {
 1140:                             $canhost = 0;
 1141:                         }
 1142:                     } else {
 1143:                         $canhost = 0;
 1144:                     }
 1145:                 }
 1146:             }
 1147:         }
 1148:     }
 1149:     if ($canhost) {
 1150:         if (ref($hostedsessions) eq 'HASH') {
 1151:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1152:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
 1153:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
 1154:                 if (($uint_dom ne '') && 
 1155:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
 1156:                     $canhost = 0;
 1157:                 } else {
 1158:                     $canhost = 1;
 1159:                 }
 1160:             }
 1161:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
 1162:                 if (($uint_dom ne '') && 
 1163:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
 1164:                     $canhost = 1;
 1165:                 } else {
 1166:                     $canhost = 0;
 1167:                 }
 1168:             }
 1169:         }
 1170:     }
 1171:     return $canhost;
 1172: }
 1173: 
 1174: sub spare_can_host {
 1175:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
 1176:     my $canhost=1;
 1177:     my $try_server_hostname = &hostname($try_server);
 1178:     my $serverhomeID = &get_server_homeID($try_server_hostname);
 1179:     my $serverhomedom = &host_domain($serverhomeID);
 1180:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
 1181:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
 1182:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
 1183:             $canhost = 0;
 1184:         }
 1185:     }
 1186:     if (($canhost) && ($uint_dom)) {
 1187:         my @intdoms;
 1188:         my $internet_names = &get_internet_names($try_server);
 1189:         if (ref($internet_names) eq 'ARRAY') {
 1190:             @intdoms = @{$internet_names};
 1191:         }
 1192:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
 1193:             my $remoterev = &get_server_loncaparev(undef,$try_server);
 1194:             $canhost = &can_host_session($udom,$try_server,$remoterev,
 1195:                                          $remotesessions,
 1196:                                          $defdomdefaults{'hostedsessions'});
 1197:         }
 1198:     }
 1199:     return $canhost;
 1200: }
 1201: 
 1202: sub this_host_spares {
 1203:     my ($dom) = @_;
 1204:     my ($dom_in_use,$lonhost_in_use,$result);
 1205:     my @hosts = &current_machine_ids();
 1206:     foreach my $lonhost (@hosts) {
 1207:         if (&host_domain($lonhost) eq $dom) {
 1208:             $dom_in_use = $dom;
 1209:             $lonhost_in_use = $lonhost;
 1210:             last;
 1211:         }
 1212:     }
 1213:     if ($dom_in_use ne '') {
 1214:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1215:     }
 1216:     if (ref($result) ne 'HASH') {
 1217:         $lonhost_in_use = $perlvar{'lonHostID'};
 1218:         $dom_in_use = &host_domain($lonhost_in_use);
 1219:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1220:         if (ref($result) ne 'HASH') {
 1221:             $result = \%spareid;
 1222:         }
 1223:     }
 1224:     return $result;
 1225: }
 1226: 
 1227: sub spares_for_offload  {
 1228:     my ($dom_in_use,$lonhost_in_use) = @_;
 1229:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
 1230:     if (defined($cached)) {
 1231:         return $result;
 1232:     } else {
 1233:         my $cachetime = 60*60*24;
 1234:         my %domconfig =
 1235:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
 1236:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
 1237:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
 1238:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
 1239:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
 1240:                 }
 1241:             }
 1242:         }
 1243:     }
 1244:     return;
 1245: }
 1246: 
 1247: sub get_lonbalancer_config {
 1248:     my ($servers) = @_;
 1249:     my ($currbalancer,$currtargets);
 1250:     if (ref($servers) eq 'HASH') {
 1251:         foreach my $server (keys(%{$servers})) {
 1252:             my %what = (
 1253:                          spareid => 1,
 1254:                          perlvar => 1,
 1255:                        );
 1256:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
 1257:             if ($result eq 'ok') {
 1258:                 if (ref($returnhash) eq 'HASH') {
 1259:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
 1260:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
 1261:                             $currbalancer = $server;
 1262:                             $currtargets = {};
 1263:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
 1264:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
 1265:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
 1266:                                 }
 1267:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
 1268:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
 1269:                                 }
 1270:                             }
 1271:                             last;
 1272:                         }
 1273:                     }
 1274:                 }
 1275:             }
 1276:         }
 1277:     }
 1278:     return ($currbalancer,$currtargets);
 1279: }
 1280: 
 1281: sub check_loadbalancing {
 1282:     my ($uname,$udom) = @_;
 1283:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
 1284:         $rule_in_effect,$offloadto,$otherserver);
 1285:     my $lonhost = $perlvar{'lonHostID'};
 1286:     my @hosts = &current_machine_ids();
 1287:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1288:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
 1289:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
 1290:     my $serverhomedom = &host_domain($lonhost);
 1291: 
 1292:     my $cachetime = 60*60*24;
 1293: 
 1294:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1295:         $dom_in_use = $udom;
 1296:         $homeintdom = 1;
 1297:     } else {
 1298:         $dom_in_use = $serverhomedom;
 1299:     }
 1300:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
 1301:     unless (defined($cached)) {
 1302:         my %domconfig =
 1303:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
 1304:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1305:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1306:         }
 1307:     }
 1308:     if (ref($result) eq 'HASH') {
 1309:         ($is_balancer,$currtargets,$currrules) = 
 1310:             &check_balancer_result($result,@hosts);
 1311:         if ($is_balancer) {
 1312:             if (ref($currrules) eq 'HASH') {
 1313:                 if ($homeintdom) {
 1314:                     if ($uname ne '') {
 1315:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
 1316:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
 1317:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
 1318:                                 $rule_in_effect = $currrules->{'_LC_author'};
 1319:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
 1320:                                 $rule_in_effect = $currrules->{'_LC_adv'}
 1321:                             }
 1322:                         }
 1323:                         if ($rule_in_effect eq '') {
 1324:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
 1325:                             if ($userenv{'inststatus'} ne '') {
 1326:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
 1327:                                 my ($othertitle,$usertypes,$types) =
 1328:                                     &Apache::loncommon::sorted_inst_types($udom);
 1329:                                 if (ref($types) eq 'ARRAY') {
 1330:                                     foreach my $type (@{$types}) {
 1331:                                         if (grep(/^\Q$type\E$/,@statuses)) {
 1332:                                             if (exists($currrules->{$type})) {
 1333:                                                 $rule_in_effect = $currrules->{$type};
 1334:                                             }
 1335:                                         }
 1336:                                     }
 1337:                                 }
 1338:                             } else {
 1339:                                 if (exists($currrules->{'default'})) {
 1340:                                     $rule_in_effect = $currrules->{'default'};
 1341:                                 }
 1342:                             }
 1343:                         }
 1344:                     } else {
 1345:                         if (exists($currrules->{'default'})) {
 1346:                             $rule_in_effect = $currrules->{'default'};
 1347:                         }
 1348:                     }
 1349:                 } else {
 1350:                     if ($currrules->{'_LC_external'} ne '') {
 1351:                         $rule_in_effect = $currrules->{'_LC_external'};
 1352:                     }
 1353:                 }
 1354:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1355:                                                        $uname,$udom);
 1356:             }
 1357:         }
 1358:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
 1359:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
 1360:         unless (defined($cached)) {
 1361:             my %domconfig =
 1362:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
 1363:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1364:                 $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1365:             }
 1366:         }
 1367:         if (ref($result) eq 'HASH') {
 1368:             ($is_balancer,$currtargets,$currrules) = 
 1369:                 &check_balancer_result($result,@hosts);
 1370:             if ($is_balancer) {
 1371:                 if (ref($currrules) eq 'HASH') {
 1372:                     if ($currrules->{'_LC_internetdom'} ne '') {
 1373:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
 1374:                     }
 1375:                 }
 1376:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1377:                                                        $uname,$udom);
 1378:             }
 1379:         } else {
 1380:             if ($perlvar{'lonBalancer'} eq 'yes') {
 1381:                 $is_balancer = 1;
 1382:                 $offloadto = &this_host_spares($dom_in_use);
 1383:             }
 1384:         }
 1385:     } else {
 1386:         if ($perlvar{'lonBalancer'} eq 'yes') {
 1387:             $is_balancer = 1;
 1388:             $offloadto = &this_host_spares($dom_in_use);
 1389:         }
 1390:     }
 1391:     if ($is_balancer) {
 1392:         my $lowest_load = 30000;
 1393:         if (ref($offloadto) eq 'HASH') {
 1394:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
 1395:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
 1396:                     ($otherserver,$lowest_load) =
 1397:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1398:                 }
 1399:             }
 1400:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
 1401: 
 1402:             if (!$found_server) {
 1403:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
 1404:                     foreach my $try_server (@{$offloadto->{'default'}}) {
 1405:                         ($otherserver,$lowest_load) =
 1406:                             &compare_server_load($try_server,$otherserver,$lowest_load);
 1407:                     }
 1408:                 }
 1409:             }
 1410:         } elsif (ref($offloadto) eq 'ARRAY') {
 1411:             if (@{$offloadto} == 1) {
 1412:                 $otherserver = $offloadto->[0];
 1413:             } elsif (@{$offloadto} > 1) {
 1414:                 foreach my $try_server (@{$offloadto}) {
 1415:                     ($otherserver,$lowest_load) =
 1416:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1417:                 }
 1418:             }
 1419:         }
 1420:         if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
 1421:             $is_balancer = 0;
 1422:             if ($uname ne '' && $udom ne '') {
 1423:                 if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
 1424:                     
 1425:                     &appenv({'user.loadbalexempt'     => $lonhost,  
 1426:                              'user.loadbalcheck.time' => time});
 1427:                 }
 1428:             }
 1429:         }
 1430:     }
 1431:     return ($is_balancer,$otherserver);
 1432: }
 1433: 
 1434: sub check_balancer_result {
 1435:     my ($result,@hosts) = @_;
 1436:     my ($is_balancer,$currtargets,$currrules);
 1437:     if (ref($result) eq 'HASH') {
 1438:         if ($result->{'lonhost'} ne '') {
 1439:             my $currbalancer = $result->{'lonhost'};
 1440:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
 1441:                 $is_balancer = 1;
 1442:                 $currtargets = $result->{'targets'};
 1443:                 $currrules = $result->{'rules'};
 1444:             }
 1445:         } else {
 1446:             foreach my $key (keys(%{$result})) {
 1447:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
 1448:                     (ref($result->{$key}) eq 'HASH')) {
 1449:                     $is_balancer = 1;
 1450:                     $currrules = $result->{$key}{'rules'};
 1451:                     $currtargets = $result->{$key}{'targets'};
 1452:                     last;
 1453:                 }
 1454:             }
 1455:         }
 1456:     }
 1457:     return ($is_balancer,$currtargets,$currrules);
 1458: }
 1459: 
 1460: sub get_loadbalancer_targets {
 1461:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
 1462:     my $offloadto;
 1463:     if ($rule_in_effect eq 'none') {
 1464:         return [$perlvar{'lonHostID'}];
 1465:     } elsif ($rule_in_effect eq '') {
 1466:         $offloadto = $currtargets;
 1467:     } else {
 1468:         if ($rule_in_effect eq 'homeserver') {
 1469:             my $homeserver = &homeserver($uname,$udom);
 1470:             if ($homeserver ne 'no_host') {
 1471:                 $offloadto = [$homeserver];
 1472:             }
 1473:         } elsif ($rule_in_effect eq 'externalbalancer') {
 1474:             my %domconfig =
 1475:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
 1476:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1477:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
 1478:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
 1479:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
 1480:                     }
 1481:                 }
 1482:             } else {
 1483:                 my %servers = &internet_dom_servers($udom);
 1484:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
 1485:                 if (&hostname($remotebalancer) ne '') {
 1486:                     $offloadto = [$remotebalancer];
 1487:                 }
 1488:             }
 1489:         } elsif (&hostname($rule_in_effect) ne '') {
 1490:             $offloadto = [$rule_in_effect];
 1491:         }
 1492:     }
 1493:     return $offloadto;
 1494: }
 1495: 
 1496: sub internet_dom_servers {
 1497:     my ($dom) = @_;
 1498:     my (%uniqservers,%servers);
 1499:     my $primaryserver = &hostname(&domain($dom,'primary'));
 1500:     my @machinedoms = &machine_domains($primaryserver);
 1501:     foreach my $mdom (@machinedoms) {
 1502:         my %currservers = %servers;
 1503:         my %server = &get_servers($mdom);
 1504:         %servers = (%currservers,%server);
 1505:     }
 1506:     my %by_hostname;
 1507:     foreach my $id (keys(%servers)) {
 1508:         push(@{$by_hostname{$servers{$id}}},$id);
 1509:     }
 1510:     foreach my $hostname (sort(keys(%by_hostname))) {
 1511:         if (@{$by_hostname{$hostname}} > 1) {
 1512:             my $match = 0;
 1513:             foreach my $id (@{$by_hostname{$hostname}}) {
 1514:                 if (&host_domain($id) eq $dom) {
 1515:                     $uniqservers{$id} = $hostname;
 1516:                     $match = 1;
 1517:                 }
 1518:             }
 1519:             unless ($match) {
 1520:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1521:             }
 1522:         } else {
 1523:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1524:         }
 1525:     }
 1526:     return %uniqservers;
 1527: }
 1528: 
 1529: # ---------------------- Find the homebase for a user from domain's lib servers
 1530: 
 1531: my %homecache;
 1532: sub homeserver {
 1533:     my ($uname,$udom,$ignoreBadCache)=@_;
 1534:     my $index="$uname:$udom";
 1535: 
 1536:     if (exists($homecache{$index})) { return $homecache{$index}; }
 1537: 
 1538:     my %servers = &get_servers($udom,'library');
 1539:     foreach my $tryserver (keys(%servers)) {
 1540:         next if ($ignoreBadCache ne 'true' && 
 1541: 		 exists($badServerCache{$tryserver}));
 1542: 
 1543: 	my $answer=reply("home:$udom:$uname",$tryserver);
 1544: 	if ($answer eq 'found') {
 1545: 	    delete($badServerCache{$tryserver}); 
 1546: 	    return $homecache{$index}=$tryserver;
 1547: 	} elsif ($answer eq 'no_host') {
 1548: 	    $badServerCache{$tryserver}=1;
 1549: 	}
 1550:     }    
 1551:     return 'no_host';
 1552: }
 1553: 
 1554: # ----- Find the usernames behind a list of student/employee IDs or clicker IDs
 1555: 
 1556: sub idget {
 1557:     my ($udom,$idsref,$namespace)=@_;
 1558:     my %returnhash=();
 1559:     my @ids=(); 
 1560:     if (ref($idsref) eq 'ARRAY') {
 1561:         @ids = @{$idsref};
 1562:     } else {
 1563:         return %returnhash; 
 1564:     }
 1565:     if ($namespace eq '') {
 1566:         $namespace = 'ids';
 1567:     }
 1568:     
 1569:     my %servers = &get_servers($udom,'library');
 1570:     foreach my $tryserver (keys(%servers)) {
 1571: 	my $idlist=join('&', map { &escape($_); } @ids);
 1572: 	if ($namespace eq 'ids') {
 1573: 	    $idlist=~tr/A-Z/a-z/;
 1574: 	}
 1575: 	my $reply;
 1576: 	if ($namespace eq 'ids') {
 1577: 	    $reply=&reply("idget:$udom:".$idlist,$tryserver);
 1578: 	} else {
 1579: 	    $reply=&reply("getdom:$udom:$namespace:$idlist",$tryserver);
 1580: 	}
 1581: 	my @answer=();
 1582: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
 1583: 	    @answer=split(/\&/,$reply);
 1584: 	}                    ;
 1585: 	my $i;
 1586: 	for ($i=0;$i<=$#ids;$i++) {
 1587: 	    if ($answer[$i]) {
 1588: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
 1589: 	    }
 1590: 	}
 1591:     }
 1592:     return %returnhash;
 1593: }
 1594: 
 1595: # ------------------------------------- Find the IDs behind a list of usernames
 1596: 
 1597: sub idrget {
 1598:     my ($udom,@unames)=@_;
 1599:     my %returnhash=();
 1600:     foreach my $uname (@unames) {
 1601:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
 1602:     }
 1603:     return %returnhash;
 1604: }
 1605: 
 1606: # Store away a list of names and associated student/employee IDs or clicker IDs
 1607: 
 1608: sub idput {
 1609:     my ($udom,$idsref,$uhom,$namespace)=@_;
 1610:     my %servers=();
 1611:     my %ids=();
 1612:     my %byid = ();
 1613:     if (ref($idsref) eq 'HASH') {
 1614:         %ids=%{$idsref};
 1615:     }
 1616:     if ($namespace eq '') {
 1617:         $namespace = 'ids'; 
 1618:     }
 1619:     foreach my $uname (keys(%ids)) {
 1620: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
 1621:         if ($uhom eq '') {
 1622:             $uhom=&homeserver($uname,$udom);
 1623:         }
 1624:         if ($uhom ne 'no_host') {
 1625:             my $esc_unam=&escape($uname);
 1626:             if ($namespace eq 'ids') {
 1627:                 my $id=&escape($ids{$uname});
 1628:                 $id=~tr/A-Z/a-z/;
 1629:                 my $esc_unam=&escape($uname);
 1630:                 $servers{$uhom}.=$id.'='.$esc_unam.'&';
 1631:             } else {
 1632:                 my @currids = split(/,/,$ids{$uname});
 1633:                 foreach my $id (@currids) {
 1634:                     $byid{$uhom}{$id} .= $uname.',';
 1635:                 }
 1636:             }
 1637:         }
 1638:     }
 1639:     if ($namespace eq 'clickers') {
 1640:         foreach my $server (keys(%byid)) {
 1641:             if (ref($byid{$server}) eq 'HASH') {
 1642:                 foreach my $id (keys(%{$byid{$server}})) {
 1643:                     $byid{$server} =~ s/,$//;
 1644:                     $servers{$uhom}.=&escape($id).'='.&escape($byid{$server}).'&'; 
 1645:                 }
 1646:             }
 1647:         }
 1648:     }
 1649:     foreach my $server (keys(%servers)) {
 1650:         $servers{$server} =~ s/\&$//;
 1651:         if ($namespace eq 'ids') {     
 1652:             &critical('idput:'.$udom.':'.$servers{$server},$server);
 1653:         } else {
 1654:             &critical('updateclickers:'.$udom.':add:'.$servers{$server},$server);
 1655:         }
 1656:     }
 1657: }
 1658: 
 1659: # ------------- Delete unwanted student/employee IDs or clicker IDs from domain
 1660: 
 1661: sub iddel {
 1662:     my ($udom,$idshashref,$uhome,$namespace)=@_;
 1663:     my %result=();
 1664:     my %ids=();
 1665:     my %byid = ();
 1666:     if (ref($idshashref) eq 'HASH') {
 1667:         %ids=%{$idshashref};
 1668:     } else {
 1669:         return %result;
 1670:     }
 1671:     if ($namespace eq '') {
 1672:         $namespace = 'ids';
 1673:     }
 1674:     my %servers=();
 1675:     while (my ($id,$unamestr) = each(%ids)) {
 1676:         if ($namespace eq 'ids') {
 1677:             my $uhom = $uhome;
 1678:             if ($uhom eq '') { 
 1679:                 $uhom=&homeserver($unamestr,$udom);
 1680:             }
 1681:             if ($uhom ne 'no_host') {
 1682:                 $servers{$uhom}.='&'.&escape($id);
 1683:             }
 1684:          } else {
 1685:             my @curritems = split(/,/,$ids{$id});
 1686:             foreach my $uname (@curritems) {
 1687:                 my $uhom = $uhome;
 1688:                 if ($uhom eq '') {
 1689:                     $uhom=&homeserver($uname,$udom);
 1690:                 }
 1691:                 if ($uhom ne 'no_host') { 
 1692:                     $byid{$uhom}{$id} .= $uname.',';
 1693:                 }
 1694:             }
 1695:         }
 1696:     }
 1697:     if ($namespace eq 'clickers') {
 1698:         foreach my $server (keys(%byid)) {
 1699:             if (ref($byid{$server}) eq 'HASH') {
 1700:                 foreach my $id (keys(%{$byid{$server}})) {
 1701:                     $byid{$server}{$id} =~ s/,$//;
 1702:                     $servers{$server}.=&escape($id).'='.&escape($byid{$server}{$id}).'&';
 1703:                 }
 1704:             }
 1705:         }
 1706:     }
 1707:     foreach my $server (keys(%servers)) {
 1708:         $servers{$server} =~ s/\&$//;
 1709:         if ($namespace eq 'ids') {
 1710:             $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
 1711:         } elsif ($namespace eq 'clickers') {
 1712:             $result{$server} = &critical('updateclickers:'.$udom.':del:'.$servers{$server},$server);
 1713:         }
 1714:     }
 1715:     return %result;
 1716: }
 1717: 
 1718: # ----- Update clicker ID-to-username look-ups in clickers.db on library server 
 1719: 
 1720: sub updateclickers {
 1721:     my ($udom,$action,$idshashref,$uhome,$critical) = @_;
 1722:     my %clickers;
 1723:     if (ref($idshashref) eq 'HASH') {
 1724:         %clickers=%{$idshashref};
 1725:     } else {
 1726:         return;
 1727:     }
 1728:     my $items='';
 1729:     foreach my $item (keys(%clickers)) {
 1730:         $items.=&escape($item).'='.&escape($clickers{$item}).'&';
 1731:     }
 1732:     $items=~s/\&$//;
 1733:     my $request = "updateclickers:$udom:$action:$items";
 1734:     if ($critical) {
 1735:         return &critical($request,$uhome);
 1736:     } else {
 1737:         return &reply($request,$uhome);
 1738:     }
 1739: }
 1740: 
 1741: # ------------------------------dump from db file owned by domainconfig user
 1742: sub dump_dom {
 1743:     my ($namespace, $udom, $regexp) = @_;
 1744: 
 1745:     $udom ||= $env{'user.domain'};
 1746: 
 1747:     return () unless $udom;
 1748: 
 1749:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
 1750: }
 1751: 
 1752: # ------------------------------------------ get items from domain db files   
 1753: 
 1754: sub get_dom {
 1755:     my ($namespace,$storearr,$udom,$uhome)=@_;
 1756:     return if ($udom eq 'public');
 1757:     my $items='';
 1758:     foreach my $item (@$storearr) {
 1759:         $items.=&escape($item).'&';
 1760:     }
 1761:     $items=~s/\&$//;
 1762:     if (!$udom) {
 1763:         $udom=$env{'user.domain'};
 1764:         return if ($udom eq 'public');
 1765:         if (defined(&domain($udom,'primary'))) {
 1766:             $uhome=&domain($udom,'primary');
 1767:         } else {
 1768:             undef($uhome);
 1769:         }
 1770:     } else {
 1771:         if (!$uhome) {
 1772:             if (defined(&domain($udom,'primary'))) {
 1773:                 $uhome=&domain($udom,'primary');
 1774:             }
 1775:         }
 1776:     }
 1777:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1778:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
 1779:         my %returnhash;
 1780:         if ($rep eq '' || $rep =~ /^error: 2 /) {
 1781:             return %returnhash;
 1782:         }
 1783:         my @pairs=split(/\&/,$rep);
 1784:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 1785:             return @pairs;
 1786:         }
 1787:         my $i=0;
 1788:         foreach my $item (@$storearr) {
 1789:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
 1790:             $i++;
 1791:         }
 1792:         return %returnhash;
 1793:     } else {
 1794:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
 1795:     }
 1796: }
 1797: 
 1798: # -------------------------------------------- put items in domain db files 
 1799: 
 1800: sub put_dom {
 1801:     my ($namespace,$storehash,$udom,$uhome)=@_;
 1802:     if (!$udom) {
 1803:         $udom=$env{'user.domain'};
 1804:         if (defined(&domain($udom,'primary'))) {
 1805:             $uhome=&domain($udom,'primary');
 1806:         } else {
 1807:             undef($uhome);
 1808:         }
 1809:     } else {
 1810:         if (!$uhome) {
 1811:             if (defined(&domain($udom,'primary'))) {
 1812:                 $uhome=&domain($udom,'primary');
 1813:             }
 1814:         }
 1815:     } 
 1816:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1817:         my $items='';
 1818:         foreach my $item (keys(%$storehash)) {
 1819:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 1820:         }
 1821:         $items=~s/\&$//;
 1822:         return &reply("putdom:$udom:$namespace:$items",$uhome);
 1823:     } else {
 1824:         &logthis("put_dom failed - no homeserver and/or domain");
 1825:     }
 1826: }
 1827: 
 1828: # --------------------- newput for items in db file owned by domainconfig user
 1829: sub newput_dom {
 1830:     my ($namespace,$storehash,$udom) = @_;
 1831:     my $result;
 1832:     if (!$udom) {
 1833:         $udom=$env{'user.domain'};
 1834:     }
 1835:     if ($udom) {
 1836:         my $uname = &get_domainconfiguser($udom);
 1837:         $result = &newput($namespace,$storehash,$udom,$uname);
 1838:     }
 1839:     return $result;
 1840: }
 1841: 
 1842: # --------------------- delete for items in db file owned by domainconfig user
 1843: sub del_dom {
 1844:     my ($namespace,$storearr,$udom)=@_;
 1845:     if (ref($storearr) eq 'ARRAY') {
 1846:         if (!$udom) {
 1847:             $udom=$env{'user.domain'};
 1848:         }
 1849:         if ($udom) {
 1850:             my $uname = &get_domainconfiguser($udom); 
 1851:             return &del($namespace,$storearr,$udom,$uname);
 1852:         }
 1853:     }
 1854: }
 1855: 
 1856: # ----------------------------------construct domainconfig user for a domain 
 1857: sub get_domainconfiguser {
 1858:     my ($udom) = @_;
 1859:     return $udom.'-domainconfig';
 1860: }
 1861: 
 1862: sub retrieve_inst_usertypes {
 1863:     my ($udom) = @_;
 1864:     my (%returnhash,@order);
 1865:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 1866:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
 1867:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
 1868:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
 1869:     } else {
 1870:         if (defined(&domain($udom,'primary'))) {
 1871:             my $uhome=&domain($udom,'primary');
 1872:             my $rep=&reply("inst_usertypes:$udom",$uhome);
 1873:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
 1874:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
 1875:                 return (\%returnhash,\@order);
 1876:             }
 1877:             my ($hashitems,$orderitems) = split(/:/,$rep); 
 1878:             my @pairs=split(/\&/,$hashitems);
 1879:             foreach my $item (@pairs) {
 1880:                 my ($key,$value)=split(/=/,$item,2);
 1881:                 $key = &unescape($key);
 1882:                 next if ($key =~ /^error: 2 /);
 1883:                 $returnhash{$key}=&thaw_unescape($value);
 1884:             }
 1885:             my @esc_order = split(/\&/,$orderitems);
 1886:             foreach my $item (@esc_order) {
 1887:                 push(@order,&unescape($item));
 1888:             }
 1889:         } else {
 1890:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
 1891:         }
 1892:         return (\%returnhash,\@order);
 1893:     }
 1894: }
 1895: 
 1896: sub is_domainimage {
 1897:     my ($url) = @_;
 1898:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
 1899:         if (&domain($1) ne '') {
 1900:             return '1';
 1901:         }
 1902:     }
 1903:     return;
 1904: }
 1905: 
 1906: sub inst_directory_query {
 1907:     my ($srch) = @_;
 1908:     my $udom = $srch->{'srchdomain'};
 1909:     my %results;
 1910:     my $homeserver = &domain($udom,'primary');
 1911:     my $outcome;
 1912:     if ($homeserver ne '') {
 1913: 	my $queryid=&reply("querysend:instdirsearch:".
 1914: 			   &escape($srch->{'srchby'}).':'.
 1915: 			   &escape($srch->{'srchterm'}).':'.
 1916: 			   &escape($srch->{'srchtype'}),$homeserver);
 1917: 	my $host=&hostname($homeserver);
 1918: 	if ($queryid !~/^\Q$host\E\_/) {
 1919: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1920: 	    return;
 1921: 	}
 1922: 	my $response = &get_query_reply($queryid);
 1923: 	my $maxtries = 5;
 1924: 	my $tries = 1;
 1925: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1926: 	    $response = &get_query_reply($queryid);
 1927: 	    $tries ++;
 1928: 	}
 1929: 
 1930:         if (!&error($response) && $response ne 'refused') {
 1931:             if ($response eq 'unavailable') {
 1932:                 $outcome = $response;
 1933:             } else {
 1934:                 $outcome = 'ok';
 1935:                 my @matches = split(/\n/,$response);
 1936:                 foreach my $match (@matches) {
 1937:                     my ($key,$value) = split(/=/,$match);
 1938:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 1939:                 }
 1940:             }
 1941:         }
 1942:     }
 1943:     return ($outcome,%results);
 1944: }
 1945: 
 1946: sub usersearch {
 1947:     my ($srch) = @_;
 1948:     my $dom = $srch->{'srchdomain'};
 1949:     my %results;
 1950:     my %libserv = &all_library();
 1951:     my $query = 'usersearch';
 1952:     foreach my $tryserver (keys(%libserv)) {
 1953:         if (&host_domain($tryserver) eq $dom) {
 1954:             my $host=&hostname($tryserver);
 1955:             my $queryid=
 1956:                 &reply("querysend:".&escape($query).':'.
 1957:                        &escape($srch->{'srchby'}).':'.
 1958:                        &escape($srch->{'srchtype'}).':'.
 1959:                        &escape($srch->{'srchterm'}),$tryserver);
 1960:             if ($queryid !~/^\Q$host\E\_/) {
 1961:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 1962:                 next;
 1963:             }
 1964:             my $reply = &get_query_reply($queryid);
 1965:             my $maxtries = 1;
 1966:             my $tries = 1;
 1967:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 1968:                 $reply = &get_query_reply($queryid);
 1969:                 $tries ++;
 1970:             }
 1971:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 1972:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 1973:             } else {
 1974:                 my @matches;
 1975:                 if ($reply =~ /\n/) {
 1976:                     @matches = split(/\n/,$reply);
 1977:                 } else {
 1978:                     @matches = split(/\&/,$reply);
 1979:                 }
 1980:                 foreach my $match (@matches) {
 1981:                     my ($uname,$udom,%userhash);
 1982:                     foreach my $entry (split(/:/,$match)) {
 1983:                         my ($key,$value) =
 1984:                             map {&unescape($_);} split(/=/,$entry);
 1985:                         $userhash{$key} = $value;
 1986:                         if ($key eq 'username') {
 1987:                             $uname = $value;
 1988:                         } elsif ($key eq 'domain') {
 1989:                             $udom = $value;
 1990:                         }
 1991:                     }
 1992:                     $results{$uname.':'.$udom} = \%userhash;
 1993:                 }
 1994:             }
 1995:         }
 1996:     }
 1997:     return %results;
 1998: }
 1999: 
 2000: sub get_instuser {
 2001:     my ($udom,$uname,$id) = @_;
 2002:     my $homeserver = &domain($udom,'primary');
 2003:     my ($outcome,%results);
 2004:     if ($homeserver ne '') {
 2005:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 2006:                            &escape($id).':'.&escape($udom),$homeserver);
 2007:         my $host=&hostname($homeserver);
 2008:         if ($queryid !~/^\Q$host\E\_/) {
 2009:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 2010:             return;
 2011:         }
 2012:         my $response = &get_query_reply($queryid);
 2013:         my $maxtries = 5;
 2014:         my $tries = 1;
 2015:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 2016:             $response = &get_query_reply($queryid);
 2017:             $tries ++;
 2018:         }
 2019:         if (!&error($response) && $response ne 'refused') {
 2020:             if ($response eq 'unavailable') {
 2021:                 $outcome = $response;
 2022:             } else {
 2023:                 $outcome = 'ok';
 2024:                 my @matches = split(/\n/,$response);
 2025:                 foreach my $match (@matches) {
 2026:                     my ($key,$value) = split(/=/,$match);
 2027:                     $results{&unescape($key)} = &thaw_unescape($value);
 2028:                 }
 2029:             }
 2030:         }
 2031:     }
 2032:     my %userinfo;
 2033:     if (ref($results{$uname}) eq 'HASH') {
 2034:         %userinfo = %{$results{$uname}};
 2035:     } 
 2036:     return ($outcome,%userinfo);
 2037: }
 2038: 
 2039: sub get_multiple_instusers {
 2040:     my ($udom,$users,$caller) = @_;
 2041:     my ($outcome,$results);
 2042:     if (ref($users) eq 'HASH') {
 2043:         my $count = keys(%{$users}); 
 2044:         my $requested = &freeze_escape($users);
 2045:         my $homeserver = &domain($udom,'primary');
 2046:         if ($homeserver ne '') {
 2047:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
 2048:             my $host=&hostname($homeserver);
 2049:             if ($queryid !~/^\Q$host\E\_/) {
 2050:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
 2051:                          ' for host: '.$homeserver.'in domain '.$udom);
 2052:                 return ($outcome,$results);
 2053:             }
 2054:             my $response = &get_query_reply($queryid);
 2055:             my $maxtries = 5;
 2056:             if ($count > 100) {
 2057:                 $maxtries = 1+int($count/20);
 2058:             }
 2059:             my $tries = 1;
 2060:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
 2061:                 $response = &get_query_reply($queryid);
 2062:                 $tries ++;
 2063:             }
 2064:             if ($response eq '') {
 2065:                 $results = {};
 2066:                 foreach my $key (keys(%{$users})) {
 2067:                     my ($uname,$id);
 2068:                     if ($caller eq 'id') {
 2069:                         $id = $key;
 2070:                     } else {
 2071:                         $uname = $key;
 2072:                     }
 2073:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
 2074:                     $outcome = $resp;
 2075:                     if ($resp eq 'ok') {
 2076:                         %{$results} = (%{$results}, %info);
 2077:                     } else {
 2078:                         last;
 2079:                     }
 2080:                 }
 2081:             } elsif(!&error($response) && ($response ne 'refused')) {
 2082:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
 2083:                     $outcome = $response;
 2084:                 } else {
 2085:                     ($outcome,my $userdata) = split(/=/,$response,2);
 2086:                     if ($outcome eq 'ok') {
 2087:                         $results = &thaw_unescape($userdata); 
 2088:                     }
 2089:                 }
 2090:             }
 2091:         }
 2092:     }
 2093:     return ($outcome,$results);
 2094: }
 2095: 
 2096: sub inst_rulecheck {
 2097:     my ($udom,$uname,$id,$item,$rules) = @_;
 2098:     my %returnhash;
 2099:     if ($udom ne '') {
 2100:         if (ref($rules) eq 'ARRAY') {
 2101:             @{$rules} = map {&escape($_);} (@{$rules});
 2102:             my $rulestr = join(':',@{$rules});
 2103:             my $homeserver=&domain($udom,'primary');
 2104:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 2105:                 my $response;
 2106:                 if ($item eq 'username') {                
 2107:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 2108:                                               ':'.&escape($uname).':'.$rulestr,
 2109:                                               $homeserver));
 2110:                 } elsif ($item eq 'id') {
 2111:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 2112:                                               ':'.&escape($id).':'.$rulestr,
 2113:                                               $homeserver));
 2114:                 } elsif ($item eq 'selfcreate') {
 2115:                     $response=&unescape(&reply('instselfcreatecheck:'.
 2116:                                                &escape($udom).':'.&escape($uname).
 2117:                                               ':'.$rulestr,$homeserver));
 2118:                 }
 2119:                 if ($response ne 'refused') {
 2120:                     my @pairs=split(/\&/,$response);
 2121:                     foreach my $item (@pairs) {
 2122:                         my ($key,$value)=split(/=/,$item,2);
 2123:                         $key = &unescape($key);
 2124:                         next if ($key =~ /^error: 2 /);
 2125:                         $returnhash{$key}=&thaw_unescape($value);
 2126:                     }
 2127:                 }
 2128:             }
 2129:         }
 2130:     }
 2131:     return %returnhash;
 2132: }
 2133: 
 2134: sub inst_userrules {
 2135:     my ($udom,$check) = @_;
 2136:     my (%ruleshash,@ruleorder);
 2137:     if ($udom ne '') {
 2138:         my $homeserver=&domain($udom,'primary');
 2139:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 2140:             my $response;
 2141:             if ($check eq 'id') {
 2142:                 $response=&reply('instidrules:'.&escape($udom),
 2143:                                  $homeserver);
 2144:             } elsif ($check eq 'email') {
 2145:                 $response=&reply('instemailrules:'.&escape($udom),
 2146:                                  $homeserver);
 2147:             } else {
 2148:                 $response=&reply('instuserrules:'.&escape($udom),
 2149:                                  $homeserver);
 2150:             }
 2151:             if (($response ne 'refused') && ($response ne 'error') && 
 2152:                 ($response ne 'unknown_cmd') && 
 2153:                 ($response ne 'no_such_host')) {
 2154:                 my ($hashitems,$orderitems) = split(/:/,$response);
 2155:                 my @pairs=split(/\&/,$hashitems);
 2156:                 foreach my $item (@pairs) {
 2157:                     my ($key,$value)=split(/=/,$item,2);
 2158:                     $key = &unescape($key);
 2159:                     next if ($key =~ /^error: 2 /);
 2160:                     $ruleshash{$key}=&thaw_unescape($value);
 2161:                 }
 2162:                 my @esc_order = split(/\&/,$orderitems);
 2163:                 foreach my $item (@esc_order) {
 2164:                     push(@ruleorder,&unescape($item));
 2165:                 }
 2166:             }
 2167:         }
 2168:     }
 2169:     return (\%ruleshash,\@ruleorder);
 2170: }
 2171: 
 2172: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 2173: 
 2174: sub get_domain_defaults {
 2175:     my ($domain,$ignore_cache) = @_;
 2176:     return if (($domain eq '') || ($domain eq 'public'));
 2177:     my $cachetime = 60*60*24;
 2178:     unless ($ignore_cache) {
 2179:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 2180:         if (defined($cached)) {
 2181:             if (ref($result) eq 'HASH') {
 2182:                 return %{$result};
 2183:             }
 2184:         }
 2185:     }
 2186:     my %domdefaults;
 2187:     my %domconfig =
 2188:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
 2189:                                   'requestcourses','inststatus',
 2190:                                   'coursedefaults','usersessions',
 2191:                                   'requestauthor','selfenrollment',
 2192:                                   'coursecategories'],$domain);
 2193:     my @coursetypes = ('official','unofficial','community','textbook');
 2194:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 2195:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 2196:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 2197:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 2198:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 2199:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
 2200:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
 2201:     } else {
 2202:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 2203:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 2204:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 2205:     }
 2206:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 2207:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 2208:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 2209:         } else {
 2210:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 2211:         }
 2212:         my @usertools = ('aboutme','blog','webdav','portfolio');
 2213:         foreach my $item (@usertools) {
 2214:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 2215:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 2216:             }
 2217:         }
 2218:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
 2219:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
 2220:         }
 2221:     }
 2222:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 2223:         foreach my $item ('official','unofficial','community','textbook') {
 2224:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
 2225:         }
 2226:     }
 2227:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
 2228:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
 2229:     }
 2230:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
 2231:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
 2232:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
 2233:         }
 2234:     }
 2235:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
 2236:         $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
 2237:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
 2238:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
 2239:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
 2240:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
 2241:         }
 2242:         foreach my $type (@coursetypes) {
 2243:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
 2244:                 unless ($type eq 'community') {
 2245:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
 2246:                 }
 2247:             }
 2248:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
 2249:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
 2250:             }
 2251:             if ($domdefaults{'postsubmit'} eq 'on') {
 2252:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
 2253:                     $domdefaults{$type.'postsubtimeout'} = 
 2254:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type}; 
 2255:                 }
 2256:             }
 2257:         }
 2258:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
 2259:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
 2260:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
 2261:                 if (@clonecodes) {
 2262:                     $domdefaults{'canclone'} = join('+',@clonecodes);
 2263:                 }
 2264:             }
 2265:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
 2266:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
 2267:         }
 2268:     }
 2269:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
 2270:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
 2271:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
 2272:         }
 2273:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
 2274:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
 2275:         }
 2276:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
 2277:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
 2278:         }
 2279:     }
 2280:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
 2281:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
 2282:             my @settings = ('types','registered','enroll_dates','access_dates','section',
 2283:                             'approval','limit');
 2284:             foreach my $type (@coursetypes) {
 2285:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
 2286:                     my @mgrdc = ();
 2287:                     foreach my $item (@settings) {
 2288:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
 2289:                             push(@mgrdc,$item);
 2290:                         }
 2291:                     }
 2292:                     if (@mgrdc) {
 2293:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
 2294:                     }
 2295:                 }
 2296:             }
 2297:         }
 2298:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
 2299:             foreach my $type (@coursetypes) {
 2300:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
 2301:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
 2302:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
 2303:                     }
 2304:                 }
 2305:             }
 2306:         }
 2307:     }
 2308:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 2309:         $domdefaults{'catauth'} = 'std';
 2310:         $domdefaults{'catunauth'} = 'std';
 2311:         if ($domconfig{'coursecategories'}{'auth'}) { 
 2312:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
 2313:         }
 2314:         if ($domconfig{'coursecategories'}{'unauth'}) {
 2315:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
 2316:         }
 2317:     }
 2318:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
 2319:     return %domdefaults;
 2320: }
 2321: 
 2322: # --------------------------------------------------- Assign a key to a student
 2323: 
 2324: sub assign_access_key {
 2325: #
 2326: # a valid key looks like uname:udom#comments
 2327: # comments are being appended
 2328: #
 2329:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 2330:     $kdom=
 2331:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 2332:     $knum=
 2333:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 2334:     $cdom=
 2335:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2336:     $cnum=
 2337:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2338:     $udom=$env{'user.name'} unless (defined($udom));
 2339:     $uname=$env{'user.domain'} unless (defined($uname));
 2340:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 2341:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 2342:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 2343:                                                   # assigned to this person
 2344:                                                   # - this should not happen,
 2345:                                                   # unless something went wrong
 2346:                                                   # the first time around
 2347: # ready to assign
 2348:         $logentry=$1.'; '.$logentry;
 2349:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 2350:                                                  $kdom,$knum) eq 'ok') {
 2351: # key now belongs to user
 2352: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 2353:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 2354:                 &appenv({'environment.'.$envkey => $ckey});
 2355:                 return 'ok';
 2356:             } else {
 2357:                 return 
 2358:   'error: Count not permanently assign key, will need to be re-entered later.';
 2359: 	    }
 2360:         } else {
 2361:             return 'error: Could not assign key, try again later.';
 2362:         }
 2363:     } elsif (!$existing{$ckey}) {
 2364: # the key does not exist
 2365: 	return 'error: The key does not exist';
 2366:     } else {
 2367: # the key is somebody else's
 2368: 	return 'error: The key is already in use';
 2369:     }
 2370: }
 2371: 
 2372: # ------------------------------------------ put an additional comment on a key
 2373: 
 2374: sub comment_access_key {
 2375: #
 2376: # a valid key looks like uname:udom#comments
 2377: # comments are being appended
 2378: #
 2379:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 2380:     $cdom=
 2381:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2382:     $cnum=
 2383:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2384:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2385:     if ($existing{$ckey}) {
 2386:         $existing{$ckey}.='; '.$logentry;
 2387: # ready to assign
 2388:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 2389:                                                  $cdom,$cnum) eq 'ok') {
 2390: 	    return 'ok';
 2391:         } else {
 2392: 	    return 'error: Count not store comment.';
 2393:         }
 2394:     } else {
 2395: # the key does not exist
 2396: 	return 'error: The key does not exist';
 2397:     }
 2398: }
 2399: 
 2400: # ------------------------------------------------------ Generate a set of keys
 2401: 
 2402: sub generate_access_keys {
 2403:     my ($number,$cdom,$cnum,$logentry)=@_;
 2404:     $cdom=
 2405:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2406:     $cnum=
 2407:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2408:     unless (&allowed('mky',$cdom)) { return 0; }
 2409:     unless (($cdom) && ($cnum)) { return 0; }
 2410:     if ($number>10000) { return 0; }
 2411:     sleep(2); # make sure don't get same seed twice
 2412:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 2413:     my $total=0;
 2414:     for (my $i=1;$i<=$number;$i++) {
 2415:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 2416:                   sprintf("%lx",int(100000*rand)).'-'.
 2417:                   sprintf("%lx",int(100000*rand));
 2418:        $newkey=~s/1/g/g; # folks mix up 1 and l
 2419:        $newkey=~s/0/h/g; # and also 0 and O
 2420:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 2421:        if ($existing{$newkey}) {
 2422:            $i--;
 2423:        } else {
 2424: 	  if (&put('accesskeys',
 2425:               { $newkey => '# generated '.localtime().
 2426:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 2427:                            '; '.$logentry },
 2428: 		   $cdom,$cnum) eq 'ok') {
 2429:               $total++;
 2430: 	  }
 2431:        }
 2432:     }
 2433:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 2434:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 2435:     return $total;
 2436: }
 2437: 
 2438: # ------------------------------------------------------- Validate an accesskey
 2439: 
 2440: sub validate_access_key {
 2441:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 2442:     $cdom=
 2443:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2444:     $cnum=
 2445:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2446:     $udom=$env{'user.domain'} unless (defined($udom));
 2447:     $uname=$env{'user.name'} unless (defined($uname));
 2448:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2449:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 2450: }
 2451: 
 2452: # ------------------------------------- Find the section of student in a course
 2453: sub devalidate_getsection_cache {
 2454:     my ($udom,$unam,$courseid)=@_;
 2455:     my $hashid="$udom:$unam:$courseid";
 2456:     &devalidate_cache_new('getsection',$hashid);
 2457: }
 2458: 
 2459: sub courseid_to_courseurl {
 2460:     my ($courseid) = @_;
 2461:     #already url style courseid
 2462:     return $courseid if ($courseid =~ m{^/});
 2463: 
 2464:     if (exists($env{'course.'.$courseid.'.num'})) {
 2465: 	my $cnum = $env{'course.'.$courseid.'.num'};
 2466: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 2467: 	return "/$cdom/$cnum";
 2468:     }
 2469: 
 2470:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 2471:     if (exists($courseinfo{'num'})) {
 2472: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 2473:     }
 2474: 
 2475:     return undef;
 2476: }
 2477: 
 2478: sub getsection {
 2479:     my ($udom,$unam,$courseid)=@_;
 2480:     my $cachetime=1800;
 2481: 
 2482:     my $hashid="$udom:$unam:$courseid";
 2483:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 2484:     if (defined($cached)) { return $result; }
 2485: 
 2486:     my %Pending; 
 2487:     my %Expired;
 2488:     #
 2489:     # Each role can either have not started yet (pending), be active, 
 2490:     #    or have expired.
 2491:     #
 2492:     # If there is an active role, we are done.
 2493:     #
 2494:     # If there is more than one role which has not started yet, 
 2495:     #     choose the one which will start sooner
 2496:     # If there is one role which has not started yet, return it.
 2497:     #
 2498:     # If there is more than one expired role, choose the one which ended last.
 2499:     # If there is a role which has expired, return it.
 2500:     #
 2501:     $courseid = &courseid_to_courseurl($courseid);
 2502:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 2503:     foreach my $key (keys(%roleshash)) {
 2504:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 2505:         my $section=$1;
 2506:         if ($key eq $courseid.'_st') { $section=''; }
 2507:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 2508:         my $now=time;
 2509:         if (defined($end) && $end && ($now > $end)) {
 2510:             $Expired{$end}=$section;
 2511:             next;
 2512:         }
 2513:         if (defined($start) && $start && ($now < $start)) {
 2514:             $Pending{$start}=$section;
 2515:             next;
 2516:         }
 2517:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 2518:     }
 2519:     #
 2520:     # Presumedly there will be few matching roles from the above
 2521:     # loop and the sorting time will be negligible.
 2522:     if (scalar(keys(%Pending))) {
 2523:         my ($time) = sort {$a <=> $b} keys(%Pending);
 2524:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 2525:     } 
 2526:     if (scalar(keys(%Expired))) {
 2527:         my @sorted = sort {$a <=> $b} keys(%Expired);
 2528:         my $time = pop(@sorted);
 2529:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 2530:     }
 2531:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 2532: }
 2533: 
 2534: sub save_cache {
 2535:     &purge_remembered();
 2536:     #&Apache::loncommon::validate_page();
 2537:     undef(%env);
 2538:     undef($env_loaded);
 2539: }
 2540: 
 2541: my $to_remember=-1;
 2542: my %remembered;
 2543: my %accessed;
 2544: my $kicks=0;
 2545: my $hits=0;
 2546: sub make_key {
 2547:     my ($name,$id) = @_;
 2548:     if (length($id) > 65 
 2549: 	&& length(&escape($id)) > 200) {
 2550: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 2551:     }
 2552:     return &escape($name.':'.$id);
 2553: }
 2554: 
 2555: sub devalidate_cache_new {
 2556:     my ($name,$id,$debug) = @_;
 2557:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 2558:     $id=&make_key($name,$id);
 2559:     $memcache->delete($id);
 2560:     delete($remembered{$id});
 2561:     delete($accessed{$id});
 2562: }
 2563: 
 2564: sub is_cached_new {
 2565:     my ($name,$id,$debug) = @_;
 2566:     $id=&make_key($name,$id);
 2567:     if (exists($remembered{$id})) {
 2568: 	if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
 2569: 	$accessed{$id}=[&gettimeofday()];
 2570: 	$hits++;
 2571: 	return ($remembered{$id},1);
 2572:     }
 2573:     my $value = $memcache->get($id);
 2574:     if (!(defined($value))) {
 2575: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 2576: 	return (undef,undef);
 2577:     }
 2578:     if ($value eq '__undef__') {
 2579: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 2580: 	$value=undef;
 2581:     }
 2582:     &make_room($id,$value,$debug);
 2583:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 2584:     return ($value,1);
 2585: }
 2586: 
 2587: sub do_cache_new {
 2588:     my ($name,$id,$value,$time,$debug) = @_;
 2589:     $id=&make_key($name,$id);
 2590:     my $setvalue=$value;
 2591:     if (!defined($setvalue)) {
 2592: 	$setvalue='__undef__';
 2593:     }
 2594:     if (!defined($time) ) {
 2595: 	$time=600;
 2596:     }
 2597:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 2598:     my $result = $memcache->set($id,$setvalue,$time);
 2599:     if (! $result) {
 2600: 	&logthis("caching of id -> $id  failed");
 2601: 	$memcache->disconnect_all();
 2602:     }
 2603:     # need to make a copy of $value
 2604:     &make_room($id,$value,$debug);
 2605:     return $value;
 2606: }
 2607: 
 2608: sub make_room {
 2609:     my ($id,$value,$debug)=@_;
 2610: 
 2611:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
 2612:                                     : $value;
 2613:     if ($to_remember<0) { return; }
 2614:     $accessed{$id}=[&gettimeofday()];
 2615:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 2616:     my $to_kick;
 2617:     my $max_time=0;
 2618:     foreach my $other (keys(%accessed)) {
 2619: 	if (&tv_interval($accessed{$other}) > $max_time) {
 2620: 	    $to_kick=$other;
 2621: 	    $max_time=&tv_interval($accessed{$other});
 2622: 	}
 2623:     }
 2624:     delete($remembered{$to_kick});
 2625:     delete($accessed{$to_kick});
 2626:     $kicks++;
 2627:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 2628:     return;
 2629: }
 2630: 
 2631: sub purge_remembered {
 2632:     #&logthis("Tossing ".scalar(keys(%remembered)));
 2633:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 2634:     undef(%remembered);
 2635:     undef(%accessed);
 2636: }
 2637: # ------------------------------------- Read an entry from a user's environment
 2638: 
 2639: sub userenvironment {
 2640:     my ($udom,$unam,@what)=@_;
 2641:     my $items;
 2642:     foreach my $item (@what) {
 2643:         $items.=&escape($item).'&';
 2644:     }
 2645:     $items=~s/\&$//;
 2646:     my %returnhash=();
 2647:     my $uhome = &homeserver($unam,$udom);
 2648:     unless ($uhome eq 'no_host') {
 2649:         my @answer=split(/\&/, 
 2650:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
 2651:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
 2652:             return %returnhash;
 2653:         }
 2654:         my $i;
 2655:         for ($i=0;$i<=$#what;$i++) {
 2656: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
 2657:         }
 2658:     }
 2659:     return %returnhash;
 2660: }
 2661: 
 2662: # ---------------------------------------------------------- Get a studentphoto
 2663: sub studentphoto {
 2664:     my ($udom,$unam,$ext) = @_;
 2665:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 2666:     if (defined($env{'request.course.id'})) {
 2667:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 2668:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 2669:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 2670:             } else {
 2671:                 my ($result,$perm_reqd)=
 2672: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 2673:                 if ($result eq 'ok') {
 2674:                     if (!($perm_reqd eq 'yes')) {
 2675:                         return(&retrievestudentphoto($udom,$unam,$ext));
 2676:                     }
 2677:                 }
 2678:             }
 2679:         }
 2680:     } else {
 2681:         my ($result,$perm_reqd) = 
 2682: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 2683:         if ($result eq 'ok') {
 2684:             if (!($perm_reqd eq 'yes')) {
 2685:                 return(&retrievestudentphoto($udom,$unam,$ext));
 2686:             }
 2687:         }
 2688:     }
 2689:     return '/adm/lonKaputt/lonlogo_broken.gif';
 2690: }
 2691: 
 2692: sub retrievestudentphoto {
 2693:     my ($udom,$unam,$ext,$type) = @_;
 2694:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 2695:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 2696:     if ($ret eq 'ok') {
 2697:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 2698:         if ($type eq 'thumbnail') {
 2699:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 2700:         }
 2701:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 2702:         return $tokenurl;
 2703:     } else {
 2704:         if ($type eq 'thumbnail') {
 2705:             return '/adm/lonKaputt/genericstudent_tn.gif';
 2706:         } else { 
 2707:             return '/adm/lonKaputt/lonlogo_broken.gif';
 2708:         }
 2709:     }
 2710: }
 2711: 
 2712: # -------------------------------------------------------------------- New chat
 2713: 
 2714: sub chatsend {
 2715:     my ($newentry,$anon,$group)=@_;
 2716:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 2717:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2718:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 2719:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 2720: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 2721: 		   &escape($newentry)).':'.$group,$chome);
 2722: }
 2723: 
 2724: # ------------------------------------------ Find current version of a resource
 2725: 
 2726: sub getversion {
 2727:     my $fname=&clutter(shift);
 2728:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
 2729:     return &currentversion(&filelocation('',$fname));
 2730: }
 2731: 
 2732: sub currentversion {
 2733:     my $fname=shift;
 2734:     my $author=$fname;
 2735:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2736:     my ($udom,$uname)=split(/\//,$author);
 2737:     my $home=&homeserver($uname,$udom);
 2738:     if ($home eq 'no_host') { 
 2739:         return -1; 
 2740:     }
 2741:     my $answer=&reply("currentversion:$fname",$home);
 2742:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 2743: 	return -1;
 2744:     }
 2745:     return $answer;
 2746: }
 2747: 
 2748: #
 2749: # Return special version number of resource if set by override, empty otherwise
 2750: #
 2751: sub usedversion {
 2752:     my $fname=shift;
 2753:     unless ($fname) { $fname=$env{'request.uri'}; }
 2754:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
 2755:     if ($urlversion) { return $urlversion; }
 2756:     return '';
 2757: }
 2758: 
 2759: # ----------------------------- Subscribe to a resource, return URL if possible
 2760: 
 2761: sub subscribe {
 2762:     my $fname=shift;
 2763:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 2764:     $fname=~s/[\n\r]//g;
 2765:     my $author=$fname;
 2766:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2767:     my ($udom,$uname)=split(/\//,$author);
 2768:     my $home=homeserver($uname,$udom);
 2769:     if ($home eq 'no_host') {
 2770:         return 'not_found';
 2771:     }
 2772:     my $answer=reply("sub:$fname",$home);
 2773:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 2774: 	$answer.=' by '.$home;
 2775:     }
 2776:     return $answer;
 2777: }
 2778:     
 2779: # -------------------------------------------------------------- Replicate file
 2780: 
 2781: sub repcopy {
 2782:     my $filename=shift;
 2783:     $filename=~s/\/+/\//g;
 2784:     my $londocroot = $perlvar{'lonDocRoot'};
 2785:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
 2786:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
 2787:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
 2788: 	$filename=~m{^/*(uploaded|editupload)/}) {
 2789: 	return &repcopy_userfile($filename);
 2790:     }
 2791:     $filename=~s/[\n\r]//g;
 2792:     my $transname="$filename.in.transfer";
 2793: # FIXME: this should flock
 2794:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 2795:     my $remoteurl=subscribe($filename);
 2796:     if ($remoteurl =~ /^con_lost by/) {
 2797: 	   &logthis("Subscribe returned $remoteurl: $filename");
 2798:            return 'unavailable';
 2799:     } elsif ($remoteurl eq 'not_found') {
 2800: 	   #&logthis("Subscribe returned not_found: $filename");
 2801: 	   return 'not_found';
 2802:     } elsif ($remoteurl =~ /^rejected by/) {
 2803: 	   &logthis("Subscribe returned $remoteurl: $filename");
 2804:            return 'forbidden';
 2805:     } elsif ($remoteurl eq 'directory') {
 2806:            return 'ok';
 2807:     } else {
 2808:         my $author=$filename;
 2809:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2810:         my ($udom,$uname)=split(/\//,$author);
 2811:         my $home=homeserver($uname,$udom);
 2812:         unless ($home eq $perlvar{'lonHostID'}) {
 2813:            my @parts=split(/\//,$filename);
 2814:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 2815:            if ($path ne "$londocroot/res") {
 2816:                &logthis("Malconfiguration for replication: $filename");
 2817: 	       return 'bad_request';
 2818:            }
 2819:            my $count;
 2820:            for ($count=5;$count<$#parts;$count++) {
 2821:                $path.="/$parts[$count]";
 2822:                if ((-e $path)!=1) {
 2823: 		   mkdir($path,0777);
 2824:                }
 2825:            }
 2826:            my $ua=new LWP::UserAgent;
 2827:            my $request=new HTTP::Request('GET',"$remoteurl");
 2828:            my $response=$ua->request($request,$transname);
 2829:            if ($response->is_error()) {
 2830: 	       unlink($transname);
 2831:                my $message=$response->status_line;
 2832:                &logthis("<font color=\"blue\">WARNING:"
 2833:                        ." LWP get: $message: $filename</font>");
 2834:                return 'unavailable';
 2835:            } else {
 2836: 	       if ($remoteurl!~/\.meta$/) {
 2837:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 2838:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
 2839:                   if ($mresponse->is_error()) {
 2840: 		      unlink($filename.'.meta');
 2841:                       &logthis(
 2842:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 2843:                   }
 2844: 	       }
 2845:                rename($transname,$filename);
 2846:                return 'ok';
 2847:            }
 2848:        }
 2849:     }
 2850: }
 2851: 
 2852: # ------------------------------------------------ Get server side include body
 2853: sub ssi_body {
 2854:     my ($filelink,%form)=@_;
 2855:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 2856:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 2857:     }
 2858:     my $output='';
 2859:     my $response;
 2860:     if ($filelink=~/^https?\:/) {
 2861:        ($output,$response)=&externalssi($filelink);
 2862:     } else {
 2863:        $filelink .= $filelink=~/\?/ ? '&' : '?';
 2864:        $filelink .= 'inhibitmenu=yes';
 2865:        ($output,$response)=&ssi($filelink,%form);
 2866:     }
 2867:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 2868:     $output=~s/^.*?\<body[^\>]*\>//si;
 2869:     $output=~s/\<\/body\s*\>.*?$//si;
 2870:     if (wantarray) {
 2871:         return ($output, $response);
 2872:     } else {
 2873:         return $output;
 2874:     }
 2875: }
 2876: 
 2877: # --------------------------------------------------------- Server Side Include
 2878: 
 2879: sub absolute_url {
 2880:     my ($host_name) = @_;
 2881:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 2882:     if ($host_name eq '') {
 2883: 	$host_name = $ENV{'SERVER_NAME'};
 2884:     }
 2885:     return $protocol.$host_name;
 2886: }
 2887: 
 2888: #
 2889: #   Server side include.
 2890: # Parameters:
 2891: #  fn     Possibly encrypted resource name/id.
 2892: #  form   Hash that describes how the rendering should be done
 2893: #         and other things.
 2894: # Returns:
 2895: #   Scalar context: The content of the response.
 2896: #   Array context:  2 element list of the content and the full response object.
 2897: #     
 2898: sub ssi {
 2899: 
 2900:     my ($fn,%form)=@_;
 2901:     my $ua=new LWP::UserAgent;
 2902:     my $request;
 2903: 
 2904:     $form{'no_update_last_known'}=1;
 2905:     &Apache::lonenc::check_encrypt(\$fn);
 2906:     if (%form) {
 2907:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 2908:       $request->content(join('&',map { 
 2909:             my $name = escape($_);
 2910:             "$name=" . ( ref($form{$_}) eq 'ARRAY' 
 2911:             ? join("&$name=", map {escape($_) } @{$form{$_}}) 
 2912:             : &escape($form{$_}) );    
 2913:         } keys(%form)));
 2914:     } else {
 2915:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 2916:     }
 2917: 
 2918:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 2919:     my $response= $ua->request($request);
 2920:     my $content = $response->content;
 2921: 
 2922: 
 2923:     if (wantarray) {
 2924: 	return ($content, $response);
 2925:     } else {
 2926: 	return $content;
 2927:     }
 2928: }
 2929: 
 2930: sub externalssi {
 2931:     my ($url)=@_;
 2932:     my $ua=new LWP::UserAgent;
 2933:     my $request=new HTTP::Request('GET',$url);
 2934:     my $response=$ua->request($request);
 2935:     if (wantarray) {
 2936:         return ($response->content, $response);
 2937:     } else {
 2938:         return $response->content;
 2939:     }
 2940: }
 2941: 
 2942: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 2943: 
 2944: sub allowuploaded {
 2945:     my ($srcurl,$url)=@_;
 2946:     $url=&clutter(&declutter($url));
 2947:     my $dir=$url;
 2948:     $dir=~s/\/[^\/]+$//;
 2949:     my %httpref=();
 2950:     my $httpurl=&hreflocation('',$url);
 2951:     $httpref{'httpref.'.$httpurl}=$srcurl;
 2952:     &Apache::lonnet::appenv(\%httpref);
 2953: }
 2954: 
 2955: #
 2956: # Determine if the current user should be able to edit a particular resource,
 2957: # when viewing in course context.
 2958: # (a) When viewing resource used to determine if "Edit" item is included in 
 2959: #     Functions.
 2960: # (b) When displaying folder contents in course editor, used to determine if
 2961: #     "Edit" link will be displayed alongside resource.
 2962: #
 2963: #  input: six args -- filename (decluttered), course number, course domain,
 2964: #                   url, symb (if registered) and group (if this is a group
 2965: #                   item -- e.g., bulletin board, group page etc.).
 2966: #  output: array of five scalars -- 
 2967: #          $cfile -- url for file editing if editable on current server
 2968: #          $home -- homeserver of resource (i.e., for author if published,
 2969: #                                           or course if uploaded.).
 2970: #          $switchserver --  1 if server switch will be needed.
 2971: #          $forceedit -- 1 if icon/link should be to go to edit mode 
 2972: #          $forceview -- 1 if icon/link should be to go to view mode
 2973: #
 2974: 
 2975: sub can_edit_resource {
 2976:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
 2977:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
 2978: #
 2979: # For aboutme pages user can only edit his/her own.
 2980: #
 2981:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
 2982:         my ($sdom,$sname) = ($1,$2);
 2983:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
 2984:             $home = $env{'user.home'};
 2985:             $cfile = $resurl;
 2986:             if ($env{'form.forceedit'}) {
 2987:                 $forceview = 1;
 2988:             } else {
 2989:                 $forceedit = 1;
 2990:             }
 2991:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
 2992:         } else {
 2993:             return;
 2994:         }
 2995:     }
 2996: 
 2997:     if ($env{'request.course.id'}) {
 2998:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
 2999:         if ($group ne '') {
 3000: # if this is a group homepage or group bulletin board, check group privs
 3001:             my $allowed = 0;
 3002:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
 3003:                 if ((&allowed('mdg',$env{'request.course.id'}.
 3004:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 3005:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 3006:                     $allowed = 1;
 3007:                 }
 3008:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
 3009:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 3010:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 3011:                     $allowed = 1;
 3012:                 }
 3013:             }
 3014:             if ($allowed) {
 3015:                 $home=&homeserver($cnum,$cdom);
 3016:                 if ($env{'form.forceedit'}) {
 3017:                     $forceview = 1;
 3018:                 } else {
 3019:                     $forceedit = 1;
 3020:                 }
 3021:                 $cfile = $resurl;
 3022:             } else {
 3023:                 return;
 3024:             }
 3025:         } else {
 3026:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
 3027:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
 3028:                     return;
 3029:                 }
 3030:             } elsif (!$crsedit) {
 3031: #
 3032: # No edit allowed where CC has switched to student role.
 3033: #
 3034:                 return;
 3035:             }
 3036:         }
 3037:     }
 3038: 
 3039:     if ($file ne '') {
 3040:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
 3041:             if (&is_course_upload($file,$cnum,$cdom)) {
 3042:                 $uploaded = 1;
 3043:                 $incourse = 1;
 3044:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
 3045:                     $cfile = &hreflocation('',$file);
 3046:                     if ($env{'form.forceedit'}) {
 3047:                         $forceview = 1;
 3048:                     } else {
 3049:                         $forceedit = 1;
 3050:                     }
 3051:                 }
 3052:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
 3053:                 $incourse = 1;
 3054:                 if ($env{'form.forceedit'}) {
 3055:                     $forceview = 1;
 3056:                 } else {
 3057:                     $forceedit = 1;
 3058:                 }
 3059:                 $cfile = $resurl;
 3060:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
 3061:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
 3062:                     $incourse = 1;
 3063:                     if ($env{'form.forceedit'}) {
 3064:                         $forceview = 1;
 3065:                     } else {
 3066:                         $forceedit = 1;
 3067:                     }
 3068:                     $cfile = $resurl;
 3069:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
 3070:                     $incourse = 1;
 3071:                     $cfile = $resurl.'/smpedit';
 3072:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
 3073:                     $incourse = 1;
 3074:                     if ($env{'form.forceedit'}) {
 3075:                         $forceview = 1;
 3076:                     } else {
 3077:                         $forceedit = 1;
 3078:                     }
 3079:                     $cfile = $resurl;
 3080:                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/exttools?$}) {
 3081:                     $incourse = 1;
 3082:                     if ($env{'form.forceedit'}) {
 3083:                         $forceview = 1;
 3084:                     } else {
 3085:                         $forceedit = 1;
 3086:                     }
 3087:                     $cfile = $resurl;
 3088:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 3089:                     $incourse = 1;
 3090:                     if ($env{'form.forceedit'}) {
 3091:                         $forceview = 1;
 3092:                     } else {
 3093:                         $forceedit = 1;
 3094:                     }
 3095:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 3096:                 }
 3097:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
 3098:                 my $template = '/res/lib/templates/simpleproblem.problem';
 3099:                 if (&is_on_map($template)) { 
 3100:                     $incourse = 1;
 3101:                     $forceview = 1;
 3102:                     $cfile = $template;
 3103:                 }
 3104:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 3105:                     $incourse = 1;
 3106:                     if ($env{'form.forceedit'}) {
 3107:                         $forceview = 1;
 3108:                     } else {
 3109:                         $forceedit = 1;
 3110:                     }
 3111:                     $cfile = $resurl;
 3112:             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/exttools?$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 3113:                 $incourse = 1;
 3114:                 if ($env{'form.forceedit'}) {
 3115:                     $forceview = 1;
 3116:                 } else {
 3117:                     $forceedit = 1;
 3118:                 }
 3119:                 $cfile = $resurl;
 3120:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
 3121:                 $incourse = 1;
 3122:                 $forceview = 1;
 3123:                 if ($symb) {
 3124:                     my ($map,$id,$res)=&decode_symb($symb);
 3125:                     $env{'request.symb'} = $symb;
 3126:                     $cfile = &clutter($res);
 3127:                 } else {
 3128:                     $cfile = $env{'form.suppurl'};
 3129:                     my $escfile = &unescape($cfile);
 3130:                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/exttools?$}) {
 3131:                         $cfile = '/adm/wrapper'.$escfile;
 3132:                     } else {
 3133:                         $escfile =~ s{^http://}{};
 3134:                         $cfile = &escape("/adm/wrapper/ext/$escfile");
 3135:                     }
 3136:                 }
 3137:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 3138:                 if ($env{'form.forceedit'}) {
 3139:                     $forceview = 1;
 3140:                 } else {
 3141:                     $forceedit = 1;
 3142:                 }
 3143:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 3144:             }
 3145:         }
 3146:         if ($uploaded || $incourse) {
 3147:             $home=&homeserver($cnum,$cdom);
 3148:         } elsif ($file !~ m{/$}) {
 3149:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
 3150:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
 3151:             # Check that the user has permission to edit this resource
 3152:             my $setpriv = 1;
 3153:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
 3154:             if (defined($cfudom)) {
 3155:                 $home=&homeserver($cfuname,$cfudom);
 3156:                 $cfile=$file;
 3157:             }
 3158:         }
 3159:         if (($cfile ne '') && (!$incourse || $uploaded) && 
 3160:             (($home ne '') && ($home ne 'no_host'))) {
 3161:             my @ids=&current_machine_ids();
 3162:             unless (grep(/^\Q$home\E$/,@ids)) {
 3163:                 $switchserver=1;
 3164:             }
 3165:         }
 3166:     }
 3167:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
 3168: }
 3169: 
 3170: sub is_course_upload {
 3171:     my ($file,$cnum,$cdom) = @_;
 3172:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
 3173:     $uploadpath =~ s{^\/}{};
 3174:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
 3175:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
 3176:         return 1;
 3177:     }
 3178:     return;
 3179: }
 3180: 
 3181: sub in_course {
 3182:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
 3183:     if ($hideprivileged) {
 3184:         my $skipuser;
 3185:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
 3186:         my @possdoms = ($cdom);  
 3187:         if ($coursehash{'checkforpriv'}) { 
 3188:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
 3189:         }
 3190:         if (&privileged($uname,$udom,\@possdoms)) {
 3191:             $skipuser = 1;
 3192:             if ($coursehash{'nothideprivileged'}) {
 3193:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3194:                     my $user;
 3195:                     if ($item =~ /:/) {
 3196:                         $user = $item;
 3197:                     } else {
 3198:                         $user = join(':',split(/[\@]/,$item));
 3199:                     }
 3200:                     if ($user eq $uname.':'.$udom) {
 3201:                         undef($skipuser);
 3202:                         last;
 3203:                     }
 3204:                 }
 3205:             }
 3206:             if ($skipuser) {
 3207:                 return 0;
 3208:             }
 3209:         }
 3210:     }
 3211:     $type ||= 'any';
 3212:     if (!defined($cdom) || !defined($cnum)) {
 3213:         my $cid  = $env{'request.course.id'};
 3214:         $cdom = $env{'course.'.$cid.'.domain'};
 3215:         $cnum = $env{'course.'.$cid.'.num'};
 3216:     }
 3217:     my $typesref;
 3218:     if (($type eq 'any') || ($type eq 'all')) {
 3219:         $typesref = ['active','previous','future'];
 3220:     } elsif ($type eq 'previous' || $type eq 'future') {
 3221:         $typesref = [$type];
 3222:     }
 3223:     my %roles = &get_my_roles($uname,$udom,'userroles',
 3224:                               $typesref,undef,[$cdom]);
 3225:     my ($tmp) = keys(%roles);
 3226:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
 3227:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
 3228:     if (@course_roles > 0) {
 3229:         return 1;
 3230:     }
 3231:     return 0;
 3232: }
 3233: 
 3234: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 3235: # input: action, courseID, current domain, intended
 3236: #        path to file, source of file, instruction to parse file for objects,
 3237: #        ref to hash for embedded objects,
 3238: #        ref to hash for codebase of java objects.
 3239: #        reference to scalar to accommodate mime type determined
 3240: #          from File::MMagic if $parser = parse.
 3241: #
 3242: # output: url to file (if action was uploaddoc), 
 3243: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 3244: #
 3245: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 3246: # course.
 3247: #
 3248: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3249: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 3250: #          course's home server.
 3251: #
 3252: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 3253: #          be copied from $source (current location) to 
 3254: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3255: #         and will then be copied to
 3256: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 3257: #         course's home server.
 3258: #
 3259: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3260: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 3261: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3262: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 3263: #         in course's home server.
 3264: #
 3265: 
 3266: sub process_coursefile {
 3267:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
 3268:         $mimetype)=@_;
 3269:     my $fetchresult;
 3270:     my $home=&homeserver($docuname,$docudom);
 3271:     if ($action eq 'propagate') {
 3272:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3273: 			     $home);
 3274:     } else {
 3275:         my $fpath = '';
 3276:         my $fname = $file;
 3277:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3278:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3279:         my $filepath = &build_filepath($fpath);
 3280:         if ($action eq 'copy') {
 3281:             if ($source eq '') {
 3282:                 $fetchresult = 'no source file';
 3283:                 return $fetchresult;
 3284:             } else {
 3285:                 my $destination = $filepath.'/'.$fname;
 3286:                 rename($source,$destination);
 3287:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3288:                                  $home);
 3289:             }
 3290:         } elsif ($action eq 'uploaddoc') {
 3291:             open(my $fh,'>'.$filepath.'/'.$fname);
 3292:             print $fh $env{'form.'.$source};
 3293:             close($fh);
 3294:             if ($parser eq 'parse') {
 3295:                 my $mm = new File::MMagic;
 3296:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
 3297:                 if ($type eq 'text/html') {
 3298:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 3299:                     unless ($parse_result eq 'ok') {
 3300:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 3301:                     }
 3302:                 }
 3303:                 if (ref($mimetype)) {
 3304:                     $$mimetype = $type;
 3305:                 } 
 3306:             }
 3307:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3308:                                  $home);
 3309:             if ($fetchresult eq 'ok') {
 3310:                 return '/uploaded/'.$fpath.'/'.$fname;
 3311:             } else {
 3312:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3313:                         ' to host '.$home.': '.$fetchresult);
 3314:                 return '/adm/notfound.html';
 3315:             }
 3316:         }
 3317:     }
 3318:     unless ( $fetchresult eq 'ok') {
 3319:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3320:              ' to host '.$home.': '.$fetchresult);
 3321:     }
 3322:     return $fetchresult;
 3323: }
 3324: 
 3325: sub build_filepath {
 3326:     my ($fpath) = @_;
 3327:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 3328:     unless ($fpath eq '') {
 3329:         my @parts=split('/',$fpath);
 3330:         foreach my $part (@parts) {
 3331:             $filepath.= '/'.$part;
 3332:             if ((-e $filepath)!=1) {
 3333:                 mkdir($filepath,0777);
 3334:             }
 3335:         }
 3336:     }
 3337:     return $filepath;
 3338: }
 3339: 
 3340: sub store_edited_file {
 3341:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 3342:     my $file = $primary_url;
 3343:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 3344:     my $fpath = '';
 3345:     my $fname = $file;
 3346:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3347:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3348:     my $filepath = &build_filepath($fpath);
 3349:     open(my $fh,'>'.$filepath.'/'.$fname);
 3350:     print $fh $content;
 3351:     close($fh);
 3352:     my $home=&homeserver($docuname,$docudom);
 3353:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3354: 			  $home);
 3355:     if ($$fetchresult eq 'ok') {
 3356:         return '/uploaded/'.$fpath.'/'.$fname;
 3357:     } else {
 3358:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3359: 		 ' to host '.$home.': '.$$fetchresult);
 3360:         return '/adm/notfound.html';
 3361:     }
 3362: }
 3363: 
 3364: sub clean_filename {
 3365:     my ($fname,$args)=@_;
 3366: # Replace Windows backslashes by forward slashes
 3367:     $fname=~s/\\/\//g;
 3368:     if (!$args->{'keep_path'}) {
 3369:         # Get rid of everything but the actual filename
 3370: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 3371:     }
 3372: # Replace spaces by underscores
 3373:     $fname=~s/\s+/\_/g;
 3374: # Replace all other weird characters by nothing
 3375:     $fname=~s{[^/\w\.\-]}{}g;
 3376: # Replace all .\d. sequences with _\d. so they no longer look like version
 3377: # numbers
 3378:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 3379:     return $fname;
 3380: }
 3381: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
 3382: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
 3383: # image with the same aspect ratio as the original, but with dimensions which do 
 3384: # not exceed $resizewidth and $resizeheight.
 3385:  
 3386: sub resizeImage {
 3387:     my ($img_path,$resizewidth,$resizeheight) = @_;
 3388:     my $ima = Image::Magick->new;
 3389:     my $resized;
 3390:     if (-e $img_path) {
 3391:         $ima->Read($img_path);
 3392:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
 3393:             my $width = $ima->Get('width');
 3394:             my $height = $ima->Get('height');
 3395:             if ($width > $resizewidth) {
 3396: 	        my $factor = $width/$resizewidth;
 3397:                 my $newheight = $height/$factor;
 3398:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
 3399:                 $resized = 1;
 3400:             }
 3401:         }
 3402:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
 3403:             my $width = $ima->Get('width');
 3404:             my $height = $ima->Get('height');
 3405:             if ($height > $resizeheight) {
 3406:                 my $factor = $height/$resizeheight;
 3407:                 my $newwidth = $width/$factor;
 3408:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
 3409:                 $resized = 1;
 3410:             }
 3411:         }
 3412:         if ($resized) {
 3413:             $ima->Write($img_path);
 3414:         }
 3415:     }
 3416:     return;
 3417: }
 3418: 
 3419: # --------------- Take an uploaded file and put it into the userfiles directory
 3420: # input: $formname - the contents of the file are in $env{"form.$formname"}
 3421: #                    the desired filename is in $env{"form.$formname.filename"}
 3422: #        $context - possible values: coursedoc, existingfile, overwrite, 
 3423: #                                    canceloverwrite, or ''. 
 3424: #                   if 'coursedoc': upload to the current course
 3425: #                   if 'existingfile': write file to tmp/overwrites directory 
 3426: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
 3427: #                   $context is passed as argument to &finishuserfileupload
 3428: #        $subdir - directory in userfile to store the file into
 3429: #        $parser - instruction to parse file for objects ($parser = parse)    
 3430: #        $allfiles - reference to hash for embedded objects
 3431: #        $codebase - reference to hash for codebase of java objects
 3432: #        $desuname - username for permanent storage of uploaded file
 3433: #        $dsetudom - domain for permanaent storage of uploaded file
 3434: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 3435: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 3436: #        $resizewidth - width (pixels) to which to resize uploaded image
 3437: #        $resizeheight - height (pixels) to which to resize uploaded image
 3438: #        $mimetype - reference to scalar to accommodate mime type determined
 3439: #                    from File::MMagic.
 3440: # 
 3441: # output: url of file in userspace, or error: <message> 
 3442: #             or /adm/notfound.html if failure to upload occurse
 3443: 
 3444: sub userfileupload {
 3445:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
 3446:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
 3447:     if (!defined($subdir)) { $subdir='unknown'; }
 3448:     my $fname=$env{'form.'.$formname.'.filename'};
 3449:     $fname=&clean_filename($fname);
 3450:     # See if there is anything left
 3451:     unless ($fname) { return 'error: no uploaded file'; }
 3452:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
 3453:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
 3454:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
 3455:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3456:         my $now = time;
 3457:         my $filepath;
 3458:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
 3459:              $filepath = 'tmp/helprequests/'.$now;
 3460:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
 3461:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 3462:                          '_'.$env{'user.domain'}.'/pending';
 3463:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3464:             my ($docuname,$docudom);
 3465:             if ($destudom) {
 3466:                 $docudom = $destudom;
 3467:             } else {
 3468:                 $docudom = $env{'user.domain'};
 3469:             }
 3470:             if ($destuname) {
 3471:                 $docuname = $destuname;
 3472:             } else {
 3473:                 $docuname = $env{'user.name'};
 3474:             }
 3475:             if (exists($env{'form.group'})) {
 3476:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3477:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3478:             }
 3479:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
 3480:             if ($context eq 'canceloverwrite') {
 3481:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
 3482:                 if (-e  $tempfile) {
 3483:                     my @info = stat($tempfile);
 3484:                     if ($info[9] eq $env{'form.timestamp'}) {
 3485:                         unlink($tempfile);
 3486:                     }
 3487:                 }
 3488:                 return;
 3489:             }
 3490:         }
 3491:         # Create the directory if not present
 3492:         my @parts=split(/\//,$filepath);
 3493:         my $fullpath = $perlvar{'lonDaemons'};
 3494:         for (my $i=0;$i<@parts;$i++) {
 3495:             $fullpath .= '/'.$parts[$i];
 3496:             if ((-e $fullpath)!=1) {
 3497:                 mkdir($fullpath,0777);
 3498:             }
 3499:         }
 3500:         open(my $fh,'>'.$fullpath.'/'.$fname);
 3501:         print $fh $env{'form.'.$formname};
 3502:         close($fh);
 3503:         if ($context eq 'existingfile') {
 3504:             my @info = stat($fullpath.'/'.$fname);
 3505:             return ($fullpath.'/'.$fname,$info[9]);
 3506:         } else {
 3507:             return $fullpath.'/'.$fname;
 3508:         }
 3509:     }
 3510:     if ($subdir eq 'scantron') {
 3511:         $fname = 'scantron_orig_'.$fname;
 3512:     } else {
 3513:         $fname="$subdir/$fname";
 3514:     }
 3515:     if ($context eq 'coursedoc') {
 3516: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3517: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3518:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 3519:             return &finishuserfileupload($docuname,$docudom,
 3520: 					 $formname,$fname,$parser,$allfiles,
 3521: 					 $codebase,$thumbwidth,$thumbheight,
 3522:                                          $resizewidth,$resizeheight,$context,$mimetype);
 3523:         } else {
 3524:             if ($env{'form.folder'}) {
 3525:                 $fname=$env{'form.folder'}.'/'.$fname;
 3526:             }
 3527:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 3528: 				       $fname,$formname,$parser,
 3529: 				       $allfiles,$codebase,$mimetype);
 3530:         }
 3531:     } elsif (defined($destuname)) {
 3532:         my $docuname=$destuname;
 3533:         my $docudom=$destudom;
 3534: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 3535: 				     $parser,$allfiles,$codebase,
 3536:                                      $thumbwidth,$thumbheight,
 3537:                                      $resizewidth,$resizeheight,$context,$mimetype);
 3538:     } else {
 3539:         my $docuname=$env{'user.name'};
 3540:         my $docudom=$env{'user.domain'};
 3541:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
 3542:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3543:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3544:         }
 3545: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 3546: 				     $parser,$allfiles,$codebase,
 3547:                                      $thumbwidth,$thumbheight,
 3548:                                      $resizewidth,$resizeheight,$context,$mimetype);
 3549:     }
 3550: }
 3551: 
 3552: sub finishuserfileupload {
 3553:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 3554:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
 3555:     my $path=$docudom.'/'.$docuname.'/';
 3556:     my $filepath=$perlvar{'lonDocRoot'};
 3557:   
 3558:     my ($fnamepath,$file,$fetchthumb);
 3559:     $file=$fname;
 3560:     if ($fname=~m|/|) {
 3561:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 3562: 	$path.=$fnamepath.'/';
 3563:     }
 3564:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 3565:     my $count;
 3566:     for ($count=4;$count<=$#parts;$count++) {
 3567:         $filepath.="/$parts[$count]";
 3568:         if ((-e $filepath)!=1) {
 3569: 	    mkdir($filepath,0777);
 3570:         }
 3571:     }
 3572: 
 3573: # Save the file
 3574:     {
 3575: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
 3576: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 3577: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 3578: 	    return '/adm/notfound.html';
 3579: 	}
 3580:         if ($context eq 'overwrite') {
 3581:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
 3582:             my $target = $filepath.'/'.$file;
 3583:             if (-e $source) {
 3584:                 my @info = stat($source);
 3585:                 if ($info[9] eq $env{'form.timestamp'}) {   
 3586:                     unless (&File::Copy::move($source,$target)) {
 3587:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
 3588:                         return "Moving from $source failed";
 3589:                     }
 3590:                 } else {
 3591:                     return "Temporary file: $source had unexpected date/time for last modification";
 3592:                 }
 3593:             } else {
 3594:                 return "Temporary file: $source missing";
 3595:             }
 3596:         } elsif (!print FH ($env{'form.'.$formname})) {
 3597: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 3598: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 3599: 	    return '/adm/notfound.html';
 3600: 	}
 3601: 	close(FH);
 3602:         if ($resizewidth && $resizeheight) {
 3603:             my $mm = new File::MMagic;
 3604:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
 3605:             if ($mime_type =~ m{^image/}) {
 3606: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
 3607:             }  
 3608: 	}
 3609:     }
 3610:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
 3611:         if (ref($mimetype)) {
 3612:             if ($$mimetype eq '') {
 3613:                 my $mm = new File::MMagic;
 3614:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
 3615:                 $$mimetype = $type;
 3616:             }
 3617:         }
 3618:     }
 3619:     if ($parser eq 'parse') {
 3620:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
 3621:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
 3622:                                                        $allfiles,$codebase);
 3623:             unless ($parse_result eq 'ok') {
 3624:                 &logthis('Failed to parse '.$filepath.$file.
 3625: 	   	         ' for embedded media: '.$parse_result); 
 3626:             }
 3627:         }
 3628:     }
 3629:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 3630:         my $input = $filepath.'/'.$file;
 3631:         my $output = $filepath.'/'.'tn-'.$file;
 3632:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 3633:         system("convert -sample $thumbsize $input $output");
 3634:         if (-e $filepath.'/'.'tn-'.$file) {
 3635:             $fetchthumb  = 1; 
 3636:         }
 3637:     }
 3638:  
 3639: # Notify homeserver to grep it
 3640: #
 3641:     my $docuhome=&homeserver($docuname,$docudom);	
 3642:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 3643:     if ($fetchresult eq 'ok') {
 3644:         if ($fetchthumb) {
 3645:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 3646:             if ($thumbresult ne 'ok') {
 3647:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 3648:                          $docuhome.': '.$thumbresult);
 3649:             }
 3650:         }
 3651: #
 3652: # Return the URL to it
 3653:         return '/uploaded/'.$path.$file;
 3654:     } else {
 3655:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 3656: 		 ': '.$fetchresult);
 3657:         return '/adm/notfound.html';
 3658:     }
 3659: }
 3660: 
 3661: sub extract_embedded_items {
 3662:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 3663:     my @state = ();
 3664:     my (%lastids,%related,%shockwave,%flashvars);
 3665:     my %javafiles = (
 3666:                       codebase => '',
 3667:                       code => '',
 3668:                       archive => ''
 3669:                     );
 3670:     my %mediafiles = (
 3671:                       src => '',
 3672:                       movie => '',
 3673:                      );
 3674:     my $p;
 3675:     if ($content) {
 3676:         $p = HTML::LCParser->new($content);
 3677:     } else {
 3678:         $p = HTML::LCParser->new($fullpath);
 3679:     }
 3680:     while (my $t=$p->get_token()) {
 3681: 	if ($t->[0] eq 'S') {
 3682: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 3683: 	    push(@state, $tagname);
 3684:             if (lc($tagname) eq 'allow') {
 3685:                 &add_filetype($allfiles,$attr->{'src'},'src');
 3686:             }
 3687: 	    if (lc($tagname) eq 'img') {
 3688: 		&add_filetype($allfiles,$attr->{'src'},'src');
 3689: 	    }
 3690: 	    if (lc($tagname) eq 'a') {
 3691:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
 3692:                     &add_filetype($allfiles,$attr->{'href'},'href');
 3693:                 }
 3694: 	    }
 3695:             if (lc($tagname) eq 'script') {
 3696:                 my $src;
 3697:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 3698:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 3699:                 } else {
 3700:                     if ($attr->{'src'} ne '') {
 3701:                         $src = $attr->{'src'};
 3702:                         &add_filetype($allfiles,$src,'src');
 3703:                     }
 3704:                 }
 3705:                 my $text = $p->get_trimmed_text();
 3706:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
 3707:                     my @swfargs = split(/,/,$1);
 3708:                     foreach my $item (@swfargs) {
 3709:                         $item =~ s/["']//g;
 3710:                         $item =~ s/^\s+//;
 3711:                         $item =~ s/\s+$//;
 3712:                     }
 3713:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
 3714:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
 3715:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
 3716:                         } else {
 3717:                             $related{$swfargs[0]} = [$swfargs[2]];
 3718:                         }
 3719:                     }
 3720:                 }
 3721:             }
 3722:             if (lc($tagname) eq 'link') {
 3723:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 3724:                     &add_filetype($allfiles,$attr->{'href'},'href');
 3725:                 }
 3726:             }
 3727: 	    if (lc($tagname) eq 'object' ||
 3728: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 3729: 		foreach my $item (keys(%javafiles)) {
 3730: 		    $javafiles{$item} = '';
 3731: 		}
 3732:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
 3733:                     $lastids{lc($tagname)} = $attr->{'id'};
 3734:                 }
 3735: 	    }
 3736: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 3737: 		my $name = lc($attr->{'name'});
 3738: 		foreach my $item (keys(%javafiles)) {
 3739: 		    if ($name eq $item) {
 3740: 			$javafiles{$item} = $attr->{'value'};
 3741: 			last;
 3742: 		    }
 3743: 		}
 3744:                 my $pathfrom;
 3745: 		foreach my $item (keys(%mediafiles)) {
 3746: 		    if ($name eq $item) {
 3747:                         $pathfrom = $attr->{'value'};
 3748:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
 3749: 			&add_filetype($allfiles,$pathfrom,$name);
 3750: 			last;
 3751: 		    }
 3752: 		}
 3753:                 if ($name eq 'flashvars') {
 3754:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
 3755:                 }
 3756:                 if ($pathfrom ne '') {
 3757:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
 3758:                                          $pathfrom);
 3759:                 }
 3760: 	    }
 3761: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 3762: 		foreach my $item (keys(%javafiles)) {
 3763: 		    if ($attr->{$item}) {
 3764: 			$javafiles{$item} = $attr->{$item};
 3765: 			last;
 3766: 		    }
 3767: 		}
 3768: 		foreach my $item (keys(%mediafiles)) {
 3769: 		    if ($attr->{$item}) {
 3770: 			&add_filetype($allfiles,$attr->{$item},$item);
 3771: 			last;
 3772: 		    }
 3773: 		}
 3774:                 if (lc($tagname) eq 'embed') {
 3775:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
 3776:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
 3777:                                              $attr->{'src'});
 3778:                     }
 3779:                 }
 3780: 	    }
 3781:             if (lc($tagname) eq 'iframe') {
 3782:                 my $src = $attr->{'src'} ;
 3783:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
 3784:                     &add_filetype($allfiles,$src,'src');
 3785:                 } elsif ($src =~ m{^/}) {
 3786:                     if ($env{'request.course.id'}) {
 3787:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3788:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3789:                         my $url = &hreflocation('',$fullpath);
 3790:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
 3791:                             my $relpath = $1;
 3792:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
 3793:                                 &add_filetype($allfiles,$1,'src');
 3794:                             }
 3795:                         }
 3796:                     }
 3797:                 }
 3798:             }
 3799:             if ($t->[4] =~ m{/>$}) {
 3800:                 pop(@state);
 3801:             }
 3802: 	} elsif ($t->[0] eq 'E') {
 3803: 	    my ($tagname) = ($t->[1]);
 3804: 	    if ($javafiles{'codebase'} ne '') {
 3805: 		$javafiles{'codebase'} .= '/';
 3806: 	    }  
 3807: 	    if (lc($tagname) eq 'applet' ||
 3808: 		lc($tagname) eq 'object' ||
 3809: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 3810: 		) {
 3811: 		foreach my $item (keys(%javafiles)) {
 3812: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 3813: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 3814: 			&add_filetype($allfiles,$file,$item);
 3815: 		    }
 3816: 		}
 3817: 	    } 
 3818: 	    pop @state;
 3819: 	}
 3820:     }
 3821:     foreach my $id (sort(keys(%flashvars))) {
 3822:         if ($shockwave{$id} ne '') {
 3823:             my @pairs = split(/\&/,$flashvars{$id});
 3824:             foreach my $pair (@pairs) {
 3825:                 my ($key,$value) = split(/\=/,$pair);
 3826:                 if ($key eq 'thumb') {
 3827:                     &add_filetype($allfiles,$value,$key);
 3828:                 } elsif ($key eq 'content') {
 3829:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
 3830:                     my ($ext) = ($value =~ /\.([^.]+)$/);
 3831:                     if ($ext ne '') {
 3832:                         &add_filetype($allfiles,$path.$value,$ext);
 3833:                     }
 3834:                 }
 3835:             }
 3836:         }
 3837:     }
 3838:     return 'ok';
 3839: }
 3840: 
 3841: sub add_filetype {
 3842:     my ($allfiles,$file,$type)=@_;
 3843:     if (exists($allfiles->{$file})) {
 3844: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 3845: 	    push(@{$allfiles->{$file}}, &escape($type));
 3846: 	}
 3847:     } else {
 3848: 	@{$allfiles->{$file}} = (&escape($type));
 3849:     }
 3850: }
 3851: 
 3852: sub embedded_dependency {
 3853:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
 3854:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
 3855:         if (($identifier ne '') &&
 3856:             (ref($related->{$identifier}) eq 'ARRAY') &&
 3857:             ($pathfrom ne '')) {
 3858:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
 3859:             foreach my $dep (@{$related->{$identifier}}) {
 3860:                 &add_filetype($allfiles,$path.$dep,'object');
 3861:             }
 3862:         }
 3863:     }
 3864:     return;
 3865: }
 3866: 
 3867: sub removeuploadedurl {
 3868:     my ($url)=@_;	
 3869:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 3870:     return &removeuserfile($uname,$udom,$fname);
 3871: }
 3872: 
 3873: sub removeuserfile {
 3874:     my ($docuname,$docudom,$fname)=@_;
 3875:     my $home=&homeserver($docuname,$docudom);    
 3876:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 3877:     if ($result eq 'ok') {	
 3878:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 3879:             my $metafile = $fname.'.meta';
 3880:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 3881: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 3882:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 3883:             my $sqlresult = 
 3884:                 &update_portfolio_table($docuname,$docudom,$file,
 3885:                                         'portfolio_metadata',$group,
 3886:                                         'delete');
 3887:         }
 3888:     }
 3889:     return $result;
 3890: }
 3891: 
 3892: sub mkdiruserfile {
 3893:     my ($docuname,$docudom,$dir)=@_;
 3894:     my $home=&homeserver($docuname,$docudom);
 3895:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 3896: }
 3897: 
 3898: sub renameuserfile {
 3899:     my ($docuname,$docudom,$old,$new)=@_;
 3900:     my $home=&homeserver($docuname,$docudom);
 3901:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 3902:                         &escape("$old").':'.&escape("$new"),$home);
 3903:     if ($result eq 'ok') {
 3904:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 3905:             my $oldmeta = $old.'.meta';
 3906:             my $newmeta = $new.'.meta';
 3907:             my $metaresult = 
 3908:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 3909: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 3910:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 3911:             my $sqlresult = 
 3912:                 &update_portfolio_table($docuname,$docudom,$file,
 3913:                                         'portfolio_metadata',$group,
 3914:                                         'delete');
 3915:         }
 3916:     }
 3917:     return $result;
 3918: }
 3919: 
 3920: # ------------------------------------------------------------------------- Log
 3921: 
 3922: sub log {
 3923:     my ($dom,$nam,$hom,$what)=@_;
 3924:     return critical("log:$dom:$nam:$what",$hom);
 3925: }
 3926: 
 3927: # ------------------------------------------------------------------ Course Log
 3928: #
 3929: # This routine flushes several buffers of non-mission-critical nature
 3930: #
 3931: 
 3932: sub flushcourselogs {
 3933:     &logthis('Flushing log buffers');
 3934: #
 3935: # course logs
 3936: # This is a log of all transactions in a course, which can be used
 3937: # for data mining purposes
 3938: #
 3939: # It also collects the courseid database, which lists last transaction
 3940: # times and course titles for all courseids
 3941: #
 3942:     my %courseidbuffer=();
 3943:     foreach my $crsid (keys(%courselogs)) {
 3944:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 3945: 		          &escape($courselogs{$crsid}),
 3946: 		          $coursehombuf{$crsid}) eq 'ok') {
 3947: 	    delete $courselogs{$crsid};
 3948:         } else {
 3949:             &logthis('Failed to flush log buffer for '.$crsid);
 3950:             if (length($courselogs{$crsid})>40000) {
 3951:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 3952:                         " exceeded maximum size, deleting.</font>");
 3953:                delete $courselogs{$crsid};
 3954:             }
 3955:         }
 3956:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 3957:             'description' => $coursedescrbuf{$crsid},
 3958:             'inst_code'    => $courseinstcodebuf{$crsid},
 3959:             'type'        => $coursetypebuf{$crsid},
 3960:             'owner'       => $courseownerbuf{$crsid},
 3961:         };
 3962:     }
 3963: #
 3964: # Write course id database (reverse lookup) to homeserver of courses 
 3965: # Is used in pickcourse
 3966: #
 3967:     foreach my $crs_home (keys(%courseidbuffer)) {
 3968:         my $response = &courseidput(&host_domain($crs_home),
 3969:                                     $courseidbuffer{$crs_home},
 3970:                                     $crs_home,'timeonly');
 3971:     }
 3972: #
 3973: # File accesses
 3974: # Writes to the dynamic metadata of resources to get hit counts, etc.
 3975: #
 3976:     foreach my $entry (keys(%accesshash)) {
 3977:         if ($entry =~ /___count$/) {
 3978:             my ($dom,$name);
 3979:             ($dom,$name,undef)=
 3980: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 3981:             if (! defined($dom) || $dom eq '' || 
 3982:                 ! defined($name) || $name eq '') {
 3983:                 my $cid = $env{'request.course.id'};
 3984:                 $dom  = $env{'request.'.$cid.'.domain'};
 3985:                 $name = $env{'request.'.$cid.'.num'};
 3986:             }
 3987:             my $value = $accesshash{$entry};
 3988:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 3989:             my %temphash=($url => $value);
 3990:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 3991:             if ($result eq 'ok') {
 3992:                 delete $accesshash{$entry};
 3993:             }
 3994:         } else {
 3995:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 3996:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
 3997:             my %temphash=($entry => $accesshash{$entry});
 3998:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 3999:                 delete $accesshash{$entry};
 4000:             }
 4001:         }
 4002:     }
 4003: #
 4004: # Roles
 4005: # Reverse lookup of user roles for course faculty/staff and co-authorship
 4006: #
 4007:     foreach my $entry (keys(%userrolehash)) {
 4008:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 4009: 	    split(/\:/,$entry);
 4010:         if (&Apache::lonnet::put('nohist_userroles',
 4011:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 4012:                 $rudom,$runame) eq 'ok') {
 4013: 	    delete $userrolehash{$entry};
 4014:         }
 4015:     }
 4016: #
 4017: # Reverse lookup of domain roles (dc, ad, li, sc, au)
 4018: #
 4019:     my %domrolebuffer = ();
 4020:     foreach my $entry (keys(%domainrolehash)) {
 4021:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 4022:         if ($domrolebuffer{$rudom}) {
 4023:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 4024:                       '='.&escape($domainrolehash{$entry});
 4025:         } else {
 4026:             $domrolebuffer{$rudom}.=&escape($entry).
 4027:                       '='.&escape($domainrolehash{$entry});
 4028:         }
 4029:         delete $domainrolehash{$entry};
 4030:     }
 4031:     foreach my $dom (keys(%domrolebuffer)) {
 4032: 	my %servers = &get_servers($dom,'library');
 4033: 	foreach my $tryserver (keys(%servers)) {
 4034: 	    unless (&reply('domroleput:'.$dom.':'.
 4035: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
 4036: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 4037: 	    }
 4038:         }
 4039:     }
 4040:     $dumpcount++;
 4041: }
 4042: 
 4043: sub courselog {
 4044:     my $what=shift;
 4045:     $what=time.':'.$what;
 4046:     unless ($env{'request.course.id'}) { return ''; }
 4047:     $coursedombuf{$env{'request.course.id'}}=
 4048:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 4049:     $coursenumbuf{$env{'request.course.id'}}=
 4050:        $env{'course.'.$env{'request.course.id'}.'.num'};
 4051:     $coursehombuf{$env{'request.course.id'}}=
 4052:        $env{'course.'.$env{'request.course.id'}.'.home'};
 4053:     $coursedescrbuf{$env{'request.course.id'}}=
 4054:        $env{'course.'.$env{'request.course.id'}.'.description'};
 4055:     $courseinstcodebuf{$env{'request.course.id'}}=
 4056:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 4057:     $courseownerbuf{$env{'request.course.id'}}=
 4058:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 4059:     $coursetypebuf{$env{'request.course.id'}}=
 4060:        $env{'course.'.$env{'request.course.id'}.'.type'};
 4061:     if (defined $courselogs{$env{'request.course.id'}}) {
 4062: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 4063:     } else {
 4064: 	$courselogs{$env{'request.course.id'}}.=$what;
 4065:     }
 4066:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 4067: 	&flushcourselogs();
 4068:     }
 4069: }
 4070: 
 4071: sub courseacclog {
 4072:     my $fnsymb=shift;
 4073:     unless ($env{'request.course.id'}) { return ''; }
 4074:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 4075:     if ($fnsymb=~/$LONCAPA::assess_re/) {
 4076:         $what.=':POST';
 4077:         # FIXME: Probably ought to escape things....
 4078: 	foreach my $key (keys(%env)) {
 4079:             if ($key=~/^form\.(.*)/) {
 4080:                 my $formitem = $1;
 4081:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 4082:                     $what.=':'.$formitem.'='.$env{$key};
 4083:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 4084:                     $what.=':'.$formitem.'='.$env{$key};
 4085:                 }
 4086:             }
 4087:         }
 4088:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 4089:         # FIXME: We should not be depending on a form parameter that someone
 4090:         # editing lonsearchcat.pm might change in the future.
 4091:         if ($env{'form.phase'} eq 'course_search') {
 4092:             $what.= ':POST';
 4093:             # FIXME: Probably ought to escape things....
 4094:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 4095:                                  'crsdiscuss') {
 4096:                 $what.=':'.$element.'='.$env{'form.'.$element};
 4097:             }
 4098:         }
 4099:     }
 4100:     &courselog($what);
 4101: }
 4102: 
 4103: sub countacc {
 4104:     my $url=&declutter(shift);
 4105:     return if (! defined($url) || $url eq '');
 4106:     unless ($env{'request.course.id'}) { return ''; }
 4107: #
 4108: # Mark that this url was used in this course
 4109: #
 4110:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 4111: #
 4112: # Increase the access count for this resource in this child process
 4113: #
 4114:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 4115:     $accesshash{$key}++;
 4116: }
 4117: 
 4118: sub linklog {
 4119:     my ($from,$to)=@_;
 4120:     $from=&declutter($from);
 4121:     $to=&declutter($to);
 4122:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 4123:     $accesshash{$to.'___'.$from.'___goto'}=1;
 4124: }
 4125: 
 4126: sub statslog {
 4127:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
 4128:     if ($users<2) { return; }
 4129:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
 4130:             'course'       => $env{'request.course.id'},
 4131:             'sections'     => '"all"',
 4132:             'num_students' => $users,
 4133:             'part'         => $part,
 4134:             'symb'         => $symb,
 4135:             'mean_tries'   => $av_attempts,
 4136:             'deg_of_diff'  => $degdiff});
 4137:     foreach my $key (keys(%dynstore)) {
 4138:         $accesshash{$key}=$dynstore{$key};
 4139:     }
 4140: }
 4141:   
 4142: sub userrolelog {
 4143:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 4144:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
 4145:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 4146:        $userrolehash
 4147:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 4148:                     =$tend.':'.$tstart;
 4149:     }
 4150:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
 4151:        $userrolehash
 4152:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 4153:                     =$tend.':'.$tstart;
 4154:     }
 4155:     if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
 4156:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 4157:        $domainrolehash
 4158:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 4159:                     = $tend.':'.$tstart;
 4160:     }
 4161: }
 4162: 
 4163: sub courserolelog {
 4164:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 4165:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 4166:         my $cdom = $1;
 4167:         my $cnum = $2;
 4168:         my $sec = $3;
 4169:         my $namespace = 'rolelog';
 4170:         my %storehash = (
 4171:                            role    => $trole,
 4172:                            start   => $tstart,
 4173:                            end     => $tend,
 4174:                            selfenroll => $selfenroll,
 4175:                            context    => $context,
 4176:                         );
 4177:         if ($trole eq 'gr') {
 4178:             $namespace = 'groupslog';
 4179:             $storehash{'group'} = $sec;
 4180:         } else {
 4181:             $storehash{'section'} = $sec;
 4182:         }
 4183:         &write_log('course',$namespace,\%storehash,$delflag,$username,
 4184:                    $domain,$cnum,$cdom);
 4185:         if (($trole ne 'st') || ($sec ne '')) {
 4186:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 4187:         }
 4188:     }
 4189:     return;
 4190: }
 4191: 
 4192: sub domainrolelog {
 4193:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 4194:     if ($area =~ m{^/($match_domain)/$}) {
 4195:         my $cdom = $1;
 4196:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
 4197:         my $namespace = 'rolelog';
 4198:         my %storehash = (
 4199:                            role    => $trole,
 4200:                            start   => $tstart,
 4201:                            end     => $tend,
 4202:                            context => $context,
 4203:                         );
 4204:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
 4205:                    $domain,$domconfiguser,$cdom);
 4206:     }
 4207:     return;
 4208: 
 4209: }
 4210: 
 4211: sub coauthorrolelog {
 4212:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 4213:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
 4214:         my $audom = $1;
 4215:         my $auname = $2;
 4216:         my $namespace = 'rolelog';
 4217:         my %storehash = (
 4218:                            role    => $trole,
 4219:                            start   => $tstart,
 4220:                            end     => $tend,
 4221:                            context => $context,
 4222:                         );
 4223:         &write_log('author',$namespace,\%storehash,$delflag,$username,
 4224:                    $domain,$auname,$audom);
 4225:     }
 4226:     return;
 4227: }
 4228: 
 4229: sub get_course_adv_roles {
 4230:     my ($cid,$codes) = @_;
 4231:     $cid=$env{'request.course.id'} unless (defined($cid));
 4232:     my %coursehash=&coursedescription($cid);
 4233:     my $crstype = &Apache::loncommon::course_type($cid);
 4234:     my %nothide=();
 4235:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 4236:         if ($user !~ /:/) {
 4237: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 4238:         } else {
 4239:             $nothide{$user}=1;
 4240:         }
 4241:     }
 4242:     my @possdoms = ($coursehash{'domain'});
 4243:     if ($coursehash{'checkforpriv'}) {
 4244:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
 4245:     }
 4246:     my %returnhash=();
 4247:     my %dumphash=
 4248:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 4249:     my $now=time;
 4250:     my %privileged;
 4251:     foreach my $entry (keys(%dumphash)) {
 4252: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 4253:         if (($tstart) && ($tstart<0)) { next; }
 4254:         if (($tend) && ($tend<$now)) { next; }
 4255:         if (($tstart) && ($now<$tstart)) { next; }
 4256:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 4257: 	if ($username eq '' || $domain eq '') { next; }
 4258:         if ((&privileged($username,$domain,\@possdoms)) &&
 4259:             (!$nothide{$username.':'.$domain})) { next; }
 4260: 	if ($role eq 'cr') { next; }
 4261:         if ($codes) {
 4262:             if ($section) { $role .= ':'.$section; }
 4263:             if ($returnhash{$role}) {
 4264:                 $returnhash{$role}.=','.$username.':'.$domain;
 4265:             } else {
 4266:                 $returnhash{$role}=$username.':'.$domain;
 4267:             }
 4268:         } else {
 4269:             my $key=&plaintext($role,$crstype);
 4270:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 4271:             if ($returnhash{$key}) {
 4272: 	        $returnhash{$key}.=','.$username.':'.$domain;
 4273:             } else {
 4274:                 $returnhash{$key}=$username.':'.$domain;
 4275:             }
 4276:         }
 4277:     }
 4278:     return %returnhash;
 4279: }
 4280: 
 4281: sub get_my_roles {
 4282:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 4283:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 4284:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 4285:     my (%dumphash,%nothide);
 4286:     if ($context eq 'userroles') {
 4287:         %dumphash = &dump('roles',$udom,$uname);
 4288:     } else {
 4289:         %dumphash = &dump('nohist_userroles',$udom,$uname);
 4290:         if ($hidepriv) {
 4291:             my %coursehash=&coursedescription($udom.'_'.$uname);
 4292:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 4293:                 if ($user !~ /:/) {
 4294:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 4295:                 } else {
 4296:                     $nothide{$user} = 1;
 4297:                 }
 4298:             }
 4299:         }
 4300:     }
 4301:     my %returnhash=();
 4302:     my $now=time;
 4303:     my %privileged;
 4304:     foreach my $entry (keys(%dumphash)) {
 4305:         my ($role,$tend,$tstart);
 4306:         if ($context eq 'userroles') {
 4307:             next if ($entry =~ /^rolesdef/);
 4308: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 4309:         } else {
 4310:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 4311:         }
 4312:         if (($tstart) && ($tstart<0)) { next; }
 4313:         my $status = 'active';
 4314:         if (($tend) && ($tend<=$now)) {
 4315:             $status = 'previous';
 4316:         } 
 4317:         if (($tstart) && ($now<$tstart)) {
 4318:             $status = 'future';
 4319:         }
 4320:         if (ref($types) eq 'ARRAY') {
 4321:             if (!grep(/^\Q$status\E$/,@{$types})) {
 4322:                 next;
 4323:             } 
 4324:         } else {
 4325:             if ($status ne 'active') {
 4326:                 next;
 4327:             }
 4328:         }
 4329:         my ($rolecode,$username,$domain,$section,$area);
 4330:         if ($context eq 'userroles') {
 4331:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
 4332:             (undef,$domain,$username,$section) = split(/\//,$area);
 4333:         } else {
 4334:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 4335:         }
 4336:         if (ref($roledoms) eq 'ARRAY') {
 4337:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 4338:                 next;
 4339:             }
 4340:         }
 4341:         if (ref($roles) eq 'ARRAY') {
 4342:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 4343:                 if ($role =~ /^cr\//) {
 4344:                     if (!grep(/^cr$/,@{$roles})) {
 4345:                         next;
 4346:                     }
 4347:                 } elsif ($role =~ /^gr\//) {
 4348:                     if (!grep(/^gr$/,@{$roles})) {
 4349:                         next;
 4350:                     }
 4351:                 } else {
 4352:                     next;
 4353:                 }
 4354:             }
 4355:         }
 4356:         if ($hidepriv) {
 4357:             my @privroles = ('dc','su');
 4358:             if ($context eq 'userroles') {
 4359:                 next if (grep(/^\Q$role\E$/,@privroles));
 4360:             } else {
 4361:                 my $possdoms = [$domain];
 4362:                 if (ref($roledoms) eq 'ARRAY') {
 4363:                    push(@{$possdoms},@{$roledoms}); 
 4364:                 }
 4365:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
 4366:                     if (!$nothide{$username.':'.$domain}) {
 4367:                         next;
 4368:                     }
 4369:                 }
 4370:             }
 4371:         }
 4372:         if ($withsec) {
 4373:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 4374:                 $tstart.':'.$tend;
 4375:         } else {
 4376:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 4377:         }
 4378:     }
 4379:     return %returnhash;
 4380: }
 4381: 
 4382: # ----------------------------------------------------- Frontpage Announcements
 4383: #
 4384: #
 4385: 
 4386: sub postannounce {
 4387:     my ($server,$text)=@_;
 4388:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 4389:     unless ($text=~/\w/) { $text=''; }
 4390:     return &reply('setannounce:'.&escape($text),$server);
 4391: }
 4392: 
 4393: sub getannounce {
 4394: 
 4395:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 4396: 	my $announcement='';
 4397: 	while (my $line = <$fh>) { $announcement .= $line; }
 4398: 	close($fh);
 4399: 	if ($announcement=~/\w/) { 
 4400: 	    return 
 4401:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 4402:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 4403: 	} else {
 4404: 	    return '';
 4405: 	}
 4406:     } else {
 4407: 	return '';
 4408:     }
 4409: }
 4410: 
 4411: # ---------------------------------------------------------- Course ID routines
 4412: # Deal with domain's nohist_courseid.db files
 4413: #
 4414: 
 4415: sub courseidput {
 4416:     my ($domain,$storehash,$coursehome,$caller) = @_;
 4417:     return unless (ref($storehash) eq 'HASH');
 4418:     my $outcome;
 4419:     if ($caller eq 'timeonly') {
 4420:         my $cids = '';
 4421:         foreach my $item (keys(%$storehash)) {
 4422:             $cids.=&escape($item).'&';
 4423:         }
 4424:         $cids=~s/\&$//;
 4425:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 4426:                           $coursehome);       
 4427:     } else {
 4428:         my $items = '';
 4429:         foreach my $item (keys(%$storehash)) {
 4430:             $items.= &escape($item).'='.
 4431:                      &freeze_escape($$storehash{$item}).'&';
 4432:         }
 4433:         $items=~s/\&$//;
 4434:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 4435:                           $coursehome);
 4436:     }
 4437:     if ($outcome eq 'unknown_cmd') {
 4438:         my $what;
 4439:         foreach my $cid (keys(%$storehash)) {
 4440:             $what .= &escape($cid).'=';
 4441:             foreach my $item ('description','inst_code','owner','type') {
 4442:                 $what .= &escape($storehash->{$cid}{$item}).':';
 4443:             }
 4444:             $what =~ s/\:$/&/;
 4445:         }
 4446:         $what =~ s/\&$//;  
 4447:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 4448:     } else {
 4449:         return $outcome;
 4450:     }
 4451: }
 4452: 
 4453: sub courseiddump {
 4454:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 4455:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 4456:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
 4457:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
 4458:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
 4459:     my $as_hash = 1;
 4460:     my %returnhash;
 4461:     if (!$domfilter) { $domfilter=''; }
 4462:     my %libserv = &all_library();
 4463:     foreach my $tryserver (keys(%libserv)) {
 4464:         if ( (  $hostidflag == 1 
 4465: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 4466: 	     || (!defined($hostidflag)) ) {
 4467: 
 4468: 	    if (($domfilter eq '') ||
 4469: 		(&host_domain($tryserver) eq $domfilter)) {
 4470:                 my $rep;
 4471:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
 4472:                     $rep = LONCAPA::Lond::dump_course_id_handler(
 4473:                         join(":", (&host_domain($tryserver), $sincefilter, 
 4474:                                 &escape($descfilter), &escape($instcodefilter), 
 4475:                                 &escape($ownerfilter), &escape($coursefilter),
 4476:                                 &escape($typefilter), &escape($regexp_ok), 
 4477:                                 $as_hash, &escape($selfenrollonly), 
 4478:                                 &escape($catfilter), $showhidden, $caller, 
 4479:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
 4480:                                 &escape($createdbefore), &escape($createdafter), 
 4481:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
 4482:                                 $reqcrsdom,&escape($reqinstcode))));
 4483:                 } else {
 4484:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
 4485:                              $sincefilter.':'.&escape($descfilter).':'.
 4486:                              &escape($instcodefilter).':'.&escape($ownerfilter).
 4487:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
 4488:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
 4489:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
 4490:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
 4491:                              &escape($cc_clone).':'.$cloneonly.':'.
 4492:                              &escape($createdbefore).':'.&escape($createdafter).':'.
 4493:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
 4494:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
 4495:                 }
 4496:                      
 4497:                 my @pairs=split(/\&/,$rep);
 4498:                 foreach my $item (@pairs) {
 4499:                     my ($key,$value)=split(/\=/,$item,2);
 4500:                     $key = &unescape($key);
 4501:                     next if ($key =~ /^error: 2 /);
 4502:                     my $result = &thaw_unescape($value);
 4503:                     if (ref($result) eq 'HASH') {
 4504:                         $returnhash{$key}=$result;
 4505:                     } else {
 4506:                         my @responses = split(/:/,$value);
 4507:                         my @items = ('description','inst_code','owner','type');
 4508:                         for (my $i=0; $i<@responses; $i++) {
 4509:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 4510:                         }
 4511:                     }
 4512:                 }
 4513:             }
 4514:         }
 4515:     }
 4516:     return %returnhash;
 4517: }
 4518: 
 4519: sub courselastaccess {
 4520:     my ($cdom,$cnum,$hostidref) = @_;
 4521:     my %returnhash;
 4522:     if ($cdom && $cnum) {
 4523:         my $chome = &homeserver($cnum,$cdom);
 4524:         if ($chome ne 'no_host') {
 4525:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
 4526:             &extract_lastaccess(\%returnhash,$rep);
 4527:         }
 4528:     } else {
 4529:         if (!$cdom) { $cdom=''; }
 4530:         my %libserv = &all_library();
 4531:         foreach my $tryserver (keys(%libserv)) {
 4532:             if (ref($hostidref) eq 'ARRAY') {
 4533:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
 4534:             } 
 4535:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
 4536:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
 4537:                 &extract_lastaccess(\%returnhash,$rep);
 4538:             }
 4539:         }
 4540:     }
 4541:     return %returnhash;
 4542: }
 4543: 
 4544: sub extract_lastaccess {
 4545:     my ($returnhash,$rep) = @_;
 4546:     if (ref($returnhash) eq 'HASH') {
 4547:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
 4548:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
 4549:                  $rep eq '') {
 4550:             my @pairs=split(/\&/,$rep);
 4551:             foreach my $item (@pairs) {
 4552:                 my ($key,$value)=split(/\=/,$item,2);
 4553:                 $key = &unescape($key);
 4554:                 next if ($key =~ /^error: 2 /);
 4555:                 $returnhash->{$key} = &thaw_unescape($value);
 4556:             }
 4557:         }
 4558:     }
 4559:     return;
 4560: }
 4561: 
 4562: # ---------------------------------------------------------- DC e-mail
 4563: 
 4564: sub dcmailput {
 4565:     my ($domain,$msgid,$message,$server)=@_;
 4566:     my $status = &Apache::lonnet::critical(
 4567:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 4568:        &escape($message),$server);
 4569:     return $status;
 4570: }
 4571: 
 4572: sub dcmaildump {
 4573:     my ($dom,$startdate,$enddate,$senders) = @_;
 4574:     my %returnhash=();
 4575: 
 4576:     if (defined(&domain($dom,'primary'))) {
 4577:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 4578:                                                          &escape($enddate).':';
 4579: 	my @esc_senders=map { &escape($_)} @$senders;
 4580: 	$cmd.=&escape(join('&',@esc_senders));
 4581: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 4582:             my ($key,$value) = split(/\=/,$line,2);
 4583:             if (($key) && ($value)) {
 4584:                 $returnhash{&unescape($key)} = &unescape($value);
 4585:             }
 4586:         }
 4587:     }
 4588:     return %returnhash;
 4589: }
 4590: # ---------------------------------------------------------- Domain roles
 4591: 
 4592: sub get_domain_roles {
 4593:     my ($dom,$roles,$startdate,$enddate)=@_;
 4594:     if ((!defined($startdate)) || ($startdate eq '')) {
 4595:         $startdate = '.';
 4596:     }
 4597:     if ((!defined($enddate)) || ($enddate eq '')) {
 4598:         $enddate = '.';
 4599:     }
 4600:     my $rolelist;
 4601:     if (ref($roles) eq 'ARRAY') {
 4602:         $rolelist = join('&',@{$roles});
 4603:     }
 4604:     my %personnel = ();
 4605: 
 4606:     my %servers = &get_servers($dom,'library');
 4607:     foreach my $tryserver (keys(%servers)) {
 4608: 	%{$personnel{$tryserver}}=();
 4609: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 4610: 					    &escape($startdate).':'.
 4611: 					    &escape($enddate).':'.
 4612: 					    &escape($rolelist), $tryserver))) {
 4613: 	    my ($key,$value) = split(/\=/,$line,2);
 4614: 	    if (($key) && ($value)) {
 4615: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 4616: 	    }
 4617: 	}
 4618:     }
 4619:     return %personnel;
 4620: }
 4621: 
 4622: # ----------------------------------------------------------- Interval timing 
 4623: 
 4624: {
 4625: # Caches needed for speedup of navmaps
 4626: # We don't want to cache this for very long at all (5 seconds at most)
 4627: # 
 4628: # The user for whom we cache
 4629: my $cachedkey='';
 4630: # The cached times for this user
 4631: my %cachedtimes=();
 4632: # When this was last done
 4633: my $cachedtime='';
 4634: 
 4635: sub load_all_first_access {
 4636:     my ($uname,$udom)=@_;
 4637:     if (($cachedkey eq $uname.':'.$udom) &&
 4638:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
 4639:         return;
 4640:     }
 4641:     $cachedtime=time;
 4642:     $cachedkey=$uname.':'.$udom;
 4643:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
 4644: }
 4645: 
 4646: sub get_first_access {
 4647:     my ($type,$argsymb,$argmap)=@_;
 4648:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 4649:     if ($argsymb) { $symb=$argsymb; }
 4650:     my ($map,$id,$res)=&decode_symb($symb);
 4651:     if ($argmap) { $map = $argmap; }
 4652:     if ($type eq 'course') {
 4653: 	$res='course';
 4654:     } elsif ($type eq 'map') {
 4655: 	$res=&symbread($map);
 4656:     } else {
 4657: 	$res=$symb;
 4658:     }
 4659:     &load_all_first_access($uname,$udom);
 4660:     return $cachedtimes{"$courseid\0$res"};
 4661: }
 4662: 
 4663: sub set_first_access {
 4664:     my ($type,$interval)=@_;
 4665:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 4666:     my ($map,$id,$res)=&decode_symb($symb);
 4667:     if ($type eq 'course') {
 4668: 	$res='course';
 4669:     } elsif ($type eq 'map') {
 4670: 	$res=&symbread($map);
 4671:     } else {
 4672: 	$res=$symb;
 4673:     }
 4674:     $cachedkey='';
 4675:     my $firstaccess=&get_first_access($type,$symb,$map);
 4676:     if (!$firstaccess) {
 4677:         my $start = time;
 4678: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
 4679:                           $udom,$uname);
 4680:         if ($putres eq 'ok') {
 4681:             &put('timerinterval',{"$courseid\0$res"=>$interval},
 4682:                  $udom,$uname); 
 4683:             &appenv(
 4684:                      {
 4685:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
 4686:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
 4687:                      }
 4688:                   );
 4689:         }
 4690:         return $putres;
 4691:     }
 4692:     return 'already_set';
 4693: }
 4694: }
 4695: 
 4696: # --------------------------------------------- Set Expire Date for Spreadsheet
 4697: 
 4698: sub expirespread {
 4699:     my ($uname,$udom,$stype,$usymb)=@_;
 4700:     my $cid=$env{'request.course.id'}; 
 4701:     if ($cid) {
 4702:        my $now=time;
 4703:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 4704:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 4705:                             $env{'course.'.$cid.'.num'}.
 4706: 	        	    ':nohist_expirationdates:'.
 4707:                             &escape($key).'='.$now,
 4708:                             $env{'course.'.$cid.'.home'})
 4709:     }
 4710:     return 'ok';
 4711: }
 4712: 
 4713: # ----------------------------------------------------- Devalidate Spreadsheets
 4714: 
 4715: sub devalidate {
 4716:     my ($symb,$uname,$udom)=@_;
 4717:     my $cid=$env{'request.course.id'}; 
 4718:     if ($cid) {
 4719:         # delete the stored spreadsheets for
 4720:         # - the student level sheet of this user in course's homespace
 4721:         # - the assessment level sheet for this resource 
 4722:         #   for this user in user's homespace
 4723: 	# - current conditional state info
 4724: 	my $key=$uname.':'.$udom.':';
 4725:         my $status=
 4726: 	    &del('nohist_calculatedsheets',
 4727: 		 [$key.'studentcalc:'],
 4728: 		 $env{'course.'.$cid.'.domain'},
 4729: 		 $env{'course.'.$cid.'.num'})
 4730: 		.' '.
 4731: 	    &del('nohist_calculatedsheets_'.$cid,
 4732: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 4733:         unless ($status eq 'ok ok') {
 4734:            &logthis('Could not devalidate spreadsheet '.
 4735:                     $uname.' at '.$udom.' for '.
 4736: 		    $symb.': '.$status);
 4737:         }
 4738: 	&delenv('user.state.'.$cid);
 4739:     }
 4740: }
 4741: 
 4742: sub get_scalar {
 4743:     my ($string,$end) = @_;
 4744:     my $value;
 4745:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 4746: 	$value = $1;
 4747:     } elsif ($$string =~ s/^([^&]*?)&//) {
 4748: 	$value = $1;
 4749:     }
 4750:     return &unescape($value);
 4751: }
 4752: 
 4753: sub array2str {
 4754:   my (@array) = @_;
 4755:   my $result=&arrayref2str(\@array);
 4756:   $result=~s/^__ARRAY_REF__//;
 4757:   $result=~s/__END_ARRAY_REF__$//;
 4758:   return $result;
 4759: }
 4760: 
 4761: sub arrayref2str {
 4762:   my ($arrayref) = @_;
 4763:   my $result='__ARRAY_REF__';
 4764:   foreach my $elem (@$arrayref) {
 4765:     if(ref($elem) eq 'ARRAY') {
 4766:       $result.=&arrayref2str($elem).'&';
 4767:     } elsif(ref($elem) eq 'HASH') {
 4768:       $result.=&hashref2str($elem).'&';
 4769:     } elsif(ref($elem)) {
 4770:       #print("Got a ref of ".(ref($elem))." skipping.");
 4771:     } else {
 4772:       $result.=&escape($elem).'&';
 4773:     }
 4774:   }
 4775:   $result=~s/\&$//;
 4776:   $result .= '__END_ARRAY_REF__';
 4777:   return $result;
 4778: }
 4779: 
 4780: sub hash2str {
 4781:   my (%hash) = @_;
 4782:   my $result=&hashref2str(\%hash);
 4783:   $result=~s/^__HASH_REF__//;
 4784:   $result=~s/__END_HASH_REF__$//;
 4785:   return $result;
 4786: }
 4787: 
 4788: sub hashref2str {
 4789:   my ($hashref)=@_;
 4790:   my $result='__HASH_REF__';
 4791:   foreach my $key (sort(keys(%$hashref))) {
 4792:     if (ref($key) eq 'ARRAY') {
 4793:       $result.=&arrayref2str($key).'=';
 4794:     } elsif (ref($key) eq 'HASH') {
 4795:       $result.=&hashref2str($key).'=';
 4796:     } elsif (ref($key)) {
 4797:       $result.='=';
 4798:       #print("Got a ref of ".(ref($key))." skipping.");
 4799:     } else {
 4800: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
 4801:     }
 4802: 
 4803:     if(ref($hashref->{$key}) eq 'ARRAY') {
 4804:       $result.=&arrayref2str($hashref->{$key}).'&';
 4805:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 4806:       $result.=&hashref2str($hashref->{$key}).'&';
 4807:     } elsif(ref($hashref->{$key})) {
 4808:        $result.='&';
 4809:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 4810:     } else {
 4811:       $result.=&escape($hashref->{$key}).'&';
 4812:     }
 4813:   }
 4814:   $result=~s/\&$//;
 4815:   $result .= '__END_HASH_REF__';
 4816:   return $result;
 4817: }
 4818: 
 4819: sub str2hash {
 4820:     my ($string)=@_;
 4821:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 4822:     return %$hash;
 4823: }
 4824: 
 4825: sub str2hashref {
 4826:   my ($string) = @_;
 4827: 
 4828:   my %hash;
 4829: 
 4830:   if($string !~ /^__HASH_REF__/) {
 4831:       if (! ($string eq '' || !defined($string))) {
 4832: 	  $hash{'error'}='Not hash reference';
 4833:       }
 4834:       return (\%hash, $string);
 4835:   }
 4836: 
 4837:   $string =~ s/^__HASH_REF__//;
 4838: 
 4839:   while($string !~ /^__END_HASH_REF__/) {
 4840:       #key
 4841:       my $key='';
 4842:       if($string =~ /^__HASH_REF__/) {
 4843:           ($key, $string)=&str2hashref($string);
 4844:           if(defined($key->{'error'})) {
 4845:               $hash{'error'}='Bad data';
 4846:               return (\%hash, $string);
 4847:           }
 4848:       } elsif($string =~ /^__ARRAY_REF__/) {
 4849:           ($key, $string)=&str2arrayref($string);
 4850:           if($key->[0] eq 'Array reference error') {
 4851:               $hash{'error'}='Bad data';
 4852:               return (\%hash, $string);
 4853:           }
 4854:       } else {
 4855:           $string =~ s/^(.*?)=//;
 4856: 	  $key=&unescape($1);
 4857:       }
 4858:       $string =~ s/^=//;
 4859: 
 4860:       #value
 4861:       my $value='';
 4862:       if($string =~ /^__HASH_REF__/) {
 4863:           ($value, $string)=&str2hashref($string);
 4864:           if(defined($value->{'error'})) {
 4865:               $hash{'error'}='Bad data';
 4866:               return (\%hash, $string);
 4867:           }
 4868:       } elsif($string =~ /^__ARRAY_REF__/) {
 4869:           ($value, $string)=&str2arrayref($string);
 4870:           if($value->[0] eq 'Array reference error') {
 4871:               $hash{'error'}='Bad data';
 4872:               return (\%hash, $string);
 4873:           }
 4874:       } else {
 4875: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 4876:       }
 4877:       $string =~ s/^&//;
 4878: 
 4879:       $hash{$key}=$value;
 4880:   }
 4881: 
 4882:   $string =~ s/^__END_HASH_REF__//;
 4883: 
 4884:   return (\%hash, $string);
 4885: }
 4886: 
 4887: sub str2array {
 4888:     my ($string)=@_;
 4889:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 4890:     return @$array;
 4891: }
 4892: 
 4893: sub str2arrayref {
 4894:   my ($string) = @_;
 4895:   my @array;
 4896: 
 4897:   if($string !~ /^__ARRAY_REF__/) {
 4898:       if (! ($string eq '' || !defined($string))) {
 4899: 	  $array[0]='Array reference error';
 4900:       }
 4901:       return (\@array, $string);
 4902:   }
 4903: 
 4904:   $string =~ s/^__ARRAY_REF__//;
 4905: 
 4906:   while($string !~ /^__END_ARRAY_REF__/) {
 4907:       my $value='';
 4908:       if($string =~ /^__HASH_REF__/) {
 4909:           ($value, $string)=&str2hashref($string);
 4910:           if(defined($value->{'error'})) {
 4911:               $array[0] ='Array reference error';
 4912:               return (\@array, $string);
 4913:           }
 4914:       } elsif($string =~ /^__ARRAY_REF__/) {
 4915:           ($value, $string)=&str2arrayref($string);
 4916:           if($value->[0] eq 'Array reference error') {
 4917:               $array[0] ='Array reference error';
 4918:               return (\@array, $string);
 4919:           }
 4920:       } else {
 4921: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 4922:       }
 4923:       $string =~ s/^&//;
 4924: 
 4925:       push(@array, $value);
 4926:   }
 4927: 
 4928:   $string =~ s/^__END_ARRAY_REF__//;
 4929: 
 4930:   return (\@array, $string);
 4931: }
 4932: 
 4933: # -------------------------------------------------------------------Temp Store
 4934: 
 4935: sub tmpreset {
 4936:   my ($symb,$namespace,$domain,$stuname) = @_;
 4937:   if (!$symb) {
 4938:     $symb=&symbread();
 4939:     if (!$symb) { $symb= $env{'request.url'}; }
 4940:   }
 4941:   $symb=escape($symb);
 4942: 
 4943:   if (!$namespace) { $namespace=$env{'request.state'}; }
 4944:   $namespace=~s/\//\_/g;
 4945:   $namespace=~s/\W//g;
 4946: 
 4947:   if (!$domain) { $domain=$env{'user.domain'}; }
 4948:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4949:   if ($domain eq 'public' && $stuname eq 'public') {
 4950:       $stuname=$ENV{'REMOTE_ADDR'};
 4951:   }
 4952:   my $path=LONCAPA::tempdir();
 4953:   my %hash;
 4954:   if (tie(%hash,'GDBM_File',
 4955: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4956: 	  &GDBM_WRCREAT(),0640)) {
 4957:     foreach my $key (keys(%hash)) {
 4958:       if ($key=~ /:$symb/) {
 4959: 	delete($hash{$key});
 4960:       }
 4961:     }
 4962:   }
 4963: }
 4964: 
 4965: sub tmpstore {
 4966:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4967: 
 4968:   if (!$symb) {
 4969:     $symb=&symbread();
 4970:     if (!$symb) { $symb= $env{'request.url'}; }
 4971:   }
 4972:   $symb=escape($symb);
 4973: 
 4974:   if (!$namespace) {
 4975:     # I don't think we would ever want to store this for a course.
 4976:     # it seems this will only be used if we don't have a course.
 4977:     #$namespace=$env{'request.course.id'};
 4978:     #if (!$namespace) {
 4979:       $namespace=$env{'request.state'};
 4980:     #}
 4981:   }
 4982:   $namespace=~s/\//\_/g;
 4983:   $namespace=~s/\W//g;
 4984:   if (!$domain) { $domain=$env{'user.domain'}; }
 4985:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4986:   if ($domain eq 'public' && $stuname eq 'public') {
 4987:       $stuname=$ENV{'REMOTE_ADDR'};
 4988:   }
 4989:   my $now=time;
 4990:   my %hash;
 4991:   my $path=LONCAPA::tempdir();
 4992:   if (tie(%hash,'GDBM_File',
 4993: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4994: 	  &GDBM_WRCREAT(),0640)) {
 4995:     $hash{"version:$symb"}++;
 4996:     my $version=$hash{"version:$symb"};
 4997:     my $allkeys=''; 
 4998:     foreach my $key (keys(%$storehash)) {
 4999:       $allkeys.=$key.':';
 5000:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 5001:     }
 5002:     $hash{"$version:$symb:timestamp"}=$now;
 5003:     $allkeys.='timestamp';
 5004:     $hash{"$version:keys:$symb"}=$allkeys;
 5005:     if (untie(%hash)) {
 5006:       return 'ok';
 5007:     } else {
 5008:       return "error:$!";
 5009:     }
 5010:   } else {
 5011:     return "error:$!";
 5012:   }
 5013: }
 5014: 
 5015: # -----------------------------------------------------------------Temp Restore
 5016: 
 5017: sub tmprestore {
 5018:   my ($symb,$namespace,$domain,$stuname) = @_;
 5019: 
 5020:   if (!$symb) {
 5021:     $symb=&symbread();
 5022:     if (!$symb) { $symb= $env{'request.url'}; }
 5023:   }
 5024:   $symb=escape($symb);
 5025: 
 5026:   if (!$namespace) { $namespace=$env{'request.state'}; }
 5027: 
 5028:   if (!$domain) { $domain=$env{'user.domain'}; }
 5029:   if (!$stuname) { $stuname=$env{'user.name'}; }
 5030:   if ($domain eq 'public' && $stuname eq 'public') {
 5031:       $stuname=$ENV{'REMOTE_ADDR'};
 5032:   }
 5033:   my %returnhash;
 5034:   $namespace=~s/\//\_/g;
 5035:   $namespace=~s/\W//g;
 5036:   my %hash;
 5037:   my $path=LONCAPA::tempdir();
 5038:   if (tie(%hash,'GDBM_File',
 5039: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 5040: 	  &GDBM_READER(),0640)) {
 5041:     my $version=$hash{"version:$symb"};
 5042:     $returnhash{'version'}=$version;
 5043:     my $scope;
 5044:     for ($scope=1;$scope<=$version;$scope++) {
 5045:       my $vkeys=$hash{"$scope:keys:$symb"};
 5046:       my @keys=split(/:/,$vkeys);
 5047:       my $key;
 5048:       $returnhash{"$scope:keys"}=$vkeys;
 5049:       foreach $key (@keys) {
 5050: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 5051: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 5052:       }
 5053:     }
 5054:     if (!(untie(%hash))) {
 5055:       return "error:$!";
 5056:     }
 5057:   } else {
 5058:     return "error:$!";
 5059:   }
 5060:   return %returnhash;
 5061: }
 5062: 
 5063: # ----------------------------------------------------------------------- Store
 5064: 
 5065: sub store {
 5066:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 5067:     my $home='';
 5068: 
 5069:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 5070: 
 5071:     $symb=&symbclean($symb);
 5072:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 5073: 
 5074:     if (!$domain) { $domain=$env{'user.domain'}; }
 5075:     if (!$stuname) { $stuname=$env{'user.name'}; }
 5076: 
 5077:     &devalidate($symb,$stuname,$domain);
 5078: 
 5079:     $symb=escape($symb);
 5080:     if (!$namespace) { 
 5081:        unless ($namespace=$env{'request.course.id'}) { 
 5082:           return ''; 
 5083:        } 
 5084:     }
 5085:     if (!$home) { $home=$env{'user.home'}; }
 5086: 
 5087:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 5088:     $$storehash{'host'}=$perlvar{'lonHostID'};
 5089: 
 5090:     my $namevalue='';
 5091:     foreach my $key (keys(%$storehash)) {
 5092:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 5093:     }
 5094:     $namevalue=~s/\&$//;
 5095:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 5096:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 5097: }
 5098: 
 5099: # -------------------------------------------------------------- Critical Store
 5100: 
 5101: sub cstore {
 5102:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 5103:     my $home='';
 5104: 
 5105:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 5106: 
 5107:     $symb=&symbclean($symb);
 5108:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 5109: 
 5110:     if (!$domain) { $domain=$env{'user.domain'}; }
 5111:     if (!$stuname) { $stuname=$env{'user.name'}; }
 5112: 
 5113:     &devalidate($symb,$stuname,$domain);
 5114: 
 5115:     $symb=escape($symb);
 5116:     if (!$namespace) { 
 5117:        unless ($namespace=$env{'request.course.id'}) { 
 5118:           return ''; 
 5119:        } 
 5120:     }
 5121:     if (!$home) { $home=$env{'user.home'}; }
 5122: 
 5123:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 5124:     $$storehash{'host'}=$perlvar{'lonHostID'};
 5125: 
 5126:     my $namevalue='';
 5127:     foreach my $key (keys(%$storehash)) {
 5128:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 5129:     }
 5130:     $namevalue=~s/\&$//;
 5131:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 5132:     return critical
 5133:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 5134: }
 5135: 
 5136: # --------------------------------------------------------------------- Restore
 5137: 
 5138: sub restore {
 5139:     my ($symb,$namespace,$domain,$stuname) = @_;
 5140:     my $home='';
 5141: 
 5142:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 5143: 
 5144:     if (!$symb) {
 5145:         return if ($namespace eq 'courserequests');
 5146:         unless ($symb=escape(&symbread())) { return ''; }
 5147:     } else {
 5148:         unless ($namespace eq 'courserequests') {
 5149:             $symb=&escape(&symbclean($symb));
 5150:         }
 5151:     }
 5152:     if (!$namespace) { 
 5153:        unless ($namespace=$env{'request.course.id'}) { 
 5154:           return ''; 
 5155:        } 
 5156:     }
 5157:     if (!$domain) { $domain=$env{'user.domain'}; }
 5158:     if (!$stuname) { $stuname=$env{'user.name'}; }
 5159:     if (!$home) { $home=$env{'user.home'}; }
 5160:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 5161: 
 5162:     my %returnhash=();
 5163:     foreach my $line (split(/\&/,$answer)) {
 5164: 	my ($name,$value)=split(/\=/,$line);
 5165:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 5166:     }
 5167:     my $version;
 5168:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 5169:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 5170:           $returnhash{$item}=$returnhash{$version.':'.$item};
 5171:        }
 5172:     }
 5173:     return %returnhash;
 5174: }
 5175: 
 5176: # ---------------------------------------------------------- Course Description
 5177: #
 5178: #  
 5179: 
 5180: sub coursedescription {
 5181:     my ($courseid,$args)=@_;
 5182:     $courseid=~s/^\///;
 5183:     $courseid=~s/\_/\//g;
 5184:     my ($cdomain,$cnum)=split(/\//,$courseid);
 5185:     my $chome=&homeserver($cnum,$cdomain);
 5186:     my $normalid=$cdomain.'_'.$cnum;
 5187:     # need to always cache even if we get errors otherwise we keep 
 5188:     # trying and trying and trying to get the course description.
 5189:     my %envhash=();
 5190:     my %returnhash=();
 5191:     
 5192:     my $expiretime=600;
 5193:     if ($env{'request.course.id'} eq $normalid) {
 5194: 	$expiretime=120;
 5195:     }
 5196: 
 5197:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 5198:     if (!$args->{'freshen_cache'}
 5199: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 5200: 	foreach my $key (keys(%env)) {
 5201: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 5202: 	    my ($setting) = $1;
 5203: 	    $returnhash{$setting} = $env{$key};
 5204: 	}
 5205: 	return %returnhash;
 5206:     }
 5207: 
 5208:     # get the data again
 5209: 
 5210:     if (!$args->{'one_time'}) {
 5211: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 5212:     }
 5213: 
 5214:     if ($chome ne 'no_host') {
 5215:        %returnhash=&dump('environment',$cdomain,$cnum);
 5216:        if (!exists($returnhash{'con_lost'})) {
 5217: 	   my $username = $env{'user.name'}; # Defult username
 5218: 	   if(defined $args->{'user'}) {
 5219: 	       $username = $args->{'user'};
 5220: 	   }
 5221:            $returnhash{'home'}= $chome;
 5222: 	   $returnhash{'domain'} = $cdomain;
 5223: 	   $returnhash{'num'} = $cnum;
 5224:            if (!defined($returnhash{'type'})) {
 5225:                $returnhash{'type'} = 'Course';
 5226:            }
 5227:            while (my ($name,$value) = each %returnhash) {
 5228:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 5229:            }
 5230:            $returnhash{'url'}=&clutter($returnhash{'url'});
 5231:            $returnhash{'fn'}=LONCAPA::tempdir() .
 5232: 	       $username.'_'.$cdomain.'_'.$cnum;
 5233:            $envhash{'course.'.$normalid.'.home'}=$chome;
 5234:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 5235:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 5236:        }
 5237:     }
 5238:     if (!$args->{'one_time'}) {
 5239: 	&appenv(\%envhash);
 5240:     }
 5241:     return %returnhash;
 5242: }
 5243: 
 5244: sub update_released_required {
 5245:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
 5246:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
 5247:         $cid = $env{'request.course.id'};
 5248:         $cdom = $env{'course.'.$cid.'.domain'};
 5249:         $cnum = $env{'course.'.$cid.'.num'};
 5250:         $chome = $env{'course.'.$cid.'.home'};
 5251:     }
 5252:     if ($needsrelease) {
 5253:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
 5254:         my $needsupdate;
 5255:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
 5256:             $needsupdate = 1;
 5257:         } else {
 5258:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
 5259:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
 5260:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
 5261:                 $needsupdate = 1;
 5262:             }
 5263:         }
 5264:         if ($needsupdate) {
 5265:             my %needshash = (
 5266:                              'internal.releaserequired' => $needsrelease,
 5267:                             );
 5268:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
 5269:             if ($putresult eq 'ok') {
 5270:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
 5271:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 5272:                 if (ref($crsinfo{$cid}) eq 'HASH') {
 5273:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
 5274:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
 5275:                 }
 5276:             }
 5277:         }
 5278:     }
 5279:     return;
 5280: }
 5281: 
 5282: # -------------------------------------------------See if a user is privileged
 5283: 
 5284: sub privileged {
 5285:     my ($username,$domain,$possdomains,$possroles)=@_;
 5286:     my $now = time;
 5287:     my $roles;
 5288:     if (ref($possroles) eq 'ARRAY') {
 5289:         $roles = $possroles; 
 5290:     } else {
 5291:         $roles = ['dc','su'];
 5292:     }
 5293:     if (ref($possdomains) eq 'ARRAY') {
 5294:         my %privileged = &privileged_by_domain($possdomains,$roles);
 5295:         foreach my $dom (@{$possdomains}) {
 5296:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
 5297:                 (ref($privileged{$dom}) eq 'HASH')) {
 5298:                 foreach my $role (@{$roles}) {
 5299:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 5300:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
 5301:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
 5302:                             return 1 unless (($end && $end < $now) ||
 5303:                                              ($start && $start > $now));
 5304:                         }
 5305:                     }
 5306:                 }
 5307:             }
 5308:         }
 5309:     } else {
 5310:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
 5311:         my $now = time;
 5312: 
 5313:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
 5314:             my ($trole, $tend, $tstart) = split(/_/, $role);
 5315:             if (grep(/^\Q$trole\E$/,@{$roles})) {
 5316:                 return 1 unless ($tend && $tend < $now) 
 5317:                         or ($tstart && $tstart > $now);
 5318:             }
 5319:         }
 5320:     }
 5321:     return 0;
 5322: }
 5323: 
 5324: sub privileged_by_domain {
 5325:     my ($domains,$roles) = @_;
 5326:     my %privileged = ();
 5327:     my $cachetime = 60*60*24;
 5328:     my $now = time;
 5329:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
 5330:         return %privileged;
 5331:     }
 5332:     foreach my $dom (@{$domains}) {
 5333:         next if (ref($privileged{$dom}) eq 'HASH');
 5334:         my $needroles;
 5335:         foreach my $role (@{$roles}) {
 5336:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
 5337:             if (defined($cached)) {
 5338:                 if (ref($result) eq 'HASH') {
 5339:                     $privileged{$dom}{$role} = $result;
 5340:                 }
 5341:             } else {
 5342:                 $needroles = 1;
 5343:             }
 5344:         }
 5345:         if ($needroles) {
 5346:             my %dompersonnel = &get_domain_roles($dom,$roles);
 5347:             $privileged{$dom} = {};
 5348:             foreach my $server (keys(%dompersonnel)) {
 5349:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 5350:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
 5351:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
 5352:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
 5353:                         next if ($end && $end < $now);
 5354:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
 5355:                             $dompersonnel{$server}{$item};
 5356:                     }
 5357:                 }
 5358:             }
 5359:             if (ref($privileged{$dom}) eq 'HASH') {
 5360:                 foreach my $role (@{$roles}) {
 5361:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 5362:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
 5363:                     } else {
 5364:                         my %hash = ();
 5365:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
 5366:                     }
 5367:                 }
 5368:             }
 5369:         }
 5370:     }
 5371:     return %privileged;
 5372: }
 5373: 
 5374: # -------------------------------------------------------- Get user privileges
 5375: 
 5376: sub rolesinit {
 5377:     my ($domain, $username) = @_;
 5378:     my %userroles = ('user.login.time' => time);
 5379:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
 5380: 
 5381:     # firstaccess and timerinterval are related to timed maps/resources. 
 5382:     # also, blocking can be triggered by an activating timer
 5383:     # it's saved in the user's %env.
 5384:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
 5385:     my %timerinterval = &dump('timerinterval', $domain, $username);
 5386:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
 5387:         %timerintchk, %timerintenv);
 5388: 
 5389:     foreach my $key (keys(%firstaccess)) {
 5390:         my ($cid, $rest) = split(/\0/, $key);
 5391:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
 5392:     }
 5393: 
 5394:     foreach my $key (keys(%timerinterval)) {
 5395:         my ($cid,$rest) = split(/\0/,$key);
 5396:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
 5397:     }
 5398: 
 5399:     my %allroles=();
 5400:     my %allgroups=();
 5401: 
 5402:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
 5403:         my $role = $rolesdump{$area};
 5404:         $area =~ s/\_\w\w$//;
 5405: 
 5406:         my ($trole, $tend, $tstart, $group_privs);
 5407: 
 5408:         if ($role =~ /^cr/) {
 5409:         # Custom role, defined by a user 
 5410:         # e.g., user.role.cr/msu/smith/mynewrole
 5411:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 5412:                 $trole = $1;
 5413:                 ($tend, $tstart) = split('_', $2);
 5414:             } else {
 5415:                 $trole = $role;
 5416:             }
 5417:         } elsif ($role =~ m|^gr/|) {
 5418:         # Role of member in a group, defined within a course/community
 5419:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
 5420:             ($trole, $tend, $tstart) = split(/_/, $role);
 5421:             next if $tstart eq '-1';
 5422:             ($trole, $group_privs) = split(/\//, $trole);
 5423:             $group_privs = &unescape($group_privs);
 5424:         } else {
 5425:         # Just a normal role, defined in roles.tab
 5426:             ($trole, $tend, $tstart) = split(/_/,$role);
 5427:         }
 5428: 
 5429:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 5430:                  $username);
 5431:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 5432: 
 5433:         # role expired or not available yet?
 5434:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
 5435:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
 5436: 
 5437:         next if $area eq '' or $trole eq '';
 5438: 
 5439:         my $spec = "$trole.$area";
 5440:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
 5441: 
 5442:         if ($trole =~ /^cr\//) {
 5443:         # Custom role, defined by a user
 5444:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 5445:         } elsif ($trole eq 'gr') {
 5446:         # Role of a member in a group, defined within a course/community
 5447:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 5448:             next;
 5449:         } else {
 5450:         # Normal role, defined in roles.tab
 5451:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 5452:         }
 5453: 
 5454:         my $cid = $tdomain.'_'.$trest;
 5455:         unless ($firstaccchk{$cid}) {
 5456:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
 5457:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
 5458:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
 5459:                         $coursetimerstarts{$cid}{$item}; 
 5460:                 }
 5461:             }
 5462:             $firstaccchk{$cid} = 1;
 5463:         }
 5464:         unless ($timerintchk{$cid}) {
 5465:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
 5466:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
 5467:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
 5468:                        $coursetimerintervals{$cid}{$item};
 5469:                 }
 5470:             }
 5471:             $timerintchk{$cid} = 1;
 5472:         }
 5473:     }
 5474: 
 5475:     @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
 5476:         \%allroles, \%allgroups);
 5477:     $env{'user.adv'} = $userroles{'user.adv'};
 5478: 
 5479:     return (\%userroles,\%firstaccenv,\%timerintenv);
 5480: }
 5481: 
 5482: sub set_arearole {
 5483:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
 5484:     unless ($nolog) {
 5485: # log the associated role with the area
 5486:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 5487:     }
 5488:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 5489: }
 5490: 
 5491: sub custom_roleprivs {
 5492:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 5493:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 5494:     my $homsvr = &homeserver($rauthor,$rdomain);
 5495:     if (&hostname($homsvr) ne '') {
 5496:         my ($rdummy,$roledef)=
 5497:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 5498:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 5499:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 5500:             if (defined($syspriv)) {
 5501:                 if ($trest =~ /^$match_community$/) {
 5502:                     $syspriv =~ s/bre\&S//; 
 5503:                 }
 5504:                 $$allroles{'cm./'}.=':'.$syspriv;
 5505:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 5506:             }
 5507:             if ($tdomain ne '') {
 5508:                 if (defined($dompriv)) {
 5509:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 5510:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 5511:                 }
 5512:                 if (($trest ne '') && (defined($coursepriv))) {
 5513:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 5514:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 5515:                 }
 5516:             }
 5517:         }
 5518:     }
 5519: }
 5520: 
 5521: sub group_roleprivs {
 5522:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 5523:     my $access = 1;
 5524:     my $now = time;
 5525:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 5526:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 5527:     if ($access) {
 5528:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 5529:         $$allgroups{$course}{$group} .=':'.$group_privs;
 5530:     }
 5531: }
 5532: 
 5533: sub standard_roleprivs {
 5534:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 5535:     if (defined($pr{$trole.':s'})) {
 5536:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 5537:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 5538:     }
 5539:     if ($tdomain ne '') {
 5540:         if (defined($pr{$trole.':d'})) {
 5541:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 5542:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 5543:         }
 5544:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 5545:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 5546:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 5547:         }
 5548:     }
 5549: }
 5550: 
 5551: sub set_userprivs {
 5552:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
 5553:     my $author=0;
 5554:     my $adv=0;
 5555:     my %grouproles = ();
 5556:     if (keys(%{$allgroups}) > 0) {
 5557:         my @groupkeys; 
 5558:         foreach my $role (keys(%{$allroles})) {
 5559:             push(@groupkeys,$role);
 5560:         }
 5561:         if (ref($groups_roles) eq 'HASH') {
 5562:             foreach my $key (keys(%{$groups_roles})) {
 5563:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
 5564:                     push(@groupkeys,$key);
 5565:                 }
 5566:             }
 5567:         }
 5568:         if (@groupkeys > 0) {
 5569:             foreach my $role (@groupkeys) {
 5570:                 my ($trole,$area,$sec,$extendedarea);
 5571:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 5572:                     $trole = $1;
 5573:                     $area = $2;
 5574:                     $sec = $3;
 5575:                     $extendedarea = $area.$sec;
 5576:                     if (exists($$allgroups{$area})) {
 5577:                         foreach my $group (keys(%{$$allgroups{$area}})) {
 5578:                             my $spec = $trole.'.'.$extendedarea;
 5579:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
 5580:                                                 $$allgroups{$area}{$group};
 5581:                         }
 5582:                     }
 5583:                 }
 5584:             }
 5585:         }
 5586:     }
 5587:     foreach my $group (keys(%grouproles)) {
 5588:         $$allroles{$group} = $grouproles{$group};
 5589:     }
 5590:     foreach my $role (keys(%{$allroles})) {
 5591:         my %thesepriv;
 5592:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 5593:         foreach my $item (split(/:/,$$allroles{$role})) {
 5594:             if ($item ne '') {
 5595:                 my ($privilege,$restrictions)=split(/&/,$item);
 5596:                 if ($restrictions eq '') {
 5597:                     $thesepriv{$privilege}='F';
 5598:                 } elsif ($thesepriv{$privilege} ne 'F') {
 5599:                     $thesepriv{$privilege}.=$restrictions;
 5600:                 }
 5601:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 5602:             }
 5603:         }
 5604:         my $thesestr='';
 5605:         foreach my $priv (sort(keys(%thesepriv))) {
 5606: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 5607: 	}
 5608:         $userroles->{'user.priv.'.$role} = $thesestr;
 5609:     }
 5610:     return ($author,$adv);
 5611: }
 5612: 
 5613: sub role_status {
 5614:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 5615:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 5616:         my ($one,$two) = split(m{\./},$rolekey,2);
 5617:         (undef,undef,$$role) = split(/\./,$one,3);
 5618:         unless (!defined($$role) || $$role eq '') {
 5619:             $$where = '/'.$two;
 5620:             $$trolecode=$$role.'.'.$$where;
 5621:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 5622:             $$tstatus='is';
 5623:             if ($$tstart && $$tstart>$update) {
 5624:                 $$tstatus='future';
 5625:                 if ($$tstart<$now) {
 5626:                     if ($$tstart && $$tstart>$refresh) {
 5627:                         if (($$where ne '') && ($$role ne '')) {
 5628:                             my (%allroles,%allgroups,$group_privs,
 5629:                                 %groups_roles,@rolecodes);
 5630:                             my %userroles = (
 5631:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 5632:                             );
 5633:                             @rolecodes = ('cm'); 
 5634:                             my $spec=$$role.'.'.$$where;
 5635:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 5636:                             if ($$role =~ /^cr\//) {
 5637:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 5638:                                 push(@rolecodes,'cr');
 5639:                             } elsif ($$role eq 'gr') {
 5640:                                 push(@rolecodes,$$role);
 5641:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 5642:                                                     $env{'user.name'});
 5643:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
 5644:                                 (undef,my $group_privs) = split(/\//,$trole);
 5645:                                 $group_privs = &unescape($group_privs);
 5646:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 5647:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
 5648:                                 &get_groups_roles($tdomain,$trest,
 5649:                                                   \%course_roles,\@rolecodes,
 5650:                                                   \%groups_roles);
 5651:                             } else {
 5652:                                 push(@rolecodes,$$role);
 5653:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 5654:                             }
 5655:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
 5656:                             &appenv(\%userroles,\@rolecodes);
 5657:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 5658:                         }
 5659:                     }
 5660:                     $$tstatus = 'is';
 5661:                 }
 5662:             }
 5663:             if ($$tend) {
 5664:                 if ($$tend<$update) {
 5665:                     $$tstatus='expired';
 5666:                 } elsif ($$tend<$now) {
 5667:                     $$tstatus='will_not';
 5668:                 }
 5669:             }
 5670:         }
 5671:     }
 5672: }
 5673: 
 5674: sub get_groups_roles {
 5675:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
 5676:     return unless((ref($cdom_courseroles) eq 'HASH') && 
 5677:                   (ref($rolecodes) eq 'ARRAY') && 
 5678:                   (ref($groups_roles) eq 'HASH')); 
 5679:     if (keys(%{$cdom_courseroles}) > 0) {
 5680:         my ($cnum) = ($rest =~ /^($match_courseid)/);
 5681:         if ($cdom ne '' && $cnum ne '') {
 5682:             foreach my $key (keys(%{$cdom_courseroles})) {
 5683:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
 5684:                     my $crsrole = $1;
 5685:                     my $crssec = $2;
 5686:                     if ($crsrole =~ /^cr/) {
 5687:                         unless (grep(/^cr$/,@{$rolecodes})) {
 5688:                             push(@{$rolecodes},'cr');
 5689:                         }
 5690:                     } else {
 5691:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
 5692:                             push(@{$rolecodes},$crsrole);
 5693:                         }
 5694:                     }
 5695:                     my $rolekey = "$crsrole./$cdom/$cnum";
 5696:                     if ($crssec ne '') {
 5697:                         $rolekey .= "/$crssec";
 5698:                     }
 5699:                     $rolekey .= './';
 5700:                     $groups_roles->{$rolekey} = $rolecodes;
 5701:                 }
 5702:             }
 5703:         }
 5704:     }
 5705:     return;
 5706: }
 5707: 
 5708: sub delete_env_groupprivs {
 5709:     my ($where,$courseroles,$possroles) = @_;
 5710:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
 5711:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
 5712:     unless (ref($courseroles->{$udom}) eq 'HASH') {
 5713:         %{$courseroles->{$udom}} =
 5714:             &get_my_roles('','','userroles',['active'],
 5715:                           $possroles,[$udom],1);
 5716:     }
 5717:     if (ref($courseroles->{$udom}) eq 'HASH') {
 5718:         foreach my $item (keys(%{$courseroles->{$udom}})) {
 5719:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
 5720:             my $area = '/'.$cdom.'/'.$cnum;
 5721:             my $privkey = "user.priv.$crsrole.$area";
 5722:             if ($crssec ne '') {
 5723:                 $privkey .= '/'.$crssec;
 5724:             }
 5725:             $privkey .= ".$area/$group";
 5726:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
 5727:         }
 5728:     }
 5729:     return;
 5730: }
 5731: 
 5732: sub check_adhoc_privs {
 5733:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
 5734:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 5735:     my $setprivs;
 5736:     if ($env{$cckey}) {
 5737:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 5738:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 5739:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 5740:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
 5741:             $setprivs = 1;
 5742:         }
 5743:     } else {
 5744:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
 5745:         $setprivs = 1;
 5746:     }
 5747:     return $setprivs;
 5748: }
 5749: 
 5750: sub set_adhoc_privileges {
 5751: # role can be cc or ca
 5752:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
 5753:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 5754:     my $spec = $role.'.'.$area;
 5755:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 5756:                                   $env{'user.name'},1);
 5757:     my %ccrole = ();
 5758:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
 5759:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
 5760:     &appenv(\%userroles,[$role,'cm']);
 5761:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 5762:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
 5763:         &appenv( {'request.role'        => $spec,
 5764:                   'request.role.domain' => $dcdom,
 5765:                   'request.course.sec'  => ''
 5766:                  }
 5767:                );
 5768:         my $tadv=0;
 5769:         if (&allowed('adv') eq 'F') { $tadv=1; }
 5770:         &appenv({'request.role.adv'    => $tadv});
 5771:     }
 5772: }
 5773: 
 5774: # --------------------------------------------------------------- get interface
 5775: 
 5776: sub get {
 5777:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5778:    my $items='';
 5779:    foreach my $item (@$storearr) {
 5780:        $items.=&escape($item).'&';
 5781:    }
 5782:    $items=~s/\&$//;
 5783:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5784:    if (!$uname) { $uname=$env{'user.name'}; }
 5785:    my $uhome=&homeserver($uname,$udomain);
 5786: 
 5787:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 5788:    my @pairs=split(/\&/,$rep);
 5789:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 5790:      return @pairs;
 5791:    }
 5792:    my %returnhash=();
 5793:    my $i=0;
 5794:    foreach my $item (@$storearr) {
 5795:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 5796:       $i++;
 5797:    }
 5798:    return %returnhash;
 5799: }
 5800: 
 5801: # --------------------------------------------------------------- del interface
 5802: 
 5803: sub del {
 5804:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5805:    my $items='';
 5806:    foreach my $item (@$storearr) {
 5807:        $items.=&escape($item).'&';
 5808:    }
 5809: 
 5810:    $items=~s/\&$//;
 5811:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5812:    if (!$uname) { $uname=$env{'user.name'}; }
 5813:    my $uhome=&homeserver($uname,$udomain);
 5814:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 5815: }
 5816: 
 5817: # -------------------------------------------------------------- dump interface
 5818: 
 5819: sub unserialize {
 5820:     my ($rep, $escapedkeys) = @_;
 5821: 
 5822:     return {} if $rep =~ /^error/;
 5823: 
 5824:     my %returnhash=();
 5825: 	foreach my $item (split(/\&/,$rep)) {
 5826: 	    my ($key, $value) = split(/=/, $item, 2);
 5827: 	    $key = unescape($key) unless $escapedkeys;
 5828: 	    next if $key =~ /^error: 2 /;
 5829: 	    $returnhash{$key} = &thaw_unescape($value);
 5830: 	}
 5831:     #return %returnhash;
 5832:     return \%returnhash;
 5833: }        
 5834: 
 5835: # see Lond::dump_with_regexp
 5836: # if $escapedkeys hash keys won't get unescaped.
 5837: sub dump {
 5838:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
 5839:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5840:     if (!$uname) { $uname=$env{'user.name'}; }
 5841:     my $uhome=&homeserver($uname,$udomain);
 5842: 
 5843:     if ($regexp) {
 5844:         $regexp=&escape($regexp);
 5845:     } else {
 5846:         $regexp='.';
 5847:     }
 5848:     if (grep { $_ eq $uhome } current_machine_ids()) {
 5849:         # user is hosted on this machine
 5850:         my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
 5851:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
 5852:         return %{unserialize($reply, $escapedkeys)};
 5853:     }
 5854:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 5855:     my @pairs=split(/\&/,$rep);
 5856:     my %returnhash=();
 5857:     if (!($rep =~ /^error/ )) {
 5858: 	foreach my $item (@pairs) {
 5859: 	    my ($key,$value)=split(/=/,$item,2);
 5860:         $key = unescape($key) unless $escapedkeys;
 5861:         #$key = &unescape($key);
 5862: 	    next if ($key =~ /^error: 2 /);
 5863: 	    $returnhash{$key}=&thaw_unescape($value);
 5864: 	}
 5865:     }
 5866:     return %returnhash;
 5867: }
 5868: 
 5869: 
 5870: # --------------------------------------------------------- dumpstore interface
 5871: 
 5872: sub dumpstore {
 5873:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 5874:    # same as dump but keys must be escaped. They may contain colon separated
 5875:    # lists of values that may themself contain colons (e.g. symbs).
 5876:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
 5877: }
 5878: 
 5879: # -------------------------------------------------------------- keys interface
 5880: 
 5881: sub getkeys {
 5882:    my ($namespace,$udomain,$uname)=@_;
 5883:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5884:    if (!$uname) { $uname=$env{'user.name'}; }
 5885:    my $uhome=&homeserver($uname,$udomain);
 5886:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 5887:    my @keyarray=();
 5888:    foreach my $key (split(/\&/,$rep)) {
 5889:       next if ($key =~ /^error: 2 /);
 5890:       push(@keyarray,&unescape($key));
 5891:    }
 5892:    return @keyarray;
 5893: }
 5894: 
 5895: # --------------------------------------------------------------- currentdump
 5896: sub currentdump {
 5897:    my ($courseid,$sdom,$sname)=@_;
 5898:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 5899:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 5900:    $sname    = $env{'user.name'}         if (! defined($sname));
 5901:    my $uhome = &homeserver($sname,$sdom);
 5902:    my $rep;
 5903: 
 5904:    if (grep { $_ eq $uhome } current_machine_ids()) {
 5905:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
 5906:                    $courseid)));
 5907:    } else {
 5908:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 5909:    }
 5910: 
 5911:    return if ($rep =~ /^(error:|no_such_host)/);
 5912:    #
 5913:    my %returnhash=();
 5914:    #
 5915:    if ($rep eq "unknown_cmd") { 
 5916:        # an old lond will not know currentdump
 5917:        # Do a dump and make it look like a currentdump
 5918:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 5919:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 5920:        my %hash = @tmp;
 5921:        @tmp=();
 5922:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 5923:    } else {
 5924:        my @pairs=split(/\&/,$rep);
 5925:        foreach my $pair (@pairs) {
 5926:            my ($key,$value)=split(/=/,$pair,2);
 5927:            my ($symb,$param) = split(/:/,$key);
 5928:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 5929:                                                         &thaw_unescape($value);
 5930:        }
 5931:    }
 5932:    return %returnhash;
 5933: }
 5934: 
 5935: sub convert_dump_to_currentdump{
 5936:     my %hash = %{shift()};
 5937:     my %returnhash;
 5938:     # Code ripped from lond, essentially.  The only difference
 5939:     # here is the unescaping done by lonnet::dump().  Conceivably
 5940:     # we might run in to problems with parameter names =~ /^v\./
 5941:     while (my ($key,$value) = each(%hash)) {
 5942:         my ($v,$symb,$param) = split(/:/,$key);
 5943: 	$symb  = &unescape($symb);
 5944: 	$param = &unescape($param);
 5945:         next if ($v eq 'version' || $symb eq 'keys');
 5946:         next if (exists($returnhash{$symb}) &&
 5947:                  exists($returnhash{$symb}->{$param}) &&
 5948:                  $returnhash{$symb}->{'v.'.$param} > $v);
 5949:         $returnhash{$symb}->{$param}=$value;
 5950:         $returnhash{$symb}->{'v.'.$param}=$v;
 5951:     }
 5952:     #
 5953:     # Remove all of the keys in the hashes which keep track of
 5954:     # the version of the parameter.
 5955:     while (my ($symb,$param_hash) = each(%returnhash)) {
 5956:         # use a foreach because we are going to delete from the hash.
 5957:         foreach my $key (keys(%$param_hash)) {
 5958:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 5959:         }
 5960:     }
 5961:     return \%returnhash;
 5962: }
 5963: 
 5964: # ------------------------------------------------------ critical inc interface
 5965: 
 5966: sub cinc {
 5967:     return &inc(@_,'critical');
 5968: }
 5969: 
 5970: # --------------------------------------------------------------- inc interface
 5971: 
 5972: sub inc {
 5973:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 5974:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5975:     if (!$uname) { $uname=$env{'user.name'}; }
 5976:     my $uhome=&homeserver($uname,$udomain);
 5977:     my $items='';
 5978:     if (! ref($store)) {
 5979:         # got a single value, so use that instead
 5980:         $items = &escape($store).'=&';
 5981:     } elsif (ref($store) eq 'SCALAR') {
 5982:         $items = &escape($$store).'=&';        
 5983:     } elsif (ref($store) eq 'ARRAY') {
 5984:         $items = join('=&',map {&escape($_);} @{$store});
 5985:     } elsif (ref($store) eq 'HASH') {
 5986:         while (my($key,$value) = each(%{$store})) {
 5987:             $items.= &escape($key).'='.&escape($value).'&';
 5988:         }
 5989:     }
 5990:     $items=~s/\&$//;
 5991:     if ($critical) {
 5992: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 5993:     } else {
 5994: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 5995:     }
 5996: }
 5997: 
 5998: # --------------------------------------------------------------- put interface
 5999: 
 6000: sub put {
 6001:    my ($namespace,$storehash,$udomain,$uname)=@_;
 6002:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6003:    if (!$uname) { $uname=$env{'user.name'}; }
 6004:    my $uhome=&homeserver($uname,$udomain);
 6005:    my $items='';
 6006:    foreach my $item (keys(%$storehash)) {
 6007:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 6008:    }
 6009:    $items=~s/\&$//;
 6010:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 6011: }
 6012: 
 6013: # ------------------------------------------------------------ newput interface
 6014: 
 6015: sub newput {
 6016:    my ($namespace,$storehash,$udomain,$uname)=@_;
 6017:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6018:    if (!$uname) { $uname=$env{'user.name'}; }
 6019:    my $uhome=&homeserver($uname,$udomain);
 6020:    my $items='';
 6021:    foreach my $key (keys(%$storehash)) {
 6022:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 6023:    }
 6024:    $items=~s/\&$//;
 6025:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 6026: }
 6027: 
 6028: # ---------------------------------------------------------  putstore interface
 6029: 
 6030: sub putstore {
 6031:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
 6032:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6033:    if (!$uname) { $uname=$env{'user.name'}; }
 6034:    my $uhome=&homeserver($uname,$udomain);
 6035:    my $items='';
 6036:    foreach my $key (keys(%$storehash)) {
 6037:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 6038:    }
 6039:    $items=~s/\&$//;
 6040:    my $esc_symb=&escape($symb);
 6041:    my $esc_v=&escape($version);
 6042:    my $reply =
 6043:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 6044: 	      $uhome);
 6045:    if (($tolog) && ($reply eq 'ok')) {
 6046:        my $namevalue='';
 6047:        foreach my $key (keys(%{$storehash})) {
 6048:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 6049:        }
 6050:        $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
 6051:                      '&host='.&escape($perlvar{'lonHostID'}).
 6052:                      '&version='.$esc_v.
 6053:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
 6054:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
 6055:    }
 6056:    if ($reply eq 'unknown_cmd') {
 6057:        # gfall back to way things use to be done
 6058:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 6059: 			    $uname);
 6060:    }
 6061:    return $reply;
 6062: }
 6063: 
 6064: sub old_putstore {
 6065:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 6066:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 6067:     if (!$uname) { $uname=$env{'user.name'}; }
 6068:     my $uhome=&homeserver($uname,$udomain);
 6069:     my %newstorehash;
 6070:     foreach my $item (keys(%$storehash)) {
 6071: 	my $key = $version.':'.&escape($symb).':'.$item;
 6072: 	$newstorehash{$key} = $storehash->{$item};
 6073:     }
 6074:     my $items='';
 6075:     my %allitems = ();
 6076:     foreach my $item (keys(%newstorehash)) {
 6077: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 6078: 	    my $key = $1.':keys:'.$2;
 6079: 	    $allitems{$key} .= $3.':';
 6080: 	}
 6081: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 6082:     }
 6083:     foreach my $item (keys(%allitems)) {
 6084: 	$allitems{$item} =~ s/\:$//;
 6085: 	$items.= $item.'='.$allitems{$item}.'&';
 6086:     }
 6087:     $items=~s/\&$//;
 6088:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 6089: }
 6090: 
 6091: # ------------------------------------------------------ critical put interface
 6092: 
 6093: sub cput {
 6094:    my ($namespace,$storehash,$udomain,$uname)=@_;
 6095:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6096:    if (!$uname) { $uname=$env{'user.name'}; }
 6097:    my $uhome=&homeserver($uname,$udomain);
 6098:    my $items='';
 6099:    foreach my $item (keys(%$storehash)) {
 6100:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 6101:    }
 6102:    $items=~s/\&$//;
 6103:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 6104: }
 6105: 
 6106: # -------------------------------------------------------------- eget interface
 6107: 
 6108: sub eget {
 6109:    my ($namespace,$storearr,$udomain,$uname)=@_;
 6110:    my $items='';
 6111:    foreach my $item (@$storearr) {
 6112:        $items.=&escape($item).'&';
 6113:    }
 6114:    $items=~s/\&$//;
 6115:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6116:    if (!$uname) { $uname=$env{'user.name'}; }
 6117:    my $uhome=&homeserver($uname,$udomain);
 6118:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 6119:    my @pairs=split(/\&/,$rep);
 6120:    my %returnhash=();
 6121:    my $i=0;
 6122:    foreach my $item (@$storearr) {
 6123:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 6124:       $i++;
 6125:    }
 6126:    return %returnhash;
 6127: }
 6128: 
 6129: # ------------------------------------------------------------ tmpput interface
 6130: sub tmpput {
 6131:     my ($storehash,$server,$context)=@_;
 6132:     my $items='';
 6133:     foreach my $item (keys(%$storehash)) {
 6134: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 6135:     }
 6136:     $items=~s/\&$//;
 6137:     if (defined($context)) {
 6138:         $items .= ':'.&escape($context);
 6139:     }
 6140:     return &reply("tmpput:$items",$server);
 6141: }
 6142: 
 6143: # ------------------------------------------------------------ tmpget interface
 6144: sub tmpget {
 6145:     my ($token,$server)=@_;
 6146:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 6147:     my $rep=&reply("tmpget:$token",$server);
 6148:     my %returnhash;
 6149:     foreach my $item (split(/\&/,$rep)) {
 6150: 	my ($key,$value)=split(/=/,$item);
 6151:         next if ($key =~ /^error: 2 /);
 6152: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 6153:     }
 6154:     return %returnhash;
 6155: }
 6156: 
 6157: # ------------------------------------------------------------ tmpdel interface
 6158: sub tmpdel {
 6159:     my ($token,$server)=@_;
 6160:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 6161:     return &reply("tmpdel:$token",$server);
 6162: }
 6163: 
 6164: # ------------------------------------------------------------ get_timebased_id 
 6165: 
 6166: sub get_timebased_id {
 6167:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
 6168:         $maxtries) = @_;
 6169:     my ($newid,$error,$dellock);
 6170:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
 6171:         return ('','ok','invalid call to get suffix');
 6172:     }
 6173: 
 6174: # set defaults for any optional args for which values were not supplied
 6175:     if ($who eq '') {
 6176:         $who = $env{'user.name'}.':'.$env{'user.domain'};
 6177:     }
 6178:     if (!$locktries) {
 6179:         $locktries = 3;
 6180:     }
 6181:     if (!$maxtries) {
 6182:         $maxtries = 10;
 6183:     }
 6184:     
 6185:     if (($cdom eq '') || ($cnum eq '')) {
 6186:         if ($env{'request.course.id'}) {
 6187:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6188:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 6189:         }
 6190:         if (($cdom eq '') || ($cnum eq '')) {
 6191:             return ('','ok','call to get suffix not in course context');
 6192:         }
 6193:     }
 6194: 
 6195: # construct locking item
 6196:     my $lockhash = {
 6197:                       $prefix."\0".'locked_'.$keyid => $who,
 6198:                    };
 6199:     my $tries = 0;
 6200: 
 6201: # attempt to get lock on nohist_$namespace file
 6202:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 6203:     while (($gotlock ne 'ok') && $tries <$locktries) {
 6204:         $tries ++;
 6205:         sleep 1;
 6206:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 6207:     }
 6208: 
 6209: # attempt to get unique identifier, based on current timestamp
 6210:     if ($gotlock eq 'ok') {
 6211:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
 6212:         my $id = time;
 6213:         $newid = $id;
 6214:         if ($idtype eq 'addcode') {
 6215:             $newid .= &sixnum_code();
 6216:         }
 6217:         my $idtries = 0;
 6218:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
 6219:             if ($idtype eq 'concat') {
 6220:                 $newid = $id.$idtries;
 6221:             } elsif ($idtype eq 'addcode') {
 6222:                 $newid = $newid.&sixnum_code();
 6223:             } else {
 6224:                 $newid ++;
 6225:             }
 6226:             $idtries ++;
 6227:         }
 6228:         if (!exists($inuse{$prefix."\0".$newid})) {
 6229:             my %new_item =  (
 6230:                               $prefix."\0".$newid => $who,
 6231:                             );
 6232:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
 6233:                                                  $cdom,$cnum);
 6234:             if ($putresult ne 'ok') {
 6235:                 undef($newid);
 6236:                 $error = 'error saving new item: '.$putresult;
 6237:             }
 6238:         } else {
 6239:              undef($newid);
 6240:              $error = ('error: no unique suffix available for the new item ');
 6241:         }
 6242: #  remove lock
 6243:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
 6244:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
 6245:     } else {
 6246:         $error = "error: could not obtain lockfile\n";
 6247:         $dellock = 'ok';
 6248:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
 6249:             $dellock = 'nolock';
 6250:         }
 6251:     }
 6252:     return ($newid,$dellock,$error);
 6253: }
 6254: 
 6255: sub sixnum_code {
 6256:     my $code;
 6257:     for (0..6) {
 6258:         $code .= int( rand(9) );
 6259:     }
 6260:     return $code;
 6261: }
 6262: 
 6263: # -------------------------------------------------- portfolio access checking
 6264: 
 6265: sub portfolio_access {
 6266:     my ($requrl,$clientip) = @_;
 6267:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 6268:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
 6269:     if ($result) {
 6270:         my %setters;
 6271:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 6272:             my ($startblock,$endblock) =
 6273:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 6274:             if ($startblock && $endblock) {
 6275:                 return 'B';
 6276:             }
 6277:         } else {
 6278:             my ($startblock,$endblock) =
 6279:                 &Apache::loncommon::blockcheck(\%setters,'port');
 6280:             if ($startblock && $endblock) {
 6281:                 return 'B';
 6282:             }
 6283:         }
 6284:     }
 6285:     if ($result eq 'ok') {
 6286:        return 'F';
 6287:     } elsif ($result =~ /^[^:]+:guest_/) {
 6288:        return 'A';
 6289:     }
 6290:     return '';
 6291: }
 6292: 
 6293: sub get_portfolio_access {
 6294:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
 6295: 
 6296:     if (!ref($access_hash)) {
 6297: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 6298: 	my %access_controls = &get_access_controls($current_perms,$group,
 6299: 						   $file_name);
 6300: 	$access_hash = $access_controls{$file_name};
 6301:     }
 6302: 
 6303:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
 6304:     my $now = time;
 6305:     if (ref($access_hash) eq 'HASH') {
 6306:         foreach my $key (keys(%{$access_hash})) {
 6307:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 6308:             if ($start > $now) {
 6309:                 next;
 6310:             }
 6311:             if ($end && $end<$now) {
 6312:                 next;
 6313:             }
 6314:             if ($scope eq 'public') {
 6315:                 $public = $key;
 6316:                 last;
 6317:             } elsif ($scope eq 'guest') {
 6318:                 $guest = $key;
 6319:             } elsif ($scope eq 'domains') {
 6320:                 push(@domains,$key);
 6321:             } elsif ($scope eq 'users') {
 6322:                 push(@users,$key);
 6323:             } elsif ($scope eq 'course') {
 6324:                 push(@courses,$key);
 6325:             } elsif ($scope eq 'group') {
 6326:                 push(@groups,$key);
 6327:             } elsif ($scope eq 'ip') {
 6328:                 push(@ips,$key);
 6329:             }
 6330:         }
 6331:         if ($public) {
 6332:             return 'ok';
 6333:         } elsif (@ips > 0) {
 6334:             my $allowed;
 6335:             foreach my $ipkey (@ips) {
 6336:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
 6337:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
 6338:                         $allowed = 1;
 6339:                         last; 
 6340:                     }
 6341:                 }
 6342:             }
 6343:             if ($allowed) {
 6344:                 return 'ok';
 6345:             }
 6346:         }
 6347:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 6348:             if ($guest) {
 6349:                 return $guest;
 6350:             }
 6351:         } else {
 6352:             if (@domains > 0) {
 6353:                 foreach my $domkey (@domains) {
 6354:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 6355:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 6356:                             return 'ok';
 6357:                         }
 6358:                     }
 6359:                 }
 6360:             }
 6361:             if (@users > 0) {
 6362:                 foreach my $userkey (@users) {
 6363:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 6364:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 6365:                             if (ref($item) eq 'HASH') {
 6366:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 6367:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 6368:                                     return 'ok';
 6369:                                 }
 6370:                             }
 6371:                         }
 6372:                     } 
 6373:                 }
 6374:             }
 6375:             my %roleshash;
 6376:             my @courses_and_groups = @courses;
 6377:             push(@courses_and_groups,@groups); 
 6378:             if (@courses_and_groups > 0) {
 6379:                 my (%allgroups,%allroles); 
 6380:                 my ($start,$end,$role,$sec,$group);
 6381:                 foreach my $envkey (%env) {
 6382:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 6383:                         my $cid = $2.'_'.$3; 
 6384:                         if ($1 eq 'gr') {
 6385:                             $group = $4;
 6386:                             $allgroups{$cid}{$group} = $env{$envkey};
 6387:                         } else {
 6388:                             if ($4 eq '') {
 6389:                                 $sec = 'none';
 6390:                             } else {
 6391:                                 $sec = $4;
 6392:                             }
 6393:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 6394:                         }
 6395:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 6396:                         my $cid = $2.'_'.$3;
 6397:                         if ($4 eq '') {
 6398:                             $sec = 'none';
 6399:                         } else {
 6400:                             $sec = $4;
 6401:                         }
 6402:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 6403:                     }
 6404:                 }
 6405:                 if (keys(%allroles) == 0) {
 6406:                     return;
 6407:                 }
 6408:                 foreach my $key (@courses_and_groups) {
 6409:                     my %content = %{$$access_hash{$key}};
 6410:                     my $cnum = $content{'number'};
 6411:                     my $cdom = $content{'domain'};
 6412:                     my $cid = $cdom.'_'.$cnum;
 6413:                     if (!exists($allroles{$cid})) {
 6414:                         next;
 6415:                     }    
 6416:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 6417:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 6418:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 6419:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 6420:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 6421:                         foreach my $role (keys(%{$allroles{$cid}})) {
 6422:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 6423:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 6424:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 6425:                                         if (grep/^all$/,@sections) {
 6426:                                             return 'ok';
 6427:                                         } else {
 6428:                                             if (grep/^$sec$/,@sections) {
 6429:                                                 return 'ok';
 6430:                                             }
 6431:                                         }
 6432:                                     }
 6433:                                 }
 6434:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 6435:                                     if (grep/^none$/,@groups) {
 6436:                                         return 'ok';
 6437:                                     }
 6438:                                 } else {
 6439:                                     if (grep/^all$/,@groups) {
 6440:                                         return 'ok';
 6441:                                     } 
 6442:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 6443:                                         if (grep/^$group$/,@groups) {
 6444:                                             return 'ok';
 6445:                                         }
 6446:                                     }
 6447:                                 } 
 6448:                             }
 6449:                         }
 6450:                     }
 6451:                 }
 6452:             }
 6453:             if ($guest) {
 6454:                 return $guest;
 6455:             }
 6456:         }
 6457:     }
 6458:     return;
 6459: }
 6460: 
 6461: sub course_group_datechecker {
 6462:     my ($dates,$now,$status) = @_;
 6463:     my ($start,$end) = split(/\./,$dates);
 6464:     if (!$start && !$end) {
 6465:         return 'ok';
 6466:     }
 6467:     if (grep/^active$/,@{$status}) {
 6468:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 6469:             return 'ok';
 6470:         }
 6471:     }
 6472:     if (grep/^previous$/,@{$status}) {
 6473:         if ($end > $now ) {
 6474:             return 'ok';
 6475:         }
 6476:     }
 6477:     if (grep/^future$/,@{$status}) {
 6478:         if ($start > $now) {
 6479:             return 'ok';
 6480:         }
 6481:     }
 6482:     return; 
 6483: }
 6484: 
 6485: sub parse_portfolio_url {
 6486:     my ($url) = @_;
 6487: 
 6488:     my ($type,$udom,$unum,$group,$file_name);
 6489:     
 6490:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 6491: 	$type = 1;
 6492:         $udom = $1;
 6493:         $unum = $2;
 6494:         $file_name = $3;
 6495:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 6496: 	$type = 2;
 6497:         $udom = $1;
 6498:         $unum = $2;
 6499:         $group = $3;
 6500:         $file_name = $3.'/'.$4;
 6501:     }
 6502:     if (wantarray) {
 6503: 	return ($type,$udom,$unum,$file_name,$group);
 6504:     }
 6505:     return $type;
 6506: }
 6507: 
 6508: sub is_portfolio_url {
 6509:     my ($url) = @_;
 6510:     return scalar(&parse_portfolio_url($url));
 6511: }
 6512: 
 6513: sub is_portfolio_file {
 6514:     my ($file) = @_;
 6515:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 6516:         return 1;
 6517:     }
 6518:     return;
 6519: }
 6520: 
 6521: sub usertools_access {
 6522:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
 6523:     my ($access,%tools);
 6524:     if ($context eq '') {
 6525:         $context = 'tools';
 6526:     }
 6527:     if ($context eq 'requestcourses') {
 6528:         %tools = (
 6529:                       official   => 1,
 6530:                       unofficial => 1,
 6531:                       community  => 1,
 6532:                       textbook   => 1,
 6533:                  );
 6534:     } elsif ($context eq 'requestauthor') {
 6535:         %tools = (
 6536:                       requestauthor => 1,
 6537:                  );
 6538:     } else {
 6539:         %tools = (
 6540:                       aboutme   => 1,
 6541:                       blog      => 1,
 6542:                       webdav    => 1,
 6543:                       portfolio => 1,
 6544:                  );
 6545:     }
 6546:     return if (!defined($tools{$tool}));
 6547: 
 6548:     if (($udom eq '') || ($uname eq '')) {
 6549:         $udom = $env{'user.domain'};
 6550:         $uname = $env{'user.name'};
 6551:     }
 6552: 
 6553:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 6554:         if ($action ne 'reload') {
 6555:             if ($context eq 'requestcourses') {
 6556:                 return $env{'environment.canrequest.'.$tool};
 6557:             } elsif ($context eq 'requestauthor') {
 6558:                 return $env{'environment.canrequest.author'};
 6559:             } else {
 6560:                 return $env{'environment.availabletools.'.$tool};
 6561:             }
 6562:         }
 6563:     }
 6564: 
 6565:     my ($toolstatus,$inststatus,$envkey);
 6566:     if ($context eq 'requestauthor') {
 6567:         $envkey = $context; 
 6568:     } else {
 6569:         $envkey = $context.'.'.$tool;
 6570:     }
 6571: 
 6572:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 6573:          ($action ne 'reload')) {
 6574:         $toolstatus = $env{'environment.'.$envkey};
 6575:         $inststatus = $env{'environment.inststatus'};
 6576:     } else {
 6577:         if (ref($userenvref) eq 'HASH') {
 6578:             $toolstatus = $userenvref->{$envkey};
 6579:             $inststatus = $userenvref->{'inststatus'};
 6580:         } else {
 6581:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
 6582:             $toolstatus = $userenv{$envkey};
 6583:             $inststatus = $userenv{'inststatus'};
 6584:         }
 6585:     }
 6586: 
 6587:     if ($toolstatus ne '') {
 6588:         if ($toolstatus) {
 6589:             $access = 1;
 6590:         } else {
 6591:             $access = 0;
 6592:         }
 6593:         return $access;
 6594:     }
 6595: 
 6596:     my ($is_adv,%domdef);
 6597:     if (ref($is_advref) eq 'HASH') {
 6598:         $is_adv = $is_advref->{'is_adv'};
 6599:     } else {
 6600:         $is_adv = &is_advanced_user($udom,$uname);
 6601:     }
 6602:     if (ref($domdefref) eq 'HASH') {
 6603:         %domdef = %{$domdefref};
 6604:     } else {
 6605:         %domdef = &get_domain_defaults($udom);
 6606:     }
 6607:     if (ref($domdef{$tool}) eq 'HASH') {
 6608:         if ($is_adv) {
 6609:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 6610:                 if ($domdef{$tool}{'_LC_adv'}) { 
 6611:                     $access = 1;
 6612:                 } else {
 6613:                     $access = 0;
 6614:                 }
 6615:                 return $access;
 6616:             }
 6617:         }
 6618:         if ($inststatus ne '') {
 6619:             my ($hasaccess,$hasnoaccess);
 6620:             foreach my $affiliation (split(/:/,$inststatus)) {
 6621:                 if ($domdef{$tool}{$affiliation} ne '') { 
 6622:                     if ($domdef{$tool}{$affiliation}) {
 6623:                         $hasaccess = 1;
 6624:                     } else {
 6625:                         $hasnoaccess = 1;
 6626:                     }
 6627:                 }
 6628:             }
 6629:             if ($hasaccess || $hasnoaccess) {
 6630:                 if ($hasaccess) {
 6631:                     $access = 1;
 6632:                 } elsif ($hasnoaccess) {
 6633:                     $access = 0; 
 6634:                 }
 6635:                 return $access;
 6636:             }
 6637:         } else {
 6638:             if ($domdef{$tool}{'default'} ne '') {
 6639:                 if ($domdef{$tool}{'default'}) {
 6640:                     $access = 1;
 6641:                 } elsif ($domdef{$tool}{'default'} == 0) {
 6642:                     $access = 0;
 6643:                 }
 6644:                 return $access;
 6645:             }
 6646:         }
 6647:     } else {
 6648:         if (($context eq 'tools') && ($tool ne 'webdav')) {
 6649:             $access = 1;
 6650:         } else {
 6651:             $access = 0;
 6652:         }
 6653:         return $access;
 6654:     }
 6655: }
 6656: 
 6657: sub is_course_owner {
 6658:     my ($cdom,$cnum,$udom,$uname) = @_;
 6659:     if (($udom eq '') || ($uname eq '')) {
 6660:         $udom = $env{'user.domain'};
 6661:         $uname = $env{'user.name'};
 6662:     }
 6663:     unless (($udom eq '') || ($uname eq '')) {
 6664:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
 6665:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
 6666:                 return 1;
 6667:             } else {
 6668:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
 6669:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
 6670:                     return 1;
 6671:                 }
 6672:             }
 6673:         }
 6674:     }
 6675:     return;
 6676: }
 6677: 
 6678: sub is_advanced_user {
 6679:     my ($udom,$uname) = @_;
 6680:     if ($udom ne '' && $uname ne '') {
 6681:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 6682:             if (wantarray) {
 6683:                 return ($env{'user.adv'},$env{'user.author'});
 6684:             } else {
 6685:                 return $env{'user.adv'};
 6686:             }
 6687:         }
 6688:     }
 6689:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 6690:     my %allroles;
 6691:     my ($is_adv,$is_author);
 6692:     foreach my $role (keys(%roleshash)) {
 6693:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 6694:         my $area = '/'.$tdomain.'/'.$trest;
 6695:         if ($sec ne '') {
 6696:             $area .= '/'.$sec;
 6697:         }
 6698:         if (($area ne '') && ($trole ne '')) {
 6699:             my $spec=$trole.'.'.$area;
 6700:             if ($trole =~ /^cr\//) {
 6701:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 6702:             } elsif ($trole ne 'gr') {
 6703:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 6704:             }
 6705:             if ($trole eq 'au') {
 6706:                 $is_author = 1;
 6707:             }
 6708:         }
 6709:     }
 6710:     foreach my $role (keys(%allroles)) {
 6711:         last if ($is_adv);
 6712:         foreach my $item (split(/:/,$allroles{$role})) {
 6713:             if ($item ne '') {
 6714:                 my ($privilege,$restrictions)=split(/&/,$item);
 6715:                 if ($privilege eq 'adv') {
 6716:                     $is_adv = 1;
 6717:                     last;
 6718:                 }
 6719:             }
 6720:         }
 6721:     }
 6722:     if (wantarray) {
 6723:         return ($is_adv,$is_author);
 6724:     }
 6725:     return $is_adv;
 6726: }
 6727: 
 6728: sub check_can_request {
 6729:     my ($dom,$can_request,$request_domains) = @_;
 6730:     my $canreq = 0;
 6731:     my ($types,$typename) = &Apache::loncommon::course_types();
 6732:     my @options = ('approval','validate','autolimit');
 6733:     my $optregex = join('|',@options);
 6734:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
 6735:         foreach my $type (@{$types}) {
 6736:             if (&usertools_access($env{'user.name'},
 6737:                                   $env{'user.domain'},
 6738:                                   $type,undef,'requestcourses')) {
 6739:                 $canreq ++;
 6740:                 if (ref($request_domains) eq 'HASH') {
 6741:                     push(@{$request_domains->{$type}},$env{'user.domain'});
 6742:                 }
 6743:                 if ($dom eq $env{'user.domain'}) {
 6744:                     $can_request->{$type} = 1;
 6745:                 }
 6746:             }
 6747:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
 6748:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
 6749:                 if (@curr > 0) {
 6750:                     foreach my $item (@curr) {
 6751:                         if (ref($request_domains) eq 'HASH') {
 6752:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
 6753:                             if ($otherdom ne '') {
 6754:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
 6755:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
 6756:                                         push(@{$request_domains->{$type}},$otherdom);
 6757:                                     }
 6758:                                 } else {
 6759:                                     push(@{$request_domains->{$type}},$otherdom);
 6760:                                 }
 6761:                             }
 6762:                         }
 6763:                     }
 6764:                     unless($dom eq $env{'user.domain'}) {
 6765:                         $canreq ++;
 6766:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
 6767:                             $can_request->{$type} = 1;
 6768:                         }
 6769:                     }
 6770:                 }
 6771:             }
 6772:         }
 6773:     }
 6774:     return $canreq;
 6775: }
 6776: 
 6777: # ---------------------------------------------- Custom access rule evaluation
 6778: 
 6779: sub customaccess {
 6780:     my ($priv,$uri)=@_;
 6781:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 6782:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 6783:     $udom = &LONCAPA::clean_domain($udom);
 6784:     $ucrs = &LONCAPA::clean_username($ucrs);
 6785:     my $access=0;
 6786:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 6787: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 6788: 	if ($type eq 'user') {
 6789: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 6790: 		my ($tdom,$tuname)=split(m{/},$scope);
 6791: 		if ($tdom) {
 6792: 		    if ($tdom ne $env{'user.domain'}) { next; }
 6793: 		}
 6794: 		if ($tuname) {
 6795: 		    if ($tuname ne $env{'user.name'}) { next; }
 6796: 		}
 6797: 		$access=($effect eq 'allow');
 6798: 		last;
 6799: 	    }
 6800: 	} else {
 6801: 	    if ($role) {
 6802: 		if ($role ne $urole) { next; }
 6803: 	    }
 6804: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 6805: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 6806: 		if ($tdom) {
 6807: 		    if ($tdom ne $udom) { next; }
 6808: 		}
 6809: 		if ($tcrs) {
 6810: 		    if ($tcrs ne $ucrs) { next; }
 6811: 		}
 6812: 		if ($tsec) {
 6813: 		    if ($tsec ne $usec) { next; }
 6814: 		}
 6815: 		$access=($effect eq 'allow');
 6816: 		last;
 6817: 	    }
 6818: 	    if ($realm eq '' && $role eq '') {
 6819: 		$access=($effect eq 'allow');
 6820: 	    }
 6821: 	}
 6822:     }
 6823:     return $access;
 6824: }
 6825: 
 6826: # ------------------------------------------------- Check for a user privilege
 6827: 
 6828: sub allowed {
 6829:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
 6830:     my $ver_orguri=$uri;
 6831:     $uri=&deversion($uri);
 6832:     my $orguri=$uri;
 6833:     $uri=&declutter($uri);
 6834: 
 6835:     if ($priv eq 'evb') {
 6836: # Evade communication block restrictions for specified role in a course
 6837:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 6838:             return $1;
 6839:         } else {
 6840:             return;
 6841:         }
 6842:     }
 6843: 
 6844:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 6845: # Free bre access to adm and meta resources
 6846:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
 6847: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 6848: 	&& ($priv eq 'bre')) {
 6849: 	return 'F';
 6850:     }
 6851: 
 6852: # Free bre access to user's own portfolio contents
 6853:     my ($space,$domain,$name,@dir)=split('/',$uri);
 6854:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 6855: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 6856:         my %setters;
 6857:         my ($startblock,$endblock) = 
 6858:             &Apache::loncommon::blockcheck(\%setters,'port');
 6859:         if ($startblock && $endblock) {
 6860:             return 'B';
 6861:         } else {
 6862:             return 'F';
 6863:         }
 6864:     }
 6865: 
 6866: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 6867:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 6868:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 6869:         if (exists($env{'request.course.id'})) {
 6870:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6871:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 6872:             if (($domain eq $cdom) && ($name eq $cnum)) {
 6873:                 my $courseprivid=$env{'request.course.id'};
 6874:                 $courseprivid=~s/\_/\//;
 6875:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 6876:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 6877:                     return $1; 
 6878:                 } else {
 6879:                     if ($env{'request.course.sec'}) {
 6880:                         $courseprivid.='/'.$env{'request.course.sec'};
 6881:                     }
 6882:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 6883:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 6884:                         return $2;
 6885:                     }
 6886:                 }
 6887:             }
 6888:         }
 6889:     }
 6890: 
 6891: # Free bre to public access
 6892: 
 6893:     if ($priv eq 'bre') {
 6894:         my $copyright=&metadata($uri,'copyright');
 6895: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 6896:            return 'F'; 
 6897:         }
 6898:         if ($copyright eq 'priv') {
 6899:             $uri=~/([^\/]+)\/([^\/]+)\//;
 6900: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 6901: 		return '';
 6902:             }
 6903:         }
 6904:         if ($copyright eq 'domain') {
 6905:             $uri=~/([^\/]+)\/([^\/]+)\//;
 6906: 	    unless (($env{'user.domain'} eq $1) ||
 6907:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 6908: 		return '';
 6909:             }
 6910:         }
 6911:         if ($env{'request.role'}=~ /li\.\//) {
 6912:             # Library role, so allow browsing of resources in this domain.
 6913:             return 'F';
 6914:         }
 6915:         if ($copyright eq 'custom') {
 6916: 	    unless (&customaccess($priv,$uri)) { return ''; }
 6917:         }
 6918:     }
 6919:     # Domain coordinator is trying to create a course
 6920:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 6921:         # uri is the requested domain in this case.
 6922:         # comparison to 'request.role.domain' shows if the user has selected
 6923:         # a role of dc for the domain in question.
 6924:         return 'F' if ($uri eq $env{'request.role.domain'});
 6925:     }
 6926: 
 6927:     my $thisallowed='';
 6928:     my $statecond=0;
 6929:     my $courseprivid='';
 6930: 
 6931:     my $ownaccess;
 6932:     # Community Coordinator or Assistant Co-author browsing resource space.
 6933:     if (($priv eq 'bro') && ($env{'user.author'})) {
 6934:         if ($uri eq '') {
 6935:             $ownaccess = 1;
 6936:         } else {
 6937:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
 6938:                 my $udom = $env{'user.domain'};
 6939:                 my $uname = $env{'user.name'};
 6940:                 if ($uri =~ m{^\Q$udom\E/?$}) {
 6941:                     $ownaccess = 1;
 6942:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
 6943:                     unless ($uri =~ m{\.\./}) {
 6944:                         $ownaccess = 1;
 6945:                     }
 6946:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
 6947:                     my $now = time;
 6948:                     if ($uri =~ m{^([^/]+)/?$}) {
 6949:                         my $adom = $1;
 6950:                         foreach my $key (keys(%env)) {
 6951:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
 6952:                                 my ($start,$end) = split('.',$env{$key});
 6953:                                 if (($now >= $start) && (!$end || $end < $now)) {
 6954:                                     $ownaccess = 1;
 6955:                                     last;
 6956:                                 }
 6957:                             }
 6958:                         }
 6959:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
 6960:                         my $adom = $1;
 6961:                         my $aname = $2;
 6962:                         foreach my $role ('ca','aa') { 
 6963:                             if ($env{"user.role.$role./$adom/$aname"}) {
 6964:                                 my ($start,$end) =
 6965:                                     split('.',$env{"user.role.$role./$adom/$aname"});
 6966:                                 if (($now >= $start) && (!$end || $end < $now)) {
 6967:                                     $ownaccess = 1;
 6968:                                     last;
 6969:                                 }
 6970:                             }
 6971:                         }
 6972:                     }
 6973:                 }
 6974:             }
 6975:         }
 6976:     }
 6977: 
 6978: # Course
 6979: 
 6980:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 6981:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6982:             $thisallowed.=$1;
 6983:         }
 6984:     }
 6985: 
 6986: # Domain
 6987: 
 6988:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 6989:        =~/\Q$priv\E\&([^\:]*)/) {
 6990:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6991:             $thisallowed.=$1;
 6992:         }
 6993:     }
 6994: 
 6995: # User who is not author or co-author might still be able to edit
 6996: # resource of an author in the domain (e.g., if Domain Coordinator).
 6997:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
 6998:         (&allowed('mdc',$env{'request.course.id'}))) {
 6999:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
 7000:             $thisallowed.=$1;
 7001:         }
 7002:     }
 7003: 
 7004: # Course: uri itself is a course
 7005:     my $courseuri=$uri;
 7006:     $courseuri=~s/\_(\d)/\/$1/;
 7007:     $courseuri=~s/^([^\/])/\/$1/;
 7008: 
 7009:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 7010:        =~/\Q$priv\E\&([^\:]*)/) {
 7011:         unless (($priv eq 'bro') && (!$ownaccess)) {
 7012:             $thisallowed.=$1;
 7013:         }
 7014:     }
 7015: 
 7016: # URI is an uploaded document for this course, default permissions don't matter
 7017: # not allowing 'edit' access (editupload) to uploaded course docs
 7018:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 7019: 	$thisallowed='';
 7020:         my ($match)=&is_on_map($uri);
 7021:         if ($match) {
 7022:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 7023:                   =~/\Q$priv\E\&([^\:]*)/) {
 7024:                 my $value = $1;
 7025:                 if ($noblockcheck) {
 7026:                     $thisallowed.=$value;
 7027:                 } else {
 7028:                     my @blockers = &has_comm_blocking($priv,$symb,$uri);
 7029:                     if (@blockers > 0) {
 7030:                         $thisallowed = 'B';
 7031:                     } else {
 7032:                         $thisallowed.=$value;
 7033:                     }
 7034:                 }
 7035:             }
 7036:         } else {
 7037:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 7038:             if ($refuri) {
 7039:                 if ($refuri =~ m|^/adm/|) {
 7040:                     $thisallowed='F';
 7041:                 } else {
 7042:                     $refuri=&declutter($refuri);
 7043:                     my ($match) = &is_on_map($refuri);
 7044:                     if ($match) {
 7045:                         if ($noblockcheck) {
 7046:                             $thisallowed='F';
 7047:                         } else {
 7048:                             my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 7049:                             if (@blockers > 0) {
 7050:                                 $thisallowed = 'B';
 7051:                             } else {
 7052:                                 $thisallowed='F';
 7053:                             }
 7054:                         }
 7055:                     }
 7056:                 }
 7057:             }
 7058:         }
 7059:     }
 7060: 
 7061:     if ($priv eq 'bre'
 7062: 	&& $thisallowed ne 'F' 
 7063: 	&& $thisallowed ne '2'
 7064: 	&& &is_portfolio_url($uri)) {
 7065: 	$thisallowed = &portfolio_access($uri,$clientip);
 7066:     }
 7067: 
 7068: # Full access at system, domain or course-wide level? Exit.
 7069:     if ($thisallowed=~/F/) {
 7070: 	return 'F';
 7071:     }
 7072: 
 7073: # If this is generating or modifying users, exit with special codes
 7074: 
 7075:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 7076: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 7077: 	    my ($audom,$auname)=split('/',$uri);
 7078: # no author name given, so this just checks on the general right to make a co-author in this domain
 7079: 	    unless ($auname) { return $thisallowed; }
 7080: # an author name is given, so we are about to actually make a co-author for a certain account
 7081: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 7082: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 7083: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 7084: 	}
 7085: 	return $thisallowed;
 7086:     }
 7087: #
 7088: # Gathered so far: system, domain and course wide privileges
 7089: #
 7090: # Course: See if uri or referer is an individual resource that is part of 
 7091: # the course
 7092: 
 7093:     if ($env{'request.course.id'}) {
 7094: 
 7095:        $courseprivid=$env{'request.course.id'};
 7096:        if ($env{'request.course.sec'}) {
 7097:           $courseprivid.='/'.$env{'request.course.sec'};
 7098:        }
 7099:        $courseprivid=~s/\_/\//;
 7100:        my $checkreferer=1;
 7101:        my ($match,$cond)=&is_on_map($uri);
 7102:        if ($match) {
 7103:            $statecond=$cond;
 7104:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 7105:                =~/\Q$priv\E\&([^\:]*)/) {
 7106:                my $value = $1;
 7107:                if ($priv eq 'bre') {
 7108:                    if ($noblockcheck) {
 7109:                        $thisallowed.=$value;
 7110:                    } else {
 7111:                        my @blockers = &has_comm_blocking($priv,$symb,$uri);
 7112:                        if (@blockers > 0) {
 7113:                            $thisallowed = 'B';
 7114:                        } else {
 7115:                            $thisallowed.=$value;
 7116:                        }
 7117:                    }
 7118:                } else {
 7119:                    $thisallowed.=$value;
 7120:                }
 7121:                $checkreferer=0;
 7122:            }
 7123:        }
 7124:        
 7125:        if ($checkreferer) {
 7126: 	  my $refuri=$env{'httpref.'.$orguri};
 7127:             unless ($refuri) {
 7128:                 foreach my $key (keys(%env)) {
 7129: 		    if ($key=~/^httpref\..*\*/) {
 7130: 			my $pattern=$key;
 7131:                         $pattern=~s/^httpref\.\/res\///;
 7132:                         $pattern=~s/\*/\[\^\/\]\+/g;
 7133:                         $pattern=~s/\//\\\//g;
 7134:                         if ($orguri=~/$pattern/) {
 7135: 			    $refuri=$env{$key};
 7136:                         }
 7137:                     }
 7138:                 }
 7139:             }
 7140: 
 7141:          if ($refuri) { 
 7142: 	  $refuri=&declutter($refuri);
 7143:           my ($match,$cond)=&is_on_map($refuri);
 7144:             if ($match) {
 7145:               my $refstatecond=$cond;
 7146:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 7147:                   =~/\Q$priv\E\&([^\:]*)/) {
 7148:                   my $value = $1;
 7149:                   if ($priv eq 'bre') {
 7150:                       if ($noblockcheck) {
 7151:                           $thisallowed.=$value;
 7152:                       } else {
 7153:                           my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 7154:                           if (@blockers > 0) {
 7155:                               $thisallowed = 'B';
 7156:                           } else {
 7157:                               $thisallowed.=$value;
 7158:                           }
 7159:                       }
 7160:                   } else {
 7161:                       $thisallowed.=$value;
 7162:                   }
 7163:                   $uri=$refuri;
 7164:                   $statecond=$refstatecond;
 7165:               }
 7166:           }
 7167:         }
 7168:        }
 7169:    }
 7170: 
 7171: #
 7172: # Gathered now: all privileges that could apply, and condition number
 7173: # 
 7174: #
 7175: # Full or no access?
 7176: #
 7177: 
 7178:     if ($thisallowed=~/F/) {
 7179: 	return 'F';
 7180:     }
 7181: 
 7182:     unless ($thisallowed) {
 7183:         return '';
 7184:     }
 7185: 
 7186: # Restrictions exist, deal with them
 7187: #
 7188: #   C:according to course preferences
 7189: #   R:according to resource settings
 7190: #   L:unless locked
 7191: #   X:according to user session state
 7192: #
 7193: 
 7194: # Possibly locked functionality, check all courses
 7195: # Locks might take effect only after 10 minutes cache expiration for other
 7196: # courses, and 2 minutes for current course
 7197: 
 7198:     my $envkey;
 7199:     if ($thisallowed=~/L/) {
 7200:         foreach $envkey (keys(%env)) {
 7201:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 7202:                my $courseid=$2;
 7203:                my $roleid=$1.'.'.$2;
 7204:                $courseid=~s/^\///;
 7205:                my $expiretime=600;
 7206:                if ($env{'request.role'} eq $roleid) {
 7207: 		  $expiretime=120;
 7208:                }
 7209: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 7210:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 7211:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 7212: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 7213:                }
 7214:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 7215:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 7216: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 7217:                        &log($env{'user.domain'},$env{'user.name'},
 7218:                             $env{'user.home'},
 7219:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 7220:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 7221:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 7222: 		       return '';
 7223:                    }
 7224:                }
 7225:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 7226:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 7227: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 7228:                        &log($env{'user.domain'},$env{'user.name'},
 7229:                             $env{'user.home'},
 7230:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 7231:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 7232:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 7233: 		       return '';
 7234:                    }
 7235:                }
 7236: 	   }
 7237:        }
 7238:     }
 7239:    
 7240: #
 7241: # Rest of the restrictions depend on selected course
 7242: #
 7243: 
 7244:     unless ($env{'request.course.id'}) {
 7245: 	if ($thisallowed eq 'A') {
 7246: 	    return 'A';
 7247:         } elsif ($thisallowed eq 'B') {
 7248:             return 'B';
 7249: 	} else {
 7250: 	    return '1';
 7251: 	}
 7252:     }
 7253: 
 7254: #
 7255: # Now user is definitely in a course
 7256: #
 7257: 
 7258: 
 7259: # Course preferences
 7260: 
 7261:    if ($thisallowed=~/C/) {
 7262:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 7263:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 7264:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 7265: 	   =~/\Q$rolecode\E/) {
 7266: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 7267: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 7268: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 7269: 			$env{'request.course.id'});
 7270: 	   }
 7271:            return '';
 7272:        }
 7273: 
 7274:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 7275: 	   =~/\Q$unamedom\E/) {
 7276: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 7277: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 7278: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 7279: 			$env{'request.course.id'});
 7280: 	   }
 7281:            return '';
 7282:        }
 7283:    }
 7284: 
 7285: # Resource preferences
 7286: 
 7287:    if ($thisallowed=~/R/) {
 7288:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 7289:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 7290: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 7291: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 7292: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 7293: 	   }
 7294: 	   return '';
 7295:        }
 7296:    }
 7297: 
 7298: # Restricted by state or randomout?
 7299: 
 7300:    if ($thisallowed=~/X/) {
 7301:       if ($env{'acc.randomout'}) {
 7302: 	 if (!$symb) { $symb=&symbread($uri,1); }
 7303:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 7304:             return ''; 
 7305:          }
 7306:       }
 7307:       if (&condval($statecond)) {
 7308: 	 return '2';
 7309:       } else {
 7310:          return '';
 7311:       }
 7312:    }
 7313: 
 7314:     if ($thisallowed eq 'A') {
 7315: 	return 'A';
 7316:     } elsif ($thisallowed eq 'B') {
 7317:         return 'B';
 7318:     }
 7319:    return 'F';
 7320: }
 7321: 
 7322: # ------------------------------------------- Check construction space access
 7323: 
 7324: sub constructaccess {
 7325:     my ($url,$setpriv)=@_;
 7326: 
 7327: # We do not allow editing of previous versions of files
 7328:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
 7329: 
 7330: # Get username and domain from URL
 7331:     my ($ownername,$ownerdomain,$ownerhome);
 7332: 
 7333:     ($ownerdomain,$ownername) =
 7334:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)/});
 7335: 
 7336: # The URL does not really point to any authorspace, forget it
 7337:     unless (($ownername) && ($ownerdomain)) { return ''; }
 7338: 
 7339: # Now we need to see if the user has access to the authorspace of
 7340: # $ownername at $ownerdomain
 7341: 
 7342:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
 7343: # Real author for this?
 7344:        $ownerhome = $env{'user.home'};
 7345:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
 7346:           return ($ownername,$ownerdomain,$ownerhome);
 7347:        }
 7348:     } else {
 7349: # Co-author for this?
 7350:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
 7351:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
 7352:             $ownerhome = &homeserver($ownername,$ownerdomain);
 7353:             return ($ownername,$ownerdomain,$ownerhome);
 7354:         }
 7355:     }
 7356: 
 7357: # We don't have any access right now. If we are not possibly going to do anything about this,
 7358: # we might as well leave
 7359:    unless ($setpriv) { return ''; }
 7360: 
 7361: # Backdoor access?
 7362:     my $allowed=&allowed('eco',$ownerdomain);
 7363: # Nope
 7364:     unless ($allowed) { return ''; }
 7365: # Looks like we may have access, but could be locked by the owner of the construction space
 7366:     if ($allowed eq 'U') {
 7367:         my %blocked=&get('environment',['domcoord.author'],
 7368:                          $ownerdomain,$ownername);
 7369: # Is blocked by owner
 7370:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
 7371:     }
 7372:     if (($allowed eq 'F') || ($allowed eq 'U')) {
 7373: # Grant temporary access
 7374:         my $then=$env{'user.login.time'};
 7375:         my $update=$env{'user.update.time'};
 7376:         if (!$update) { $update = $then; }
 7377:         my $refresh=$env{'user.refresh.time'};
 7378:         if (!$refresh) { $refresh = $update; }
 7379:         my $now = time;
 7380:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
 7381:                            $now,'ca','constructaccess');
 7382:         $ownerhome = &homeserver($ownername,$ownerdomain);
 7383:         return($ownername,$ownerdomain,$ownerhome);
 7384:     }
 7385: # No business here
 7386:     return '';
 7387: }
 7388: 
 7389: # ----------------------------------------------------------- Content Blocking
 7390: 
 7391: {
 7392: # Caches for faster Course Contents display where content blocking
 7393: # is in operation (i.e., interval param set) for timed quiz.
 7394: #
 7395: # User for whom data are being temporarily cached.
 7396: my $cacheduser='';
 7397: # Cached blockers for this user (a hash of blocking items). 
 7398: my %cachedblockers=();
 7399: # When the data were last cached.
 7400: my $cachedlast='';
 7401: 
 7402: sub load_all_blockers {
 7403:     my ($uname,$udom,$blocks)=@_;
 7404:     if (($uname ne '') && ($udom ne '')) { 
 7405:         if (($cacheduser eq $uname.':'.$udom) &&
 7406:             (abs($cachedlast-time)<5)) {
 7407:             return;
 7408:         }
 7409:     }
 7410:     $cachedlast=time;
 7411:     $cacheduser=$uname.':'.$udom;
 7412:     %cachedblockers = &get_commblock_resources($blocks);
 7413: }
 7414: 
 7415: sub get_comm_blocks {
 7416:     my ($cdom,$cnum) = @_;
 7417:     if ($cdom eq '' || $cnum eq '') {
 7418:         return unless ($env{'request.course.id'});
 7419:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7420:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7421:     }
 7422:     my %commblocks;
 7423:     my $hashid=$cdom.'_'.$cnum;
 7424:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
 7425:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
 7426:         %commblocks = %{$blocksref};
 7427:     } else {
 7428:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
 7429:         my $cachetime = 600;
 7430:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
 7431:     }
 7432:     return %commblocks;
 7433: }
 7434: 
 7435: sub get_commblock_resources {
 7436:     my ($blocks) = @_;
 7437:     my %blockers = ();
 7438:     return %blockers unless ($env{'request.course.id'});
 7439:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 7440:     my %commblocks;
 7441:     if (ref($blocks) eq 'HASH') {
 7442:         %commblocks = %{$blocks};
 7443:     } else {
 7444:         %commblocks = &get_comm_blocks();
 7445:     }
 7446:     return %blockers unless (keys(%commblocks) > 0); 
 7447:     my $navmap = Apache::lonnavmaps::navmap->new();
 7448:     return %blockers unless (ref($navmap));
 7449:     my $now = time;
 7450:     foreach my $block (keys(%commblocks)) {
 7451:         if ($block =~ /^(\d+)____(\d+)$/) {
 7452:             my ($start,$end) = ($1,$2);
 7453:             if ($start <= $now && $end >= $now) {
 7454:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 7455:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 7456:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 7457:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 7458:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'}; 
 7459:                             }
 7460:                         }
 7461:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 7462:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 7463:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 7464:                             }
 7465:                         }
 7466:                     }
 7467:                 }
 7468:             }
 7469:         } elsif ($block =~ /^firstaccess____(.+)$/) {
 7470:             my $item = $1;
 7471:             my @to_test;
 7472:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 7473:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 7474:                     my @interval;
 7475:                     my $type = 'map';
 7476:                     if ($item eq 'course') {
 7477:                         $type = 'course';
 7478:                         @interval=&EXT("resource.0.interval");
 7479:                     } else {
 7480:                         if ($item =~ /___\d+___/) {
 7481:                             $type = 'resource';
 7482:                             @interval=&EXT("resource.0.interval",$item);
 7483:                             if (ref($navmap)) {                        
 7484:                                 my $res = $navmap->getBySymb($item); 
 7485:                                 push(@to_test,$res);
 7486:                             }
 7487:                         } else {
 7488:                             my $mapsymb = &symbread($item,1);
 7489:                             if ($mapsymb) {
 7490:                                 if (ref($navmap)) {
 7491:                                     my $mapres = $navmap->getBySymb($mapsymb);
 7492:                                     @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
 7493:                                     foreach my $res (@to_test) {
 7494:                                         my $symb = $res->symb();
 7495:                                         next if ($symb eq $mapsymb);
 7496:                                         if ($symb ne '') {
 7497:                                             @interval=&EXT("resource.0.interval",$symb);
 7498:                                             if ($interval[1] eq 'map') {
 7499:                                                 last;
 7500:                                             }
 7501:                                         }
 7502:                                     }
 7503:                                 }
 7504:                             }
 7505:                         }
 7506:                     }
 7507:                     if ($interval[0] =~ /^\d+/) {
 7508:                         my ($timelimit) = split(/_/,$interval[0]);
 7509:                         my $first_access;
 7510:                         if ($type eq 'resource') {
 7511:                             $first_access=&get_first_access($interval[1],$item);
 7512:                         } elsif ($type eq 'map') {
 7513:                             $first_access=&get_first_access($interval[1],undef,$item);
 7514:                         } else {
 7515:                             $first_access=&get_first_access($interval[1]);
 7516:                         }
 7517:                         if ($first_access) {
 7518:                             my $timesup = $first_access+$timelimit;
 7519:                             if ($timesup > $now) {
 7520:                                 my $activeblock;
 7521:                                 foreach my $res (@to_test) {
 7522:                                     if ($res->answerable()) {
 7523:                                         $activeblock = 1;
 7524:                                         last;
 7525:                                     }
 7526:                                 }
 7527:                                 if ($activeblock) {
 7528:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 7529:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 7530:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
 7531:                                          }
 7532:                                     }
 7533:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 7534:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 7535:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 7536:                                         }
 7537:                                     }
 7538:                                 }
 7539:                             }
 7540:                         }
 7541:                     }
 7542:                 }
 7543:             }
 7544:         }
 7545:     }
 7546:     return %blockers;
 7547: }
 7548: 
 7549: sub has_comm_blocking {
 7550:     my ($priv,$symb,$uri,$blocks) = @_;
 7551:     my @blockers;
 7552:     return unless ($env{'request.course.id'});
 7553:     return unless ($priv eq 'bre');
 7554:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 7555:     return if ($env{'request.state'} eq 'construct');
 7556:     &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
 7557:     return unless (keys(%cachedblockers) > 0);
 7558:     my (%possibles,@symbs);
 7559:     if (!$symb) {
 7560:         $symb = &symbread($uri,1,1,1,\%possibles);
 7561:     }
 7562:     if ($symb) {
 7563:         @symbs = ($symb);
 7564:     } elsif (keys(%possibles)) { 
 7565:         @symbs = keys(%possibles);
 7566:     }
 7567:     my $noblock;
 7568:     foreach my $symb (@symbs) {
 7569:         last if ($noblock);
 7570:         my ($map,$resid,$resurl)=&decode_symb($symb);
 7571:         foreach my $block (keys(%cachedblockers)) {
 7572:             if ($block =~ /^firstaccess____(.+)$/) {
 7573:                 my $item = $1;
 7574:                 if (($item eq $map) || ($item eq $symb)) {
 7575:                     $noblock = 1;
 7576:                     last;
 7577:                 }
 7578:             }
 7579:             if (ref($cachedblockers{$block}) eq 'HASH') {
 7580:                 if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
 7581:                     if ($cachedblockers{$block}{'resources'}{$symb}) {
 7582:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 7583:                             push(@blockers,$block);
 7584:                         }
 7585:                     }
 7586:                 }
 7587:             }
 7588:             if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
 7589:                 if ($cachedblockers{$block}{'maps'}{$map}) {
 7590:                     unless (grep(/^\Q$block\E$/,@blockers)) {
 7591:                         push(@blockers,$block);
 7592:                     }
 7593:                 }
 7594:             }
 7595:         }
 7596:     }
 7597:     return if ($noblock);
 7598:     return @blockers;
 7599: }
 7600: }
 7601: 
 7602: # -------------------------------- Deversion and split uri into path an filename   
 7603: 
 7604: #
 7605: #   Removes the version from a URI and
 7606: #   splits it in to its filename and path to the filename.
 7607: #   Seems like File::Basename could have done this more clearly.
 7608: #   Parameters:
 7609: #      $uri   - input URI
 7610: #   Returns:
 7611: #     Two element list consisting of 
 7612: #     $pathname  - the URI up to and excluding the trailing /
 7613: #     $filename  - The part of the URI following the last /
 7614: #  NOTE:
 7615: #    Another realization of this is simply:
 7616: #    use File::Basename;
 7617: #    ...
 7618: #    $uri = shift;
 7619: #    $filename = basename($uri);
 7620: #    $path     = dirname($uri);
 7621: #    return ($filename, $path);
 7622: #
 7623: #     The implementation below is probably faster however.
 7624: #
 7625: sub split_uri_for_cond {
 7626:     my $uri=&deversion(&declutter(shift));
 7627:     my @uriparts=split(/\//,$uri);
 7628:     my $filename=pop(@uriparts);
 7629:     my $pathname=join('/',@uriparts);
 7630:     return ($pathname,$filename);
 7631: }
 7632: # --------------------------------------------------- Is a resource on the map?
 7633: 
 7634: sub is_on_map {
 7635:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 7636:     #Trying to find the conditional for the file
 7637:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 7638: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 7639:     if ($match) {
 7640: 	return (1,$1);
 7641:     } else {
 7642: 	return (0,0);
 7643:     }
 7644: }
 7645: 
 7646: # --------------------------------------------------------- Get symb from alias
 7647: 
 7648: sub get_symb_from_alias {
 7649:     my $symb=shift;
 7650:     my ($map,$resid,$url)=&decode_symb($symb);
 7651: # Already is a symb
 7652:     if ($url) { return $symb; }
 7653: # Must be an alias
 7654:     my $aliassymb='';
 7655:     my %bighash;
 7656:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7657:                             &GDBM_READER(),0640)) {
 7658:         my $rid=$bighash{'mapalias_'.$symb};
 7659: 	if ($rid) {
 7660: 	    my ($mapid,$resid)=split(/\./,$rid);
 7661: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 7662: 				    $resid,$bighash{'src_'.$rid});
 7663: 	}
 7664:         untie %bighash;
 7665:     }
 7666:     return $aliassymb;
 7667: }
 7668: 
 7669: # ----------------------------------------------------------------- Define Role
 7670: 
 7671: sub definerole {
 7672:   if (allowed('mcr','/')) {
 7673:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 7674:     foreach my $role (split(':',$sysrole)) {
 7675: 	my ($crole,$cqual)=split(/\&/,$role);
 7676:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 7677:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 7678: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 7679:                return "refused:s:$crole&$cqual"; 
 7680:             }
 7681:         }
 7682:     }
 7683:     foreach my $role (split(':',$domrole)) {
 7684: 	my ($crole,$cqual)=split(/\&/,$role);
 7685:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 7686:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 7687: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 7688:                return "refused:d:$crole&$cqual"; 
 7689:             }
 7690:         }
 7691:     }
 7692:     foreach my $role (split(':',$courole)) {
 7693: 	my ($crole,$cqual)=split(/\&/,$role);
 7694:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 7695:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 7696: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 7697:                return "refused:c:$crole&$cqual"; 
 7698:             }
 7699:         }
 7700:     }
 7701:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 7702:                 "$env{'user.domain'}:$env{'user.name'}:".
 7703: 	        "rolesdef_$rolename=".
 7704:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 7705:     return reply($command,$env{'user.home'});
 7706:   } else {
 7707:     return 'refused';
 7708:   }
 7709: }
 7710: 
 7711: # ---------------- Make a metadata query against the network of library servers
 7712: 
 7713: sub metadata_query {
 7714:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
 7715:     my %rhash;
 7716:     my %libserv = &all_library();
 7717:     my @server_list = (defined($server_array) ? @$server_array
 7718:                                               : keys(%libserv) );
 7719:     for my $server (@server_list) {
 7720:         my $domains = ''; 
 7721:         if (ref($domains_hash) eq 'HASH') {
 7722:             $domains = $domains_hash->{$server}; 
 7723:         }
 7724: 	unless ($custom or $customshow) {
 7725: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
 7726: 	    $rhash{$server}=$reply;
 7727: 	}
 7728: 	else {
 7729: 	    my $reply=&reply("querysend:".&escape($query).':'.
 7730: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
 7731: 			     $server);
 7732: 	    $rhash{$server}=$reply;
 7733: 	}
 7734:     }
 7735:     return \%rhash;
 7736: }
 7737: 
 7738: # ----------------------------------------- Send log queries and wait for reply
 7739: 
 7740: sub log_query {
 7741:     my ($uname,$udom,$query,%filters)=@_;
 7742:     my $uhome=&homeserver($uname,$udom);
 7743:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 7744:     my $uhost=&hostname($uhome);
 7745:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 7746:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 7747:                        $uhome);
 7748:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 7749:     return get_query_reply($queryid);
 7750: }
 7751: 
 7752: # -------------------------- Update MySQL table for portfolio file
 7753: 
 7754: sub update_portfolio_table {
 7755:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 7756:     if ($group ne '') {
 7757:         $file_name =~s /^\Q$group\E//;
 7758:     }
 7759:     my $homeserver = &homeserver($uname,$udom);
 7760:     my $queryid=
 7761:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 7762:                ':'.&escape($file_name).':'.$action,$homeserver);
 7763:     my $reply = &get_query_reply($queryid);
 7764:     return $reply;
 7765: }
 7766: 
 7767: # -------------------------- Update MySQL allusers table
 7768: 
 7769: sub update_allusers_table {
 7770:     my ($uname,$udom,$names) = @_;
 7771:     my $homeserver = &homeserver($uname,$udom);
 7772:     my $queryid=
 7773:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 7774:                'lastname='.&escape($names->{'lastname'}).'%%'.
 7775:                'firstname='.&escape($names->{'firstname'}).'%%'.
 7776:                'middlename='.&escape($names->{'middlename'}).'%%'.
 7777:                'generation='.&escape($names->{'generation'}).'%%'.
 7778:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 7779:                'id='.&escape($names->{'id'}),$homeserver);
 7780:     return;
 7781: }
 7782: 
 7783: # ------- Request retrieval of institutional classlists for course(s)
 7784: 
 7785: sub fetch_enrollment_query {
 7786:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 7787:     my $homeserver;
 7788:     my $maxtries = 1;
 7789:     if ($context eq 'automated') {
 7790:         $homeserver = $perlvar{'lonHostID'};
 7791:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 7792:     } else {
 7793:         $homeserver = &homeserver($cnum,$dom);
 7794:     }
 7795:     my $host=&hostname($homeserver);
 7796:     my $cmd = '';
 7797:     foreach my $affiliate (keys(%{$affiliatesref})) {
 7798:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 7799:     }
 7800:     $cmd =~ s/%%$//;
 7801:     $cmd = &escape($cmd);
 7802:     my $query = 'fetchenrollment';
 7803:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 7804:     unless ($queryid=~/^\Q$host\E\_/) { 
 7805:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 7806:         return 'error: '.$queryid;
 7807:     }
 7808:     my $reply = &get_query_reply($queryid);
 7809:     my $tries = 1;
 7810:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 7811:         $reply = &get_query_reply($queryid);
 7812:         $tries ++;
 7813:     }
 7814:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 7815:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 7816:     } else {
 7817:         my @responses = split(/:/,$reply);
 7818:         if ($homeserver eq $perlvar{'lonHostID'}) {
 7819:             foreach my $line (@responses) {
 7820:                 my ($key,$value) = split(/=/,$line,2);
 7821:                 $$replyref{$key} = $value;
 7822:             }
 7823:         } else {
 7824:             my $pathname = LONCAPA::tempdir();
 7825:             foreach my $line (@responses) {
 7826:                 my ($key,$value) = split(/=/,$line);
 7827:                 $$replyref{$key} = $value;
 7828:                 if ($value > 0) {
 7829:                     foreach my $item (@{$$affiliatesref{$key}}) {
 7830:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 7831:                         my $destname = $pathname.'/'.$filename;
 7832:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 7833:                         if ($xml_classlist =~ /^error/) {
 7834:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 7835:                         } else {
 7836:                             if ( open(FILE,">$destname") ) {
 7837:                                 print FILE &unescape($xml_classlist);
 7838:                                 close(FILE);
 7839:                             } else {
 7840:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 7841:                             }
 7842:                         }
 7843:                     }
 7844:                 }
 7845:             }
 7846:         }
 7847:         return 'ok';
 7848:     }
 7849:     return 'error';
 7850: }
 7851: 
 7852: sub get_query_reply {
 7853:     my $queryid=shift;
 7854:     my $replyfile=LONCAPA::tempdir().$queryid;
 7855:     my $reply='';
 7856:     for (1..100) {
 7857: 	sleep(0.2);
 7858:         if (-e $replyfile.'.end') {
 7859: 	    if (open(my $fh,$replyfile)) {
 7860: 		$reply = join('',<$fh>);
 7861: 		close($fh);
 7862: 	   } else { return 'error: reply_file_error'; }
 7863:            return &unescape($reply);
 7864: 	}
 7865:     }
 7866:     return 'timeout:'.$queryid;
 7867: }
 7868: 
 7869: sub courselog_query {
 7870: #
 7871: # possible filters:
 7872: # url: url or symb
 7873: # username
 7874: # domain
 7875: # action: view, submit, grade
 7876: # start: timestamp
 7877: # end: timestamp
 7878: #
 7879:     my (%filters)=@_;
 7880:     unless ($env{'request.course.id'}) { return 'no_course'; }
 7881:     if ($filters{'url'}) {
 7882: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 7883:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 7884:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 7885:     }
 7886:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7887:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7888:     return &log_query($cname,$cdom,'courselog',%filters);
 7889: }
 7890: 
 7891: sub userlog_query {
 7892: #
 7893: # possible filters:
 7894: # action: log check role
 7895: # start: timestamp
 7896: # end: timestamp
 7897: #
 7898:     my ($uname,$udom,%filters)=@_;
 7899:     return &log_query($uname,$udom,'userlog',%filters);
 7900: }
 7901: 
 7902: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 7903: 
 7904: sub auto_run {
 7905:     my ($cnum,$cdom) = @_;
 7906:     my $response = 0;
 7907:     my $settings;
 7908:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 7909:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 7910:         $settings = $domconfig{'autoenroll'};
 7911:         if ($settings->{'run'} eq '1') {
 7912:             $response = 1;
 7913:         }
 7914:     } else {
 7915:         my $homeserver;
 7916:         if (&is_course($cdom,$cnum)) {
 7917:             $homeserver = &homeserver($cnum,$cdom);
 7918:         } else {
 7919:             $homeserver = &domain($cdom,'primary');
 7920:         }
 7921:         if ($homeserver ne 'no_host') {
 7922:             $response = &reply('autorun:'.$cdom,$homeserver);
 7923:         }
 7924:     }
 7925:     return $response;
 7926: }
 7927: 
 7928: sub auto_get_sections {
 7929:     my ($cnum,$cdom,$inst_coursecode) = @_;
 7930:     my $homeserver;
 7931:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
 7932:         $homeserver = &homeserver($cnum,$cdom);
 7933:     }
 7934:     if (!defined($homeserver)) { 
 7935:         if ($cdom =~ /^$match_domain$/) {
 7936:             $homeserver = &domain($cdom,'primary');
 7937:         }
 7938:     }
 7939:     my @secs;
 7940:     if (defined($homeserver)) {
 7941:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 7942:         unless ($response eq 'refused') {
 7943:             @secs = split(/:/,$response);
 7944:         }
 7945:     }
 7946:     return @secs;
 7947: }
 7948: 
 7949: sub auto_new_course {
 7950:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
 7951:     my $homeserver = &homeserver($cnum,$cdom);
 7952:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
 7953:     return $response;
 7954: }
 7955: 
 7956: sub auto_validate_courseID {
 7957:     my ($cnum,$cdom,$inst_course_id) = @_;
 7958:     my $homeserver = &homeserver($cnum,$cdom);
 7959:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 7960:     return $response;
 7961: }
 7962: 
 7963: sub auto_validate_instcode {
 7964:     my ($cnum,$cdom,$instcode,$owner) = @_;
 7965:     my ($homeserver,$response);
 7966:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 7967:         $homeserver = &homeserver($cnum,$cdom);
 7968:     }
 7969:     if (!defined($homeserver)) {
 7970:         if ($cdom =~ /^$match_domain$/) {
 7971:             $homeserver = &domain($cdom,'primary');
 7972:         }
 7973:     }
 7974:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
 7975:                         &escape($instcode).':'.&escape($owner),$homeserver));
 7976:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
 7977:     return ($outcome,$description,$defaultcredits);
 7978: }
 7979: 
 7980: sub auto_create_password {
 7981:     my ($cnum,$cdom,$authparam,$udom) = @_;
 7982:     my ($homeserver,$response);
 7983:     my $create_passwd = 0;
 7984:     my $authchk = '';
 7985:     if ($udom =~ /^$match_domain$/) {
 7986:         $homeserver = &domain($udom,'primary');
 7987:     }
 7988:     if ($homeserver eq '') {
 7989:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 7990:             $homeserver = &homeserver($cnum,$cdom);
 7991:         }
 7992:     }
 7993:     if ($homeserver eq '') {
 7994:         $authchk = 'nodomain';
 7995:     } else {
 7996:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 7997:         if ($response eq 'refused') {
 7998:             $authchk = 'refused';
 7999:         } else {
 8000:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 8001:         }
 8002:     }
 8003:     return ($authparam,$create_passwd,$authchk);
 8004: }
 8005: 
 8006: sub auto_photo_permission {
 8007:     my ($cnum,$cdom,$students) = @_;
 8008:     my $homeserver = &homeserver($cnum,$cdom);
 8009:     my ($outcome,$perm_reqd,$conditions) = 
 8010: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 8011:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 8012: 	return (undef,undef);
 8013:     }
 8014:     return ($outcome,$perm_reqd,$conditions);
 8015: }
 8016: 
 8017: sub auto_checkphotos {
 8018:     my ($uname,$udom,$pid) = @_;
 8019:     my $homeserver = &homeserver($uname,$udom);
 8020:     my ($result,$resulttype);
 8021:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 8022: 				   &escape($uname).':'.&escape($pid),
 8023: 				   $homeserver));
 8024:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 8025: 	return (undef,undef);
 8026:     }
 8027:     if ($outcome) {
 8028:         ($result,$resulttype) = split(/:/,$outcome);
 8029:     } 
 8030:     return ($result,$resulttype);
 8031: }
 8032: 
 8033: sub auto_photochoice {
 8034:     my ($cnum,$cdom) = @_;
 8035:     my $homeserver = &homeserver($cnum,$cdom);
 8036:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 8037: 						       &escape($cdom),
 8038: 						       $homeserver)));
 8039:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 8040: 	return (undef,undef);
 8041:     }
 8042:     return ($update,$comment);
 8043: }
 8044: 
 8045: sub auto_photoupdate {
 8046:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 8047:     my $homeserver = &homeserver($cnum,$dom);
 8048:     my $host=&hostname($homeserver);
 8049:     my $cmd = '';
 8050:     my $maxtries = 1;
 8051:     foreach my $affiliate (keys(%{$affiliatesref})) {
 8052:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 8053:     }
 8054:     $cmd =~ s/%%$//;
 8055:     $cmd = &escape($cmd);
 8056:     my $query = 'institutionalphotos';
 8057:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 8058:     unless ($queryid=~/^\Q$host\E\_/) {
 8059:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 8060:         return 'error: '.$queryid;
 8061:     }
 8062:     my $reply = &get_query_reply($queryid);
 8063:     my $tries = 1;
 8064:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 8065:         $reply = &get_query_reply($queryid);
 8066:         $tries ++;
 8067:     }
 8068:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 8069:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 8070:     } else {
 8071:         my @responses = split(/:/,$reply);
 8072:         my $outcome = shift(@responses); 
 8073:         foreach my $item (@responses) {
 8074:             my ($key,$value) = split(/=/,$item);
 8075:             $$photo{$key} = $value;
 8076:         }
 8077:         return $outcome;
 8078:     }
 8079:     return 'error';
 8080: }
 8081: 
 8082: sub auto_instcode_format {
 8083:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 8084: 	$cat_order) = @_;
 8085:     my $courses = '';
 8086:     my @homeservers;
 8087:     if ($caller eq 'global') {
 8088: 	my %servers = &get_servers($codedom,'library');
 8089: 	foreach my $tryserver (keys(%servers)) {
 8090: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 8091: 		push(@homeservers,$tryserver);
 8092: 	    }
 8093:         }
 8094:     } elsif ($caller eq 'requests') {
 8095:         if ($codedom =~ /^$match_domain$/) {
 8096:             my $chome = &domain($codedom,'primary');
 8097:             unless ($chome eq 'no_host') {
 8098:                 push(@homeservers,$chome);
 8099:             }
 8100:         }
 8101:     } else {
 8102:         push(@homeservers,&homeserver($caller,$codedom));
 8103:     }
 8104:     foreach my $code (keys(%{$instcodes})) {
 8105:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 8106:     }
 8107:     chop($courses);
 8108:     my $ok_response = 0;
 8109:     my $response;
 8110:     while (@homeservers > 0 && $ok_response == 0) {
 8111:         my $server = shift(@homeservers); 
 8112:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 8113:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 8114:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 8115: 		split(/:/,$response);
 8116:             %{$codes} = (%{$codes},&str2hash($codes_str));
 8117:             push(@{$codetitles},&str2array($codetitles_str));
 8118:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 8119:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 8120:             $ok_response = 1;
 8121:         }
 8122:     }
 8123:     if ($ok_response) {
 8124:         return 'ok';
 8125:     } else {
 8126:         return $response;
 8127:     }
 8128: }
 8129: 
 8130: sub auto_instcode_defaults {
 8131:     my ($domain,$returnhash,$code_order) = @_;
 8132:     my @homeservers;
 8133: 
 8134:     my %servers = &get_servers($domain,'library');
 8135:     foreach my $tryserver (keys(%servers)) {
 8136: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 8137: 	    push(@homeservers,$tryserver);
 8138: 	}
 8139:     }
 8140: 
 8141:     my $response;
 8142:     foreach my $server (@homeservers) {
 8143:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 8144:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 8145: 	
 8146: 	foreach my $pair (split(/\&/,$response)) {
 8147: 	    my ($name,$value)=split(/\=/,$pair);
 8148: 	    if ($name eq 'code_order') {
 8149: 		@{$code_order} = split(/\&/,&unescape($value));
 8150: 	    } else {
 8151: 		$returnhash->{&unescape($name)}=&unescape($value);
 8152: 	    }
 8153: 	}
 8154: 	return 'ok';
 8155:     }
 8156: 
 8157:     return $response;
 8158: }
 8159: 
 8160: sub auto_possible_instcodes {
 8161:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
 8162:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
 8163:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 8164:         return;
 8165:     }
 8166:     my (@homeservers,$uhome);
 8167:     if (defined(&domain($domain,'primary'))) {
 8168:         $uhome=&domain($domain,'primary');
 8169:         push(@homeservers,&domain($domain,'primary'));
 8170:     } else {
 8171:         my %servers = &get_servers($domain,'library');
 8172:         foreach my $tryserver (keys(%servers)) {
 8173:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 8174:                 push(@homeservers,$tryserver);
 8175:             }
 8176:         }
 8177:     }
 8178:     my $response;
 8179:     foreach my $server (@homeservers) {
 8180:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
 8181:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 8182:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
 8183:             split(':',$response);
 8184:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
 8185:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
 8186:         foreach my $item (split('&',$cat_title)) {   
 8187:             my ($name,$value)=split('=',$item);
 8188:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
 8189:         }
 8190:         foreach my $item (split('&',$cat_order)) {
 8191:             my ($name,$value)=split('=',$item);
 8192:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
 8193:         }
 8194:         return 'ok';
 8195:     }
 8196:     return $response;
 8197: }
 8198: 
 8199: sub auto_courserequest_checks {
 8200:     my ($dom) = @_;
 8201:     my ($homeserver,%validations);
 8202:     if ($dom =~ /^$match_domain$/) {
 8203:         $homeserver = &domain($dom,'primary');
 8204:     }
 8205:     unless ($homeserver eq 'no_host') {
 8206:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
 8207:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 8208:             my @items = split(/&/,$response);
 8209:             foreach my $item (@items) {
 8210:                 my ($key,$value) = split('=',$item);
 8211:                 $validations{&unescape($key)} = &thaw_unescape($value);
 8212:             }
 8213:         }
 8214:     }
 8215:     return %validations; 
 8216: }
 8217: 
 8218: sub auto_courserequest_validation {
 8219:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
 8220:     my ($homeserver,$response);
 8221:     if ($dom =~ /^$match_domain$/) {
 8222:         $homeserver = &domain($dom,'primary');
 8223:     }
 8224:     unless ($homeserver eq 'no_host') {
 8225:         my $customdata;
 8226:         if (ref($custominfo) eq 'HASH') {
 8227:             $customdata = &freeze_escape($custominfo);
 8228:         }
 8229:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
 8230:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
 8231:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
 8232:                                     $customdata,$homeserver));
 8233:     }
 8234:     return $response;
 8235: }
 8236: 
 8237: sub auto_validate_class_sec {
 8238:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 8239:     my $homeserver = &homeserver($cnum,$cdom);
 8240:     my $ownerlist;
 8241:     if (ref($owners) eq 'ARRAY') {
 8242:         $ownerlist = join(',',@{$owners});
 8243:     } else {
 8244:         $ownerlist = $owners;
 8245:     }
 8246:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 8247:                         &escape($ownerlist).':'.$cdom,$homeserver);
 8248:     return $response;
 8249: }
 8250: 
 8251: sub auto_crsreq_update {
 8252:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
 8253:         $code,$accessstart,$accessend,$inbound) = @_;
 8254:     my ($homeserver,%crsreqresponse);
 8255:     if ($cdom =~ /^$match_domain$/) {
 8256:         $homeserver = &domain($cdom,'primary');
 8257:     }
 8258:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
 8259:         my $info;
 8260:         if (ref($inbound) eq 'HASH') {
 8261:             $info = &freeze_escape($inbound);
 8262:         }
 8263:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
 8264:                             ':'.&escape($action).':'.&escape($ownername).':'.
 8265:                             &escape($ownerdomain).':'.&escape($fullname).':'.
 8266:                             &escape($title).':'.&escape($code).':'.
 8267:                             &escape($accessstart).':'.&escape($accessend).':'.$info,
 8268:                             $homeserver);
 8269:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 8270:             my @items = split(/&/,$response);
 8271:             foreach my $item (@items) {
 8272:                 my ($key,$value) = split('=',$item);
 8273:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
 8274:             }
 8275:         }
 8276:     }
 8277:     return \%crsreqresponse;
 8278: }
 8279: 
 8280: sub check_instcode_cloning {
 8281:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
 8282:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 8283:         return;
 8284:     }
 8285:     my $canclone;
 8286:     if (@{$code_order} > 0) {
 8287:         my $instcoderegexp ='^';
 8288:         my @clonecodes = split(/\&/,$cloner);
 8289:         foreach my $item (@{$code_order}) {
 8290:             if (grep(/^\Q$item\E=/,@clonecodes)) {
 8291:                 foreach my $pair (@clonecodes) {
 8292:                     my ($key,$val) = split(/\=/,$pair,2);
 8293:                     $val = &unescape($val);
 8294:                     if ($key eq $item) {
 8295:                         $instcoderegexp .= '('.$val.')';
 8296:                         last;
 8297:                     }
 8298:                 }
 8299:             } else {
 8300:                 $instcoderegexp .= $codedefaults->{$item};
 8301:             }
 8302:         }
 8303:         $instcoderegexp .= '$';
 8304:         my (@from,@to);
 8305:         eval {
 8306:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
 8307:                (@to) = ($clonetocode =~ /$instcoderegexp/);
 8308:         };
 8309:         if ((@from > 0) && (@to > 0)) {
 8310:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
 8311:             if (!@diffs) {
 8312:                 $canclone = 1;
 8313:             }
 8314:         }
 8315:     }
 8316:     return $canclone;
 8317: }
 8318: 
 8319: sub default_instcode_cloning {
 8320:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
 8321:     my (%codedefaults,@code_order,$canclone);
 8322:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
 8323:         %codedefaults = %{$codedefaultsref};
 8324:         @code_order = @{$codeorderref};
 8325:     } elsif ($clonedom) {
 8326:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
 8327:     }
 8328:     if (($domdefclone) && (@code_order)) {
 8329:         my @clonecodes = split(/\+/,$domdefclone);
 8330:         my $instcoderegexp ='^';
 8331:         foreach my $item (@code_order) {
 8332:             if (grep(/^\Q$item\E$/,@clonecodes)) {
 8333:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
 8334:             } else {
 8335:                 $instcoderegexp .= $codedefaults{$item};
 8336:             }
 8337:         }
 8338:         $instcoderegexp .= '$';
 8339:         my (@from,@to);
 8340:         eval {
 8341:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
 8342:             (@to) = ($clonetocode =~ /$instcoderegexp/);
 8343:         };
 8344:         if ((@from > 0) && (@to > 0)) {
 8345:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
 8346:             if (!@diffs) {
 8347:                 $canclone = 1;
 8348:             }
 8349:         }
 8350:     }
 8351:     return $canclone;
 8352: }
 8353: 
 8354: # ------------------------------------------------------- Course Group routines
 8355: 
 8356: sub get_coursegroups {
 8357:     my ($cdom,$cnum,$group,$namespace) = @_;
 8358:     return(&dump($namespace,$cdom,$cnum,$group));
 8359: }
 8360: 
 8361: sub modify_coursegroup {
 8362:     my ($cdom,$cnum,$groupsettings) = @_;
 8363:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 8364: }
 8365: 
 8366: sub toggle_coursegroup_status {
 8367:     my ($cdom,$cnum,$group,$action) = @_;
 8368:     my ($from_namespace,$to_namespace);
 8369:     if ($action eq 'delete') {
 8370:         $from_namespace = 'coursegroups';
 8371:         $to_namespace = 'deleted_groups';
 8372:     } else {
 8373:         $from_namespace = 'deleted_groups';
 8374:         $to_namespace = 'coursegroups';
 8375:     }
 8376:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 8377:     if (my $tmp = &error(%curr_group)) {
 8378:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 8379:         return ('read error',$tmp);
 8380:     } else {
 8381:         my %savedsettings = %curr_group; 
 8382:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 8383:         my $deloutcome;
 8384:         if ($result eq 'ok') {
 8385:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 8386:         } else {
 8387:             return ('write error',$result);
 8388:         }
 8389:         if ($deloutcome eq 'ok') {
 8390:             return 'ok';
 8391:         } else {
 8392:             return ('delete error',$deloutcome);
 8393:         }
 8394:     }
 8395: }
 8396: 
 8397: sub modify_group_roles {
 8398:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 8399:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 8400:     my $role = 'gr/'.&escape($userprivs);
 8401:     my ($uname,$udom) = split(/:/,$user);
 8402:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 8403:     if ($result eq 'ok') {
 8404:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 8405:     }
 8406:     return $result;
 8407: }
 8408: 
 8409: sub modify_coursegroup_membership {
 8410:     my ($cdom,$cnum,$membership) = @_;
 8411:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 8412:     return $result;
 8413: }
 8414: 
 8415: sub get_active_groups {
 8416:     my ($udom,$uname,$cdom,$cnum) = @_;
 8417:     my $now = time;
 8418:     my %groups = ();
 8419:     foreach my $key (keys(%env)) {
 8420:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 8421:             my ($start,$end) = split(/\./,$env{$key});
 8422:             if (($end!=0) && ($end<$now)) { next; }
 8423:             if (($start!=0) && ($start>$now)) { next; }
 8424:             if ($1 eq $cdom && $2 eq $cnum) {
 8425:                 $groups{$3} = $env{$key} ;
 8426:             }
 8427:         }
 8428:     }
 8429:     return %groups;
 8430: }
 8431: 
 8432: sub get_group_membership {
 8433:     my ($cdom,$cnum,$group) = @_;
 8434:     return(&dump('groupmembership',$cdom,$cnum,$group));
 8435: }
 8436: 
 8437: sub get_users_groups {
 8438:     my ($udom,$uname,$courseid) = @_;
 8439:     my @usersgroups;
 8440:     my $cachetime=1800;
 8441: 
 8442:     my $hashid="$udom:$uname:$courseid";
 8443:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 8444:     if (defined($cached)) {
 8445:         @usersgroups = split(/:/,$grouplist);
 8446:     } else {  
 8447:         $grouplist = '';
 8448:         my $courseurl = &courseid_to_courseurl($courseid);
 8449:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 8450:         my $access_end = $env{'course.'.$courseid.
 8451:                               '.default_enrollment_end_date'};
 8452:         my $now = time;
 8453:         foreach my $key (keys(%roleshash)) {
 8454:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 8455:                 my $group = $1;
 8456:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 8457:                     my $start = $2;
 8458:                     my $end = $1;
 8459:                     if ($start == -1) { next; } # deleted from group
 8460:                     if (($start!=0) && ($start>$now)) { next; }
 8461:                     if (($end!=0) && ($end<$now)) {
 8462:                         if ($access_end && $access_end < $now) {
 8463:                             if ($access_end - $end < 86400) {
 8464:                                 push(@usersgroups,$group);
 8465:                             }
 8466:                         }
 8467:                         next;
 8468:                     }
 8469:                     push(@usersgroups,$group);
 8470:                 }
 8471:             }
 8472:         }
 8473:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 8474:         $grouplist = join(':',@usersgroups);
 8475:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 8476:     }
 8477:     return @usersgroups;
 8478: }
 8479: 
 8480: sub devalidate_getgroups_cache {
 8481:     my ($udom,$uname,$cdom,$cnum)=@_;
 8482:     my $courseid = $cdom.'_'.$cnum;
 8483: 
 8484:     my $hashid="$udom:$uname:$courseid";
 8485:     &devalidate_cache_new('getgroups',$hashid);
 8486: }
 8487: 
 8488: # ------------------------------------------------------------------ Plain Text
 8489: 
 8490: sub plaintext {
 8491:     my ($short,$type,$cid,$forcedefault) = @_;
 8492:     if ($short =~ m{^cr/}) {
 8493: 	return (split('/',$short))[-1];
 8494:     }
 8495:     if (!defined($cid)) {
 8496:         $cid = $env{'request.course.id'};
 8497:     }
 8498:     my %rolenames = (
 8499:                       Course    => 'std',
 8500:                       Community => 'alt1',
 8501:                     );
 8502:     if ($cid ne '') {
 8503:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
 8504:             unless ($forcedefault) {
 8505:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
 8506:                 &Apache::lonlocal::mt_escape(\$roletext);
 8507:                 return &Apache::lonlocal::mt($roletext);
 8508:             }
 8509:         }
 8510:     }
 8511:     if ((defined($type)) && (defined($rolenames{$type})) &&
 8512:         (defined($rolenames{$type})) && 
 8513:         (defined($prp{$short}{$rolenames{$type}}))) {
 8514:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 8515:     } elsif ($cid ne '') {
 8516:         my $crstype = $env{'course.'.$cid.'.type'};
 8517:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
 8518:             (defined($prp{$short}{$rolenames{$crstype}}))) {
 8519:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
 8520:         }
 8521:     }
 8522:     return &Apache::lonlocal::mt($prp{$short}{'std'});
 8523: }
 8524: 
 8525: # ----------------------------------------------------------------- Assign Role
 8526: 
 8527: sub assignrole {
 8528:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
 8529:         $context)=@_;
 8530:     my $mrole;
 8531:     if ($role =~ /^cr\//) {
 8532:         my $cwosec=$url;
 8533:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 8534: 	unless (&allowed('ccr',$cwosec)) {
 8535:            my $refused = 1;
 8536:            if ($context eq 'requestcourses') {
 8537:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 8538:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
 8539:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
 8540:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 8541:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 8542:                            if ($crsenv{'internal.courseowner'} eq
 8543:                                $env{'user.name'}.':'.$env{'user.domain'}) {
 8544:                                $refused = '';
 8545:                            }
 8546:                        }
 8547:                    }
 8548:                }
 8549:            }
 8550:            if ($refused) {
 8551:                &logthis('Refused custom assignrole: '.
 8552:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
 8553:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
 8554:                return 'refused';
 8555:            }
 8556:         }
 8557:         $mrole='cr';
 8558:     } elsif ($role =~ /^gr\//) {
 8559:         my $cwogrp=$url;
 8560:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 8561:         unless (&allowed('mdg',$cwogrp)) {
 8562:             &logthis('Refused group assignrole: '.
 8563:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 8564:                     $env{'user.name'}.' at '.$env{'user.domain'});
 8565:             return 'refused';
 8566:         }
 8567:         $mrole='gr';
 8568:     } else {
 8569:         my $cwosec=$url;
 8570:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 8571:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 8572:             my $refused;
 8573:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 8574:                 if (!(&allowed('c'.$role,$url))) {
 8575:                     $refused = 1;
 8576:                 }
 8577:             } else {
 8578:                 $refused = 1;
 8579:             }
 8580:             if ($refused) {
 8581:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 8582:                 if (!$selfenroll && $context eq 'course') {
 8583:                     my %crsenv;
 8584:                     if ($role eq 'cc' || $role eq 'co') {
 8585:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 8586:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
 8587:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
 8588:                                 if ($crsenv{'internal.courseowner'} eq 
 8589:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 8590:                                     $refused = '';
 8591:                                 }
 8592:                             }
 8593:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
 8594:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
 8595:                                 if ($crsenv{'internal.courseowner'} eq 
 8596:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 8597:                                     $refused = '';
 8598:                                 }
 8599:                             }
 8600:                         }
 8601:                     }
 8602:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 8603:                     $refused = '';
 8604:                 } elsif ($context eq 'requestcourses') {
 8605:                     my @possroles = ('st','ta','ep','in','cc','co');
 8606:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
 8607:                         my $wrongcc;
 8608:                         if ($cnum =~ /^$match_community$/) {
 8609:                             $wrongcc = 1 if ($role eq 'cc');
 8610:                         } else {
 8611:                             $wrongcc = 1 if ($role eq 'co');
 8612:                         }
 8613:                         unless ($wrongcc) {
 8614:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 8615:                             if ($crsenv{'internal.courseowner'} eq 
 8616:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
 8617:                                 $refused = '';
 8618:                             }
 8619:                         }
 8620:                     }
 8621:                 } elsif ($context eq 'requestauthor') {
 8622:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
 8623:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
 8624:                         if ($env{'environment.requestauthor'} eq 'automatic') {
 8625:                             $refused = '';
 8626:                         } else {
 8627:                             my %domdefaults = &get_domain_defaults($udom);
 8628:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
 8629:                                 my $checkbystatus;
 8630:                                 if ($env{'user.adv'}) { 
 8631:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
 8632:                                     if ($disposition eq 'automatic') {
 8633:                                         $refused = '';
 8634:                                     } elsif ($disposition eq '') {
 8635:                                         $checkbystatus = 1;
 8636:                                     } 
 8637:                                 } else {
 8638:                                     $checkbystatus = 1;
 8639:                                 }
 8640:                                 if ($checkbystatus) {
 8641:                                     if ($env{'environment.inststatus'}) {
 8642:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
 8643:                                         foreach my $type (@inststatuses) {
 8644:                                             if (($type ne '') &&
 8645:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
 8646:                                                 $refused = '';
 8647:                                             }
 8648:                                         }
 8649:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
 8650:                                         $refused = '';
 8651:                                     }
 8652:                                 }
 8653:                             }
 8654:                         }
 8655:                     }
 8656:                 }
 8657:                 if ($refused) {
 8658:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 8659:                              ' '.$role.' '.$end.' '.$start.' by '.
 8660: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
 8661:                     return 'refused';
 8662:                 }
 8663:             }
 8664:         } elsif ($role eq 'au') {
 8665:             if ($url ne '/'.$udom.'/') {
 8666:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
 8667:                          ' to assign author role for '.$uname.':'.$udom.
 8668:                          ' in domain: '.$url.' refused (wrong domain).');
 8669:                 return 'refused';
 8670:             }
 8671:         }
 8672:         $mrole=$role;
 8673:     }
 8674:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 8675:                 "$udom:$uname:$url".'_'."$mrole=$role";
 8676:     if ($end) { $command.='_'.$end; }
 8677:     if ($start) {
 8678: 	if ($end) { 
 8679:            $command.='_'.$start; 
 8680:         } else {
 8681:            $command.='_0_'.$start;
 8682:         }
 8683:     }
 8684:     my $origstart = $start;
 8685:     my $origend = $end;
 8686:     my $delflag;
 8687: # actually delete
 8688:     if ($deleteflag) {
 8689: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 8690: # modify command to delete the role
 8691:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 8692:                 "$udom:$uname:$url".'_'."$mrole";
 8693: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 8694: # set start and finish to negative values for userrolelog
 8695:            $start=-1;
 8696:            $end=-1;
 8697:            $delflag = 1;
 8698:         }
 8699:     }
 8700: # send command
 8701:     my $answer=&reply($command,&homeserver($uname,$udom));
 8702: # log new user role if status is ok
 8703:     if ($answer eq 'ok') {
 8704: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 8705:         if (($role eq 'cc') || ($role eq 'in') ||
 8706:             ($role eq 'ep') || ($role eq 'ad') ||
 8707:             ($role eq 'ta') || ($role eq 'st') ||
 8708:             ($role=~/^cr/) || ($role eq 'gr') ||
 8709:             ($role eq 'co')) {
 8710: # for course roles, perform group memberships changes triggered by role change.
 8711:             unless ($role =~ /^gr/) {
 8712:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 8713:                                                  $origstart,$selfenroll,$context);
 8714:             }
 8715:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 8716:                            $selfenroll,$context);
 8717:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
 8718:                  ($role eq 'au') || ($role eq 'dc')) {
 8719:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 8720:                            $context);
 8721:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
 8722:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 8723:                              $context); 
 8724:         }
 8725:         if ($role eq 'cc') {
 8726:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
 8727:         }
 8728:     }
 8729:     return $answer;
 8730: }
 8731: 
 8732: sub autoupdate_coowners {
 8733:     my ($url,$end,$start,$uname,$udom) = @_;
 8734:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
 8735:     if (($cdom ne '') && ($cnum ne '')) {
 8736:         my $now = time;
 8737:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
 8738:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
 8739:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
 8740:             my $instcode = $coursehash{'internal.coursecode'};
 8741:             if ($instcode ne '') {
 8742:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
 8743:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
 8744:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
 8745:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
 8746:                         if ($result eq 'valid') {
 8747:                             if ($coursehash{'internal.co-owners'}) {
 8748:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 8749:                                     push(@newcoowners,$coowner);
 8750:                                 }
 8751:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
 8752:                                     push(@newcoowners,$uname.':'.$udom);
 8753:                                 }
 8754:                                 @newcoowners = sort(@newcoowners);
 8755:                             } else {
 8756:                                 push(@newcoowners,$uname.':'.$udom);
 8757:                             }
 8758:                         } else {
 8759:                             if ($coursehash{'internal.co-owners'}) {
 8760:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 8761:                                     unless ($coowner eq $uname.':'.$udom) {
 8762:                                         push(@newcoowners,$coowner);
 8763:                                     }
 8764:                                 }
 8765:                                 unless (@newcoowners > 0) {
 8766:                                     $delcoowners = 1;
 8767:                                     $coowners = '';
 8768:                                 }
 8769:                             }
 8770:                         }
 8771:                         if (@newcoowners || $delcoowners) {
 8772:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
 8773:                                             $delcoowners,@newcoowners);
 8774:                         }
 8775:                     }
 8776:                 }
 8777:             }
 8778:         }
 8779:     }
 8780: }
 8781: 
 8782: sub store_coowners {
 8783:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
 8784:     my $cid = $cdom.'_'.$cnum;
 8785:     my ($coowners,$delresult,$putresult);
 8786:     if (@newcoowners) {
 8787:         $coowners = join(',',@newcoowners);
 8788:         my %coownershash = (
 8789:                             'internal.co-owners' => $coowners,
 8790:                            );
 8791:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
 8792:         if ($putresult eq 'ok') {
 8793:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
 8794:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
 8795:             }
 8796:         }
 8797:     }
 8798:     if ($delcoowners) {
 8799:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
 8800:         if ($delresult eq 'ok') {
 8801:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
 8802:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
 8803:             }
 8804:         }
 8805:     }
 8806:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
 8807:         my %crsinfo =
 8808:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 8809:         if (ref($crsinfo{$cid}) eq 'HASH') {
 8810:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
 8811:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
 8812:         }
 8813:     }
 8814: }
 8815: 
 8816: # -------------------------------------------------- Modify user authentication
 8817: # Overrides without validation
 8818: 
 8819: sub modifyuserauth {
 8820:     my ($udom,$uname,$umode,$upass)=@_;
 8821:     my $uhome=&homeserver($uname,$udom);
 8822:     unless (&allowed('mau',$udom)) { return 'refused'; }
 8823:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 8824:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 8825:              ' in domain '.$env{'request.role.domain'});  
 8826:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 8827: 		     &escape($upass),$uhome);
 8828:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 8829:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 8830:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 8831:     &log($udom,,$uname,$uhome,
 8832:         'Authentication changed by '.$env{'user.domain'}.', '.
 8833:                                      $env{'user.name'}.', '.$umode.
 8834:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 8835:     unless ($reply eq 'ok') {
 8836:         &logthis('Authentication mode error: '.$reply);
 8837: 	return 'error: '.$reply;
 8838:     }   
 8839:     return 'ok';
 8840: }
 8841: 
 8842: # --------------------------------------------------------------- Modify a user
 8843: 
 8844: sub modifyuser {
 8845:     my ($udom,    $uname, $uid,
 8846:         $umode,   $upass, $first,
 8847:         $middle,  $last,  $gene,
 8848:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
 8849:     $udom= &LONCAPA::clean_domain($udom);
 8850:     $uname=&LONCAPA::clean_username($uname);
 8851:     my $showcandelete = 'none';
 8852:     if (ref($candelete) eq 'ARRAY') {
 8853:         if (@{$candelete} > 0) {
 8854:             $showcandelete = join(', ',@{$candelete});
 8855:         }
 8856:     }
 8857:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 8858:              $umode.', '.$first.', '.$middle.', '.
 8859: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
 8860:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 8861:                                      ' desiredhome not specified'). 
 8862:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 8863:              ' in domain '.$env{'request.role.domain'});
 8864:     my $uhome=&homeserver($uname,$udom,'true');
 8865:     my $newuser;
 8866:     if ($uhome eq 'no_host') {
 8867:         $newuser = 1;
 8868:     }
 8869: # ----------------------------------------------------------------- Create User
 8870:     if (($uhome eq 'no_host') && 
 8871: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 8872:         my $unhome='';
 8873:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 8874:             $unhome = $desiredhome;
 8875: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 8876: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 8877:         } else { # load balancing routine for determining $unhome
 8878:             my $loadm=10000000;
 8879: 	    my %servers = &get_servers($udom,'library');
 8880: 	    foreach my $tryserver (keys(%servers)) {
 8881: 		my $answer=reply('load',$tryserver);
 8882: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 8883: 		    $loadm=$answer;
 8884: 		    $unhome=$tryserver;
 8885: 		}
 8886: 	    }
 8887:         }
 8888:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 8889: 	    return 'error: unable to find a home server for '.$uname.
 8890:                    ' in domain '.$udom;
 8891:         }
 8892:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 8893:                          &escape($upass),$unhome);
 8894: 	unless ($reply eq 'ok') {
 8895:             return 'error: '.$reply;
 8896:         }   
 8897:         $uhome=&homeserver($uname,$udom,'true');
 8898:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 8899: 	    return 'error: unable verify users home machine.';
 8900:         }
 8901:     }   # End of creation of new user
 8902: # ---------------------------------------------------------------------- Add ID
 8903:     if ($uid) {
 8904:        $uid=~tr/A-Z/a-z/;
 8905:        my %uidhash=&idrget($udom,$uname);
 8906:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 8907:          && (!$forceid)) {
 8908: 	  unless ($uid eq $uidhash{$uname}) {
 8909: 	      return 'error: user id "'.$uid.'" does not match '.
 8910:                   'current user id "'.$uidhash{$uname}.'".';
 8911:           }
 8912:        } else {
 8913: 	  &idput($udom,{$uname => $uid},$uhome,'ids');
 8914:        }
 8915:     }
 8916: # -------------------------------------------------------------- Add names, etc
 8917:     my @tmp=&get('environment',
 8918: 		   ['firstname','middlename','lastname','generation','id',
 8919:                     'permanentemail','inststatus'],
 8920: 		   $udom,$uname);
 8921:     my (%names,%oldnames);
 8922:     if ($tmp[0] =~ m/^error:.*/) { 
 8923:         %names=(); 
 8924:     } else {
 8925:         %names = @tmp;
 8926:         %oldnames = %names;
 8927:     }
 8928: #
 8929: # If name, email and/or uid are blank (e.g., because an uploaded file
 8930: # of users did not contain them), do not overwrite existing values
 8931: # unless field is in $candelete array ref.  
 8932: #
 8933: 
 8934:     my @fields = ('firstname','middlename','lastname','generation',
 8935:                   'permanentemail','id');
 8936:     my %newvalues;
 8937:     if (ref($candelete) eq 'ARRAY') {
 8938:         foreach my $field (@fields) {
 8939:             if (grep(/^\Q$field\E$/,@{$candelete})) {
 8940:                 if ($field eq 'firstname') {
 8941:                     $names{$field} = $first;
 8942:                 } elsif ($field eq 'middlename') {
 8943:                     $names{$field} = $middle;
 8944:                 } elsif ($field eq 'lastname') {
 8945:                     $names{$field} = $last;
 8946:                 } elsif ($field eq 'generation') { 
 8947:                     $names{$field} = $gene;
 8948:                 } elsif ($field eq 'permanentemail') {
 8949:                     $names{$field} = $email;
 8950:                 } elsif ($field eq 'id') {
 8951:                     $names{$field}  = $uid;
 8952:                 }
 8953:             }
 8954:         }
 8955:     }
 8956:     if ($first)  { $names{'firstname'}  = $first; }
 8957:     if (defined($middle)) { $names{'middlename'} = $middle; }
 8958:     if ($last)   { $names{'lastname'}   = $last; }
 8959:     if (defined($gene))   { $names{'generation'} = $gene; }
 8960:     if ($email) {
 8961:        $email=~s/[^\w\@\.\-\,]//gs;
 8962:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
 8963:     }
 8964:     if ($uid) { $names{'id'}  = $uid; }
 8965:     if (defined($inststatus)) {
 8966:         $names{'inststatus'} = '';
 8967:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
 8968:         if (ref($usertypes) eq 'HASH') {
 8969:             my @okstatuses; 
 8970:             foreach my $item (split(/:/,$inststatus)) {
 8971:                 if (defined($usertypes->{$item})) {
 8972:                     push(@okstatuses,$item);  
 8973:                 }
 8974:             }
 8975:             if (@okstatuses) {
 8976:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
 8977:             }
 8978:         }
 8979:     }
 8980:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
 8981:                  $umode.', '.$first.', '.$middle.', '.
 8982:                  $last.', '.$gene.', '.$email.', '.$inststatus;
 8983:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
 8984:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
 8985:     } else {
 8986:         $logmsg .= ' during self creation';
 8987:     }
 8988:     my $changed;
 8989:     if ($newuser) {
 8990:         $changed = 1;
 8991:     } else {
 8992:         foreach my $field (@fields) {
 8993:             if ($names{$field} ne $oldnames{$field}) {
 8994:                 $changed = 1;
 8995:                 last;
 8996:             }
 8997:         }
 8998:     }
 8999:     unless ($changed) {
 9000:         $logmsg = 'No changes in user information needed for: '.$logmsg;
 9001:         &logthis($logmsg);
 9002:         return 'ok';
 9003:     }
 9004:     my $reply = &put('environment', \%names, $udom,$uname);
 9005:     if ($reply ne 'ok') { 
 9006:         return 'error: '.$reply;
 9007:     }
 9008:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
 9009:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
 9010:     }
 9011:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
 9012:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 9013:     $logmsg = 'Success modifying user '.$logmsg;
 9014:     &logthis($logmsg);
 9015:     return 'ok';
 9016: }
 9017: 
 9018: # -------------------------------------------------------------- Modify student
 9019: 
 9020: sub modifystudent {
 9021:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 9022:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
 9023:         $selfenroll,$context,$inststatus,$credits)=@_;
 9024:     if (!$cid) {
 9025: 	unless ($cid=$env{'request.course.id'}) {
 9026: 	    return 'not_in_class';
 9027: 	}
 9028:     }
 9029: # --------------------------------------------------------------- Make the user
 9030:     my $reply=&modifyuser
 9031: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 9032:          $desiredhome,$email,$inststatus);
 9033:     unless ($reply eq 'ok') { return $reply; }
 9034:     # This will cause &modify_student_enrollment to get the uid from the
 9035:     # student's environment
 9036:     $uid = undef if (!$forceid);
 9037:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 9038:                                         $gene,$usec,$end,$start,$type,$locktype,
 9039:                                         $cid,$selfenroll,$context,$credits);
 9040:     return $reply;
 9041: }
 9042: 
 9043: sub modify_student_enrollment {
 9044:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
 9045:         $locktype,$cid,$selfenroll,$context,$credits) = @_;
 9046:     my ($cdom,$cnum,$chome);
 9047:     if (!$cid) {
 9048: 	unless ($cid=$env{'request.course.id'}) {
 9049: 	    return 'not_in_class';
 9050: 	}
 9051: 	$cdom=$env{'course.'.$cid.'.domain'};
 9052: 	$cnum=$env{'course.'.$cid.'.num'};
 9053:     } else {
 9054: 	($cdom,$cnum)=split(/_/,$cid);
 9055:     }
 9056:     $chome=$env{'course.'.$cid.'.home'};
 9057:     if (!$chome) {
 9058: 	$chome=&homeserver($cnum,$cdom);
 9059:     }
 9060:     if (!$chome) { return 'unknown_course'; }
 9061:     # Make sure the user exists
 9062:     my $uhome=&homeserver($uname,$udom);
 9063:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 9064: 	return 'error: no such user';
 9065:     }
 9066:     # Get student data if we were not given enough information
 9067:     if (!defined($first)  || $first  eq '' || 
 9068:         !defined($last)   || $last   eq '' || 
 9069:         !defined($uid)    || $uid    eq '' || 
 9070:         !defined($middle) || $middle eq '' || 
 9071:         !defined($gene)   || $gene   eq '') {
 9072:         # They did not supply us with enough data to enroll the student, so
 9073:         # we need to pick up more information.
 9074:         my %tmp = &get('environment',
 9075:                        ['firstname','middlename','lastname', 'generation','id']
 9076:                        ,$udom,$uname);
 9077: 
 9078:         #foreach my $key (keys(%tmp)) {
 9079:         #    &logthis("key $key = ".$tmp{$key});
 9080:         #}
 9081:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 9082:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 9083:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 9084:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 9085:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 9086:     }
 9087:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 9088:     my $user = "$uname:$udom";
 9089:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
 9090:     my $reply=cput('classlist',
 9091: 		   {$user => 
 9092: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits) },
 9093: 		   $cdom,$cnum);
 9094:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
 9095:         &devalidate_getsection_cache($udom,$uname,$cid);
 9096:     } else { 
 9097: 	return 'error: '.$reply;
 9098:     }
 9099:     # Add student role to user
 9100:     my $uurl='/'.$cid;
 9101:     $uurl=~s/\_/\//g;
 9102:     if ($usec) {
 9103: 	$uurl.='/'.$usec;
 9104:     }
 9105:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
 9106:                              $selfenroll,$context);
 9107:     if ($result ne 'ok') {
 9108:         if ($old_entry{$user} ne '') {
 9109:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
 9110:         } else {
 9111:             $reply = &del('classlist',[$user],$cdom,$cnum);
 9112:         }
 9113:     }
 9114:     return $result; 
 9115: }
 9116: 
 9117: sub format_name {
 9118:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 9119:     my $name;
 9120:     if ($first ne 'lastname') {
 9121: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 9122:     } else {
 9123: 	if ($lastname=~/\S/) {
 9124: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 9125: 	    $name=~s/\s+,/,/;
 9126: 	} else {
 9127: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 9128: 	}
 9129:     }
 9130:     $name=~s/^\s+//;
 9131:     $name=~s/\s+$//;
 9132:     $name=~s/\s+/ /g;
 9133:     return $name;
 9134: }
 9135: 
 9136: # ------------------------------------------------- Write to course preferences
 9137: 
 9138: sub writecoursepref {
 9139:     my ($courseid,%prefs)=@_;
 9140:     $courseid=~s/^\///;
 9141:     $courseid=~s/\_/\//g;
 9142:     my ($cdomain,$cnum)=split(/\//,$courseid);
 9143:     my $chome=homeserver($cnum,$cdomain);
 9144:     if (($chome eq '') || ($chome eq 'no_host')) { 
 9145: 	return 'error: no such course';
 9146:     }
 9147:     my $cstring='';
 9148:     foreach my $pref (keys(%prefs)) {
 9149: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 9150:     }
 9151:     $cstring=~s/\&$//;
 9152:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 9153: }
 9154: 
 9155: # ---------------------------------------------------------- Make/modify course
 9156: 
 9157: sub createcourse {
 9158:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 9159:         $course_owner,$crstype,$cnum,$context,$category)=@_;
 9160:     $url=&declutter($url);
 9161:     my $cid='';
 9162:     if ($context eq 'requestcourses') {
 9163:         my $can_create = 0;
 9164:         my ($ownername,$ownerdom) = split(':',$course_owner);
 9165:         if ($udom eq $ownerdom) {
 9166:             if (&usertools_access($ownername,$ownerdom,$category,undef,
 9167:                                   $context)) {
 9168:                 $can_create = 1;
 9169:             }
 9170:         } else {
 9171:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
 9172:                                            $category);
 9173:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
 9174:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
 9175:                 if (@curr > 0) {
 9176:                     my @options = qw(approval validate autolimit);
 9177:                     my $optregex = join('|',@options);
 9178:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
 9179:                         $can_create = 1;
 9180:                     }
 9181:                 }
 9182:             }
 9183:         }
 9184:         if ($can_create) {
 9185:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
 9186:                 unless (&allowed('ccc',$udom)) {
 9187:                     return 'refused'; 
 9188:                 }
 9189:             }
 9190:         } else {
 9191:             return 'refused';
 9192:         }
 9193:     } elsif (!&allowed('ccc',$udom)) {
 9194:         return 'refused';
 9195:     }
 9196: # --------------------------------------------------------------- Get Unique ID
 9197:     my $uname;
 9198:     if ($cnum =~ /^$match_courseid$/) {
 9199:         my $chome=&homeserver($cnum,$udom,'true');
 9200:         if (($chome eq '') || ($chome eq 'no_host')) {
 9201:             $uname = $cnum;
 9202:         } else {
 9203:             $uname = &generate_coursenum($udom,$crstype);
 9204:         }
 9205:     } else {
 9206:         $uname = &generate_coursenum($udom,$crstype);
 9207:     }
 9208:     return $uname if ($uname =~ /^error/);
 9209: # -------------------------------------------------- Check supplied server name
 9210:     if (!defined($course_server)) {
 9211:         if (defined(&domain($udom,'primary'))) {
 9212:             $course_server = &domain($udom,'primary');
 9213:         } else {
 9214:             $course_server = $env{'user.home'}; 
 9215:         }
 9216:     }
 9217:     my %host_servers =
 9218:         &Apache::lonnet::get_servers($udom,'library');
 9219:     unless ($host_servers{$course_server}) {
 9220:         return 'error: invalid home server for course: '.$course_server;
 9221:     }
 9222: # ------------------------------------------------------------- Make the course
 9223:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 9224:                       $course_server);
 9225:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 9226:     my $uhome=&homeserver($uname,$udom,'true');
 9227:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 9228: 	return 'error: no such course';
 9229:     }
 9230: # ----------------------------------------------------------------- Course made
 9231: # log existence
 9232:     my $now = time;
 9233:     my $newcourse = {
 9234:                     $udom.'_'.$uname => {
 9235:                                      description => $description,
 9236:                                      inst_code   => $inst_code,
 9237:                                      owner       => $course_owner,
 9238:                                      type        => $crstype,
 9239:                                      creator     => $env{'user.name'}.':'.
 9240:                                                     $env{'user.domain'},
 9241:                                      created     => $now,
 9242:                                      context     => $context,
 9243:                                                 },
 9244:                     };
 9245:     &courseidput($udom,$newcourse,$uhome,'notime');
 9246: # set toplevel url
 9247:     my $topurl=$url;
 9248:     unless ($nonstandard) {
 9249: # ------------------------------------------ For standard courses, make top url
 9250:         my $mapurl=&clutter($url);
 9251:         if ($mapurl eq '/res/') { $mapurl=''; }
 9252:         $env{'form.initmap'}=(<<ENDINITMAP);
 9253: <map>
 9254: <resource id="1" type="start"></resource>
 9255: <resource id="2" src="$mapurl"></resource>
 9256: <resource id="3" type="finish"></resource>
 9257: <link index="1" from="1" to="2"></link>
 9258: <link index="2" from="2" to="3"></link>
 9259: </map>
 9260: ENDINITMAP
 9261:         $topurl=&declutter(
 9262:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 9263:                           );
 9264:     }
 9265: # ----------------------------------------------------------- Write preferences
 9266:     &writecoursepref($udom.'_'.$uname,
 9267:                      ('description'              => $description,
 9268:                       'url'                      => $topurl,
 9269:                       'internal.creator'         => $env{'user.name'}.':'.
 9270:                                                     $env{'user.domain'},
 9271:                       'internal.created'         => $now,
 9272:                       'internal.creationcontext' => $context)
 9273:                     );
 9274:     return '/'.$udom.'/'.$uname;
 9275: }
 9276: 
 9277: # ------------------------------------------------------------------- Create ID
 9278: sub generate_coursenum {
 9279:     my ($udom,$crstype) = @_;
 9280:     my $domdesc = &domain($udom);
 9281:     return 'error: invalid domain' if ($domdesc eq '');
 9282:     my $first;
 9283:     if ($crstype eq 'Community') {
 9284:         $first = '0';
 9285:     } else {
 9286:         $first = int(1+rand(9)); 
 9287:     } 
 9288:     my $uname=$first.
 9289:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 9290:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
 9291:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 9292: # ----------------------------------------------- Make sure that does not exist
 9293:     my $uhome=&homeserver($uname,$udom,'true');
 9294:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
 9295:         if ($crstype eq 'Community') {
 9296:             $first = '0';
 9297:         } else {
 9298:             $first = int(1+rand(9));
 9299:         }
 9300:         $uname=$first.
 9301:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 9302:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
 9303:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 9304:         $uhome=&homeserver($uname,$udom,'true');
 9305:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
 9306:             return 'error: unable to generate unique course-ID';
 9307:         }
 9308:     }
 9309:     return $uname;
 9310: }
 9311: 
 9312: sub is_course {
 9313:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
 9314:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
 9315: 
 9316:     return unless $cdom and $cnum;
 9317: 
 9318:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
 9319:         '.');
 9320: 
 9321:     return unless(exists($courses{$cdom.'_'.$cnum}));
 9322:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
 9323: }
 9324: 
 9325: sub store_userdata {
 9326:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
 9327:     my $result;
 9328:     if ($datakey ne '') {
 9329:         if (ref($storehash) eq 'HASH') {
 9330:             if ($udom eq '' || $uname eq '') {
 9331:                 $udom = $env{'user.domain'};
 9332:                 $uname = $env{'user.name'};
 9333:             }
 9334:             my $uhome=&homeserver($uname,$udom);
 9335:             if (($uhome eq '') || ($uhome eq 'no_host')) {
 9336:                 $result = 'error: no_host';
 9337:             } else {
 9338:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
 9339:                 $storehash->{'host'} = $perlvar{'lonHostID'};
 9340: 
 9341:                 my $namevalue='';
 9342:                 foreach my $key (keys(%{$storehash})) {
 9343:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 9344:                 }
 9345:                 $namevalue=~s/\&$//;
 9346:                 unless ($namespace eq 'courserequests') {
 9347:                     $datakey = &escape($datakey);
 9348:                 }
 9349:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
 9350:                                   $namevalue,$uhome);
 9351:             }
 9352:         } else {
 9353:             $result = 'error: data to store was not a hash reference'; 
 9354:         }
 9355:     } else {
 9356:         $result= 'error: invalid requestkey'; 
 9357:     }
 9358:     return $result;
 9359: }
 9360: 
 9361: # ---------------------------------------------------------- Assign Custom Role
 9362: 
 9363: sub assigncustomrole {
 9364:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
 9365:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 9366:                        $end,$start,$deleteflag,$selfenroll,$context);
 9367: }
 9368: 
 9369: # ----------------------------------------------------------------- Revoke Role
 9370: 
 9371: sub revokerole {
 9372:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
 9373:     my $now=time;
 9374:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
 9375: }
 9376: 
 9377: # ---------------------------------------------------------- Revoke Custom Role
 9378: 
 9379: sub revokecustomrole {
 9380:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
 9381:     my $now=time;
 9382:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 9383:            $deleteflag,$selfenroll,$context);
 9384: }
 9385: 
 9386: # ------------------------------------------------------------ Disk usage
 9387: sub diskusage {
 9388:     my ($udom,$uname,$directorypath,$getpropath)=@_;
 9389:     $directorypath =~ s/\/$//;
 9390:     my $listing=&reply('du2:'.&escape($directorypath).':'
 9391:                        .&escape($getpropath).':'.&escape($uname).':'
 9392:                        .&escape($udom),homeserver($uname,$udom));
 9393:     if ($listing eq 'unknown_cmd') {
 9394:         if ($getpropath) {
 9395:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
 9396:         }
 9397:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
 9398:     }
 9399:     return $listing;
 9400: }
 9401: 
 9402: sub is_locked {
 9403:     my ($file_name, $domain, $user, $which) = @_;
 9404:     my @check;
 9405:     my $is_locked;
 9406:     push (@check,$file_name);
 9407:     my %locked = &get('file_permissions',\@check,
 9408: 		      $env{'user.domain'},$env{'user.name'});
 9409:     my ($tmp)=keys(%locked);
 9410:     if ($tmp=~/^error:/) { undef(%locked); }
 9411:     
 9412:     if (ref($locked{$file_name}) eq 'ARRAY') {
 9413:         $is_locked = 'false';
 9414:         foreach my $entry (@{$locked{$file_name}}) {
 9415:            if (ref($entry) eq 'ARRAY') {
 9416:                $is_locked = 'true';
 9417:                if (ref($which) eq 'ARRAY') {
 9418:                    push(@{$which},$entry);
 9419:                } else {
 9420:                    last;
 9421:                }
 9422:            }
 9423:        }
 9424:     } else {
 9425:         $is_locked = 'false';
 9426:     }
 9427:     return $is_locked;
 9428: }
 9429: 
 9430: sub declutter_portfile {
 9431:     my ($file) = @_;
 9432:     $file =~ s{^(/portfolio/|portfolio/)}{/};
 9433:     return $file;
 9434: }
 9435: 
 9436: # ------------------------------------------------------------- Mark as Read Only
 9437: 
 9438: sub mark_as_readonly {
 9439:     my ($domain,$user,$files,$what) = @_;
 9440:     my %current_permissions = &dump('file_permissions',$domain,$user);
 9441:     my ($tmp)=keys(%current_permissions);
 9442:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 9443:     foreach my $file (@{$files}) {
 9444: 	$file = &declutter_portfile($file);
 9445:         push(@{$current_permissions{$file}},$what);
 9446:     }
 9447:     &put('file_permissions',\%current_permissions,$domain,$user);
 9448:     return;
 9449: }
 9450: 
 9451: # ------------------------------------------------------------Save Selected Files
 9452: 
 9453: sub save_selected_files {
 9454:     my ($user, $path, @files) = @_;
 9455:     my $filename = $user."savedfiles";
 9456:     my @other_files = &files_not_in_path($user, $path);
 9457:     open (OUT, '>'.$tmpdir.$filename);
 9458:     foreach my $file (@files) {
 9459:         print (OUT $env{'form.currentpath'}.$file."\n");
 9460:     }
 9461:     foreach my $file (@other_files) {
 9462:         print (OUT $file."\n");
 9463:     }
 9464:     close (OUT);
 9465:     return 'ok';
 9466: }
 9467: 
 9468: sub clear_selected_files {
 9469:     my ($user) = @_;
 9470:     my $filename = $user."savedfiles";
 9471:     open (OUT, '>'.LONCAPA::tempdir().$filename);
 9472:     print (OUT undef);
 9473:     close (OUT);
 9474:     return ("ok");    
 9475: }
 9476: 
 9477: sub files_in_path {
 9478:     my ($user, $path) = @_;
 9479:     my $filename = $user."savedfiles";
 9480:     my %return_files;
 9481:     open (IN, '<'.LONCAPA::tempdir().$filename);
 9482:     while (my $line_in = <IN>) {
 9483:         chomp ($line_in);
 9484:         my @paths_and_file = split (m!/!, $line_in);
 9485:         my $file_part = pop (@paths_and_file);
 9486:         my $path_part = join ('/', @paths_and_file);
 9487:         $path_part.='/';
 9488:         my $path_and_file = $path_part.$file_part;
 9489:         if ($path_part eq $path) {
 9490:             $return_files{$file_part}= 'selected';
 9491:         }
 9492:     }
 9493:     close (IN);
 9494:     return (\%return_files);
 9495: }
 9496: 
 9497: # called in portfolio select mode, to show files selected NOT in current directory
 9498: sub files_not_in_path {
 9499:     my ($user, $path) = @_;
 9500:     my $filename = $user."savedfiles";
 9501:     my @return_files;
 9502:     my $path_part;
 9503:     open(IN, '<'.LONCAPA::.$filename);
 9504:     while (my $line = <IN>) {
 9505:         #ok, I know it's clunky, but I want it to work
 9506:         my @paths_and_file = split(m|/|, $line);
 9507:         my $file_part = pop(@paths_and_file);
 9508:         chomp($file_part);
 9509:         my $path_part = join('/', @paths_and_file);
 9510:         $path_part .= '/';
 9511:         my $path_and_file = $path_part.$file_part;
 9512:         if ($path_part ne $path) {
 9513:             push(@return_files, ($path_and_file));
 9514:         }
 9515:     }
 9516:     close(OUT);
 9517:     return (@return_files);
 9518: }
 9519: 
 9520: #------------------------------Submitted/Handedback Portfolio Files Versioning
 9521:  
 9522: sub portfiles_versioning {
 9523:     my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
 9524:     my $portfolio_root = '/userfiles/portfolio';
 9525:     return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
 9526:     foreach my $file (@{$portfiles}) {
 9527:         &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
 9528:         my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
 9529:         my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
 9530:         my $getpropath = 1;
 9531:         my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
 9532:                                              $stu_name,$getpropath);
 9533:         my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
 9534:         my $new_answer = 
 9535:             &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
 9536:         if ($new_answer ne 'problem getting file') {
 9537:             push(@{$versioned_portfiles}, $directory.$new_answer);
 9538:             &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
 9539:                               [$symb,$env{'request.course.id'},'graded']);
 9540:         }
 9541:     }
 9542: }
 9543: 
 9544: sub get_next_version {
 9545:     my ($answer_name, $answer_ext, $dir_list) = @_;
 9546:     my $version;
 9547:     if (ref($dir_list) eq 'ARRAY') {
 9548:         foreach my $row (@{$dir_list}) {
 9549:             my ($file) = split(/\&/,$row,2);
 9550:             my ($file_name,$file_version,$file_ext) =
 9551:                 &file_name_version_ext($file);
 9552:             if (($file_name eq $answer_name) &&
 9553:                 ($file_ext eq $answer_ext)) {
 9554:                      # gets here if filename and extension match,
 9555:                      # regardless of version
 9556:                 if ($file_version ne '') {
 9557:                     # a versioned file is found  so save it for later
 9558:                     if ($file_version > $version) {
 9559:                         $version = $file_version;
 9560:                     }
 9561:                 }
 9562:             }
 9563:         }
 9564:     }
 9565:     $version ++;
 9566:     return($version);
 9567: }
 9568: 
 9569: sub version_selected_portfile {
 9570:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
 9571:     my ($answer_name,$answer_ver,$answer_ext) =
 9572:         &file_name_version_ext($file_name);
 9573:     my $new_answer;
 9574:     $env{'form.copy'} =
 9575:         &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
 9576:     if($env{'form.copy'} eq '-1') {
 9577:         $new_answer = 'problem getting file';
 9578:     } else {
 9579:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
 9580:         my $copy_result = 
 9581:             &finishuserfileupload($stu_name,$domain,'copy',
 9582:                                   '/portfolio'.$directory.$new_answer);
 9583:     }
 9584:     undef($env{'form.copy'});
 9585:     return ($new_answer);
 9586: }
 9587: 
 9588: sub file_name_version_ext {
 9589:     my ($file)=@_;
 9590:     my @file_parts = split(/\./, $file);
 9591:     my ($name,$version,$ext);
 9592:     if (@file_parts > 1) {
 9593:         $ext=pop(@file_parts);
 9594:         if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
 9595:             $version=pop(@file_parts);
 9596:         }
 9597:         $name=join('.',@file_parts);
 9598:     } else {
 9599:         $name=join('.',@file_parts);
 9600:     }
 9601:     return($name,$version,$ext);
 9602: }
 9603: 
 9604: #----------------------------------------------Get portfolio file permissions
 9605: 
 9606: sub get_portfile_permissions {
 9607:     my ($domain,$user) = @_;
 9608:     my %current_permissions = &dump('file_permissions',$domain,$user);
 9609:     my ($tmp)=keys(%current_permissions);
 9610:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 9611:     return \%current_permissions;
 9612: }
 9613: 
 9614: #---------------------------------------------Get portfolio file access controls
 9615: 
 9616: sub get_access_controls {
 9617:     my ($current_permissions,$group,$file) = @_;
 9618:     my %access;
 9619:     my $real_file = $file;
 9620:     $file =~ s/\.meta$//;
 9621:     if (defined($file)) {
 9622:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
 9623:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
 9624:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
 9625:             }
 9626:         }
 9627:     } else {
 9628:         foreach my $key (keys(%{$current_permissions})) {
 9629:             if ($key =~ /\0accesscontrol$/) {
 9630:                 if (defined($group)) {
 9631:                     if ($key !~ m-^\Q$group\E/-) {
 9632:                         next;
 9633:                     }
 9634:                 }
 9635:                 my ($fullpath) = split(/\0/,$key);
 9636:                 if (ref($$current_permissions{$key}) eq 'HASH') {
 9637:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
 9638:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
 9639:                     }
 9640:                 }
 9641:             }
 9642:         }
 9643:     }
 9644:     return %access;
 9645: }
 9646: 
 9647: sub modify_access_controls {
 9648:     my ($file_name,$changes,$domain,$user)=@_;
 9649:     my ($outcome,$deloutcome);
 9650:     my %store_permissions;
 9651:     my %new_values;
 9652:     my %new_control;
 9653:     my %translation;
 9654:     my @deletions = ();
 9655:     my $now = time;
 9656:     if (exists($$changes{'activate'})) {
 9657:         if (ref($$changes{'activate'}) eq 'HASH') {
 9658:             my @newitems = sort(keys(%{$$changes{'activate'}}));
 9659:             my $numnew = scalar(@newitems);
 9660:             for (my $i=0; $i<$numnew; $i++) {
 9661:                 my $newkey = $newitems[$i];
 9662:                 my $newid = &Apache::loncommon::get_cgi_id();
 9663:                 if ($newkey =~ /^\d+:/) { 
 9664:                     $newkey =~ s/^(\d+)/$newid/;
 9665:                     $translation{$1} = $newid;
 9666:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
 9667:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
 9668:                     $translation{$1} = $newid;
 9669:                 }
 9670:                 $new_values{$file_name."\0".$newkey} = 
 9671:                                           $$changes{'activate'}{$newitems[$i]};
 9672:                 $new_control{$newkey} = $now;
 9673:             }
 9674:         }
 9675:     }
 9676:     my %todelete;
 9677:     my %changed_items;
 9678:     foreach my $action ('delete','update') {
 9679:         if (exists($$changes{$action})) {
 9680:             if (ref($$changes{$action}) eq 'HASH') {
 9681:                 foreach my $key (keys(%{$$changes{$action}})) {
 9682:                     my ($itemnum) = ($key =~ /^([^:]+):/);
 9683:                     if ($action eq 'delete') { 
 9684:                         $todelete{$itemnum} = 1;
 9685:                     } else {
 9686:                         $changed_items{$itemnum} = $key;
 9687:                     }
 9688:                 }
 9689:             }
 9690:         }
 9691:     }
 9692:     # get lock on access controls for file.
 9693:     my $lockhash = {
 9694:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
 9695:                                                        ':'.$env{'user.domain'},
 9696:                    }; 
 9697:     my $tries = 0;
 9698:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 9699:    
 9700:     while (($gotlock ne 'ok') && $tries < 10) {
 9701:         $tries ++;
 9702:         sleep(0.1);
 9703:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 9704:     }
 9705:     if ($gotlock eq 'ok') {
 9706:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
 9707:         my ($tmp)=keys(%curr_permissions);
 9708:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
 9709:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
 9710:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
 9711:             if (ref($curr_controls) eq 'HASH') {
 9712:                 foreach my $control_item (keys(%{$curr_controls})) {
 9713:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
 9714:                     if (defined($todelete{$itemnum})) {
 9715:                         push(@deletions,$file_name."\0".$control_item);
 9716:                     } else {
 9717:                         if (defined($changed_items{$itemnum})) {
 9718:                             $new_control{$changed_items{$itemnum}} = $now;
 9719:                             push(@deletions,$file_name."\0".$control_item);
 9720:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
 9721:                         } else {
 9722:                             $new_control{$control_item} = $$curr_controls{$control_item};
 9723:                         }
 9724:                     }
 9725:                 }
 9726:             }
 9727:         }
 9728:         my ($group);
 9729:         if (&is_course($domain,$user)) {
 9730:             ($group,my $file) = split(/\//,$file_name,2);
 9731:         }
 9732:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
 9733:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
 9734:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
 9735:         #  remove lock
 9736:         my @del_lock = ($file_name."\0".'locked_access_records');
 9737:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
 9738:         my $sqlresult =
 9739:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
 9740:                                     $group);
 9741:     } else {
 9742:         $outcome = "error: could not obtain lockfile\n";  
 9743:     }
 9744:     return ($outcome,$deloutcome,\%new_values,\%translation);
 9745: }
 9746: 
 9747: sub make_public_indefinitely {
 9748:     my (@requrl) = @_;
 9749:     return &automated_portfile_access('public',\@requrl);
 9750: }
 9751: 
 9752: sub automated_portfile_access {
 9753:     my ($accesstype,$addsref,$delsref,$info) = @_;
 9754:     unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
 9755:         return 'invalid';
 9756:     }
 9757:     my %urls;
 9758:     if (ref($addsref) eq 'ARRAY') {
 9759:         foreach my $requrl (@{$addsref}) {
 9760:             if (&is_portfolio_url($requrl)) {
 9761:                 unless (exists($urls{$requrl})) {
 9762:                     $urls{$requrl} = 'add';
 9763:                 }
 9764:             }
 9765:         }
 9766:     }
 9767:     if (ref($delsref) eq 'ARRAY') {
 9768:         foreach my $requrl (@{$delsref}) { 
 9769:             if (&is_portfolio_url($requrl)) {
 9770:                 unless (exists($urls{$requrl})) {
 9771:                     $urls{$requrl} = 'delete'; 
 9772:                 }
 9773:             }
 9774:         }
 9775:     }
 9776:     unless (keys(%urls)) {
 9777:         return 'invalid';
 9778:     }
 9779:     my $ip;
 9780:     if ($accesstype eq 'ip') {
 9781:         if (ref($info) eq 'HASH') {
 9782:             if ($info->{'ip'} ne '') {
 9783:                 $ip = $info->{'ip'};
 9784:             }
 9785:         }
 9786:         if ($ip eq '') {
 9787:             return 'invalid';
 9788:         }
 9789:     }
 9790:     my $errors;
 9791:     my $now = time;
 9792:     my %current_perms;
 9793:     foreach my $requrl (sort(keys(%urls))) {
 9794:         my $action;
 9795:         if ($urls{$requrl} eq 'add') {
 9796:             $action = 'activate';
 9797:         } else {
 9798:             $action = 'none';
 9799:         }
 9800:         my $aclnum = 0;
 9801:         my (undef,$udom,$unum,$file_name,$group) =
 9802:             &parse_portfolio_url($requrl);
 9803:         unless (exists($current_perms{$unum.':'.$udom})) {
 9804:             $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
 9805:         }
 9806:         my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
 9807:                                                    $group,$file_name);
 9808:         foreach my $key (keys(%{$access_controls{$file_name}})) {
 9809:             my ($num,$scope,$end,$start) = 
 9810:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 9811:             if ($scope eq $accesstype) {
 9812:                 if (($start <= $now) && ($end == 0)) {
 9813:                     if ($accesstype eq 'ip') {
 9814:                         if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
 9815:                             if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
 9816:                                 if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
 9817:                                     if ($urls{$requrl} eq 'add') {
 9818:                                         $action = 'none';
 9819:                                         last;
 9820:                                     } else {
 9821:                                         $action = 'delete';
 9822:                                         $aclnum = $num;
 9823:                                         last;
 9824:                                     }
 9825:                                 }
 9826:                             }
 9827:                         }
 9828:                     } elsif ($accesstype eq 'public') {
 9829:                         if ($urls{$requrl} eq 'add') {
 9830:                             $action = 'none';
 9831:                             last;
 9832:                         } else {
 9833:                             $action = 'delete';
 9834:                             $aclnum = $num;
 9835:                             last;
 9836:                         }
 9837:                     }
 9838:                 } elsif ($accesstype eq 'public') {
 9839:                     $action = 'update';
 9840:                     $aclnum = $num;
 9841:                     last;
 9842:                 }
 9843:             }
 9844:         }
 9845:         if ($action eq 'none') {
 9846:             next;
 9847:         } else {
 9848:             my %changes;
 9849:             my $newend = 0;
 9850:             my $newstart = $now;
 9851:             my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
 9852:             $changes{$action}{$newkey} = {
 9853:                 type => $accesstype,
 9854:                 time => {
 9855:                     start => $newstart,
 9856:                     end   => $newend,
 9857:                 },
 9858:             };
 9859:             if ($accesstype eq 'ip') {
 9860:                 $changes{$action}{$newkey}{'ip'} = [$ip];
 9861:             }
 9862:             my ($outcome,$deloutcome,$new_values,$translation) =
 9863:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
 9864:             unless ($outcome eq 'ok') {
 9865:                 $errors .= $outcome.' ';
 9866:             }
 9867:         }
 9868:     }
 9869:     if ($errors) {
 9870:         $errors =~ s/\s$//;
 9871:         return $errors;
 9872:     } else {
 9873:         return 'ok';
 9874:     }
 9875: }
 9876: 
 9877: #------------------------------------------------------Get Marked as Read Only
 9878: 
 9879: sub get_marked_as_readonly {
 9880:     my ($domain,$user,$what,$group) = @_;
 9881:     my $current_permissions = &get_portfile_permissions($domain,$user);
 9882:     my @readonly_files;
 9883:     my $cmp1=$what;
 9884:     if (ref($what)) { $cmp1=join('',@{$what}) };
 9885:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 9886:         if (defined($group)) {
 9887:             if ($file_name !~ m-^\Q$group\E/-) {
 9888:                 next;
 9889:             }
 9890:         }
 9891:         if (ref($value) eq "ARRAY"){
 9892:             foreach my $stored_what (@{$value}) {
 9893:                 my $cmp2=$stored_what;
 9894:                 if (ref($stored_what) eq 'ARRAY') {
 9895:                     $cmp2=join('',@{$stored_what});
 9896:                 }
 9897:                 if ($cmp1 eq $cmp2) {
 9898:                     push(@readonly_files, $file_name);
 9899:                     last;
 9900:                 } elsif (!defined($what)) {
 9901:                     push(@readonly_files, $file_name);
 9902:                     last;
 9903:                 }
 9904:             }
 9905:         }
 9906:     }
 9907:     return @readonly_files;
 9908: }
 9909: #-----------------------------------------------------------Get Marked as Read Only Hash
 9910: 
 9911: sub get_marked_as_readonly_hash {
 9912:     my ($current_permissions,$group,$what) = @_;
 9913:     my %readonly_files;
 9914:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 9915:         if (defined($group)) {
 9916:             if ($file_name !~ m-^\Q$group\E/-) {
 9917:                 next;
 9918:             }
 9919:         }
 9920:         if (ref($value) eq "ARRAY"){
 9921:             foreach my $stored_what (@{$value}) {
 9922:                 if (ref($stored_what) eq 'ARRAY') {
 9923:                     foreach my $lock_descriptor(@{$stored_what}) {
 9924:                         if ($lock_descriptor eq 'graded') {
 9925:                             $readonly_files{$file_name} = 'graded';
 9926:                         } elsif ($lock_descriptor eq 'handback') {
 9927:                             $readonly_files{$file_name} = 'handback';
 9928:                         } else {
 9929:                             if (!exists($readonly_files{$file_name})) {
 9930:                                 $readonly_files{$file_name} = 'locked';
 9931:                             }
 9932:                         }
 9933:                     }
 9934:                 } 
 9935:             }
 9936:         } 
 9937:     }
 9938:     return %readonly_files;
 9939: }
 9940: # ------------------------------------------------------------ Unmark as Read Only
 9941: 
 9942: sub unmark_as_readonly {
 9943:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
 9944:     # for portfolio submissions, $what contains [$symb,$crsid] 
 9945:     my ($domain,$user,$what,$file_name,$group) = @_;
 9946:     $file_name = &declutter_portfile($file_name);
 9947:     my $symb_crs = $what;
 9948:     if (ref($what)) { $symb_crs=join('',@$what); }
 9949:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
 9950:     my ($tmp)=keys(%current_permissions);
 9951:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 9952:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
 9953:     foreach my $file (@readonly_files) {
 9954: 	my $clean_file = &declutter_portfile($file);
 9955: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
 9956: 	my $current_locks = $current_permissions{$file};
 9957:         my @new_locks;
 9958:         my @del_keys;
 9959:         if (ref($current_locks) eq "ARRAY"){
 9960:             foreach my $locker (@{$current_locks}) {
 9961:                 my $compare=$locker;
 9962:                 if (ref($locker) eq 'ARRAY') {
 9963:                     $compare=join('',@{$locker});
 9964:                     if ($compare ne $symb_crs) {
 9965:                         push(@new_locks, $locker);
 9966:                     }
 9967:                 }
 9968:             }
 9969:             if (scalar(@new_locks) > 0) {
 9970:                 $current_permissions{$file} = \@new_locks;
 9971:             } else {
 9972:                 push(@del_keys, $file);
 9973:                 &del('file_permissions',\@del_keys, $domain, $user);
 9974:                 delete($current_permissions{$file});
 9975:             }
 9976:         }
 9977:     }
 9978:     &put('file_permissions',\%current_permissions,$domain,$user);
 9979:     return;
 9980: }
 9981: 
 9982: # ------------------------------------------------------------ Directory lister
 9983: 
 9984: sub dirlist {
 9985:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
 9986:     $uri=~s/^\///;
 9987:     $uri=~s/\/$//;
 9988:     my ($udom, $uname);
 9989:     if ($getuserdir) {
 9990:         $udom = $userdomain;
 9991:         $uname = $username;
 9992:     } else {
 9993:         (undef,$udom,$uname)=split(/\//,$uri);
 9994:         if(defined($userdomain)) {
 9995:             $udom = $userdomain;
 9996:         }
 9997:         if(defined($username)) {
 9998:             $uname = $username;
 9999:         }
10000:     }
10001:     my ($dirRoot,$listing,@listing_results);
10002: 
10003:     $dirRoot = $perlvar{'lonDocRoot'};
10004:     if (defined($getpropath)) {
10005:         $dirRoot = &propath($udom,$uname);
10006:         $dirRoot =~ s/\/$//;
10007:     } elsif (defined($getuserdir)) {
10008:         my $subdir=$uname.'__';
10009:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
10010:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
10011:                    ."/$udom/$subdir/$uname";
10012:     } elsif (defined($alternateRoot)) {
10013:         $dirRoot = $alternateRoot;
10014:     }
10015: 
10016:     if($udom) {
10017:         if($uname) {
10018:             my $uhome = &homeserver($uname,$udom);
10019:             if ($uhome eq 'no_host') {
10020:                 return ([],'no_host');
10021:             }
10022:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
10023:                               .$getuserdir.':'.&escape($dirRoot)
10024:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
10025:             if ($listing eq 'unknown_cmd') {
10026:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
10027:             } else {
10028:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
10029:             }
10030:             if ($listing eq 'unknown_cmd') {
10031:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
10032:                 @listing_results = split(/:/,$listing);
10033:             } else {
10034:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
10035:             }
10036:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
10037:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
10038:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
10039:                 return ([],$listing);
10040:             } else {
10041:                 return (\@listing_results);
10042:             }
10043:         } elsif(!$alternateRoot) {
10044:             my (%allusers,%listerror);
10045: 	    my %servers = &get_servers($udom,'library');
10046:  	    foreach my $tryserver (keys(%servers)) {
10047:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
10048:                                   &escape($udom),$tryserver);
10049:                 if ($listing eq 'unknown_cmd') {
10050: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
10051: 				      $udom, $tryserver);
10052:                 } else {
10053:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
10054:                 }
10055: 		if ($listing eq 'unknown_cmd') {
10056: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
10057: 				      $udom, $tryserver);
10058: 		    @listing_results = split(/:/,$listing);
10059: 		} else {
10060: 		    @listing_results =
10061: 			map { &unescape($_); } split(/:/,$listing);
10062: 		}
10063:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
10064:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
10065:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
10066:                     $listerror{$tryserver} = $listing;
10067:                 } else {
10068: 		    foreach my $line (@listing_results) {
10069: 			my ($entry) = split(/&/,$line,2);
10070: 			$allusers{$entry} = 1;
10071: 		    }
10072: 		}
10073:             }
10074:             my @alluserslist=();
10075:             foreach my $user (sort(keys(%allusers))) {
10076:                 push(@alluserslist,$user.'&user');
10077:             }
10078:             return (\@alluserslist);
10079:         } else {
10080:             return ([],'missing username');
10081:         }
10082:     } elsif(!defined($getpropath)) {
10083:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
10084:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
10085:         return (\@all_domains);
10086:     } else {
10087:         return ([],'missing domain');
10088:     }
10089: }
10090: 
10091: # --------------------------------------------- GetFileTimestamp
10092: # This function utilizes dirlist and returns the date stamp for
10093: # when it was last modified.  It will also return an error of -1
10094: # if an error occurs
10095: 
10096: sub GetFileTimestamp {
10097:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
10098:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
10099:     $studentName   = &LONCAPA::clean_username($studentName);
10100:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
10101:                                     undef,$getuserdir);
10102:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
10103:         return -1;
10104:     }
10105:     if (ref($fileref) eq 'ARRAY') {
10106:         my @stats = split('&',$fileref->[0]);
10107:         # @stats contains first the filename, then the stat output
10108:         return $stats[10]; # so this is 10 instead of 9.
10109:     } else {
10110:         return -1;
10111:     }
10112: }
10113: 
10114: sub stat_file {
10115:     my ($uri) = @_;
10116:     $uri = &clutter_with_no_wrapper($uri);
10117: 
10118:     my ($udom,$uname,$file);
10119:     if ($uri =~ m-^/(uploaded|editupload)/-) {
10120: 	($udom,$uname,$file) =
10121: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
10122: 	$file = 'userfiles/'.$file;
10123:     }
10124:     if ($uri =~ m-^/res/-) {
10125: 	($udom,$uname) = 
10126: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
10127: 	$file = $uri;
10128:     }
10129: 
10130:     if (!$udom || !$uname || !$file) {
10131: 	# unable to handle the uri
10132: 	return ();
10133:     }
10134:     my $getpropath;
10135:     if ($file =~ /^userfiles\//) {
10136:         $getpropath = 1;
10137:     }
10138:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
10139:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
10140:         return ();
10141:     } else {
10142:         if (ref($listref) eq 'ARRAY') {
10143:             my @stats = split('&',$listref->[0]);
10144: 	    shift(@stats); #filename is first
10145: 	    return @stats;
10146:         }
10147:     }
10148:     return ();
10149: }
10150: 
10151: # -------------------------------------------------------- Value of a Condition
10152: 
10153: # gets the value of a specific preevaluated condition
10154: #    stored in the string  $env{user.state.<cid>}
10155: # or looks up a condition reference in the bighash and if if hasn't
10156: # already been evaluated recurses into docondval to get the value of
10157: # the condition, then memoizing it to 
10158: #   $env{user.state.<cid>.<condition>}
10159: sub directcondval {
10160:     my $number=shift;
10161:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
10162: 	&Apache::lonuserstate::evalstate();
10163:     }
10164:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
10165: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
10166:     } elsif ($number =~ /^_/) {
10167: 	my $sub_condition;
10168: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10169: 		&GDBM_READER(),0640)) {
10170: 	    $sub_condition=$bighash{'conditions'.$number};
10171: 	    untie(%bighash);
10172: 	}
10173: 	my $value = &docondval($sub_condition);
10174: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
10175: 	return $value;
10176:     }
10177:     if ($env{'user.state.'.$env{'request.course.id'}}) {
10178:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
10179:     } else {
10180:        return 2;
10181:     }
10182: }
10183: 
10184: # get the collection of conditions for this resource
10185: sub condval {
10186:     my $condidx=shift;
10187:     my $allpathcond='';
10188:     foreach my $cond (split(/\|/,$condidx)) {
10189: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
10190: 	    $allpathcond.=
10191: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
10192: 	}
10193:     }
10194:     $allpathcond=~s/\|$//;
10195:     return &docondval($allpathcond);
10196: }
10197: 
10198: #evaluates an expression of conditions
10199: sub docondval {
10200:     my ($allpathcond) = @_;
10201:     my $result=0;
10202:     if ($env{'request.course.id'}
10203: 	&& defined($allpathcond)) {
10204: 	my $operand='|';
10205: 	my @stack;
10206: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
10207: 	    if ($chunk eq '(') {
10208: 		push @stack,($operand,$result);
10209: 	    } elsif ($chunk eq ')') {
10210: 		my $before=pop @stack;
10211: 		if (pop @stack eq '&') {
10212: 		    $result=$result>$before?$before:$result;
10213: 		} else {
10214: 		    $result=$result>$before?$result:$before;
10215: 		}
10216: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
10217: 		$operand=$chunk;
10218: 	    } else {
10219: 		my $new=directcondval($chunk);
10220: 		if ($operand eq '&') {
10221: 		    $result=$result>$new?$new:$result;
10222: 		} else {
10223: 		    $result=$result>$new?$result:$new;
10224: 		}
10225: 	    }
10226: 	}
10227:     }
10228:     return $result;
10229: }
10230: 
10231: # ---------------------------------------------------- Devalidate courseresdata
10232: 
10233: sub devalidatecourseresdata {
10234:     my ($coursenum,$coursedomain)=@_;
10235:     my $hashid=$coursenum.':'.$coursedomain;
10236:     &devalidate_cache_new('courseres',$hashid);
10237: }
10238: 
10239: 
10240: # --------------------------------------------------- Course Resourcedata Query
10241: #
10242: #  Parameters:
10243: #      $coursenum    - Number of the course.
10244: #      $coursedomain - Domain at which the course was created.
10245: #  Returns:
10246: #     A hash of the course parameters along (I think) with timestamps
10247: #     and version info.
10248: 
10249: sub get_courseresdata {
10250:     my ($coursenum,$coursedomain)=@_;
10251:     my $coursehom=&homeserver($coursenum,$coursedomain);
10252:     my $hashid=$coursenum.':'.$coursedomain;
10253:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
10254:     my %dumpreply;
10255:     unless (defined($cached)) {
10256: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
10257: 	$result=\%dumpreply;
10258: 	my ($tmp) = keys(%dumpreply);
10259: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
10260: 	    &do_cache_new('courseres',$hashid,$result,600);
10261: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
10262: 	    return $tmp;
10263: 	} elsif ($tmp =~ /^(error)/) {
10264: 	    $result=undef;
10265: 	    &do_cache_new('courseres',$hashid,$result,600);
10266: 	}
10267:     }
10268:     return $result;
10269: }
10270: 
10271: sub devalidateuserresdata {
10272:     my ($uname,$udom)=@_;
10273:     my $hashid="$udom:$uname";
10274:     &devalidate_cache_new('userres',$hashid);
10275: }
10276: 
10277: sub get_userresdata {
10278:     my ($uname,$udom)=@_;
10279:     #most student don\'t have any data set, check if there is some data
10280:     if (&EXT_cache_status($udom,$uname)) { return undef; }
10281: 
10282:     my $hashid="$udom:$uname";
10283:     my ($result,$cached)=&is_cached_new('userres',$hashid);
10284:     if (!defined($cached)) {
10285: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
10286: 	$result=\%resourcedata;
10287: 	&do_cache_new('userres',$hashid,$result,600);
10288:     }
10289:     my ($tmp)=keys(%$result);
10290:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
10291: 	return $result;
10292:     }
10293:     #error 2 occurs when the .db doesn't exist
10294:     if ($tmp!~/error: 2 /) {
10295:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
10296: 	    &logthis("<font color=\"blue\">WARNING:".
10297: 		     " Trying to get resource data for ".
10298: 		     $uname." at ".$udom.": ".
10299: 		     $tmp."</font>");
10300:         }
10301:     } elsif ($tmp=~/error: 2 /) {
10302: 	#&EXT_cache_set($udom,$uname);
10303: 	&do_cache_new('userres',$hashid,undef,600);
10304: 	undef($tmp); # not really an error so don't send it back
10305:     }
10306:     return $tmp;
10307: }
10308: #----------------------------------------------- resdata - return resource data
10309: #  Purpose:
10310: #    Return resource data for either users or for a course.
10311: #  Parameters:
10312: #     $name      - Course/user name.
10313: #     $domain    - Name of the domain the user/course is registered on.
10314: #     $type      - Type of thing $name is (must be 'course' or 'user'
10315: #     $mapp      - decluttered URL of enclosing map  
10316: #     $recursed  - Ref to scalar -- set to 1, if nested maps have been recursed.
10317: #     $recurseup - Ref to array of map URLs, starting with map containing
10318: #                  $mapp up through hierarchy of nested maps to top level map.  
10319: #     $courseid  - CourseID (first part of param identifier).
10320: #     $modifier  - Middle part of param identifier.
10321: #     $what      - Last part of param identifier.
10322: #     @which     - Array of names of resources desired.
10323: #  Returns:
10324: #     The value of the first reasource in @which that is found in the
10325: #     resource hash.
10326: #  Exceptional Conditions:
10327: #     If the $type passed in is not valid (not the string 'course' or 
10328: #     'user', an undefined  reference is returned.
10329: #     If none of the resources are found, an undef is returned
10330: sub resdata {
10331:     my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
10332:         $modifier,$what,@which)=@_;
10333:     my $result;
10334:     if ($type eq 'course') {
10335: 	$result=&get_courseresdata($name,$domain);
10336:     } elsif ($type eq 'user') {
10337: 	$result=&get_userresdata($name,$domain);
10338:     }
10339:     if (!ref($result)) { return $result; }    
10340:     foreach my $item (@which) {
10341:         if ($item->[1] eq 'course') {
10342:             if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
10343:                 unless ($$recursed) {
10344:                     @{$recurseup} = &get_map_hierarchy($mapp);
10345:                     $$recursed = 1;
10346:                 }
10347:                 foreach my $item (@${recurseup}) {
10348:                     my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
10349:                     last if (defined($result->{$norecursechk}));
10350:                     my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
10351:                     if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
10352:                 }
10353:             }
10354:         }
10355:         if (defined($result->{$item->[0]})) {
10356: 	    return [$result->{$item->[0]},$item->[1]];
10357: 	}
10358:     }
10359:     return undef;
10360: }
10361: 
10362: sub get_domain_ltitools {
10363:     my ($cdom) = @_;
10364:     my %ltitools;
10365:     my ($result,$cached)=&is_cached_new('ltitools',$cdom);
10366:     if (defined($cached)) {
10367:         if (ref($result) eq 'HASH') {
10368:             %ltitools = %{$result};
10369:         }
10370:     } else {
10371:         my %domconfig = &get_dom('configuration',['ltitools'],$cdom);
10372:         if (ref($domconfig{'ltitools'}) eq 'HASH') {
10373:             %ltitools = %{$domconfig{'ltitools'}};
10374:         }
10375:         my $cachetime = 24*60*60;
10376:         &do_cache_new('ltitools',$cdom,\%ltitools,$cachetime);
10377:     }
10378:     return %ltitools;
10379: }
10380: 
10381: sub get_numsuppfiles {
10382:     my ($cnum,$cdom,$ignorecache)=@_;
10383:     my $hashid=$cnum.':'.$cdom;
10384:     my ($suppcount,$cached);
10385:     unless ($ignorecache) {
10386:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
10387:     }
10388:     unless (defined($cached)) {
10389:         my $chome=&homeserver($cnum,$cdom);
10390:         unless ($chome eq 'no_host') {
10391:             ($suppcount,my $errors) = (0,0);
10392:             my $suppmap = 'supplemental.sequence';
10393:             ($suppcount,$errors) = 
10394:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
10395:         }
10396:         &do_cache_new('suppcount',$hashid,$suppcount,600);
10397:     }
10398:     return $suppcount;
10399: }
10400: 
10401: #
10402: # EXT resource caching routines
10403: #
10404: 
10405: sub clear_EXT_cache_status {
10406:     &delenv('cache.EXT.');
10407: }
10408: 
10409: sub EXT_cache_status {
10410:     my ($target_domain,$target_user) = @_;
10411:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
10412:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
10413:         # We know already the user has no data
10414:         return 1;
10415:     } else {
10416:         return 0;
10417:     }
10418: }
10419: 
10420: sub EXT_cache_set {
10421:     my ($target_domain,$target_user) = @_;
10422:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
10423:     #&appenv({$cachename => time});
10424: }
10425: 
10426: # --------------------------------------------------------- Value of a Variable
10427: sub EXT {
10428: 
10429:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
10430:     unless ($varname) { return ''; }
10431:     #get real user name/domain, courseid and symb
10432:     my $courseid;
10433:     my $publicuser;
10434:     if ($symbparm) {
10435: 	$symbparm=&get_symb_from_alias($symbparm);
10436:     }
10437:     if (!($uname && $udom)) {
10438:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
10439:       if (!$symbparm) {	$symbparm=$cursymb; }
10440:     } else {
10441: 	$courseid=$env{'request.course.id'};
10442:     }
10443:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
10444:     my $rest;
10445:     if (defined($therest[0])) {
10446:        $rest=join('.',@therest);
10447:     } else {
10448:        $rest='';
10449:     }
10450: 
10451:     my $qualifierrest=$qualifier;
10452:     if ($rest) { $qualifierrest.='.'.$rest; }
10453:     my $spacequalifierrest=$space;
10454:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
10455:     if ($realm eq 'user') {
10456: # --------------------------------------------------------------- user.resource
10457: 	if ($space eq 'resource') {
10458: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
10459: 		  || defined($Apache::lonhomework::parsing_a_task))
10460: 		 &&
10461: 		 ($symbparm eq &symbread()) ) {	
10462: 		# if we are in the middle of processing the resource the
10463: 		# get the value we are planning on committing
10464:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
10465:                     return $Apache::lonhomework::results{$qualifierrest};
10466:                 } else {
10467:                     return $Apache::lonhomework::history{$qualifierrest};
10468:                 }
10469: 	    } else {
10470: 		my %restored;
10471: 		if ($publicuser || $env{'request.state'} eq 'construct') {
10472: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
10473: 		} else {
10474: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
10475: 		}
10476: 		return $restored{$qualifierrest};
10477: 	    }
10478: # ----------------------------------------------------------------- user.access
10479:         } elsif ($space eq 'access') {
10480: 	    # FIXME - not supporting calls for a specific user
10481:             return &allowed($qualifier,$rest);
10482: # ------------------------------------------ user.preferences, user.environment
10483:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
10484: 	    if (($uname eq $env{'user.name'}) &&
10485: 		($udom eq $env{'user.domain'})) {
10486: 		return $env{join('.',('environment',$qualifierrest))};
10487: 	    } else {
10488: 		my %returnhash;
10489: 		if (!$publicuser) {
10490: 		    %returnhash=&userenvironment($udom,$uname,
10491: 						 $qualifierrest);
10492: 		}
10493: 		return $returnhash{$qualifierrest};
10494: 	    }
10495: # ----------------------------------------------------------------- user.course
10496:         } elsif ($space eq 'course') {
10497: 	    # FIXME - not supporting calls for a specific user
10498:             return $env{join('.',('request.course',$qualifier))};
10499: # ------------------------------------------------------------------- user.role
10500:         } elsif ($space eq 'role') {
10501: 	    # FIXME - not supporting calls for a specific user
10502:             my ($role,$where)=split(/\./,$env{'request.role'});
10503:             if ($qualifier eq 'value') {
10504: 		return $role;
10505:             } elsif ($qualifier eq 'extent') {
10506:                 return $where;
10507:             }
10508: # ----------------------------------------------------------------- user.domain
10509:         } elsif ($space eq 'domain') {
10510:             return $udom;
10511: # ------------------------------------------------------------------- user.name
10512:         } elsif ($space eq 'name') {
10513:             return $uname;
10514: # ---------------------------------------------------- Any other user namespace
10515:         } else {
10516: 	    my %reply;
10517: 	    if (!$publicuser) {
10518: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
10519: 	    }
10520: 	    return $reply{$qualifierrest};
10521:         }
10522:     } elsif ($realm eq 'query') {
10523: # ---------------------------------------------- pull stuff out of query string
10524:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
10525: 						[$spacequalifierrest]);
10526: 	return $env{'form.'.$spacequalifierrest}; 
10527:    } elsif ($realm eq 'request') {
10528: # ------------------------------------------------------------- request.browser
10529:         if ($space eq 'browser') {
10530:             return $env{'browser.'.$qualifier};
10531: # ------------------------------------------------------------ request.filename
10532:         } else {
10533:             return $env{'request.'.$spacequalifierrest};
10534:         }
10535:     } elsif ($realm eq 'course') {
10536: # ---------------------------------------------------------- course.description
10537:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
10538:     } elsif ($realm eq 'resource') {
10539: 
10540: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
10541: 	    if (!$symbparm) { $symbparm=&symbread(); }
10542: 	}
10543: 
10544:         if ($qualifier eq '') {
10545: 	    if ($space eq 'title') {
10546: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
10547: 	        return &gettitle($symbparm);
10548: 	    }
10549: 	
10550: 	    if ($space eq 'map') {
10551: 	        my ($map) = &decode_symb($symbparm);
10552: 	        return &symbread($map);
10553: 	    }
10554:             if ($space eq 'maptitle') {
10555:                 my ($map) = &decode_symb($symbparm);
10556:                 return &gettitle($map);
10557:             }
10558: 	    if ($space eq 'filename') {
10559: 	        if ($symbparm) {
10560: 		    return &clutter((&decode_symb($symbparm))[2]);
10561: 	        }
10562: 	        return &hreflocation('',$env{'request.filename'});
10563: 	    }
10564: 
10565:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
10566:                 if ($space eq 'visibleparts') {
10567:                     my $navmap = Apache::lonnavmaps::navmap->new();
10568:                     my $item;
10569:                     if (ref($navmap)) {
10570:                         my $res = $navmap->getBySymb($symbparm);
10571:                         my $parts = $res->parts();
10572:                         if (ref($parts) eq 'ARRAY') {
10573:                             $item = join(',',@{$parts});
10574:                         }
10575:                         undef($navmap);
10576:                     }
10577:                     return $item;
10578:                 }
10579:             }
10580:         }
10581: 
10582: 	my ($section, $group, @groups, @recurseup, $recursed);
10583: 	my ($courselevelm,$courseleveli,$courselevel,$mapp);
10584:         if (($courseid eq '') && ($cid)) {
10585:             $courseid = $cid;
10586:         }
10587: 	if (($symbparm && $courseid) && 
10588: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
10589: 
10590: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
10591: 
10592: # ----------------------------------------------------- Cascading lookup scheme
10593: 	    my $symbp=$symbparm;
10594: 	    $mapp=&deversion((&decode_symb($symbp))[0]);
10595:             @recurseup=();
10596: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
10597:             my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
10598: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
10599: 	    if (($env{'user.name'} eq $uname) &&
10600: 		($env{'user.domain'} eq $udom)) {
10601: 		$section=$env{'request.course.sec'};
10602:                 @groups = split(/:/,$env{'request.course.groups'});  
10603:                 @groups=&sort_course_groups($courseid,@groups); 
10604: 	    } else {
10605: 		if (! defined($usection)) {
10606: 		    $section=&getsection($udom,$uname,$courseid);
10607: 		} else {
10608: 		    $section = $usection;
10609: 		}
10610:                 @groups = &get_users_groups($udom,$uname,$courseid);
10611: 	    }
10612: 
10613: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
10614: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
10615:             my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
10616: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
10617: 
10618: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
10619: 	    my $courselevelr=$courseid.'.'.$symbparm;
10620:             $courseleveli=$courseid.'.'.$recurseparm;
10621: 	    $courselevelm=$courseid.'.'.$mapparm;
10622: 
10623: # ----------------------------------------------------------- first, check user
10624: 
10625: 	    my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
10626:                                    \@recurseup,$courseid,'.',$spacequalifierrest, 
10627: 				       ([$courselevelr,'resource'],
10628: 					[$courselevelm,'map'     ],
10629:                                         [$courseleveli,'map'     ],
10630: 					[$courselevel, 'course'  ]));
10631: 	    if (defined($userreply)) { return &get_reply($userreply); }
10632: 
10633: # ------------------------------------------------ second, check some of course
10634:             my $coursereply;
10635:             if (@groups > 0) {
10636:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
10637:                                        $recurseparm,$mapparm,$spacequalifierrest,
10638:                                        $mapp,\$recursed,\@recurseup);
10639:                 if (defined($coursereply)) { return &get_reply($coursereply); } 
10640:             }
10641: 
10642: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
10643: 				  $env{'course.'.$courseid.'.domain'},
10644: 				  'course',$mapp,\$recursed,\@recurseup,
10645:                                   $courseid,'.['.$section.'].',$spacequalifierrest,
10646: 				  ([$seclevelr,   'resource'],
10647: 				   [$seclevelm,   'map'     ],
10648:                                    [$secleveli,   'map'     ],
10649: 				   [$seclevel,    'course'  ],
10650: 				   [$courselevelr,'resource']));
10651: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
10652: 
10653: # ------------------------------------------------------ third, check map parms
10654: 	    my %parmhash=();
10655: 	    my $thisparm='';
10656: 	    if (tie(%parmhash,'GDBM_File',
10657: 		    $env{'request.course.fn'}.'_parms.db',
10658: 		    &GDBM_READER(),0640)) {
10659: 		$thisparm=$parmhash{$symbparm};
10660: 		untie(%parmhash);
10661: 	    }
10662: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
10663: 	}
10664: # ------------------------------------------ fourth, look in resource metadata
10665:  
10666:         my $what = $spacequalifierrest;
10667: 	$what=~s/\./\_/;
10668: 	my $filename;
10669: 	if (!$symbparm) { $symbparm=&symbread(); }
10670: 	if ($symbparm) {
10671: 	    $filename=(&decode_symb($symbparm))[2];
10672: 	} else {
10673: 	    $filename=$env{'request.filename'};
10674: 	}
10675: 	my $metadata=&metadata($filename,$what);
10676: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
10677: 	$metadata=&metadata($filename,'parameter_'.$what);
10678: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
10679: 
10680: # ----------------------------------------------- fifth, look in rest of course
10681: 	if ($symbparm && defined($courseid) && 
10682: 	    $courseid eq $env{'request.course.id'}) {
10683: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
10684: 				     $env{'course.'.$courseid.'.domain'},
10685: 				     'course',$mapp,\$recursed,\@recurseup,
10686:                                      $courseid,'.',$spacequalifierrest,
10687: 				     ([$courselevelm,'map'   ],
10688:                                       [$courseleveli,'map'   ],
10689: 				      [$courselevel, 'course']));
10690: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
10691: 	}
10692: # ------------------------------------------------------------------ Cascade up
10693: 	unless ($space eq '0') {
10694: 	    my @parts=split(/_/,$space);
10695: 	    my $id=pop(@parts);
10696: 	    my $part=join('_',@parts);
10697: 	    if ($part eq '') { $part='0'; }
10698: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
10699: 				 $symbparm,$udom,$uname,$section,1);
10700: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
10701: 	}
10702: 	if ($recurse) { return undef; }
10703: 	my $pack_def=&packages_tab_default($filename,$varname);
10704: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
10705: # ---------------------------------------------------- Any other user namespace
10706:     } elsif ($realm eq 'environment') {
10707: # ----------------------------------------------------------------- environment
10708: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
10709: 	    return $env{'environment.'.$spacequalifierrest};
10710: 	} else {
10711: 	    if ($uname eq 'anonymous' && $udom eq '') {
10712: 		return '';
10713: 	    }
10714: 	    my %returnhash=&userenvironment($udom,$uname,
10715: 					    $spacequalifierrest);
10716: 	    return $returnhash{$spacequalifierrest};
10717: 	}
10718:     } elsif ($realm eq 'system') {
10719: # ----------------------------------------------------------------- system.time
10720: 	if ($space eq 'time') {
10721: 	    return time;
10722:         }
10723:     } elsif ($realm eq 'server') {
10724: # ----------------------------------------------------------------- system.time
10725: 	if ($space eq 'name') {
10726: 	    return $ENV{'SERVER_NAME'};
10727:         }
10728:     }
10729:     return '';
10730: }
10731: 
10732: sub get_reply {
10733:     my ($reply_value) = @_;
10734:     if (ref($reply_value) eq 'ARRAY') {
10735:         if (wantarray) {
10736: 	    return @$reply_value;
10737:         }
10738:         return $reply_value->[0];
10739:     } else {
10740:         return $reply_value;
10741:     }
10742: }
10743: 
10744: sub check_group_parms {
10745:     my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
10746:         $recursed,$recurseupref) = @_;
10747:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
10748:                   [$what,'course']);
10749:     my $coursereply;
10750:     foreach my $group (@{$groups}) {
10751:         my @groupitems = ();
10752:         foreach my $level (@levels) {
10753:              my $item = $courseid.'.['.$group.'].'.$level->[0];
10754:              push(@groupitems,[$item,$level->[1]]);
10755:         }
10756:         my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
10757:                                    $env{'course.'.$courseid.'.domain'},
10758:                                    'course',$mapp,$recursed,$recurseupref,
10759:                                    $courseid,'.['.$group.'].',$what,
10760:                                    @groupitems);
10761:         last if (defined($coursereply));
10762:     }
10763:     return $coursereply;
10764: }
10765: 
10766: sub get_map_hierarchy {
10767:     my ($mapname) = @_;
10768:     my @recurseup = (); 
10769:     if ($mapname) {
10770:         my $navmap = Apache::lonnavmaps::navmap->new();
10771:         if (ref($navmap)) {
10772:             @recurseup = $navmap->recurseup_maps($mapname);
10773:             undef($navmap);
10774:         }
10775:     }
10776:     return @recurseup;
10777: }
10778: 
10779: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
10780:     my ($courseid,@groups) = @_;
10781:     @groups = sort(@groups);
10782:     return @groups;
10783: }
10784: 
10785: sub packages_tab_default {
10786:     my ($uri,$varname)=@_;
10787:     my (undef,$part,$name)=split(/\./,$varname);
10788: 
10789:     my (@extension,@specifics,$do_default);
10790:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
10791: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
10792: 	if ($pack_type eq 'default') {
10793: 	    $do_default=1;
10794: 	} elsif ($pack_type eq 'extension') {
10795: 	    push(@extension,[$package,$pack_type,$pack_part]);
10796: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
10797: 	    # only look at packages defaults for packages that this id is
10798: 	    push(@specifics,[$package,$pack_type,$pack_part]);
10799: 	}
10800:     }
10801:     # first look for a package that matches the requested part id
10802:     foreach my $package (@specifics) {
10803: 	my (undef,$pack_type,$pack_part)=@{$package};
10804: 	next if ($pack_part ne $part);
10805: 	if (defined($packagetab{"$pack_type&$name&default"})) {
10806: 	    return $packagetab{"$pack_type&$name&default"};
10807: 	}
10808:     }
10809:     # look for any possible matching non extension_ package
10810:     foreach my $package (@specifics) {
10811: 	my (undef,$pack_type,$pack_part)=@{$package};
10812: 	if (defined($packagetab{"$pack_type&$name&default"})) {
10813: 	    return $packagetab{"$pack_type&$name&default"};
10814: 	}
10815: 	if ($pack_type eq 'part') { $pack_part='0'; }
10816: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
10817: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
10818: 	}
10819:     }
10820:     # look for any posible extension_ match
10821:     foreach my $package (@extension) {
10822: 	my ($package,$pack_type)=@{$package};
10823: 	if (defined($packagetab{"$pack_type&$name&default"})) {
10824: 	    return $packagetab{"$pack_type&$name&default"};
10825: 	}
10826: 	if (defined($packagetab{$package."&$name&default"})) {
10827: 	    return $packagetab{$package."&$name&default"};
10828: 	}
10829:     }
10830:     # look for a global default setting
10831:     if ($do_default && defined($packagetab{"default&$name&default"})) {
10832: 	return $packagetab{"default&$name&default"};
10833:     }
10834:     return undef;
10835: }
10836: 
10837: sub add_prefix_and_part {
10838:     my ($prefix,$part)=@_;
10839:     my $keyroot;
10840:     if (defined($prefix) && $prefix !~ /^__/) {
10841: 	# prefix that has a part already
10842: 	$keyroot=$prefix;
10843:     } elsif (defined($prefix)) {
10844: 	# prefix that is missing a part
10845: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
10846:     } else {
10847: 	# no prefix at all
10848: 	if (defined($part)) { $keyroot='_'.$part; }
10849:     }
10850:     return $keyroot;
10851: }
10852: 
10853: # ---------------------------------------------------------------- Get metadata
10854: 
10855: my %metaentry;
10856: my %importedpartids;
10857: sub metadata {
10858:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
10859:     $uri=&declutter($uri);
10860:     # if it is a non metadata possible uri return quickly
10861:     if (($uri eq '') || 
10862: 	(($uri =~ m|^/*adm/|) && 
10863: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|exttools?)$})) ||
10864:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
10865: 	return undef;
10866:     }
10867:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
10868: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
10869: 	return undef;
10870:     }
10871:     my $filename=$uri;
10872:     $uri=~s/\.meta$//;
10873: #
10874: # Is the metadata already cached?
10875: # Look at timestamp of caching
10876: # Everything is cached by the main uri, libraries are never directly cached
10877: #
10878:     if (!defined($liburi)) {
10879: 	my ($result,$cached)=&is_cached_new('meta',$uri);
10880: 	if (defined($cached)) { return $result->{':'.$what}; }
10881:     }
10882:     {
10883: # Imported parts would go here
10884:         my %importedids=();
10885:         my @origfileimportpartids=();
10886:         my $importedparts=0;
10887: #
10888: # Is this a recursive call for a library?
10889: #
10890: #	if (! exists($metacache{$uri})) {
10891: #	    $metacache{$uri}={};
10892: #	}
10893: 	my $cachetime = 60*60;
10894:         if ($liburi) {
10895: 	    $liburi=&declutter($liburi);
10896:             $filename=$liburi;
10897:         } else {
10898: 	    &devalidate_cache_new('meta',$uri);
10899: 	    undef(%metaentry);
10900: 	}
10901:         my %metathesekeys=();
10902:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
10903: 	my $metastring;
10904: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
10905: 	    my $which = &hreflocation('','/'.($liburi || $uri));
10906: 	    $metastring = 
10907: 		&Apache::lonnet::ssi_body($which,
10908: 					  ('grade_target' => 'meta'));
10909: 	    $cachetime = 1; # only want this cached in the child not long term
10910: 	} elsif (($uri !~ m -^(editupload)/-) && 
10911:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
10912: 	    my $file=&filelocation('',&clutter($filename));
10913: 	    #push(@{$metaentry{$uri.'.file'}},$file);
10914: 	    $metastring=&getfile($file);
10915: 	}
10916:         my $parser=HTML::LCParser->new(\$metastring);
10917:         my $token;
10918:         undef %metathesekeys;
10919:         while ($token=$parser->get_token) {
10920: 	    if ($token->[0] eq 'S') {
10921: 		if (defined($token->[2]->{'package'})) {
10922: #
10923: # This is a package - get package info
10924: #
10925: 		    my $package=$token->[2]->{'package'};
10926: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10927: 		    if (defined($token->[2]->{'id'})) { 
10928: 			$keyroot.='_'.$token->[2]->{'id'}; 
10929: 		    }
10930: 		    if ($metaentry{':packages'}) {
10931: 			$metaentry{':packages'}.=','.$package.$keyroot;
10932: 		    } else {
10933: 			$metaentry{':packages'}=$package.$keyroot;
10934: 		    }
10935: 		    foreach my $pack_entry (keys(%packagetab)) {
10936: 			my $part=$keyroot;
10937: 			$part=~s/^\_//;
10938: 			if ($pack_entry=~/^\Q$package\E\&/ || 
10939: 			    $pack_entry=~/^\Q$package\E_0\&/) {
10940: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
10941: 			    # ignore package.tab specified default values
10942:                             # here &package_tab_default() will fetch those
10943: 			    if ($subp eq 'default') { next; }
10944: 			    my $value=$packagetab{$pack_entry};
10945: 			    my $unikey;
10946: 			    if ($pack =~ /_0$/) {
10947: 				$unikey='parameter_0_'.$name;
10948: 				$part=0;
10949: 			    } else {
10950: 				$unikey='parameter'.$keyroot.'_'.$name;
10951: 			    }
10952: 			    if ($subp eq 'display') {
10953: 				$value.=' [Part: '.$part.']';
10954: 			    }
10955: 			    $metaentry{':'.$unikey.'.part'}=$part;
10956: 			    $metathesekeys{$unikey}=1;
10957: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10958: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
10959: 			    }
10960: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
10961: 				$metaentry{':'.$unikey}=
10962: 				    $metaentry{':'.$unikey.'.default'};
10963: 			    }
10964: 			}
10965: 		    }
10966: 		} else {
10967: #
10968: # This is not a package - some other kind of start tag
10969: #
10970: 		    my $entry=$token->[1];
10971: 		    my $unikey='';
10972: 
10973: 		    if ($entry eq 'import') {
10974: #
10975: # Importing a library here
10976: #
10977:                         my $location=$parser->get_text('/import');
10978:                         my $dir=$filename;
10979:                         $dir=~s|[^/]*$||;
10980:                         $location=&filelocation($dir,$location);
10981:                        
10982:                         my $importmode=$token->[2]->{'importmode'};
10983:                         if ($importmode eq 'problem') {
10984: # Import as problem/response
10985:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10986:                         } elsif ($importmode eq 'part') {
10987: # Import as part(s)
10988:                            $importedparts=1;
10989: # We need to get the original file and the imported file to get the part order correct
10990: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
10991: # Load and inspect original file
10992:                            if ($#origfileimportpartids<0) {
10993:                               undef(%importedpartids);
10994:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
10995:                               my $origfile=&getfile($origfilelocation);
10996:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10997:                            }
10998: 
10999: # Load and inspect imported file
11000:                            my $impfile=&getfile($location);
11001:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
11002:                            if ($#impfilepartids>=0) {
11003: # This problem had parts
11004:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
11005:                            } else {
11006: # Importing by turning a single problem into a problem part
11007: # It gets the import-tags ID as part-ID
11008:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
11009:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
11010:                            }
11011:                         } else {
11012: # Normal import
11013:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11014:                            if (defined($token->[2]->{'id'})) {
11015:                               $unikey.='_'.$token->[2]->{'id'};
11016:                            }
11017:                         }
11018: 
11019: 			if ($depthcount<20) {
11020: 			    my $metadata = 
11021: 				&metadata($uri,'keys', $location,$unikey,
11022: 					  $depthcount+1);
11023: 			    foreach my $meta (split(',',$metadata)) {
11024: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
11025: 				$metathesekeys{$meta}=1;
11026: 			    }
11027: 			
11028:                         }
11029: 		    } else {
11030: #
11031: # Not importing, some other kind of non-package, non-library start tag
11032: # 
11033:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
11034:                         if (defined($token->[2]->{'id'})) {
11035:                             $unikey.='_'.$token->[2]->{'id'};
11036:                         }
11037: 			if (defined($token->[2]->{'name'})) { 
11038: 			    $unikey.='_'.$token->[2]->{'name'}; 
11039: 			}
11040: 			$metathesekeys{$unikey}=1;
11041: 			foreach my $param (@{$token->[3]}) {
11042: 			    $metaentry{':'.$unikey.'.'.$param} =
11043: 				$token->[2]->{$param};
11044: 			}
11045: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
11046: 			my $default=$metaentry{':'.$unikey.'.default'};
11047: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
11048: 		 # only ws inside the tag, and not in default, so use default
11049: 		 # as value
11050: 			    $metaentry{':'.$unikey}=$default;
11051: 			} elsif ( $internaltext =~ /\S/ ) {
11052: 		  # something interesting inside the tag
11053: 			    $metaentry{':'.$unikey}=$internaltext;
11054: 			} else {
11055: 		  # no interesting values, don't set a default
11056: 			}
11057: # end of not-a-package not-a-library import
11058: 		    }
11059: # end of not-a-package start tag
11060: 		}
11061: # the next is the end of "start tag"
11062: 	    }
11063: 	}
11064: 	my ($extension) = ($uri =~ /\.(\w+)$/);
11065: 	$extension = lc($extension);
11066: 	if ($extension eq 'htm') { $extension='html'; }
11067: 
11068: 	foreach my $key (keys(%packagetab)) {
11069: 	    #no specific packages #how's our extension
11070: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
11071: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
11072: 					 \%metathesekeys);
11073: 	}
11074: 
11075: 	if (!exists($metaentry{':packages'})
11076: 	    || $packagetab{"import_defaults&extension_$extension"}) {
11077: 	    foreach my $key (keys(%packagetab)) {
11078: 		#no specific packages well let's get default then
11079: 		if ($key!~/^default&/) { next; }
11080: 		&metadata_create_package_def($uri,$key,'default',
11081: 					     \%metathesekeys);
11082: 	    }
11083: 	}
11084: # are there custom rights to evaluate
11085: 	if ($metaentry{':copyright'} eq 'custom') {
11086: 
11087:     #
11088:     # Importing a rights file here
11089:     #
11090: 	    unless ($depthcount) {
11091: 		my $location=$metaentry{':customdistributionfile'};
11092: 		my $dir=$filename;
11093: 		$dir=~s|[^/]*$||;
11094: 		$location=&filelocation($dir,$location);
11095: 		my $rights_metadata =
11096: 		    &metadata($uri,'keys',$location,'_rights',
11097: 			      $depthcount+1);
11098: 		foreach my $rights (split(',',$rights_metadata)) {
11099: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
11100: 		    $metathesekeys{$rights}=1;
11101: 		}
11102: 	    }
11103: 	}
11104: 	# uniqifiy package listing
11105: 	my %seen;
11106: 	my @uniq_packages =
11107: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
11108: 	$metaentry{':packages'} = join(',',@uniq_packages);
11109: 
11110:         if ($importedparts) {
11111: # We had imported parts and need to rebuild partorder
11112:            $metaentry{':partorder'}='';
11113:            $metathesekeys{'partorder'}=1;
11114:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
11115:                if ($origfileimportpartids[$index] eq 'part') {
11116: # original part, part of the problem
11117:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
11118:                } else {
11119: # we have imported parts at this position
11120:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
11121:                }
11122:            }
11123:            $metaentry{':partorder'}=~s/^\,//;
11124:         }
11125: 
11126: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
11127: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
11128: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
11129: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
11130: # this is the end of "was not already recently cached
11131:     }
11132:     return $metaentry{':'.$what};
11133: }
11134: 
11135: sub metadata_create_package_def {
11136:     my ($uri,$key,$package,$metathesekeys)=@_;
11137:     my ($pack,$name,$subp)=split(/\&/,$key);
11138:     if ($subp eq 'default') { next; }
11139:     
11140:     if (defined($metaentry{':packages'})) {
11141: 	$metaentry{':packages'}.=','.$package;
11142:     } else {
11143: 	$metaentry{':packages'}=$package;
11144:     }
11145:     my $value=$packagetab{$key};
11146:     my $unikey;
11147:     $unikey='parameter_0_'.$name;
11148:     $metaentry{':'.$unikey.'.part'}=0;
11149:     $$metathesekeys{$unikey}=1;
11150:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
11151: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
11152:     }
11153:     if (defined($metaentry{':'.$unikey.'.default'})) {
11154: 	$metaentry{':'.$unikey}=
11155: 	    $metaentry{':'.$unikey.'.default'};
11156:     }
11157: }
11158: 
11159: sub metadata_generate_part0 {
11160:     my ($metadata,$metacache,$uri) = @_;
11161:     my %allnames;
11162:     foreach my $metakey (keys(%$metadata)) {
11163: 	if ($metakey=~/^parameter\_(.*)/) {
11164: 	  my $part=$$metacache{':'.$metakey.'.part'};
11165: 	  my $name=$$metacache{':'.$metakey.'.name'};
11166: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
11167: 	    $allnames{$name}=$part;
11168: 	  }
11169: 	}
11170:     }
11171:     foreach my $name (keys(%allnames)) {
11172:       $$metadata{"parameter_0_$name"}=1;
11173:       my $key=":parameter_0_$name";
11174:       $$metacache{"$key.part"}='0';
11175:       $$metacache{"$key.name"}=$name;
11176:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
11177: 					   $allnames{$name}.'_'.$name.
11178: 					   '.type'};
11179:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
11180: 			     '.display'};
11181:       my $expr='[Part: '.$allnames{$name}.']';
11182:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
11183:       $$metacache{"$key.display"}=$olddis;
11184:     }
11185: }
11186: 
11187: # ------------------------------------------------------ Devalidate title cache
11188: 
11189: sub devalidate_title_cache {
11190:     my ($url)=@_;
11191:     if (!$env{'request.course.id'}) { return; }
11192:     my $symb=&symbread($url);
11193:     if (!$symb) { return; }
11194:     my $key=$env{'request.course.id'}."\0".$symb;
11195:     &devalidate_cache_new('title',$key);
11196: }
11197: 
11198: # ------------------------------------------------- Get the title of a course
11199: 
11200: sub current_course_title {
11201:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
11202: }
11203: # ------------------------------------------------- Get the title of a resource
11204: 
11205: sub gettitle {
11206:     my $urlsymb=shift;
11207:     my $symb=&symbread($urlsymb);
11208:     if ($symb) {
11209: 	my $key=$env{'request.course.id'}."\0".$symb;
11210: 	my ($result,$cached)=&is_cached_new('title',$key);
11211: 	if (defined($cached)) { 
11212: 	    return $result;
11213: 	}
11214: 	my ($map,$resid,$url)=&decode_symb($symb);
11215: 	my $title='';
11216: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
11217: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
11218: 	} else {
11219: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
11220: 		    &GDBM_READER(),0640)) {
11221: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
11222: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
11223: 		untie(%bighash);
11224: 	    }
11225: 	}
11226: 	$title=~s/\&colon\;/\:/gs;
11227: 	if ($title) {
11228: # Remember both $symb and $title for dynamic metadata
11229:             $accesshash{$symb.'___crstitle'}=$title;
11230:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
11231: # Cache this title and then return it
11232: 	    return &do_cache_new('title',$key,$title,600);
11233: 	}
11234: 	$urlsymb=$url;
11235:     }
11236:     my $title=&metadata($urlsymb,'title');
11237:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
11238:     return $title;
11239: }
11240: 
11241: sub get_slot {
11242:     my ($which,$cnum,$cdom)=@_;
11243:     if (!$cnum || !$cdom) {
11244: 	(undef,my $courseid)=&whichuser();
11245: 	$cdom=$env{'course.'.$courseid.'.domain'};
11246: 	$cnum=$env{'course.'.$courseid.'.num'};
11247:     }
11248:     my $key=join("\0",'slots',$cdom,$cnum,$which);
11249:     my %slotinfo;
11250:     if (exists($remembered{$key})) {
11251: 	$slotinfo{$which} = $remembered{$key};
11252:     } else {
11253: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
11254: 	&Apache::lonhomework::showhash(%slotinfo);
11255: 	my ($tmp)=keys(%slotinfo);
11256: 	if ($tmp=~/^error:/) { return (); }
11257: 	$remembered{$key} = $slotinfo{$which};
11258:     }
11259:     if (ref($slotinfo{$which}) eq 'HASH') {
11260: 	return %{$slotinfo{$which}};
11261:     }
11262:     return $slotinfo{$which};
11263: }
11264: 
11265: sub get_reservable_slots {
11266:     my ($cnum,$cdom,$uname,$udom) = @_;
11267:     my $now = time;
11268:     my $reservable_info;
11269:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
11270:     if (exists($remembered{$key})) {
11271:         $reservable_info = $remembered{$key};
11272:     } else {
11273:         my %resv;
11274:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
11275:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
11276:         $reservable_info = \%resv;
11277:         $remembered{$key} = $reservable_info;
11278:     }
11279:     return $reservable_info;
11280: }
11281: 
11282: sub get_course_slots {
11283:     my ($cnum,$cdom) = @_;
11284:     my $hashid=$cnum.':'.$cdom;
11285:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
11286:     if (defined($cached)) {
11287:         if (ref($result) eq 'HASH') {
11288:             return %{$result};
11289:         }
11290:     } else {
11291:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
11292:         my ($tmp) = keys(%slots);
11293:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
11294:             &do_cache_new('allslots',$hashid,\%slots,600);
11295:             return %slots;
11296:         }
11297:     }
11298:     return;
11299: }
11300: 
11301: sub devalidate_slots_cache {
11302:     my ($cnum,$cdom)=@_;
11303:     my $hashid=$cnum.':'.$cdom;
11304:     &devalidate_cache_new('allslots',$hashid);
11305: }
11306: 
11307: sub get_coursechange {
11308:     my ($cdom,$cnum) = @_;
11309:     if ($cdom eq '' || $cnum eq '') {
11310:         return unless ($env{'request.course.id'});
11311:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
11312:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
11313:     }
11314:     my $hashid=$cdom.'_'.$cnum;
11315:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
11316:     if ((defined($cached)) && ($change ne '')) {
11317:         return $change;
11318:     } else {
11319:         my %crshash;
11320:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
11321:         if ($crshash{'internal.contentchange'} eq '') {
11322:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
11323:             if ($change eq '') {
11324:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
11325:                 $change = $crshash{'internal.created'};
11326:             }
11327:         } else {
11328:             $change = $crshash{'internal.contentchange'};
11329:         }
11330:         my $cachetime = 600;
11331:         &do_cache_new('crschange',$hashid,$change,$cachetime);
11332:     }
11333:     return $change;
11334: }
11335: 
11336: sub devalidate_coursechange_cache {
11337:     my ($cnum,$cdom)=@_;
11338:     my $hashid=$cnum.':'.$cdom;
11339:     &devalidate_cache_new('crschange',$hashid);
11340: }
11341: 
11342: # ------------------------------------------------- Update symbolic store links
11343: 
11344: sub symblist {
11345:     my ($mapname,%newhash)=@_;
11346:     $mapname=&deversion(&declutter($mapname));
11347:     my %hash;
11348:     if (($env{'request.course.fn'}) && (%newhash)) {
11349:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
11350:                       &GDBM_WRCREAT(),0640)) {
11351: 	    foreach my $url (keys(%newhash)) {
11352: 		next if ($url eq 'last_known'
11353: 			 && $env{'form.no_update_last_known'});
11354: 		$hash{declutter($url)}=&encode_symb($mapname,
11355: 						    $newhash{$url}->[1],
11356: 						    $newhash{$url}->[0]);
11357:             }
11358:             if (untie(%hash)) {
11359: 		return 'ok';
11360:             }
11361:         }
11362:     }
11363:     return 'error';
11364: }
11365: 
11366: # --------------------------------------------------------------- Verify a symb
11367: 
11368: sub symbverify {
11369:     my ($symb,$thisurl,$encstate)=@_;
11370:     my $thisfn=$thisurl;
11371:     $thisfn=&declutter($thisfn);
11372: # direct jump to resource in page or to a sequence - will construct own symbs
11373:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
11374: # check URL part
11375:     my ($map,$resid,$url)=&decode_symb($symb);
11376: 
11377:     unless ($url eq $thisfn) { return 0; }
11378: 
11379:     $symb=&symbclean($symb);
11380:     $thisurl=&deversion($thisurl);
11381:     $thisfn=&deversion($thisfn);
11382: 
11383:     my %bighash;
11384:     my $okay=0;
11385: 
11386:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
11387:                             &GDBM_READER(),0640)) {
11388:         my $noclutter;
11389:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
11390:             $thisurl =~ s/\?.+$//;
11391:             if ($map =~ m{^uploaded/.+\.page$}) {
11392:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
11393:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
11394:                 $noclutter = 1;
11395:             }
11396:         }
11397:         my $ids;
11398:         if ($noclutter) {
11399:             $ids=$bighash{'ids_'.$thisurl};
11400:         } else {
11401:             $ids=$bighash{'ids_'.&clutter($thisurl)};
11402:         }
11403:         unless ($ids) {
11404:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
11405:             $ids=$bighash{$idkey};
11406:         }
11407:         if ($ids) {
11408: # ------------------------------------------------------------------- Has ID(s)
11409:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
11410:                 $symb =~ s/\?.+$//;
11411:             }
11412: 	    foreach my $id (split(/\,/,$ids)) {
11413: 	       my ($mapid,$resid)=split(/\./,$id);
11414:                if (
11415:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
11416:    eq $symb) {
11417:                    if (ref($encstate)) {
11418:                        $$encstate = $bighash{'encrypted_'.$id};
11419:                    }
11420: 		   if (($env{'request.role.adv'}) ||
11421: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
11422:                        ($thisurl eq '/adm/navmaps')) {
11423: 		       $okay=1;
11424:                        last;
11425: 		   }
11426: 	       }
11427: 	   }
11428:         }
11429: 	untie(%bighash);
11430:     }
11431:     return $okay;
11432: }
11433: 
11434: # --------------------------------------------------------------- Clean-up symb
11435: 
11436: sub symbclean {
11437:     my $symb=shift;
11438:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
11439: # remove version from map
11440:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
11441: 
11442: # remove version from URL
11443:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
11444: 
11445: # remove wrapper
11446: 
11447:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
11448:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
11449:     return $symb;
11450: }
11451: 
11452: # ---------------------------------------------- Split symb to find map and url
11453: 
11454: sub encode_symb {
11455:     my ($map,$resid,$url)=@_;
11456:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
11457: }
11458: 
11459: sub decode_symb {
11460:     my $symb=shift;
11461:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
11462:     my ($map,$resid,$url)=split(/___/,$symb);
11463:     return (&fixversion($map),$resid,&fixversion($url));
11464: }
11465: 
11466: sub fixversion {
11467:     my $fn=shift;
11468:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
11469:     my %bighash;
11470:     my $uri=&clutter($fn);
11471:     my $key=$env{'request.course.id'}.'_'.$uri;
11472: # is this cached?
11473:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
11474:     if (defined($cached)) { return $result; }
11475: # unfortunately not cached, or expired
11476:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
11477: 	    &GDBM_READER(),0640)) {
11478:  	if ($bighash{'version_'.$uri}) {
11479:  	    my $version=$bighash{'version_'.$uri};
11480:  	    unless (($version eq 'mostrecent') || 
11481: 		    ($version==&getversion($uri))) {
11482:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
11483:  	    }
11484:  	}
11485:  	untie %bighash;
11486:     }
11487:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
11488: }
11489: 
11490: sub deversion {
11491:     my $url=shift;
11492:     $url=~s/\.\d+\.(\w+)$/\.$1/;
11493:     return $url;
11494: }
11495: 
11496: # ------------------------------------------------------ Return symb list entry
11497: 
11498: sub symbread {
11499:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
11500:     my $cache_str='request.symbread.cached.'.$thisfn;
11501:     if (defined($env{$cache_str})) {
11502:         if ($ignorecachednull) {
11503:             return $env{$cache_str} unless ($env{$cache_str} eq '');
11504:         } else {
11505:             return $env{$cache_str};
11506:         }
11507:     }
11508: # no filename provided? try from environment
11509:     unless ($thisfn) {
11510:         if ($env{'request.symb'}) {
11511: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
11512: 	}
11513: 	$thisfn=$env{'request.filename'};
11514:     }
11515:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
11516: # is that filename actually a symb? Verify, clean, and return
11517:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
11518: 	if (&symbverify($thisfn,$1)) {
11519: 	    return $env{$cache_str}=&symbclean($thisfn);
11520: 	}
11521:     }
11522:     $thisfn=declutter($thisfn);
11523:     my %hash;
11524:     my %bighash;
11525:     my $syval='';
11526:     if (($env{'request.course.fn'}) && ($thisfn)) {
11527:         my $targetfn = $thisfn;
11528:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
11529:             $targetfn = 'adm/wrapper/'.$thisfn;
11530:         }
11531: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
11532: 	    $targetfn=$1;
11533: 	}
11534:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
11535:                       &GDBM_READER(),0640)) {
11536: 	    $syval=$hash{$targetfn};
11537:             untie(%hash);
11538:         }
11539: # ---------------------------------------------------------- There was an entry
11540:         if ($syval) {
11541: 	    #unless ($syval=~/\_\d+$/) {
11542: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
11543: 		    #&appenv({'request.ambiguous' => $thisfn});
11544: 		    #return $env{$cache_str}='';
11545: 		#}    
11546: 		#$syval.=$1;
11547: 	    #}
11548:         } else {
11549: # ------------------------------------------------------- Was not in symb table
11550:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
11551:                             &GDBM_READER(),0640)) {
11552: # ---------------------------------------------- Get ID(s) for current resource
11553:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
11554:               unless ($ids) { 
11555:                  $ids=$bighash{'ids_/'.$thisfn};
11556:               }
11557:               unless ($ids) {
11558: # alias?
11559: 		  $ids=$bighash{'mapalias_'.$thisfn};
11560:               }
11561:               if ($ids) {
11562: # ------------------------------------------------------------------- Has ID(s)
11563:                  my @possibilities=split(/\,/,$ids);
11564:                  if ($#possibilities==0) {
11565: # ----------------------------------------------- There is only one possibility
11566: 		     my ($mapid,$resid)=split(/\./,$ids);
11567: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
11568: 						    $resid,$thisfn);
11569:                      if (ref($possibles) eq 'HASH') {
11570:                          $possibles->{$syval} = 1;    
11571:                      }
11572:                      if ($checkforblock) {
11573:                          my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
11574:                          if (@blockers) {
11575:                              $syval = '';
11576:                              return;
11577:                          }
11578:                      }
11579:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) { 
11580: # ------------------------------------------ There is more than one possibility
11581:                      my $realpossible=0;
11582:                      foreach my $id (@possibilities) {
11583: 			 my $file=$bighash{'src_'.$id};
11584:                          my $canaccess;
11585:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
11586:                              $canaccess = 1;
11587:                          } else { 
11588:                              $canaccess = &allowed('bre',$file);
11589:                          }
11590:                          if ($canaccess) {
11591:          		     my ($mapid,$resid)=split(/\./,$id);
11592:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
11593:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
11594: 						             $resid,$thisfn);
11595:                                  if (ref($possibles) eq 'HASH') {
11596:                                      $possibles->{$syval} = 1;
11597:                                  }
11598:                                  if ($checkforblock) {
11599:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
11600:                                      unless (@blockers > 0) {
11601:                                          $syval = $poss_syval;
11602:                                          $realpossible++;
11603:                                      }
11604:                                  } else {
11605:                                      $syval = $poss_syval;
11606:                                      $realpossible++;
11607:                                  }
11608:                              }
11609: 			 }
11610:                      }
11611: 		     if ($realpossible!=1) { $syval=''; }
11612:                  } else {
11613:                      $syval='';
11614:                  }
11615: 	      }
11616:               untie(%bighash);
11617:            }
11618:         }
11619:         if ($syval) {
11620: 	    return $env{$cache_str}=$syval;
11621:         }
11622:     }
11623:     &appenv({'request.ambiguous' => $thisfn});
11624:     return $env{$cache_str}='';
11625: }
11626: 
11627: # ---------------------------------------------------------- Return random seed
11628: 
11629: sub numval {
11630:     my $txt=shift;
11631:     $txt=~tr/A-J/0-9/;
11632:     $txt=~tr/a-j/0-9/;
11633:     $txt=~tr/K-T/0-9/;
11634:     $txt=~tr/k-t/0-9/;
11635:     $txt=~tr/U-Z/0-5/;
11636:     $txt=~tr/u-z/0-5/;
11637:     $txt=~s/\D//g;
11638:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
11639:     return int($txt);
11640: }
11641: 
11642: sub numval2 {
11643:     my $txt=shift;
11644:     $txt=~tr/A-J/0-9/;
11645:     $txt=~tr/a-j/0-9/;
11646:     $txt=~tr/K-T/0-9/;
11647:     $txt=~tr/k-t/0-9/;
11648:     $txt=~tr/U-Z/0-5/;
11649:     $txt=~tr/u-z/0-5/;
11650:     $txt=~s/\D//g;
11651:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
11652:     my $total;
11653:     foreach my $val (@txts) { $total+=$val; }
11654:     if ($_64bit) { if ($total > 2**32) { return -1; } }
11655:     return int($total);
11656: }
11657: 
11658: sub numval3 {
11659:     use integer;
11660:     my $txt=shift;
11661:     $txt=~tr/A-J/0-9/;
11662:     $txt=~tr/a-j/0-9/;
11663:     $txt=~tr/K-T/0-9/;
11664:     $txt=~tr/k-t/0-9/;
11665:     $txt=~tr/U-Z/0-5/;
11666:     $txt=~tr/u-z/0-5/;
11667:     $txt=~s/\D//g;
11668:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
11669:     my $total;
11670:     foreach my $val (@txts) { $total+=$val; }
11671:     if ($_64bit) { $total=(($total<<32)>>32); }
11672:     return $total;
11673: }
11674: 
11675: sub digest {
11676:     my ($data)=@_;
11677:     my $digest=&Digest::MD5::md5($data);
11678:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
11679:     my ($e,$f);
11680:     {
11681:         use integer;
11682:         $e=($a+$b);
11683:         $f=($c+$d);
11684:         if ($_64bit) {
11685:             $e=(($e<<32)>>32);
11686:             $f=(($f<<32)>>32);
11687:         }
11688:     }
11689:     if (wantarray) {
11690: 	return ($e,$f);
11691:     } else {
11692: 	my $g;
11693: 	{
11694: 	    use integer;
11695: 	    $g=($e+$f);
11696: 	    if ($_64bit) {
11697: 		$g=(($g<<32)>>32);
11698: 	    }
11699: 	}
11700: 	return $g;
11701:     }
11702: }
11703: 
11704: sub latest_rnd_algorithm_id {
11705:     return '64bit5';
11706: }
11707: 
11708: sub get_rand_alg {
11709:     my ($courseid)=@_;
11710:     if (!$courseid) { $courseid=(&whichuser())[1]; }
11711:     if ($courseid) {
11712: 	return $env{"course.$courseid.rndseed"};
11713:     }
11714:     return &latest_rnd_algorithm_id();
11715: }
11716: 
11717: sub validCODE {
11718:     my ($CODE)=@_;
11719:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
11720:     return 0;
11721: }
11722: 
11723: sub getCODE {
11724:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
11725:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
11726: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
11727: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
11728: 	return $Apache::lonhomework::history{'resource.CODE'};
11729:     }
11730:     return undef;
11731: }
11732: #
11733: #  Determines the random seed for a specific context:
11734: #
11735: # parameters:
11736: #   symb      - in course context the symb for the seed.
11737: #   course_id - The course id of the form domain_coursenum.
11738: #   domain    - Domain for the user.
11739: #   course    - Course for the user.
11740: #   cenv      - environment of the course.
11741: #
11742: # NOTE:
11743: #   All parameters are picked out of the environment if missing
11744: #   or not defined.
11745: #   If a symb cannot be determined the current time is used instead.
11746: #
11747: #  For a given well defined symb, courside, domain, username,
11748: #  and course environment, the seed is reproducible.
11749: #
11750: sub rndseed {
11751:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
11752:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
11753:     if (!defined($symb)) {
11754: 	unless ($symb=$wsymb) { return time; }
11755:     }
11756:     if (!defined $courseid) { 
11757: 	$courseid=$wcourseid; 
11758:     }
11759:     if (!defined $domain) { $domain=$wdomain; }
11760:     if (!defined $username) { $username=$wusername }
11761: 
11762:     my $which;
11763:     if (defined($cenv->{'rndseed'})) {
11764: 	$which = $cenv->{'rndseed'};
11765:     } else {
11766: 	$which =&get_rand_alg($courseid);
11767:     }
11768:     if (defined(&getCODE())) {
11769: 
11770: 	if ($which eq '64bit5') {
11771: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
11772: 	} elsif ($which eq '64bit4') {
11773: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
11774: 	} else {
11775: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
11776: 	}
11777:     } elsif ($which eq '64bit5') {
11778: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
11779:     } elsif ($which eq '64bit4') {
11780: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
11781:     } elsif ($which eq '64bit3') {
11782: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
11783:     } elsif ($which eq '64bit2') {
11784: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
11785:     } elsif ($which eq '64bit') {
11786: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
11787:     }
11788:     return &rndseed_32bit($symb,$courseid,$domain,$username);
11789: }
11790: 
11791: sub rndseed_32bit {
11792:     my ($symb,$courseid,$domain,$username)=@_;
11793:     {
11794: 	use integer;
11795: 	my $symbchck=unpack("%32C*",$symb) << 27;
11796: 	my $symbseed=numval($symb) << 22;
11797: 	my $namechck=unpack("%32C*",$username) << 17;
11798: 	my $nameseed=numval($username) << 12;
11799: 	my $domainseed=unpack("%32C*",$domain) << 7;
11800: 	my $courseseed=unpack("%32C*",$courseid);
11801: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
11802: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11803: 	#&logthis("rndseed :$num:$symb");
11804: 	if ($_64bit) { $num=(($num<<32)>>32); }
11805: 	return $num;
11806:     }
11807: }
11808: 
11809: sub rndseed_64bit {
11810:     my ($symb,$courseid,$domain,$username)=@_;
11811:     {
11812: 	use integer;
11813: 	my $symbchck=unpack("%32S*",$symb) << 21;
11814: 	my $symbseed=numval($symb) << 10;
11815: 	my $namechck=unpack("%32S*",$username);
11816: 	
11817: 	my $nameseed=numval($username) << 21;
11818: 	my $domainseed=unpack("%32S*",$domain) << 10;
11819: 	my $courseseed=unpack("%32S*",$courseid);
11820: 	
11821: 	my $num1=$symbchck+$symbseed+$namechck;
11822: 	my $num2=$nameseed+$domainseed+$courseseed;
11823: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11824: 	#&logthis("rndseed :$num:$symb");
11825: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11826: 	return "$num1,$num2";
11827:     }
11828: }
11829: 
11830: sub rndseed_64bit2 {
11831:     my ($symb,$courseid,$domain,$username)=@_;
11832:     {
11833: 	use integer;
11834: 	# strings need to be an even # of cahracters long, it it is odd the
11835:         # last characters gets thrown away
11836: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
11837: 	my $symbseed=numval($symb) << 10;
11838: 	my $namechck=unpack("%32S*",$username.' ');
11839: 	
11840: 	my $nameseed=numval($username) << 21;
11841: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
11842: 	my $courseseed=unpack("%32S*",$courseid.' ');
11843: 	
11844: 	my $num1=$symbchck+$symbseed+$namechck;
11845: 	my $num2=$nameseed+$domainseed+$courseseed;
11846: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11847: 	#&logthis("rndseed :$num:$symb");
11848: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11849: 	return "$num1,$num2";
11850:     }
11851: }
11852: 
11853: sub rndseed_64bit3 {
11854:     my ($symb,$courseid,$domain,$username)=@_;
11855:     {
11856: 	use integer;
11857: 	# strings need to be an even # of cahracters long, it it is odd the
11858:         # last characters gets thrown away
11859: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
11860: 	my $symbseed=numval2($symb) << 10;
11861: 	my $namechck=unpack("%32S*",$username.' ');
11862: 	
11863: 	my $nameseed=numval2($username) << 21;
11864: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
11865: 	my $courseseed=unpack("%32S*",$courseid.' ');
11866: 	
11867: 	my $num1=$symbchck+$symbseed+$namechck;
11868: 	my $num2=$nameseed+$domainseed+$courseseed;
11869: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11870: 	#&logthis("rndseed :$num1:$num2:$_64bit");
11871: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11872: 	
11873: 	return "$num1:$num2";
11874:     }
11875: }
11876: 
11877: sub rndseed_64bit4 {
11878:     my ($symb,$courseid,$domain,$username)=@_;
11879:     {
11880: 	use integer;
11881: 	# strings need to be an even # of cahracters long, it it is odd the
11882:         # last characters gets thrown away
11883: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
11884: 	my $symbseed=numval3($symb) << 10;
11885: 	my $namechck=unpack("%32S*",$username.' ');
11886: 	
11887: 	my $nameseed=numval3($username) << 21;
11888: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
11889: 	my $courseseed=unpack("%32S*",$courseid.' ');
11890: 	
11891: 	my $num1=$symbchck+$symbseed+$namechck;
11892: 	my $num2=$nameseed+$domainseed+$courseseed;
11893: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11894: 	#&logthis("rndseed :$num1:$num2:$_64bit");
11895: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11896: 	
11897: 	return "$num1:$num2";
11898:     }
11899: }
11900: 
11901: sub rndseed_64bit5 {
11902:     my ($symb,$courseid,$domain,$username)=@_;
11903:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
11904:     return "$num1:$num2";
11905: }
11906: 
11907: sub rndseed_CODE_64bit {
11908:     my ($symb,$courseid,$domain,$username)=@_;
11909:     {
11910: 	use integer;
11911: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
11912: 	my $symbseed=numval2($symb);
11913: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11914: 	my $CODEseed=numval(&getCODE());
11915: 	my $courseseed=unpack("%32S*",$courseid.' ');
11916: 	my $num1=$symbseed+$CODEchck;
11917: 	my $num2=$CODEseed+$courseseed+$symbchck;
11918: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11919: 	#&logthis("rndseed :$num1:$num2:$symb");
11920: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
11921: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
11922: 	return "$num1:$num2";
11923:     }
11924: }
11925: 
11926: sub rndseed_CODE_64bit4 {
11927:     my ($symb,$courseid,$domain,$username)=@_;
11928:     {
11929: 	use integer;
11930: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
11931: 	my $symbseed=numval3($symb);
11932: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11933: 	my $CODEseed=numval3(&getCODE());
11934: 	my $courseseed=unpack("%32S*",$courseid.' ');
11935: 	my $num1=$symbseed+$CODEchck;
11936: 	my $num2=$CODEseed+$courseseed+$symbchck;
11937: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11938: 	#&logthis("rndseed :$num1:$num2:$symb");
11939: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
11940: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
11941: 	return "$num1:$num2";
11942:     }
11943: }
11944: 
11945: sub rndseed_CODE_64bit5 {
11946:     my ($symb,$courseid,$domain,$username)=@_;
11947:     my $code = &getCODE();
11948:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
11949:     return "$num1:$num2";
11950: }
11951: 
11952: sub setup_random_from_rndseed {
11953:     my ($rndseed)=@_;
11954:     if ($rndseed =~/([,:])/) {
11955:         my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
11956:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
11957:             &Math::Random::random_set_seed_from_phrase($rndseed);
11958:         } else {
11959:             &Math::Random::random_set_seed($num1,$num2);
11960:         }
11961:     } else {
11962: 	&Math::Random::random_set_seed_from_phrase($rndseed);
11963:     }
11964: }
11965: 
11966: sub latest_receipt_algorithm_id {
11967:     return 'receipt3';
11968: }
11969: 
11970: sub recunique {
11971:     my $fucourseid=shift;
11972:     my $unique;
11973:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
11974: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
11975: 	$unique=$env{"course.$fucourseid.internal.encseed"};
11976:     } else {
11977: 	$unique=$perlvar{'lonReceipt'};
11978:     }
11979:     return unpack("%32C*",$unique);
11980: }
11981: 
11982: sub recprefix {
11983:     my $fucourseid=shift;
11984:     my $prefix;
11985:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
11986: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
11987: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
11988:     } else {
11989: 	$prefix=$perlvar{'lonHostID'};
11990:     }
11991:     return unpack("%32C*",$prefix);
11992: }
11993: 
11994: sub ireceipt {
11995:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
11996: 
11997:     my $return =&recprefix($fucourseid).'-';
11998: 
11999:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
12000: 	$env{'request.state'} eq 'construct') {
12001: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
12002: 	return $return;
12003:     }
12004: 
12005:     my $cuname=unpack("%32C*",$funame);
12006:     my $cudom=unpack("%32C*",$fudom);
12007:     my $cucourseid=unpack("%32C*",$fucourseid);
12008:     my $cusymb=unpack("%32C*",$fusymb);
12009:     my $cunique=&recunique($fucourseid);
12010:     my $cpart=unpack("%32S*",$part);
12011:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
12012: 
12013: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
12014: 			       
12015: 	$return.= ($cunique%$cuname+
12016: 		   $cunique%$cudom+
12017: 		   $cusymb%$cuname+
12018: 		   $cusymb%$cudom+
12019: 		   $cucourseid%$cuname+
12020: 		   $cucourseid%$cudom+
12021: 		   $cpart%$cuname+
12022: 		   $cpart%$cudom);
12023:     } else {
12024: 	$return.= ($cunique%$cuname+
12025: 		   $cunique%$cudom+
12026: 		   $cusymb%$cuname+
12027: 		   $cusymb%$cudom+
12028: 		   $cucourseid%$cuname+
12029: 		   $cucourseid%$cudom);
12030:     }
12031:     return $return;
12032: }
12033: 
12034: sub receipt {
12035:     my ($part)=@_;
12036:     my ($symb,$courseid,$domain,$name) = &whichuser();
12037:     return &ireceipt($name,$domain,$courseid,$symb,$part);
12038: }
12039: 
12040: sub whichuser {
12041:     my ($passedsymb)=@_;
12042:     my ($symb,$courseid,$domain,$name,$publicuser);
12043:     if (defined($env{'form.grade_symb'})) {
12044: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
12045: 	my $allowed=&allowed('vgr',$tmp_courseid);
12046: 	if (!$allowed &&
12047: 	    exists($env{'request.course.sec'}) &&
12048: 	    $env{'request.course.sec'} !~ /^\s*$/) {
12049: 	    $allowed=&allowed('vgr',$tmp_courseid.
12050: 			      '/'.$env{'request.course.sec'});
12051: 	}
12052: 	if ($allowed) {
12053: 	    ($symb)=&get_env_multiple('form.grade_symb');
12054: 	    $courseid=$tmp_courseid;
12055: 	    ($domain)=&get_env_multiple('form.grade_domain');
12056: 	    ($name)=&get_env_multiple('form.grade_username');
12057: 	    return ($symb,$courseid,$domain,$name,$publicuser);
12058: 	}
12059:     }
12060:     if (!$passedsymb) {
12061: 	$symb=&symbread();
12062:     } else {
12063: 	$symb=$passedsymb;
12064:     }
12065:     $courseid=$env{'request.course.id'};
12066:     $domain=$env{'user.domain'};
12067:     $name=$env{'user.name'};
12068:     if ($name eq 'public' && $domain eq 'public') {
12069: 	if (!defined($env{'form.username'})) {
12070: 	    $env{'form.username'}.=time.rand(10000000);
12071: 	}
12072: 	$name.=$env{'form.username'};
12073:     }
12074:     return ($symb,$courseid,$domain,$name,$publicuser);
12075: 
12076: }
12077: 
12078: # ------------------------------------------------------------ Serves up a file
12079: # returns either the contents of the file or 
12080: # -1 if the file doesn't exist
12081: #
12082: # if the target is a file that was uploaded via DOCS, 
12083: # a check will be made to see if a current copy exists on the local server,
12084: # if it does this will be served, otherwise a copy will be retrieved from
12085: # the home server for the course and stored in /home/httpd/html/userfiles on
12086: # the local server.   
12087: 
12088: sub getfile {
12089:     my ($file) = @_;
12090:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
12091:     &repcopy($file);
12092:     return &readfile($file);
12093: }
12094: 
12095: sub repcopy_userfile {
12096:     my ($file)=@_;
12097:     my $londocroot = $perlvar{'lonDocRoot'};
12098:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
12099:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
12100:     my ($cdom,$cnum,$filename) = 
12101: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
12102:     my $uri="/uploaded/$cdom/$cnum/$filename";
12103:     if (-e "$file") {
12104: # we already have a local copy, check it out
12105: 	my @fileinfo = stat($file);
12106: 	my $rtncode;
12107: 	my $info;
12108: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
12109: 	if ($lwpresp ne 'ok') {
12110: # there is no such file anymore, even though we had a local copy
12111: 	    if ($rtncode eq '404') {
12112: 		unlink($file);
12113: 	    }
12114: 	    return -1;
12115: 	}
12116: 	if ($info < $fileinfo[9]) {
12117: # nice, the file we have is up-to-date, just say okay
12118: 	    return 'ok';
12119: 	} else {
12120: # the file is outdated, get rid of it
12121: 	    unlink($file);
12122: 	}
12123:     }
12124: # one way or the other, at this point, we don't have the file
12125: # construct the correct path for the file
12126:     my @parts = ($cdom,$cnum); 
12127:     if ($filename =~ m|^(.+)/[^/]+$|) {
12128: 	push @parts, split(/\//,$1);
12129:     }
12130:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
12131:     foreach my $part (@parts) {
12132: 	$path .= '/'.$part;
12133: 	if (!-e $path) {
12134: 	    mkdir($path,0770);
12135: 	}
12136:     }
12137: # now the path exists for sure
12138: # get a user agent
12139:     my $ua=new LWP::UserAgent;
12140:     my $transferfile=$file.'.in.transfer';
12141: # FIXME: this should flock
12142:     if (-e $transferfile) { return 'ok'; }
12143:     my $request;
12144:     $uri=~s/^\///;
12145:     my $homeserver = &homeserver($cnum,$cdom);
12146:     my $protocol = $protocol{$homeserver};
12147:     $protocol = 'http' if ($protocol ne 'https');
12148:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
12149:     my $response=$ua->request($request,$transferfile);
12150: # did it work?
12151:     if ($response->is_error()) {
12152: 	unlink($transferfile);
12153: 	&logthis("Userfile repcopy failed for $uri");
12154: 	return -1;
12155:     }
12156: # worked, rename the transfer file
12157:     rename($transferfile,$file);
12158:     return 'ok';
12159: }
12160: 
12161: sub tokenwrapper {
12162:     my $uri=shift;
12163:     $uri=~s|^https?\://([^/]+)||;
12164:     $uri=~s|^/||;
12165:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
12166:     my $token=$1;
12167:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
12168:     if ($udom && $uname && $file) {
12169: 	$file=~s|(\?\.*)*$||;
12170:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
12171:         my $homeserver = &homeserver($uname,$udom);
12172:         my $protocol = $protocol{$homeserver};
12173:         $protocol = 'http' if ($protocol ne 'https');
12174:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
12175:                (($uri=~/\?/)?'&':'?').'token='.$token.
12176:                                '&tokenissued='.$perlvar{'lonHostID'};
12177:     } else {
12178:         return '/adm/notfound.html';
12179:     }
12180: }
12181: 
12182: # call with reqtype HEAD: get last modification time
12183: # call with reqtype GET: get the file contents
12184: # Do not call this with reqtype GET for large files! It loads everything into memory
12185: #
12186: sub getuploaded {
12187:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
12188:     $uri=~s/^\///;
12189:     my $homeserver = &homeserver($cnum,$cdom);
12190:     my $protocol = $protocol{$homeserver};
12191:     $protocol = 'http' if ($protocol ne 'https');
12192:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
12193:     my $ua=new LWP::UserAgent;
12194:     my $request=new HTTP::Request($reqtype,$uri);
12195:     my $response=$ua->request($request);
12196:     $$rtncode = $response->code;
12197:     if (! $response->is_success()) {
12198: 	return 'failed';
12199:     }      
12200:     if ($reqtype eq 'HEAD') {
12201: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
12202:     } elsif ($reqtype eq 'GET') {
12203: 	$$info = $response->content;
12204:     }
12205:     return 'ok';
12206: }
12207: 
12208: sub readfile {
12209:     my $file = shift;
12210:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
12211:     my $fh;
12212:     open($fh,"<$file");
12213:     my $a='';
12214:     while (my $line = <$fh>) { $a .= $line; }
12215:     return $a;
12216: }
12217: 
12218: sub filelocation {
12219:     my ($dir,$file) = @_;
12220:     my $location;
12221:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
12222: 
12223:     if ($file =~ m-^/adm/-) {
12224: 	$file=~s-^/adm/wrapper/-/-;
12225: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
12226:     }
12227: 
12228:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
12229:         $location = $file;
12230:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
12231:         my ($udom,$uname,$filename)=
12232:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
12233:         my $home=&homeserver($uname,$udom);
12234:         my $is_me=0;
12235:         my @ids=&current_machine_ids();
12236:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
12237:         if ($is_me) {
12238:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
12239:         } else {
12240:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
12241:   	      $udom.'/'.$uname.'/'.$filename;
12242:         }
12243:     } elsif ($file =~ m-^/adm/-) {
12244: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
12245:     } else {
12246:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
12247:         $file=~s:^/(res|priv)/:/:;
12248:         my $space=$1;
12249:         if ( !( $file =~ m:^/:) ) {
12250:             $location = $dir. '/'.$file;
12251:         } else {
12252:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
12253:         }
12254:     }
12255:     $location=~s://+:/:g; # remove duplicate /
12256:     while ($location=~m{/\.\./}) {
12257: 	if ($location =~ m{/[^/]+/\.\./}) {
12258: 	    $location=~ s{/[^/]+/\.\./}{/}g;
12259: 	} else {
12260: 	    $location=~ s{/\.\./}{/}g;
12261: 	}
12262:     } #remove dir/..
12263:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
12264:     return $location;
12265: }
12266: 
12267: sub hreflocation {
12268:     my ($dir,$file)=@_;
12269:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
12270: 	$file=filelocation($dir,$file);
12271:     } elsif ($file=~m-^/adm/-) {
12272: 	$file=~s-^/adm/wrapper/-/-;
12273: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
12274:     }
12275:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
12276: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
12277:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
12278: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
12279: 	        {/uploaded/$1/$2/}x;
12280:     }
12281:     if ($file=~ m{^/userfiles/}) {
12282: 	$file =~ s{^/userfiles/}{/uploaded/};
12283:     }
12284:     return $file;
12285: }
12286: 
12287: 
12288: 
12289: 
12290: 
12291: sub current_machine_domains {
12292:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
12293: }
12294: 
12295: sub machine_domains {
12296:     my ($hostname) = @_;
12297:     my @domains;
12298:     my %hostname = &all_hostnames();
12299:     while( my($id, $name) = each(%hostname)) {
12300: #	&logthis("-$id-$name-$hostname-");
12301: 	if ($hostname eq $name) {
12302: 	    push(@domains,&host_domain($id));
12303: 	}
12304:     }
12305:     return @domains;
12306: }
12307: 
12308: sub current_machine_ids {
12309:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
12310: }
12311: 
12312: sub machine_ids {
12313:     my ($hostname) = @_;
12314:     $hostname ||= &hostname($perlvar{'lonHostID'});
12315:     my @ids;
12316:     my %name_to_host = &all_names();
12317:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
12318: 	return @{ $name_to_host{$hostname} };
12319:     }
12320:     return;
12321: }
12322: 
12323: sub additional_machine_domains {
12324:     my @domains;
12325:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
12326:     while( my $line = <$fh>) {
12327:         $line =~ s/\s//g;
12328:         push(@domains,$line);
12329:     }
12330:     return @domains;
12331: }
12332: 
12333: sub default_login_domain {
12334:     my $domain = $perlvar{'lonDefDomain'};
12335:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
12336:     foreach my $posdom (&current_machine_domains(),
12337:                         &additional_machine_domains()) {
12338:         if (lc($posdom) eq lc($testdomain)) {
12339:             $domain=$posdom;
12340:             last;
12341:         }
12342:     }
12343:     return $domain;
12344: }
12345: 
12346: # ------------------------------------------------------------- Declutters URLs
12347: 
12348: sub declutter {
12349:     my $thisfn=shift;
12350:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
12351:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
12352:         $thisfn=~s{^/home/httpd/html}{};
12353:     }
12354:     $thisfn=~s/^\///;
12355:     $thisfn=~s|^adm/wrapper/||;
12356:     $thisfn=~s|^adm/coursedocs/showdoc/||;
12357:     $thisfn=~s/^res\///;
12358:     $thisfn=~s/^priv\///;
12359:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
12360:         $thisfn=~s/\?.+$//;
12361:     }
12362:     return $thisfn;
12363: }
12364: 
12365: # ------------------------------------------------------------- Clutter up URLs
12366: 
12367: sub clutter {
12368:     my $thisfn='/'.&declutter(shift);
12369:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
12370: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
12371:        $thisfn='/res'.$thisfn; 
12372:     }
12373:     if ($thisfn !~m|^/adm|) {
12374: 	if ($thisfn =~ m|^/ext/|) {
12375: 	    $thisfn='/adm/wrapper'.$thisfn;
12376: 	} else {
12377: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
12378: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
12379: 	    if ($embstyle eq 'ssi'
12380: 		|| ($embstyle eq 'hdn')
12381: 		|| ($embstyle eq 'rat')
12382: 		|| ($embstyle eq 'prv')
12383: 		|| ($embstyle eq 'ign')) {
12384: 		#do nothing with these
12385: 	    } elsif (($embstyle eq 'img') 
12386: 		|| ($embstyle eq 'emb')
12387: 		|| ($embstyle eq 'wrp')) {
12388: 		$thisfn='/adm/wrapper'.$thisfn;
12389: 	    } elsif ($embstyle eq 'unk'
12390: 		     && $thisfn!~/\.(sequence|page)$/) {
12391: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
12392: 	    } else {
12393: #		&logthis("Got a blank emb style");
12394: 	    }
12395: 	}
12396:     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/exttools?$}) {
12397:         $thisfn='/adm/wrapper'.$thisfn;
12398:     }
12399:     return $thisfn;
12400: }
12401: 
12402: sub clutter_with_no_wrapper {
12403:     my $uri = &clutter(shift);
12404:     if ($uri =~ m-^/adm/-) {
12405: 	$uri =~ s-^/adm/wrapper/-/-;
12406: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
12407:     }
12408:     return $uri;
12409: }
12410: 
12411: sub freeze_escape {
12412:     my ($value)=@_;
12413:     if (ref($value)) {
12414: 	$value=&nfreeze($value);
12415: 	return '__FROZEN__'.&escape($value);
12416:     }
12417:     return &escape($value);
12418: }
12419: 
12420: 
12421: sub thaw_unescape {
12422:     my ($value)=@_;
12423:     if ($value =~ /^__FROZEN__/) {
12424: 	substr($value,0,10,undef);
12425: 	$value=&unescape($value);
12426: 	return &thaw($value);
12427:     }
12428:     return &unescape($value);
12429: }
12430: 
12431: sub correct_line_ends {
12432:     my ($result)=@_;
12433:     $$result =~s/\r\n/\n/mg;
12434:     $$result =~s/\r/\n/mg;
12435: }
12436: # ================================================================ Main Program
12437: 
12438: sub goodbye {
12439:    &logthis("Starting Shut down");
12440: #not converted to using infrastruture and probably shouldn't be
12441:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
12442: #converted
12443: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
12444:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
12445: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
12446: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
12447: #1.1 only
12448: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
12449: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
12450: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
12451: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
12452:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
12453:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
12454:    &logthis(sprintf("%-20s is %s",'hits',$hits));
12455:    &flushcourselogs();
12456:    &logthis("Shutting down");
12457: }
12458: 
12459: sub get_dns {
12460:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
12461:     if (!$ignore_cache) {
12462: 	my ($content,$cached)=
12463: 	    &Apache::lonnet::is_cached_new('dns',$url);
12464: 	if ($cached) {
12465: 	    &$func($content,$hashref);
12466: 	    return;
12467: 	}
12468:     }
12469: 
12470:     my %alldns;
12471:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
12472:     foreach my $dns (<$config>) {
12473: 	next if ($dns !~ /^\^(\S*)/x);
12474:         my $line = $1;
12475:         my ($host,$protocol) = split(/:/,$line);
12476:         if ($protocol ne 'https') {
12477:             $protocol = 'http';
12478:         }
12479: 	$alldns{$host} = $protocol;
12480:     }
12481:     while (%alldns) {
12482: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
12483: 	my $ua=new LWP::UserAgent;
12484:         $ua->timeout(30);
12485: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
12486: 	my $response=$ua->request($request);
12487:         delete($alldns{$dns});
12488: 	next if ($response->is_error());
12489: 	my @content = split("\n",$response->content);
12490: 	unless ($nocache) {
12491: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
12492: 	}
12493: 	&$func(\@content,$hashref);
12494: 	return;
12495:     }
12496:     close($config);
12497:     my $which = (split('/',$url))[3];
12498:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
12499:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
12500:     my @content = <$config>;
12501:     &$func(\@content,$hashref);
12502:     return;
12503: }
12504: 
12505: # ------------------------------------------------------Get DNS checksums file
12506: sub parse_dns_checksums_tab {
12507:     my ($lines,$hashref) = @_;
12508:     my $lonhost = $perlvar{'lonHostID'};
12509:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
12510:     my $loncaparev = &get_server_loncaparev($machine_dom);
12511:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
12512:     my $webconfdir = '/etc/httpd/conf';
12513:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
12514:         $webconfdir = '/etc/apache2';
12515:     } elsif ($distro =~ /^sles(\d+)$/) {
12516:         if ($1 >= 10) {
12517:             $webconfdir = '/etc/apache2';
12518:         }
12519:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
12520:         if ($1 >= 10.0) {
12521:             $webconfdir = '/etc/apache2';
12522:         }
12523:     }
12524:     my ($release,$timestamp) = split(/\-/,$loncaparev);
12525:     my (%chksum,%revnum);
12526:     if (ref($lines) eq 'ARRAY') {
12527:         chomp(@{$lines});
12528:         my $version = shift(@{$lines});
12529:         if ($version eq $release) {  
12530:             foreach my $line (@{$lines}) {
12531:                 my ($file,$version,$shasum) = split(/,/,$line);
12532:                 if ($file =~ m{^/etc/httpd/conf}) {
12533:                     if ($webconfdir eq '/etc/apache2') {
12534:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
12535:                     }
12536:                 }
12537:                 $chksum{$file} = $shasum;
12538:                 $revnum{$file} = $version;
12539:             }
12540:             if (ref($hashref) eq 'HASH') {
12541:                 %{$hashref} = (
12542:                                 sums     => \%chksum,
12543:                                 versions => \%revnum,
12544:                               );
12545:             }
12546:         }
12547:     }
12548:     return;
12549: }
12550: 
12551: sub fetch_dns_checksums {
12552:     my %checksums;
12553:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
12554:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
12555:     my ($release,$timestamp) = split(/\-/,$loncaparev);
12556:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
12557:              \%checksums);
12558:     return \%checksums;
12559: }
12560: 
12561: # ------------------------------------------------------------ Read domain file
12562: {
12563:     my $loaded;
12564:     my %domain;
12565: 
12566:     sub parse_domain_tab {
12567: 	my ($lines) = @_;
12568: 	foreach my $line (@$lines) {
12569: 	    next if ($line =~ /^(\#|\s*$ )/x);
12570: 
12571: 	    chomp($line);
12572: 	    my ($name,@elements) = split(/:/,$line,9);
12573: 	    my %this_domain;
12574: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
12575: 			       'lang_def', 'city', 'longi', 'lati',
12576: 			       'primary') {
12577: 		$this_domain{$field} = shift(@elements);
12578: 	    }
12579: 	    $domain{$name} = \%this_domain;
12580: 	}
12581:     }
12582: 
12583:     sub reset_domain_info {
12584: 	undef($loaded);
12585: 	undef(%domain);
12586:     }
12587: 
12588:     sub load_domain_tab {
12589: 	my ($ignore_cache,$nocache) = @_;
12590: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
12591: 	my $fh;
12592: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
12593: 	    my @lines = <$fh>;
12594: 	    &parse_domain_tab(\@lines);
12595: 	}
12596: 	close($fh);
12597: 	$loaded = 1;
12598:     }
12599: 
12600:     sub domain {
12601: 	&load_domain_tab() if (!$loaded);
12602: 
12603: 	my ($name,$what) = @_;
12604: 	return if ( !exists($domain{$name}) );
12605: 
12606: 	if (!$what) {
12607: 	    return $domain{$name}{'description'};
12608: 	}
12609: 	return $domain{$name}{$what};
12610:     }
12611: 
12612:     sub domain_info {
12613:         &load_domain_tab() if (!$loaded);
12614:         return %domain;
12615:     }
12616: 
12617: }
12618: 
12619: 
12620: # ------------------------------------------------------------- Read hosts file
12621: {
12622:     my %hostname;
12623:     my %hostdom;
12624:     my %libserv;
12625:     my $loaded;
12626:     my %name_to_host;
12627:     my %internetdom;
12628:     my %LC_dns_serv;
12629: 
12630:     sub parse_hosts_tab {
12631: 	my ($file) = @_;
12632: 	foreach my $configline (@$file) {
12633: 	    next if ($configline =~ /^(\#|\s*$ )/x);
12634:             chomp($configline);
12635: 	    if ($configline =~ /^\^/) {
12636:                 if ($configline =~ /^\^([\w.\-]+)/) {
12637:                     $LC_dns_serv{$1} = 1;
12638:                 }
12639:                 next;
12640:             }
12641: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
12642: 	    $name=~s/\s//g;
12643: 	    if ($id && $domain && $role && $name) {
12644: 		$hostname{$id}=$name;
12645: 		push(@{$name_to_host{$name}}, $id);
12646: 		$hostdom{$id}=$domain;
12647: 		if ($role eq 'library') { $libserv{$id}=$name; }
12648:                 if (defined($protocol)) {
12649:                     if ($protocol eq 'https') {
12650:                         $protocol{$id} = $protocol;
12651:                     } else {
12652:                         $protocol{$id} = 'http'; 
12653:                     }
12654:                 } else {
12655:                     $protocol{$id} = 'http';
12656:                 }
12657:                 if (defined($intdom)) {
12658:                     $internetdom{$id} = $intdom;
12659:                 }
12660: 	    }
12661: 	}
12662:     }
12663:     
12664:     sub reset_hosts_info {
12665: 	&purge_remembered();
12666: 	&reset_domain_info();
12667: 	&reset_hosts_ip_info();
12668: 	undef(%name_to_host);
12669: 	undef(%hostname);
12670: 	undef(%hostdom);
12671: 	undef(%libserv);
12672: 	undef($loaded);
12673:     }
12674: 
12675:     sub load_hosts_tab {
12676: 	my ($ignore_cache,$nocache) = @_;
12677: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
12678: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
12679: 	my @config = <$config>;
12680: 	&parse_hosts_tab(\@config);
12681: 	close($config);
12682: 	$loaded=1;
12683:     }
12684: 
12685:     sub hostname {
12686: 	&load_hosts_tab() if (!$loaded);
12687: 
12688: 	my ($lonid) = @_;
12689: 	return $hostname{$lonid};
12690:     }
12691: 
12692:     sub all_hostnames {
12693: 	&load_hosts_tab() if (!$loaded);
12694: 
12695: 	return %hostname;
12696:     }
12697: 
12698:     sub all_names {
12699:         my ($ignore_cache,$nocache) = @_;
12700: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
12701: 
12702: 	return %name_to_host;
12703:     }
12704: 
12705:     sub all_host_domain {
12706:         &load_hosts_tab() if (!$loaded);
12707:         return %hostdom;
12708:     }
12709: 
12710:     sub is_library {
12711: 	&load_hosts_tab() if (!$loaded);
12712: 
12713: 	return exists($libserv{$_[0]});
12714:     }
12715: 
12716:     sub all_library {
12717: 	&load_hosts_tab() if (!$loaded);
12718: 
12719: 	return %libserv;
12720:     }
12721: 
12722:     sub unique_library {
12723: 	#2x reverse removes all hostnames that appear more than once
12724:         my %unique = reverse &all_library();
12725:         return reverse %unique;
12726:     }
12727: 
12728:     sub get_servers {
12729: 	&load_hosts_tab() if (!$loaded);
12730: 
12731: 	my ($domain,$type) = @_;
12732: 	my %possible_hosts = ($type eq 'library') ? %libserv
12733: 	                                          : %hostname;
12734: 	my %result;
12735: 	if (ref($domain) eq 'ARRAY') {
12736: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
12737: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
12738: 		    $result{$host} = $hostname;
12739: 		}
12740: 	    }
12741: 	} else {
12742: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
12743: 		if ($hostdom{$host} eq $domain) {
12744: 		    $result{$host} = $hostname;
12745: 		}
12746: 	    }
12747: 	}
12748: 	return %result;
12749:     }
12750: 
12751:     sub get_unique_servers {
12752:         my %unique = reverse &get_servers(@_);
12753: 	return reverse %unique;
12754:     }
12755: 
12756:     sub host_domain {
12757: 	&load_hosts_tab() if (!$loaded);
12758: 
12759: 	my ($lonid) = @_;
12760: 	return $hostdom{$lonid};
12761:     }
12762: 
12763:     sub all_domains {
12764: 	&load_hosts_tab() if (!$loaded);
12765: 
12766: 	my %seen;
12767: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
12768: 	return @uniq;
12769:     }
12770: 
12771:     sub internet_dom {
12772:         &load_hosts_tab() if (!$loaded);
12773: 
12774:         my ($lonid) = @_;
12775:         return $internetdom{$lonid};
12776:     }
12777: 
12778:     sub is_LC_dns {
12779:         &load_hosts_tab() if (!$loaded);
12780: 
12781:         my ($hostname) = @_;
12782:         return exists($LC_dns_serv{$hostname});
12783:     }
12784: 
12785: }
12786: 
12787: { 
12788:     my %iphost;
12789:     my %name_to_ip;
12790:     my %lonid_to_ip;
12791: 
12792:     sub get_hosts_from_ip {
12793: 	my ($ip) = @_;
12794: 	my %iphosts = &get_iphost();
12795: 	if (ref($iphosts{$ip})) {
12796: 	    return @{$iphosts{$ip}};
12797: 	}
12798: 	return;
12799:     }
12800:     
12801:     sub reset_hosts_ip_info {
12802: 	undef(%iphost);
12803: 	undef(%name_to_ip);
12804: 	undef(%lonid_to_ip);
12805:     }
12806: 
12807:     sub get_host_ip {
12808: 	my ($lonid) = @_;
12809: 	if (exists($lonid_to_ip{$lonid})) {
12810: 	    return $lonid_to_ip{$lonid};
12811: 	}
12812: 	my $name=&hostname($lonid);
12813:    	my $ip = gethostbyname($name);
12814: 	return if (!$ip || length($ip) ne 4);
12815: 	$ip=inet_ntoa($ip);
12816: 	$name_to_ip{$name}   = $ip;
12817: 	$lonid_to_ip{$lonid} = $ip;
12818: 	return $ip;
12819:     }
12820:     
12821:     sub get_iphost {
12822: 	my ($ignore_cache,$nocache) = @_;
12823: 
12824: 	if (!$ignore_cache) {
12825: 	    if (%iphost) {
12826: 		return %iphost;
12827: 	    }
12828: 	    my ($ip_info,$cached)=
12829: 		&Apache::lonnet::is_cached_new('iphost','iphost');
12830: 	    if ($cached) {
12831: 		%iphost      = %{$ip_info->[0]};
12832: 		%name_to_ip  = %{$ip_info->[1]};
12833: 		%lonid_to_ip = %{$ip_info->[2]};
12834: 		return %iphost;
12835: 	    }
12836: 	}
12837: 
12838: 	# get yesterday's info for fallback
12839: 	my %old_name_to_ip;
12840: 	my ($ip_info,$cached)=
12841: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
12842: 	if ($cached) {
12843: 	    %old_name_to_ip = %{$ip_info->[1]};
12844: 	}
12845: 
12846: 	my %name_to_host = &all_names($ignore_cache,$nocache);
12847: 	foreach my $name (keys(%name_to_host)) {
12848: 	    my $ip;
12849: 	    if (!exists($name_to_ip{$name})) {
12850: 		$ip = gethostbyname($name);
12851: 		if (!$ip || length($ip) ne 4) {
12852: 		    if (defined($old_name_to_ip{$name})) {
12853: 			$ip = $old_name_to_ip{$name};
12854: 			&logthis("Can't find $name defaulting to old $ip");
12855: 		    } else {
12856: 			&logthis("Name $name no IP found");
12857: 			next;
12858: 		    }
12859: 		} else {
12860: 		    $ip=inet_ntoa($ip);
12861: 		}
12862: 		$name_to_ip{$name} = $ip;
12863: 	    } else {
12864: 		$ip = $name_to_ip{$name};
12865: 	    }
12866: 	    foreach my $id (@{ $name_to_host{$name} }) {
12867: 		$lonid_to_ip{$id} = $ip;
12868: 	    }
12869: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
12870: 	}
12871:         unless ($nocache) {
12872: 	    &do_cache_new('iphost','iphost',
12873: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
12874: 		          48*60*60);
12875:         }
12876: 
12877: 	return %iphost;
12878:     }
12879: 
12880:     #
12881:     #  Given a DNS returns the loncapa host name for that DNS 
12882:     # 
12883:     sub host_from_dns {
12884:         my ($dns) = @_;
12885:         my @hosts;
12886:         my $ip;
12887: 
12888:         if (exists($name_to_ip{$dns})) {
12889:             $ip = $name_to_ip{$dns};
12890:         }
12891:         if (!$ip) {
12892:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
12893:             if (length($ip) == 4) { 
12894: 	        $ip   = &IO::Socket::inet_ntoa($ip);
12895:             }
12896:         }
12897:         if ($ip) {
12898: 	    @hosts = get_hosts_from_ip($ip);
12899: 	    return $hosts[0];
12900:         }
12901:         return undef;
12902:     }
12903: 
12904:     sub get_internet_names {
12905:         my ($lonid) = @_;
12906:         return if ($lonid eq '');
12907:         my ($idnref,$cached)=
12908:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
12909:         if ($cached) {
12910:             return $idnref;
12911:         }
12912:         my $ip = &get_host_ip($lonid);
12913:         my @hosts = &get_hosts_from_ip($ip);
12914:         my %iphost = &get_iphost();
12915:         my (@idns,%seen);
12916:         foreach my $id (@hosts) {
12917:             my $dom = &host_domain($id);
12918:             my $prim_id = &domain($dom,'primary');
12919:             my $prim_ip = &get_host_ip($prim_id);
12920:             next if ($seen{$prim_ip});
12921:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
12922:                 foreach my $id (@{$iphost{$prim_ip}}) {
12923:                     my $intdom = &internet_dom($id);
12924:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
12925:                         push(@idns,$intdom);
12926:                     }
12927:                 }
12928:             }
12929:             $seen{$prim_ip} = 1;
12930:         }
12931:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
12932:     }
12933: 
12934: }
12935: 
12936: sub all_loncaparevs {
12937:     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 2.11);
12938: }
12939: 
12940: # ---------------------------------------------------------- Read loncaparev table
12941: {
12942:     sub load_loncaparevs { 
12943:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
12944:             if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
12945:                 while (my $configline=<$config>) {
12946:                     chomp($configline);
12947:                     my ($hostid,$loncaparev)=split(/:/,$configline);
12948:                     $loncaparevs{$hostid}=$loncaparev;
12949:                 }
12950:                 close($config);
12951:             }
12952:         }
12953:     }
12954: }
12955: 
12956: # ---------------------------------------------------------- Read serverhostID table
12957: {
12958:     sub load_serverhomeIDs {
12959:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
12960:             if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
12961:                 while (my $configline=<$config>) {
12962:                     chomp($configline);
12963:                     my ($name,$id)=split(/:/,$configline);
12964:                     $serverhomeIDs{$name}=$id;
12965:                 }
12966:                 close($config);
12967:             }
12968:         }
12969:     }
12970: }
12971: 
12972: 
12973: BEGIN {
12974: 
12975: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
12976:     unless ($readit) {
12977: {
12978:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
12979:     %perlvar = (%perlvar,%{$configvars});
12980: }
12981: 
12982: 
12983: # ------------------------------------------------------ Read spare server file
12984: {
12985:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
12986: 
12987:     while (my $configline=<$config>) {
12988:        chomp($configline);
12989:        if ($configline) {
12990: 	   my ($host,$type) = split(':',$configline,2);
12991: 	   if (!defined($type) || $type eq '') { $type = 'default' };
12992: 	   push(@{ $spareid{$type} }, $host);
12993:        }
12994:     }
12995:     close($config);
12996: }
12997: # ------------------------------------------------------------ Read permissions
12998: {
12999:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
13000: 
13001:     while (my $configline=<$config>) {
13002: 	chomp($configline);
13003: 	if ($configline) {
13004: 	    my ($role,$perm)=split(/ /,$configline);
13005: 	    if ($perm ne '') { $pr{$role}=$perm; }
13006: 	}
13007:     }
13008:     close($config);
13009: }
13010: 
13011: # -------------------------------------------- Read plain texts for permissions
13012: {
13013:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
13014: 
13015:     while (my $configline=<$config>) {
13016: 	chomp($configline);
13017: 	if ($configline) {
13018: 	    my ($short,@plain)=split(/:/,$configline);
13019:             %{$prp{$short}} = ();
13020: 	    if (@plain > 0) {
13021:                 $prp{$short}{'std'} = $plain[0];
13022:                 for (my $i=1; $i<@plain; $i++) {
13023:                     $prp{$short}{'alt'.$i} = $plain[$i];  
13024:                 }
13025:             }
13026: 	}
13027:     }
13028:     close($config);
13029: }
13030: 
13031: # ---------------------------------------------------------- Read package table
13032: {
13033:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
13034: 
13035:     while (my $configline=<$config>) {
13036: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
13037: 	chomp($configline);
13038: 	my ($short,$plain)=split(/:/,$configline);
13039: 	my ($pack,$name)=split(/\&/,$short);
13040: 	if ($plain ne '') {
13041: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
13042: 	    $packagetab{$short}=$plain; 
13043: 	}
13044:     }
13045:     close($config);
13046: }
13047: 
13048: # ---------------------------------------------------------- Read loncaparev table
13049: 
13050: &load_loncaparevs();
13051: 
13052: # ---------------------------------------------------------- Read serverhostID table
13053: 
13054: &load_serverhomeIDs();
13055: 
13056: # ---------------------------------------------------------- Read releaseslist XML
13057: {
13058:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
13059:     if (-e $file) {
13060:         my $parser = HTML::LCParser->new($file);
13061:         while (my $token = $parser->get_token()) {
13062:             if ($token->[0] eq 'S') {
13063:                 my $item = $token->[1];
13064:                 my $name = $token->[2]{'name'};
13065:                 my $value = $token->[2]{'value'};
13066:                 my $valuematch = $token->[2]{'valuematch'};
13067:                 if ($item ne '' && $name ne '' && ($value ne '' || $valuematch ne '')) {
13068:                     my $release = $parser->get_text();
13069:                     $release =~ s/(^\s*|\s*$ )//gx;
13070:                     $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch} = $release;
13071:                 }
13072:             }
13073:         }
13074:     }
13075: }
13076: 
13077: # ---------------------------------------------------------- Read managers table
13078: {
13079:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
13080:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
13081:             while (my $configline=<$config>) {
13082:                 chomp($configline);
13083:                 next if ($configline =~ /^\#/);
13084:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
13085:                     $managerstab{$configline} = 1;
13086:                 }
13087:             }
13088:             close($config);
13089:         }
13090:     }
13091: }
13092: 
13093: # ------------- set up temporary directory
13094: {
13095:     $tmpdir = LONCAPA::tempdir();
13096: 
13097: }
13098: 
13099: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
13100: 				'compress_threshold'=> 20_000,
13101:  			        });
13102: 
13103: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
13104: $dumpcount=0;
13105: $locknum=0;
13106: 
13107: &logtouch();
13108: &logthis('<font color="yellow">INFO: Read configuration</font>');
13109: $readit=1;
13110:     {
13111: 	use integer;
13112: 	my $test=(2**32)+1;
13113: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
13114: 	&logthis(" Detected 64bit platform ($_64bit)");
13115:     }
13116: }
13117: }
13118: 
13119: 1;
13120: __END__
13121: 
13122: =pod
13123: 
13124: =head1 NAME
13125: 
13126: Apache::lonnet - Subroutines to ask questions about things in the network.
13127: 
13128: =head1 SYNOPSIS
13129: 
13130: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
13131: 
13132:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
13133: 
13134: Common parameters:
13135: 
13136: =over 4
13137: 
13138: =item *
13139: 
13140: $uname : an internal username (if $cname expecting a course Id specifically)
13141: 
13142: =item *
13143: 
13144: $udom : a domain (if $cdom expecting a course's domain specifically)
13145: 
13146: =item *
13147: 
13148: $symb : a resource instance identifier
13149: 
13150: =item *
13151: 
13152: $namespace : the name of a .db file that contains the data needed or
13153: being set.
13154: 
13155: =back
13156: 
13157: =head1 OVERVIEW
13158: 
13159: lonnet provides subroutines which interact with the
13160: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
13161: about classes, users, and resources.
13162: 
13163: For many of these objects you can also use this to store data about
13164: them or modify them in various ways.
13165: 
13166: =head2 Symbs
13167: 
13168: To identify a specific instance of a resource, LON-CAPA uses symbols
13169: or "symbs"X<symb>. These identifiers are built from the URL of the
13170: map, the resource number of the resource in the map, and the URL of
13171: the resource itself. The latter is somewhat redundant, but might help
13172: if maps change.
13173: 
13174: An example is
13175: 
13176:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
13177: 
13178: The respective map entry is
13179: 
13180:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
13181:   title="Problem 2">
13182:  </resource>
13183: 
13184: Symbs are used by the random number generator, as well as to store and
13185: restore data specific to a certain instance of for example a problem.
13186: 
13187: =head2 Storing And Retrieving Data
13188: 
13189: X<store()>X<cstore()>X<restore()>Three of the most important functions
13190: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
13191: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
13192: is is the non-critical message twin of cstore. These functions are for
13193: handlers to store a perl hash to a user's permanent data space in an
13194: easy manner, and to retrieve it again on another call. It is expected
13195: that a handler would use this once at the beginning to retrieve data,
13196: and then again once at the end to send only the new data back.
13197: 
13198: The data is stored in the user's data directory on the user's
13199: homeserver under the ID of the course.
13200: 
13201: The hash that is returned by restore will have all of the previous
13202: value for all of the elements of the hash.
13203: 
13204: Example:
13205: 
13206:  #creating a hash
13207:  my %hash;
13208:  $hash{'foo'}='bar';
13209: 
13210:  #storing it
13211:  &Apache::lonnet::cstore(\%hash);
13212: 
13213:  #changing a value
13214:  $hash{'foo'}='notbar';
13215: 
13216:  #adding a new value
13217:  $hash{'bar'}='foo';
13218:  &Apache::lonnet::cstore(\%hash);
13219: 
13220:  #retrieving the hash
13221:  my %history=&Apache::lonnet::restore();
13222: 
13223:  #print the hash
13224:  foreach my $key (sort(keys(%history))) {
13225:    print("\%history{$key} = $history{$key}");
13226:  }
13227: 
13228: Will print out:
13229: 
13230:  %history{1:foo} = bar
13231:  %history{1:keys} = foo:timestamp
13232:  %history{1:timestamp} = 990455579
13233:  %history{2:bar} = foo
13234:  %history{2:foo} = notbar
13235:  %history{2:keys} = foo:bar:timestamp
13236:  %history{2:timestamp} = 990455580
13237:  %history{bar} = foo
13238:  %history{foo} = notbar
13239:  %history{timestamp} = 990455580
13240:  %history{version} = 2
13241: 
13242: Note that the special hash entries C<keys>, C<version> and
13243: C<timestamp> were added to the hash. C<version> will be equal to the
13244: total number of versions of the data that have been stored. The
13245: C<timestamp> attribute will be the UNIX time the hash was
13246: stored. C<keys> is available in every historical section to list which
13247: keys were added or changed at a specific historical revision of a
13248: hash.
13249: 
13250: B<Warning>: do not store the hash that restore returns directly. This
13251: will cause a mess since it will restore the historical keys as if the
13252: were new keys. I.E. 1:foo will become 1:1:foo etc.
13253: 
13254: Calling convention:
13255: 
13256:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
13257:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
13258: 
13259: For more detailed information, see lonnet specific documentation.
13260: 
13261: =head1 RETURN MESSAGES
13262: 
13263: =over 4
13264: 
13265: =item * B<con_lost>: unable to contact remote host
13266: 
13267: =item * B<con_delayed>: unable to contact remote host, message will be delivered
13268: when the connection is brought back up
13269: 
13270: =item * B<con_failed>: unable to contact remote host and unable to save message
13271: for later delivery
13272: 
13273: =item * B<error:>: an error a occurred, a description of the error follows the :
13274: 
13275: =item * B<no_such_host>: unable to fund a host associated with the user/domain
13276: that was requested
13277: 
13278: =back
13279: 
13280: =head1 PUBLIC SUBROUTINES
13281: 
13282: =head2 Session Environment Functions
13283: 
13284: =over 4
13285: 
13286: =item * 
13287: X<appenv()>
13288: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
13289: the user envirnoment file, and will be restored for each access this
13290: user makes during this session, also modifies the %env for the current
13291: process. Optional rolesarrayref - if defined contains a reference to an array
13292: of roles which are exempt from the restriction on modifying user.role entries 
13293: in the user's environment.db and in %env.    
13294: 
13295: =item *
13296: X<delenv()>
13297: B<delenv($delthis,$regexp)>: removes all items from the session
13298: environment file that begin with $delthis. If the 
13299: optional second arg - $regexp - is true, $delthis is treated as a 
13300: regular expression, otherwise \Q$delthis\E is used. 
13301: The values are also deleted from the current processes %env.
13302: 
13303: =item * get_env_multiple($name) 
13304: 
13305: gets $name from the %env hash, it seemlessly handles the cases where multiple
13306: values may be defined and end up as an array ref.
13307: 
13308: returns an array of values
13309: 
13310: =back
13311: 
13312: =head2 User Information
13313: 
13314: =over 4
13315: 
13316: =item *
13317: X<queryauthenticate()>
13318: B<queryauthenticate($uname,$udom)>: try to determine user's current 
13319: authentication scheme
13320: 
13321: =item *
13322: X<authenticate()>
13323: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
13324: authenticate user from domain's lib servers (first use the current
13325: one). C<$upass> should be the users password.
13326: $checkdefauth is optional (value is 1 if a check should be made to
13327:    authenticate user using default authentication method, and allow
13328:    account creation if username does not have account in the domain).
13329: $clientcancheckhost is optional (value is 1 if checking whether the
13330:    server can host will occur on the client side in lonauth.pm).   
13331: 
13332: =item *
13333: X<homeserver()>
13334: B<homeserver($uname,$udom)>: find the server which has
13335: the user's directory and files (there must be only one), this caches
13336: the answer, and also caches if there is a borken connection.
13337: 
13338: =item *
13339: X<idget()>
13340: B<idget($udom,$idsref,$namespace)>: find the usernames behind either 
13341: a list of student/employee IDs or clicker IDs
13342: (student/employee IDs are a unique resource in a domain, there must be 
13343: only 1 ID per username, and only 1 username per ID in a specific domain).
13344: clickerIDs are not necessarily unique, as students might share clickers.
13345: (returns hash: id=>name,id=>name)
13346: 
13347: =item *
13348: X<idrget()>
13349: B<idrget($udom,@unames)>: find the IDs behind a list of
13350: usernames (returns hash: name=>id,name=>id)
13351: 
13352: =item *
13353: X<idput()>
13354: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of 
13355: names and associated student/employee IDs or clicker IDs.
13356: 
13357: =item *
13358: X<iddel()>
13359: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted 
13360: student/employee ID or clicker ID username look-ups from domain.
13361: The homeserver ($uhome) and namespace ($namespace) are optional.
13362: If no $uhome is provided, it will be determined usig &homeserver()
13363: for each user.  If no $namespace is provided, the default is ids.
13364: 
13365: =item *
13366: X<updateclickers()>
13367: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update 
13368: clicker ID-to-username look-ups in clickers.db on library server.
13369: Permitted actions are add or del (i.e., add or delete). The 
13370: clickers.db contains clickerID as keys (escaped), and each corresponding
13371: value is an escaped comma-separated list of usernames (for whom the
13372: library server is the homeserver), who registered that particular ID.
13373: If $critical is true, the update will be sent via &critical, otherwise
13374: &reply() will be used.
13375: 
13376: =item *
13377: X<rolesinit()>
13378: B<rolesinit($udom,$username)>: get user privileges.
13379: returns user role, first access and timer interval hashes
13380: 
13381: =item *
13382: X<privileged()>
13383: B<privileged($username,$domain)>: returns a true if user has a
13384: privileged and active role (i.e. su or dc), false otherwise.
13385: 
13386: =item *
13387: X<getsection()>
13388: B<getsection($udom,$uname,$cname)>: finds the section of student in the
13389: course $cname, return section name/number or '' for "not in course"
13390: and '-1' for "no section"
13391: 
13392: =item *
13393: X<userenvironment()>
13394: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
13395: passed in @what from the requested user's environment, returns a hash
13396: 
13397: =item * 
13398: X<userlog_query()>
13399: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
13400: activity.log file. %filters defines filters applied when parsing the
13401: log file. These can be start or end timestamps, or the type of action
13402: - log to look for Login or Logout events, check for Checkin or
13403: Checkout, role for role selection. The response is in the form
13404: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
13405: escaped strings of the action recorded in the activity.log file.
13406: 
13407: =back
13408: 
13409: =head2 User Roles
13410: 
13411: =over 4
13412: 
13413: =item *
13414: 
13415: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
13416: returns codes for allowed actions.
13417: 
13418: The first argument is required, all others are optional.
13419: 
13420: $priv is the privilege being checked.
13421: $uri contains additional information about what is being checked for access (e.g.,
13422: URL, course ID etc.). 
13423: $symb is the unique resource instance identifier in a course; if needed,
13424: but not provided, it will be retrieved via a call to &symbread(). 
13425: $role is the role for which a priv is being checked (only used if priv is evb). 
13426: $clientip is the user's IP address (only used when checking for access to portfolio 
13427: files).
13428: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This 
13429: prevents recursive calls to &allowed.
13430: 
13431:  F: full access
13432:  U,I,K: authentication modes (cxx only)
13433:  '': forbidden
13434:  1: user needs to choose course
13435:  2: browse allowed
13436:  A: passphrase authentication needed
13437:  B: access temporarily blocked because of a blocking event in a course.
13438: 
13439: =item *
13440: 
13441: constructaccess($url,$setpriv) : check for access to construction space URL
13442: 
13443: See if the owner domain and name in the URL match those in the
13444: expected environment.  If so, return three element list
13445: ($ownername,$ownerdomain,$ownerhome).
13446: 
13447: Otherwise return the null string.
13448: 
13449: If second argument 'setpriv' is true, it assigns the privileges,
13450: and returns the same three element list, unless the owner has
13451: blocked "ad hoc" Domain Coordinator access to the Author Space,
13452: in which case the null string is returned.
13453: 
13454: =item *
13455: 
13456: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
13457: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
13458: and course level
13459: 
13460: =item *
13461: 
13462: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
13463: (rolesplain.tab); plain text explanation of a user role term.
13464: $type is Course (default) or Community.
13465: If $forcedefault evaluates to true, text returned will be default 
13466: text for $type. Otherwise, if this is a course, the text returned 
13467: will be a custom name for the role (if defined in the course's 
13468: environment).  If no custom name is defined the default is returned.
13469:    
13470: =item *
13471: 
13472: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
13473: All arguments are optional. Returns a hash of a roles, either for
13474: co-author/assistant author roles for a user's Construction Space
13475: (default), or if $context is 'userroles', roles for the user himself,
13476: In the hash, keys are set to colon-separated $uname,$udom,$role, and
13477: (optionally) if $withsec is true, a fourth colon-separated item - $section.
13478: For each key, value is set to colon-separated start and end times for
13479: the role.  If no username and domain are specified, will default to
13480: current user/domain. Types, roles, and roledoms are references to arrays
13481: of role statuses (active, future or previous), roles 
13482: (e.g., cc,in, st etc.) and domains of the roles which can be used
13483: to restrict the list of roles reported. If no array ref is 
13484: provided for types, will default to return only active roles.
13485: 
13486: =item *
13487: 
13488: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
13489: user: $uname:$udom has a role in the course: $cdom_$cnum. 
13490: 
13491: Additional optional arguments are: $type (if role checking is to be restricted 
13492: to certain user status types -- previous (expired roles), active (currently
13493: available roles) or future (roles available in the future), and
13494: $hideprivileged -- if true will not report course roles for users who
13495: have active Domain Coordinator role in course's domain or in additional
13496: domains (specified in 'Domains to check for privileged users' in course
13497: environment -- set via:  Course Settings -> Classlists and staff listing).
13498: 
13499: =item *
13500: 
13501: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
13502: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
13503: $possdomains and $possroles are optional array refs -- to domains to check and
13504: roles to check.  If $possdomains is not specified, a dump will be done of the
13505: users' roles.db to check for a dc or su role in any domain. This can be
13506: time consuming if &privileged is called repeatedly (e.g., when displaying a
13507: classlist), so in such cases, supplying a $possdomains array is preferred, as
13508: this then allows &privileged_by_domain() to be used, which caches the identity
13509: of privileged users, eliminating the need for repeated calls to &dump().
13510: 
13511: =item *
13512: 
13513: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
13514: where the outer hash keys are domains specified in the $possdomains array ref,
13515: next inner hash keys are privileged roles specified in the $roles array ref,
13516: and the innermost hash contains key = value pairs for username:domain = end:start
13517: for active or future "privileged" users with that role in that domain. To avoid
13518: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
13519: innerhash are cached using priv_$role and $dom as the identifiers.
13520: 
13521: =back
13522: 
13523: =head2 User Modification
13524: 
13525: =over 4
13526: 
13527: =item *
13528: 
13529: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
13530: user for the level given by URL.  Optional start and end dates (leave empty
13531: string or zero for "no date")
13532: 
13533: =item *
13534: 
13535: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
13536: change a users, password, possible return values are: ok,
13537: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
13538: refused
13539: 
13540: =item *
13541: 
13542: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
13543: 
13544: =item *
13545: 
13546: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
13547:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
13548: 
13549: will update user information (firstname,middlename,lastname,generation,
13550: permanentemail), and if forceid is true, student/employee ID also.
13551: A user's institutional affiliation(s) can also be updated.
13552: User information fields will not be overwritten with empty entries 
13553: unless the field is included in the $candelete array reference.
13554: This array is included when a single user is modified via "Manage Users",
13555: or when Autoupdate.pl is run by cron in a domain.
13556: 
13557: =item *
13558: 
13559: modifystudent
13560: 
13561: modify a student's enrollment and identification information.
13562: The course id is resolved based on the current user's environment.  
13563: This means the invoking user must be a course coordinator or otherwise
13564: associated with a course.
13565: 
13566: This call is essentially a wrapper for lonnet::modifyuser and
13567: lonnet::modify_student_enrollment
13568: 
13569: Inputs: 
13570: 
13571: =over 4
13572: 
13573: =item B<$udom> Student's loncapa domain
13574: 
13575: =item B<$uname> Student's loncapa login name
13576: 
13577: =item B<$uid> Student/Employee ID
13578: 
13579: =item B<$umode> Student's authentication mode
13580: 
13581: =item B<$upass> Student's password
13582: 
13583: =item B<$first> Student's first name
13584: 
13585: =item B<$middle> Student's middle name
13586: 
13587: =item B<$last> Student's last name
13588: 
13589: =item B<$gene> Student's generation
13590: 
13591: =item B<$usec> Student's section in course
13592: 
13593: =item B<$end> Unix time of the roles expiration
13594: 
13595: =item B<$start> Unix time of the roles start date
13596: 
13597: =item B<$forceid> If defined, allow $uid to be changed
13598: 
13599: =item B<$desiredhome> server to use as home server for student
13600: 
13601: =item B<$email> Student's permanent e-mail address
13602: 
13603: =item B<$type> Type of enrollment (auto or manual)
13604: 
13605: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
13606: 
13607: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
13608: 
13609: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
13610: 
13611: =item B<$context> role change context (shown in User Management Logs display in a course)
13612: 
13613: =item B<$inststatus> institutional status of user - : separated string of escaped status types
13614: 
13615: =item B<$credits> Number of credits student will earn from this class - only needs to be supplied if value needs to be different from default credits for class.
13616: 
13617: =back
13618: 
13619: =item *
13620: 
13621: modify_student_enrollment
13622: 
13623: Change a student's enrollment status in a class.  The environment variable
13624: 'role.request.course' must be defined for this function to proceed.
13625: 
13626: Inputs:
13627: 
13628: =over 4
13629: 
13630: =item $udom, student's domain
13631: 
13632: =item $uname, student's name
13633: 
13634: =item $uid, student's user id
13635: 
13636: =item $first, student's first name
13637: 
13638: =item $middle
13639: 
13640: =item $last
13641: 
13642: =item $gene
13643: 
13644: =item $usec
13645: 
13646: =item $end
13647: 
13648: =item $start
13649: 
13650: =item $type
13651: 
13652: =item $locktype
13653: 
13654: =item $cid
13655: 
13656: =item $selfenroll
13657: 
13658: =item $context
13659: 
13660: =item $credits, number of credits student will earn from this class
13661: 
13662: =back
13663: 
13664: 
13665: =item *
13666: 
13667: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
13668: custom role; give a custom role to a user for the level given by URL.  Specify
13669: name and domain of role author, and role name
13670: 
13671: =item *
13672: 
13673: revokerole($udom,$uname,$url,$role) : revoke a role for url
13674: 
13675: =item *
13676: 
13677: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
13678: 
13679: =back
13680: 
13681: =head2 Course Infomation
13682: 
13683: =over 4
13684: 
13685: =item *
13686: 
13687: coursedescription($courseid,$options) : returns a hash of information about the
13688: specified course id, including all environment settings for the
13689: course, the description of the course will be in the hash under the
13690: key 'description'
13691: 
13692: $options is an optional parameter that if supplied is a hash reference that controls
13693: what how this function works.  It has the following key/values:
13694: 
13695: =over 4
13696: 
13697: =item freshen_cache
13698: 
13699: If defined, and the environment cache for the course is valid, it is 
13700: returned in the returned hash.
13701: 
13702: =item one_time
13703: 
13704: If defined, the last cache time is set to _now_
13705: 
13706: =item user
13707: 
13708: If defined, the supplied username is used instead of the current user.
13709: 
13710: 
13711: =back
13712: 
13713: =item *
13714: 
13715: resdata($name,$domain,$type,@which) : request for current parameter
13716: setting for a specific $type, where $type is either 'course' or 'user',
13717: @what should be a list of parameters to ask about. This routine caches
13718: answers for 10 minutes.
13719: 
13720: =item *
13721: 
13722: get_courseresdata($courseid, $domain) : dump the entire course resource
13723: data base, returning a hash that is keyed by the resource name and has
13724: values that are the resource value.  I believe that the timestamps and
13725: versions are also returned.
13726: 
13727: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
13728: supplemental content area. This routine caches the number of files for 
13729: 10 minutes.
13730: 
13731: =back
13732: 
13733: =head2 Course Modification
13734: 
13735: =over 4
13736: 
13737: =item *
13738: 
13739: writecoursepref($courseid,%prefs) : write preferences (environment
13740: database) for a course
13741: 
13742: =item *
13743: 
13744: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
13745: 
13746: =item *
13747: 
13748: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
13749: 
13750: =item *
13751: 
13752: is_course($courseid), is_course($cdom, $cnum)
13753: 
13754: Accepts either a combined $courseid (in the form of domain_courseid) or the
13755: two component version $cdom, $cnum. It checks if the specified course exists.
13756: 
13757: Returns:
13758:     undef if the course doesn't exist, otherwise
13759:     in scalar context the combined courseid.
13760:     in list context the two components of the course identifier, domain and 
13761:     courseid.    
13762: 
13763: =back
13764: 
13765: =head2 Resource Subroutines
13766: 
13767: =over 4
13768: 
13769: =item *
13770: 
13771: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
13772: 
13773: =item *
13774: 
13775: repcopy($filename) : subscribes to the requested file, and attempts to
13776: replicate from the owning library server, Might return
13777: 'unavailable', 'not_found', 'forbidden', 'ok', or
13778: 'bad_request', also attempts to grab the metadata for the
13779: resource. Expects the local filesystem pathname
13780: (/home/httpd/html/res/....)
13781: 
13782: =back
13783: 
13784: =head2 Resource Information
13785: 
13786: =over 4
13787: 
13788: =item *
13789: 
13790: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
13791: and returns the value of a variety of different possible values,
13792: $varname should be a request string, and the other parameters can be
13793: used to specify who and what one is asking about. Ordinarily, $cid 
13794: does not need to be specified, as it is retrived from 
13795: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
13796: within lonuserstate::loadmap() when initializing a course, before
13797: $env{'request.course.id'} has been set, so it needs to be provided
13798: in that one case.
13799: 
13800: Possible values for $varname are environment.lastname (or other item
13801: from the envirnment hash), user.name (or someother aspect about the
13802: user), resource.0.maxtries (or some other part and parameter of a
13803: resource)
13804: 
13805: =item *
13806: 
13807: directcondval($number) : get current value of a condition; reads from a state
13808: string
13809: 
13810: =item *
13811: 
13812: condval($condidx) : value of condition index based on state
13813: 
13814: =item *
13815: 
13816: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
13817: resource's metadata, $what should be either a specific key, or either
13818: 'keys' (to get a list of possible keys) or 'packages' to get a list of
13819: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
13820: 
13821: this function automatically caches all requests
13822: 
13823: =item *
13824: 
13825: metadata_query($query,$custom,$customshow) : make a metadata query against the
13826: network of library servers; returns file handle of where SQL and regex results
13827: will be stored for query
13828: 
13829: =item *
13830: 
13831: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) : 
13832: return symbolic list entry (all arguments optional). 
13833: 
13834: Args: filename is the filename (including path) for the file for which a symb 
13835: is required; donotrecurse, if true will prevent calls to allowed() being made 
13836: to check access status if more than one resource was found in the bighash 
13837: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of 
13838: a randompick); ignorecachednull, if true will prevent a symb of '' being 
13839: returned if $env{$cache_str} is defined as ''; checkforblock if true will
13840: cause possible symbs to be checked to determine if they are subject to content
13841: blocking, if so they will not be included as possible symbs; possibles is a
13842: ref to a hash, which, as a side effect, will be populated with all possible 
13843: symbs (content blocking not tested).
13844:  
13845: returns the data handle
13846: 
13847: =item *
13848: 
13849: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
13850: and is a possible symb for the URL in $thisfn, and if is an encrypted
13851: resource that the user accessed using /enc/ returns a 1 on success, 0
13852: on failure, user must be in a course, as it assumes the existence of
13853: the course initial hash, and uses $env('request.course.id'}.  The third
13854: arg is an optional reference to a scalar.  If this arg is passed in the 
13855: call to symbverify, it will be set to 1 if the symb has been set to be 
13856: encrypted; otherwise it will be null.  
13857: 
13858: =item *
13859: 
13860: symbclean($symb) : removes versions numbers from a symb, returns the
13861: cleaned symb
13862: 
13863: =item *
13864: 
13865: is_on_map($uri) : checks if the $uri is somewhere on the current
13866: course map, user must be in a course for it to work.
13867: 
13868: =item *
13869: 
13870: numval($salt) : return random seed value (addend for rndseed)
13871: 
13872: =item *
13873: 
13874: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
13875: a random seed, all arguments are optional, if they aren't sent it uses the
13876: environment to derive them. Note: if symb isn't sent and it can't get one
13877: from &symbread it will use the current time as its return value
13878: 
13879: =item *
13880: 
13881: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
13882: unfakeable, receipt
13883: 
13884: =item *
13885: 
13886: receipt() : API to ireceipt working off of env values; given out to users
13887: 
13888: =item *
13889: 
13890: countacc($url) : count the number of accesses to a given URL
13891: 
13892: =item *
13893: 
13894: 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
13895: 
13896: =item *
13897: 
13898: 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)
13899: 
13900: =item *
13901: 
13902: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
13903: 
13904: =item *
13905: 
13906: devalidate($symb) : devalidate temporary spreadsheet calculations,
13907: forcing spreadsheet to reevaluate the resource scores next time.
13908: 
13909: =item * 
13910: 
13911: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
13912: when viewing in course context.
13913: 
13914:  input: six args -- filename (decluttered), course number, course domain,
13915:                     url, symb (if registered) and group (if this is a 
13916:                     group item -- e.g., bulletin board, group page etc.).
13917: 
13918:  output: array of five scalars --
13919:          $cfile -- url for file editing if editable on current server
13920:          $home -- homeserver of resource (i.e., for author if published,
13921:                                           or course if uploaded.).
13922:          $switchserver --  1 if server switch will be needed.
13923:          $forceedit -- 1 if icon/link should be to go to edit mode 
13924:          $forceview -- 1 if icon/link should be to go to view mode
13925: 
13926: =item *
13927: 
13928: is_course_upload($file,$cnum,$cdom)
13929: 
13930: Used in course context to determine if current file was uploaded to 
13931: the course (i.e., would be found in /userfiles/docs on the course's 
13932: homeserver.
13933: 
13934:   input: 3 args -- filename (decluttered), course number and course domain.
13935:   output: boolean -- 1 if file was uploaded.
13936: 
13937: =back
13938: 
13939: =head2 Storing/Retreiving Data
13940: 
13941: =over 4
13942: 
13943: =item *
13944: 
13945: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
13946: permanently for this url; hashref needs to be given and should be a \%hashname;
13947: the remaining args aren't required and if they aren't passed or are '' they will
13948: be derived from the env (with the exception of $laststore, which is an 
13949: optional arg used when a user's submission is stored in grading).
13950: $laststore is $version=$timestamp, where $version is the most recent version
13951: number retrieved for the corresponding $symb in the $namespace db file, and
13952: $timestamp is the timestamp for that transaction (UNIX time).
13953: $laststore is currently only passed when cstore() is called by 
13954: structuretags::finalize_storage().
13955: 
13956: =item *
13957: 
13958: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
13959: but uses critical subroutine
13960: 
13961: =item *
13962: 
13963: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
13964: all args are optional
13965: 
13966: =item *
13967: 
13968: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
13969: dumps the complete (or key matching regexp) namespace into a hash
13970: ($udom, $uname, $regexp, $range are optional) for a namespace that is
13971: normally &store()ed into
13972: 
13973: $range should be either an integer '100' (give me the first 100
13974:                                            matching records)
13975:               or be  two integers sperated by a - with no spaces
13976:                  '30-50' (give me the 30th through the 50th matching
13977:                           records)
13978: 
13979: 
13980: =item *
13981: 
13982: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
13983: replaces a &store() version of data with a replacement set of data
13984: for a particular resource in a namespace passed in the $storehash hash 
13985: reference. If $tolog is true, the transaction is logged in the courselog
13986: with an action=PUTSTORE.
13987: 
13988: =item *
13989: 
13990: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
13991: works very similar to store/cstore, but all data is stored in a
13992: temporary location and can be reset using tmpreset, $storehash should
13993: be a hash reference, returns nothing on success
13994: 
13995: =item *
13996: 
13997: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
13998: similar to restore, but all data is stored in a temporary location and
13999: can be reset using tmpreset. Returns a hash of values on success,
14000: error string otherwise.
14001: 
14002: =item *
14003: 
14004: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
14005: deltes all keys for $symb form the temporary storage hash.
14006: 
14007: =item *
14008: 
14009: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
14010: reference filled in from namesp ($udom and $uname are optional)
14011: 
14012: =item *
14013: 
14014: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
14015: namesp ($udom and $uname are optional)
14016: 
14017: =item *
14018: 
14019: dump($namespace,$udom,$uname,$regexp,$range) : 
14020: dumps the complete (or key matching regexp) namespace into a hash
14021: ($udom, $uname, $regexp, $range are optional)
14022: 
14023: $range should be either an integer '100' (give me the first 100
14024:                                            matching records)
14025:               or be  two integers sperated by a - with no spaces
14026:                  '30-50' (give me the 30th through the 50th matching
14027:                           records)
14028: =item *
14029: 
14030: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
14031: $store can be a scalar, an array reference, or if the amount to be 
14032: incremented is > 1, a hash reference.
14033: 
14034: ($udom and $uname are optional)
14035: 
14036: =item *
14037: 
14038: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
14039: ($udom and $uname are optional)
14040: 
14041: =item *
14042: 
14043: cput($namespace,$storehash,$udom,$uname) : critical put
14044: ($udom and $uname are optional)
14045: 
14046: =item *
14047: 
14048: newput($namespace,$storehash,$udom,$uname) :
14049: 
14050: Attempts to store the items in the $storehash, but only if they don't
14051: currently exist, if this succeeds you can be certain that you have 
14052: successfully created a new key value pair in the $namespace db.
14053: 
14054: 
14055: Args:
14056:  $namespace: name of database to store values to
14057:  $storehash: hashref to store to the db
14058:  $udom: (optional) domain of user containing the db
14059:  $uname: (optional) name of user caontaining the db
14060: 
14061: Returns:
14062:  'ok' -> succeeded in storing all keys of $storehash
14063:  'key_exists: <key>' -> failed to anything out of $storehash, as at
14064:                         least <key> already existed in the db (other
14065:                         requested keys may also already exist)
14066:  'error: <msg>' -> unable to tie the DB or other error occurred
14067:  'con_lost' -> unable to contact request server
14068:  'refused' -> action was not allowed by remote machine
14069: 
14070: 
14071: =item *
14072: 
14073: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
14074: reference filled in from namesp (encrypts the return communication)
14075: ($udom and $uname are optional)
14076: 
14077: =item *
14078: 
14079: log($udom,$name,$home,$message) : write to permanent log for user; use
14080: critical subroutine
14081: 
14082: =item *
14083: 
14084: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
14085: array reference filled in from namespace found in domain level on either
14086: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
14087: 
14088: =item *
14089: 
14090: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
14091: domain level either on specified domain server ($uhome) or primary domain 
14092: server ($udom and $uhome are optional)
14093: 
14094: =item * 
14095: 
14096: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
14097: for: authentication, language, quotas, timezone, date locale, and portal URL in
14098: the target domain.
14099: 
14100: May also include additional key => value pairs for the following groups:
14101: 
14102: =over
14103: 
14104: =item
14105: disk quotas (MB allocated by default to portfolios and authoring spaces).
14106: 
14107: =over
14108: 
14109: =item defaultquota, authorquota
14110: 
14111: =back
14112: 
14113: =item
14114: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
14115: portfolio for users).
14116: 
14117: =over
14118: 
14119: =item
14120: aboutme, blog, webdav, portfolio
14121: 
14122: =back
14123: 
14124: =item
14125: requestcourses: ability to request courses, and how requests are processed.
14126: 
14127: =over
14128: 
14129: =item
14130: official, unofficial, community, textbook
14131: 
14132: =back
14133: 
14134: =item
14135: inststatus: types of institutional affiliation, and order in which they are displayed.
14136: 
14137: =over
14138: 
14139: =item
14140: inststatustypes, inststatusorder, inststatusguest
14141: 
14142: =back
14143: 
14144: =item
14145: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
14146: for course's uploaded content.
14147: 
14148: =over
14149: 
14150: =item
14151: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
14152: communityquota, textbookquota
14153: 
14154: =back
14155: 
14156: =item
14157: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
14158: on your servers.
14159: 
14160: =over
14161: 
14162: =item 
14163: remotesessions, hostedsessions
14164: 
14165: =back
14166: 
14167: =back
14168: 
14169: In cases where a domain coordinator has never used the "Set Domain Configuration"
14170: utility to create a configuration.db file on a domain's primary library server 
14171: only the following domain defaults: auth_def, auth_arg_def, lang_def
14172: -- corresponding values are authentication type (internal, krb4, krb5,
14173: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
14174: will be available. Values are retrieved from cache (if current), unless the
14175: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
14176: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
14177: 
14178: Typical usage:
14179: 
14180: %domdefaults = &get_domain_defaults($target_domain);
14181: 
14182: =back
14183: 
14184: =head2 Network Status Functions
14185: 
14186: =over 4
14187: 
14188: =item *
14189: 
14190: dirlist() : return directory list based on URI (first arg).
14191: 
14192: Inputs: 1 required, 5 optional.
14193: 
14194: =over
14195: 
14196: =item 
14197: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
14198: 
14199: =item
14200: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
14201: 
14202: =item
14203: $username -  username of user/course to be listed. Extracted from $uri if absent. 
14204: 
14205: =item
14206: $getpropath - boolean: 1 if prepend path using &propath(). 
14207: 
14208: =item
14209: $getuserdir - boolean: 1 if prepend path for "userfiles".
14210: 
14211: =item 
14212: $alternateRoot - path to prepend in place of path from $uri.
14213: 
14214: =back
14215: 
14216: Returns: Array of up to two items.
14217: 
14218: =over
14219: 
14220: a reference to an array of files/subdirectories
14221: 
14222: =over
14223: 
14224: Each element in the array of files/subdirectories is a & separated list of
14225: item name and the result of running stat on the item.  If dirlist was requested
14226: for a file instead of a directory, the item name will be ''. For a directory 
14227: listing, if the item is a metadata file, the element will end &N&M 
14228: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
14229: default copyright set (1).  
14230: 
14231: =back
14232: 
14233: a scalar containing error condition (if encountered).
14234: 
14235: =over
14236: 
14237: =item 
14238: no_host (no homeserver identified for $username:$domain).
14239: 
14240: =item 
14241: no_such_host (server contacted for listing not identified as valid host).
14242: 
14243: =item 
14244: con_lost (connection to remote server failed).
14245: 
14246: =item 
14247: refused (invalid $username:$domain received on lond side).
14248: 
14249: =item 
14250: no_such_dir (directory at specified path on lond side does not exist). 
14251: 
14252: =item 
14253: empty (directory at specified path on lond side is empty).
14254: 
14255: =over
14256: 
14257: This is currently not encountered because the &ls3, &ls2, 
14258: &ls (_handler) routines on the lond side do not filter out
14259: . and .. from a directory listing. 
14260: 
14261: =back
14262: 
14263: =back
14264: 
14265: =back
14266: 
14267: =item *
14268: 
14269: spareserver() : find server with least workload from spare.tab
14270: 
14271: 
14272: =item *
14273: 
14274: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
14275: if there is no corresponding loncapa host.
14276: 
14277: =back
14278: 
14279: 
14280: =head2 Apache Request
14281: 
14282: =over 4
14283: 
14284: =item *
14285: 
14286: ssi($url,%hash) : server side include, does a complete request cycle on url to
14287: localhost, posts hash
14288: 
14289: =back
14290: 
14291: =head2 Data to String to Data
14292: 
14293: =over 4
14294: 
14295: =item *
14296: 
14297: hash2str(%hash) : convert a hash into a string complete with escaping and '='
14298: and '&' separators, supports elements that are arrayrefs and hashrefs
14299: 
14300: =item *
14301: 
14302: hashref2str($hashref) : convert a hashref into a string complete with
14303: escaping and '=' and '&' separators, supports elements that are
14304: arrayrefs and hashrefs
14305: 
14306: =item *
14307: 
14308: arrayref2str($arrayref) : convert an arrayref into a string complete
14309: with escaping and '&' separators, supports elements that are arrayrefs
14310: and hashrefs
14311: 
14312: =item *
14313: 
14314: str2hash($string) : convert string to hash using unescaping and
14315: splitting on '=' and '&', supports elements that are arrayrefs and
14316: hashrefs
14317: 
14318: =item *
14319: 
14320: str2array($string) : convert string to hash using unescaping and
14321: splitting on '&', supports elements that are arrayrefs and hashrefs
14322: 
14323: =back
14324: 
14325: =head2 Logging Routines
14326: 
14327: 
14328: These routines allow one to make log messages in the lonnet.log and
14329: lonnet.perm logfiles.
14330: 
14331: =over 4
14332: 
14333: =item *
14334: 
14335: logtouch() : make sure the logfile, lonnet.log, exists
14336: 
14337: =item *
14338: 
14339: logthis() : append message to the normal lonnet.log file, it gets
14340: preiodically rolled over and deleted.
14341: 
14342: =item *
14343: 
14344: logperm() : append a permanent message to lonnet.perm.log, this log
14345: file never gets deleted by any automated portion of the system, only
14346: messages of critical importance should go in here.
14347: 
14348: 
14349: =back
14350: 
14351: =head2 General File Helper Routines
14352: 
14353: =over 4
14354: 
14355: =item *
14356: 
14357: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
14358: (a) files in /uploaded
14359:   (i) If a local copy of the file exists - 
14360:       compares modification date of local copy with last-modified date for 
14361:       definitive version stored on home server for course. If local copy is 
14362:       stale, requests a new version from the home server and stores it. 
14363:       If the original has been removed from the home server, then local copy 
14364:       is unlinked.
14365:   (ii) If local copy does not exist -
14366:       requests the file from the home server and stores it. 
14367:   
14368:   If $caller is 'uploadrep':  
14369:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
14370:     for request for files originally uploaded via DOCS. 
14371:      - returns 'ok' if fresh local copy now available, -1 otherwise.
14372:   
14373:   Otherwise:
14374:      This indicates a call from the content generation phase of the request.
14375:      -  returns the entire contents of the file or -1.
14376:      
14377: (b) files in /res
14378:    - returns the entire contents of a file or -1; 
14379:    it properly subscribes to and replicates the file if neccessary.
14380: 
14381: 
14382: =item *
14383: 
14384: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
14385:                   reference
14386: 
14387: returns either a stat() list of data about the file or an empty list
14388: if the file doesn't exist or couldn't find out about it (connection
14389: problems or user unknown)
14390: 
14391: =item *
14392: 
14393: filelocation($dir,$file) : returns file system location of a file
14394: based on URI; meant to be "fairly clean" absolute reference, $dir is a
14395: directory that relative $file lookups are to looked in ($dir of /a/dir
14396: and a file of ../bob will become /a/bob)
14397: 
14398: =item *
14399: 
14400: hreflocation($dir,$file) : returns file system location or a URL; same as
14401: filelocation except for hrefs
14402: 
14403: =item *
14404: 
14405: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
14406: also removes beginning /home/httpd/html unless /priv/ follows it.
14407: 
14408: =back
14409: 
14410: =head2 Usererfile file routines (/uploaded*)
14411: 
14412: =over 4
14413: 
14414: =item *
14415: 
14416: userfileupload(): main rotine for putting a file in a user or course's
14417:                   filespace, arguments are,
14418: 
14419:  formname - required - this is the name of the element in $env where the
14420:            filename, and the contents of the file to create/modifed exist
14421:            the filename is in $env{'form.'.$formname.'.filename'} and the
14422:            contents of the file is located in $env{'form.'.$formname}
14423:  context - if coursedoc, store the file in the course of the active role
14424:              of the current user; 
14425:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
14426:            if 'canceloverwrite': delete file in tmp/overwrites directory
14427:  subdir - required - subdirectory to put the file in under ../userfiles/
14428:          if undefined, it will be placed in "unknown"
14429: 
14430:  (This routine calls clean_filename() to remove any dangerous
14431:  characters from the filename, and then calls finuserfileupload() to
14432:  complete the transaction)
14433: 
14434:  returns either the url of the uploaded file (/uploaded/....) if successful
14435:  and /adm/notfound.html if unsuccessful
14436: 
14437: =item *
14438: 
14439: clean_filename(): routine for cleaing a filename up for storage in
14440:                  userfile space, argument is:
14441: 
14442:  filename - proposed filename
14443: 
14444: returns: the new clean filename
14445: 
14446: =item *
14447: 
14448: finishuserfileupload(): routine that creates and sends the file to
14449: userspace, probably shouldn't be called directly
14450: 
14451:   docuname: username or courseid of destination for the file
14452:   docudom: domain of user/course of destination for the file
14453:   formname: same as for userfileupload()
14454:   fname: filename (including subdirectories) for the file
14455:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
14456:   allfiles: reference to hash used to store objects found by parser
14457:   codebase: reference to hash used for codebases of java objects found by parser
14458:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
14459:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
14460:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
14461:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
14462:   context: if 'overwrite', will move the uploaded file from its temporary location to
14463:             userfiles to facilitate overwriting a previously uploaded file with same name.
14464:   mimetype: reference to scalar to accommodate mime type determined
14465:             from File::MMagic if $parser = parse.
14466: 
14467:  returns either the url of the uploaded file (/uploaded/....) if successful
14468:  and /adm/notfound.html if unsuccessful (or an error message if context 
14469:  was 'overwrite').
14470:  
14471: 
14472: =item *
14473: 
14474: renameuserfile(): renames an existing userfile to a new name
14475: 
14476:   Args:
14477:    docuname: username or courseid of destination for the file
14478:    docudom: domain of user/course of destination for the file
14479:    old: current file name (including any subdirs under userfiles)
14480:    new: desired file name (including any subdirs under userfiles)
14481: 
14482: =item *
14483: 
14484: mkdiruserfile(): creates a directory is a userfiles dir
14485: 
14486:   Args:
14487:    docuname: username or courseid of destination for the file
14488:    docudom: domain of user/course of destination for the file
14489:    dir: dir to create (including any subdirs under userfiles)
14490: 
14491: =item *
14492: 
14493: removeuserfile(): removes a file that exists in userfiles
14494: 
14495:   Args:
14496:    docuname: username or courseid of destination for the file
14497:    docudom: domain of user/course of destination for the file
14498:    fname: filname to delete (including any subdirs under userfiles)
14499: 
14500: =item *
14501: 
14502: removeuploadedurl(): convience function for removeuserfile()
14503: 
14504:   Args:
14505:    url:  a full /uploaded/... url to delete
14506: 
14507: =item * 
14508: 
14509: get_portfile_permissions():
14510:   Args:
14511:     domain: domain of user or course contain the portfolio files
14512:     user: name of user or num of course contain the portfolio files
14513:   Returns:
14514:     hashref of a dump of the proper file_permissions.db
14515:    
14516: 
14517: =item * 
14518: 
14519: get_access_controls():
14520: 
14521: Args:
14522:   current_permissions: the hash ref returned from get_portfile_permissions()
14523:   group: (optional) the group you want the files associated with
14524:   file: (optional) the file you want access info on
14525: 
14526: Returns:
14527:     a hash (keys are file names) of hashes containing
14528:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
14529:         values are XML containing access control settings (see below) 
14530: 
14531: Internal notes:
14532: 
14533:  access controls are stored in file_permissions.db as key=value pairs.
14534:     key -> path to file/file_name\0uniqueID:scope_end_start
14535:         where scope -> public,guest,course,group,domains or users.
14536:               end -> UNIX time for end of access (0 -> no end date)
14537:               start -> UNIX time for start of access
14538: 
14539:     value -> XML description of access control
14540:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
14541:             <start></start>
14542:             <end></end>
14543: 
14544:             <password></password>  for scope type = guest
14545: 
14546:             <domain></domain>     for scope type = course or group
14547:             <number></number>
14548:             <roles id="">
14549:              <role></role>
14550:              <access></access>
14551:              <section></section>
14552:              <group></group>
14553:             </roles>
14554: 
14555:             <dom></dom>         for scope type = domains
14556: 
14557:             <users>             for scope type = users
14558:              <user>
14559:               <uname></uname>
14560:               <udom></udom>
14561:              </user>
14562:             </users>
14563:            </scope> 
14564:               
14565:  Access data is also aggregated for each file in an additional key=value pair:
14566:  key -> path to file/file_name\0accesscontrol 
14567:  value -> reference to hash
14568:           hash contains key = value pairs
14569:           where key = uniqueID:scope_end_start
14570:                 value = UNIX time record was last updated
14571: 
14572:           Used to improve speed of look-ups of access controls for each file.  
14573:  
14574:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
14575: 
14576: =item *
14577: 
14578: modify_access_controls():
14579: 
14580: Modifies access controls for a portfolio file
14581: Args
14582: 1. file name
14583: 2. reference to hash of required changes,
14584: 3. domain
14585: 4. username
14586:   where domain,username are the domain of the portfolio owner 
14587:   (either a user or a course) 
14588: 
14589: Returns:
14590: 1. result of additions or updates ('ok' or 'error', with error message). 
14591: 2. result of deletions ('ok' or 'error', with error message).
14592: 3. reference to hash of any new or updated access controls.
14593: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
14594:    key = integer (inbound ID)
14595:    value = uniqueID
14596: 
14597: =item *
14598: 
14599: get_timebased_id():
14600: 
14601: Attempts to get a unique timestamp-based suffix for use with items added to a 
14602: course via the Course Editor (e.g., folders, composite pages, 
14603: group bulletin boards).
14604: 
14605: Args: (first three required; six others optional)
14606: 
14607: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
14608:    docssequence, or name of group
14609: 
14610: 2. keyid (alphanumeric): name of temporary locking key in hash,
14611:    e.g., num, boardids
14612: 
14613: 3. namespace: name of gdbm file used to store suffixes already assigned;  
14614:    file will be named nohist_namespace.db
14615: 
14616: 4. cdom: domain of course; default is current course domain from %env
14617: 
14618: 5. cnum: course number; default is current course number from %env
14619: 
14620: 6. idtype: set to concat if an additional digit is to be appended to the 
14621:    unix timestamp to form the suffix, if the plain timestamp is already
14622:    in use.  Default is to not do this, but simply increment the unix 
14623:    timestamp by 1 until a unique key is obtained.
14624: 
14625: 7. who: holder of locking key; defaults to user:domain for user.
14626: 
14627: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
14628:    retrying); default is 3.
14629: 
14630: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
14631: 
14632: Returns:
14633: 
14634: 1. suffix obtained (numeric)
14635: 
14636: 2. result of deleting locking key (ok if deleted, or lock never obtained)
14637: 
14638: 3. error: contains (localized) error message if an error occurred.
14639: 
14640: 
14641: =back
14642: 
14643: =head2 HTTP Helper Routines
14644: 
14645: =over 4
14646: 
14647: =item *
14648: 
14649: escape() : unpack non-word characters into CGI-compatible hex codes
14650: 
14651: =item *
14652: 
14653: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
14654: 
14655: =back
14656: 
14657: =head1 PRIVATE SUBROUTINES
14658: 
14659: =head2 Underlying communication routines (Shouldn't call)
14660: 
14661: =over 4
14662: 
14663: =item *
14664: 
14665: subreply() : tries to pass a message to lonc, returns con_lost if incapable
14666: 
14667: =item *
14668: 
14669: reply() : uses subreply to send a message to remote machine, logs all failures
14670: 
14671: =item *
14672: 
14673: critical() : passes a critical message to another server; if cannot
14674: get through then place message in connection buffer directory and
14675: returns con_delayed, if incapable of saving message, returns
14676: con_failed
14677: 
14678: =item *
14679: 
14680: reconlonc() : tries to reconnect lonc client processes.
14681: 
14682: =back
14683: 
14684: =head2 Resource Access Logging
14685: 
14686: =over 4
14687: 
14688: =item *
14689: 
14690: flushcourselogs() : flush (save) buffer logs and access logs
14691: 
14692: =item *
14693: 
14694: courselog($what) : save message for course in hash
14695: 
14696: =item *
14697: 
14698: courseacclog($what) : save message for course using &courselog().  Perform
14699: special processing for specific resource types (problems, exams, quizzes, etc).
14700: 
14701: =item *
14702: 
14703: goodbye() : flush course logs and log shutting down; it is called in srm.conf
14704: as a PerlChildExitHandler
14705: 
14706: =back
14707: 
14708: =head2 Other
14709: 
14710: =over 4
14711: 
14712: =item *
14713: 
14714: symblist($mapname,%newhash) : update symbolic storage links
14715: 
14716: =back
14717: 
14718: =cut
14719: 

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