File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1242: download - view: text, annotated - select for diffs
Sat Oct 12 01:15:38 2013 UTC (10 years, 10 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Sanity checking.
- No domain defaults for domain: "public".

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1242 2013/10/12 01:15:38 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 $apache
   82:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
   83:             %managerstab);
   84: 
   85: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
   86:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
   87:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
   88:     %courseownerbuf, %coursetypebuf,$locknum);
   89: 
   90: use IO::Socket;
   91: use GDBM_File;
   92: use HTML::LCParser;
   93: use Fcntl qw(:flock);
   94: use Storable qw(thaw nfreeze);
   95: use Time::HiRes qw( gettimeofday tv_interval );
   96: use Cache::Memcached;
   97: use Digest::MD5;
   98: use Math::Random;
   99: use File::MMagic;
  100: use LONCAPA qw(:DEFAULT :match);
  101: use LONCAPA::Configuration;
  102: use LONCAPA::lonmetadata;
  103: use LONCAPA::Lond;
  104: 
  105: use File::Copy;
  106: 
  107: my $readit;
  108: my $max_connection_retries = 10;     # Or some such value.
  109: 
  110: require Exporter;
  111: 
  112: our @ISA = qw (Exporter);
  113: our @EXPORT = qw(%env);
  114: 
  115: 
  116: # ------------------------------------ Logging (parameters, docs, slots, roles)
  117: {
  118:     my $logid;
  119:     sub write_log {
  120: 	my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
  121:         if ($context eq 'course') {
  122:             if (($cnum eq '') || ($cdom eq '')) {
  123:                 $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
  124:                 $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
  125:             }
  126:         }
  127: 	$logid ++;
  128:         my $now = time();
  129: 	my $id=$now.'00000'.$$.'00000'.$logid;
  130:         my $logentry = { 
  131:                           $id => {
  132:                                    'exe_uname' => $env{'user.name'},
  133:                                    'exe_udom'  => $env{'user.domain'},
  134:                                    'exe_time'  => $now,
  135:                                    'exe_ip'    => $ENV{'REMOTE_ADDR'},
  136:                                    'delflag'   => $delflag,
  137:                                    'logentry'  => $storehash,
  138:                                    'uname'     => $uname,
  139:                                    'udom'      => $udom,
  140:                                   }
  141:                        };
  142: 	return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
  143:     }
  144: }
  145: 
  146: sub logtouch {
  147:     my $execdir=$perlvar{'lonDaemons'};
  148:     unless (-e "$execdir/logs/lonnet.log") {	
  149: 	open(my $fh,">>$execdir/logs/lonnet.log");
  150: 	close $fh;
  151:     }
  152:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
  153:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
  154: }
  155: 
  156: sub logthis {
  157:     my $message=shift;
  158:     my $execdir=$perlvar{'lonDaemons'};
  159:     my $now=time;
  160:     my $local=localtime($now);
  161:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
  162: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
  163: 	print $fh $logstring;
  164: 	close($fh);
  165:     }
  166:     return 1;
  167: }
  168: 
  169: sub logperm {
  170:     my $message=shift;
  171:     my $execdir=$perlvar{'lonDaemons'};
  172:     my $now=time;
  173:     my $local=localtime($now);
  174:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
  175: 	print $fh "$now:$message:$local\n";
  176: 	close($fh);
  177:     }
  178:     return 1;
  179: }
  180: 
  181: sub create_connection {
  182:     my ($hostname,$lonid) = @_;
  183:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
  184: 				     Type    => SOCK_STREAM,
  185: 				     Timeout => 10);
  186:     return 0 if (!$client);
  187:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
  188:     my $result = <$client>;
  189:     chomp($result);
  190:     return 1 if ($result eq 'done');
  191:     return 0;
  192: }
  193: 
  194: sub get_server_timezone {
  195:     my ($cnum,$cdom) = @_;
  196:     my $home=&homeserver($cnum,$cdom);
  197:     if ($home ne 'no_host') {
  198:         my $cachetime = 24*3600;
  199:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
  200:         if (defined($cached)) {
  201:             return $timezone;
  202:         } else {
  203:             my $timezone = &reply('servertimezone',$home);
  204:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
  205:         }
  206:     }
  207: }
  208: 
  209: sub get_server_distarch {
  210:     my ($lonhost,$ignore_cache) = @_;
  211:     if (defined($lonhost)) {
  212:         if (!defined(&hostname($lonhost))) {
  213:             return;
  214:         }
  215:         my $cachetime = 12*3600;
  216:         if (!$ignore_cache) {
  217:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
  218:             if (defined($cached)) {
  219:                 return $distarch;
  220:             }
  221:         }
  222:         my $rep = &reply('serverdistarch',$lonhost);
  223:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
  224:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
  225:                 $rep eq '') {
  226:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
  227:         }
  228:     }
  229:     return;
  230: }
  231: 
  232: sub get_server_loncaparev {
  233:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
  234:     if (defined($lonhost)) {
  235:         if (!defined(&hostname($lonhost))) {
  236:             undef($lonhost);
  237:         }
  238:     }
  239:     if (!defined($lonhost)) {
  240:         if (defined(&domain($dom,'primary'))) {
  241:             $lonhost=&domain($dom,'primary');
  242:             if ($lonhost eq 'no_host') {
  243:                 undef($lonhost);
  244:             }
  245:         }
  246:     }
  247:     if (defined($lonhost)) {
  248:         my $cachetime = 12*3600;
  249:         if (!$ignore_cache) {
  250:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
  251:             if (defined($cached)) {
  252:                 return $loncaparev;
  253:             }
  254:         }
  255:         my ($answer,$loncaparev);
  256:         my @ids=&current_machine_ids();
  257:         if (grep(/^\Q$lonhost\E$/,@ids)) {
  258:             $answer = $perlvar{'lonVersion'};
  259:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  260:                 $loncaparev = $1;
  261:             }
  262:         } else {
  263:             $answer = &reply('serverloncaparev',$lonhost);
  264:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
  265:                 if ($caller eq 'loncron') {
  266:                     my $ua=new LWP::UserAgent;
  267:                     $ua->timeout(4);
  268:                     my $protocol = $protocol{$lonhost};
  269:                     $protocol = 'http' if ($protocol ne 'https');
  270:                     my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
  271:                     my $request=new HTTP::Request('GET',$url);
  272:                     my $response=$ua->request($request);
  273:                     unless ($response->is_error()) {
  274:                         my $content = $response->content;
  275:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
  276:                             $loncaparev = $1;
  277:                         }
  278:                     }
  279:                 } else {
  280:                     $loncaparev = $loncaparevs{$lonhost};
  281:                 }
  282:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  283:                 $loncaparev = $1;
  284:             }
  285:         }
  286:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
  287:     }
  288: }
  289: 
  290: sub get_server_homeID {
  291:     my ($hostname,$ignore_cache,$caller) = @_;
  292:     unless ($ignore_cache) {
  293:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
  294:         if (defined($cached)) {
  295:             return $serverhomeID;
  296:         }
  297:     }
  298:     my $cachetime = 12*3600;
  299:     my $serverhomeID;
  300:     if ($caller eq 'loncron') { 
  301:         my @machine_ids = &machine_ids($hostname);
  302:         foreach my $id (@machine_ids) {
  303:             my $response = &reply('serverhomeID',$id);
  304:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
  305:                 $serverhomeID = $response;
  306:                 last;
  307:             }
  308:         }
  309:         if ($serverhomeID eq '') {
  310:             $serverhomeID = $machine_ids[-1];
  311:         }
  312:     } else {
  313:         $serverhomeID = $serverhomeIDs{$hostname};
  314:     }
  315:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
  316: }
  317: 
  318: sub get_remote_globals {
  319:     my ($lonhost,$whathash,$ignore_cache) = @_;
  320:     my ($result,%returnhash,%whatneeded);
  321:     if (ref($whathash) eq 'HASH') {
  322:         foreach my $what (sort(keys(%{$whathash}))) {
  323:             my $hashid = $lonhost.'-'.$what;
  324:             my ($response,$cached);
  325:             unless ($ignore_cache) {
  326:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
  327:             }
  328:             if (defined($cached)) {
  329:                 $returnhash{$what} = $response;
  330:             } else {
  331:                 $whatneeded{$what} = 1;
  332:             }
  333:         }
  334:         if (keys(%whatneeded) == 0) {
  335:             $result = 'ok';
  336:         } else {
  337:             my $requested = &freeze_escape(\%whatneeded);
  338:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
  339:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
  340:                 ($rep eq 'unknown_cmd')) {
  341:                 $result = $rep;
  342:             } else {
  343:                 $result = 'ok';
  344:                 my @pairs=split(/\&/,$rep);
  345:                 foreach my $item (@pairs) {
  346:                     my ($key,$value)=split(/=/,$item,2);
  347:                     my $what = &unescape($key);
  348:                     my $hashid = $lonhost.'-'.$what;
  349:                     $returnhash{$what}=&thaw_unescape($value);
  350:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
  351:                 }
  352:             }
  353:         }
  354:     }
  355:     return ($result,\%returnhash);
  356: }
  357: 
  358: sub remote_devalidate_cache {
  359:     my ($lonhost,$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(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(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:     my $hostname = &hostname($lonid);
  426:     if ($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("$perlvar{'lonSockDir'}/$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 2;
  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) = @_;
  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:     if (($r->user() eq '') && ($apache >= 2.4)) {
  641:         if ($disk_env{'user.domain'} eq $r->dir_config('lonDefDomain')) {
  642:             $r->user($disk_env{'user.name'});
  643:         } else {
  644:             $r->user($disk_env{'user.name'}.':'.$disk_env{'user.domain'});
  645:         }
  646:     }
  647:     return $handle;
  648: }
  649: 
  650: sub timed_flock {
  651:     my ($file,$lock_type) = @_;
  652:     my $failed=0;
  653:     eval {
  654: 	local $SIG{__DIE__}='DEFAULT';
  655: 	local $SIG{ALRM}=sub {
  656: 	    $failed=1;
  657: 	    die("failed lock");
  658: 	};
  659: 	alarm(13);
  660: 	flock($file,$lock_type);
  661: 	alarm(0);
  662:     };
  663:     if ($failed) {
  664: 	return undef;
  665:     } else {
  666: 	return 1;
  667:     }
  668: }
  669: 
  670: # ---------------------------------------------------------- Append Environment
  671: 
  672: sub appenv {
  673:     my ($newenv,$roles) = @_;
  674:     if (ref($newenv) eq 'HASH') {
  675:         foreach my $key (keys(%{$newenv})) {
  676:             my $refused = 0;
  677: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
  678:                 $refused = 1;
  679:                 if (ref($roles) eq 'ARRAY') {
  680:                     my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
  681:                     if (grep(/^\Q$role\E$/,@{$roles})) {
  682:                         $refused = 0;
  683:                     }
  684:                 }
  685:             }
  686:             if ($refused) {
  687:                 &logthis("<font color=\"blue\">WARNING: ".
  688:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
  689:                          .'</font>');
  690: 	        delete($newenv->{$key});
  691:             } else {
  692:                 $env{$key}=$newenv->{$key};
  693:             }
  694:         }
  695:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
  696:         if ($opened
  697: 	    && &timed_flock($env_file,LOCK_EX)
  698: 	    &&
  699: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  700: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  701: 	    while (my ($key,$value) = each(%{$newenv})) {
  702: 	        $disk_env{$key} = $value;
  703: 	    }
  704: 	    untie(%disk_env);
  705:         }
  706:     }
  707:     return 'ok';
  708: }
  709: # ----------------------------------------------------- Delete from Environment
  710: 
  711: sub delenv {
  712:     my ($delthis,$regexp,$roles) = @_;
  713:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
  714:         my $refused = 1;
  715:         if (ref($roles) eq 'ARRAY') {
  716:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
  717:             if (grep(/^\Q$role\E$/,@{$roles})) {
  718:                 $refused = 0;
  719:             }
  720:         }
  721:         if ($refused) {
  722:             &logthis("<font color=\"blue\">WARNING: ".
  723:                      "Attempt to delete from environment ".$delthis);
  724:             return 'error';
  725:         }
  726:     }
  727:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
  728:     if ($opened
  729: 	&& &timed_flock($env_file,LOCK_EX)
  730: 	&&
  731: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  732: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  733: 	foreach my $key (keys(%disk_env)) {
  734: 	    if ($regexp) {
  735:                 if ($key=~/^$delthis/) {
  736:                     delete($env{$key});
  737:                     delete($disk_env{$key});
  738:                 } 
  739:             } else {
  740:                 if ($key=~/^\Q$delthis\E/) {
  741: 		    delete($env{$key});
  742: 		    delete($disk_env{$key});
  743: 	        }
  744:             }
  745: 	}
  746: 	untie(%disk_env);
  747:     }
  748:     return 'ok';
  749: }
  750: 
  751: sub get_env_multiple {
  752:     my ($name) = @_;
  753:     my @values;
  754:     if (defined($env{$name})) {
  755:         # exists is it an array
  756:         if (ref($env{$name})) {
  757:             @values=@{ $env{$name} };
  758:         } else {
  759:             $values[0]=$env{$name};
  760:         }
  761:     }
  762:     return(@values);
  763: }
  764: 
  765: # ------------------------------------------------------------------- Locking
  766: 
  767: sub set_lock {
  768:     my ($text)=@_;
  769:     $locknum++;
  770:     my $id=$$.'-'.$locknum;
  771:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
  772:              'session.lock.'.$id => $text});
  773:     return $id;
  774: }
  775: 
  776: sub get_locks {
  777:     my $num=0;
  778:     my %texts=();
  779:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  780:        if ($lock=~/\w/) {
  781:           $num++;
  782:           $texts{$lock}=$env{'session.lock.'.$lock};
  783:        }
  784:    }
  785:    return ($num,%texts);
  786: }
  787: 
  788: sub remove_lock {
  789:     my ($id)=@_;
  790:     my $newlocks='';
  791:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  792:        if (($lock=~/\w/) && ($lock ne $id)) {
  793:           $newlocks.=','.$lock;
  794:        }
  795:     }
  796:     &appenv({'session.locks' => $newlocks});
  797:     &delenv('session.lock.'.$id);
  798: }
  799: 
  800: sub remove_all_locks {
  801:     my $activelocks=$env{'session.locks'};
  802:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  803:        if ($lock=~/\w/) {
  804:           &remove_lock($lock);
  805:        }
  806:     }
  807: }
  808: 
  809: 
  810: # ------------------------------------------ Find out current server userload
  811: sub userload {
  812:     my $numusers=0;
  813:     {
  814: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  815: 	my $filename;
  816: 	my $curtime=time;
  817: 	while ($filename=readdir(LONIDS)) {
  818: 	    next if ($filename eq '.' || $filename eq '..');
  819: 	    next if ($filename =~ /publicuser_\d+\.id/);
  820: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  821: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  822: 	}
  823: 	closedir(LONIDS);
  824:     }
  825:     my $userloadpercent=0;
  826:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  827:     if ($maxuserload) {
  828: 	$userloadpercent=100*$numusers/$maxuserload;
  829:     }
  830:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  831:     return $userloadpercent;
  832: }
  833: 
  834: # ------------------------------ Find server with least workload from spare.tab
  835: 
  836: sub spareserver {
  837:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
  838:     my $spare_server;
  839:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  840:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
  841:                                                      :  $userloadpercent;
  842:     my ($uint_dom,$remotesessions);
  843:     if (($udom ne '') && (&domain($udom) ne '')) {
  844:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
  845:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
  846:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
  847:         $remotesessions = $udomdefaults{'remotesessions'};
  848:     }
  849:     my $spareshash = &this_host_spares($udom);
  850:     if (ref($spareshash) eq 'HASH') {
  851:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
  852:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
  853:                 if ($uint_dom) {
  854:                     next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
  855:                                                  $try_server));
  856:                 }
  857: 	        ($spare_server, $lowest_load) =
  858: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
  859:             }
  860:         }
  861: 
  862:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
  863: 
  864:         if (!$found_server) {
  865:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
  866: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
  867:                     if ($uint_dom) {
  868:                         next unless (&spare_can_host($udom,$uint_dom,
  869:                                                      $remotesessions,$try_server));
  870:                     }
  871: 	            ($spare_server, $lowest_load) =
  872: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
  873:                 }
  874: 	    }
  875:         }
  876:     }
  877: 
  878:     if (!$want_server_name) {
  879:         my $protocol = 'http';
  880:         if ($protocol{$spare_server} eq 'https') {
  881:             $protocol = $protocol{$spare_server};
  882:         }
  883:         if (defined($spare_server)) {
  884:             my $hostname = &hostname($spare_server);
  885:             if (defined($hostname)) {
  886: 	        $spare_server = $protocol.'://'.$hostname;
  887:             }
  888:         }
  889:     }
  890:     return $spare_server;
  891: }
  892: 
  893: sub compare_server_load {
  894:     my ($try_server, $spare_server, $lowest_load) = @_;
  895: 
  896:     my $loadans     = &reply('load',    $try_server);
  897:     my $userloadans = &reply('userload',$try_server);
  898: 
  899:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
  900: 	return ($spare_server, $lowest_load); #didn't get a number from the server
  901:     }
  902: 
  903:     my $load;
  904:     if ($loadans =~ /\d/) {
  905: 	if ($userloadans =~ /\d/) {
  906: 	    #both are numbers, pick the bigger one
  907: 	    $load = ($loadans > $userloadans) ? $loadans 
  908: 		                              : $userloadans;
  909: 	} else {
  910: 	    $load = $loadans;
  911: 	}
  912:     } else {
  913: 	$load = $userloadans;
  914:     }
  915: 
  916:     if (($load =~ /\d/) && ($load < $lowest_load)) {
  917: 	$spare_server = $try_server;
  918: 	$lowest_load  = $load;
  919:     }
  920:     return ($spare_server,$lowest_load);
  921: }
  922: 
  923: # --------------------------- ask offload servers if user already has a session
  924: sub find_existing_session {
  925:     my ($udom,$uname) = @_;
  926:     my $spareshash = &this_host_spares($udom);
  927:     if (ref($spareshash) eq 'HASH') {
  928:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
  929:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
  930:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
  931:             }
  932:         }
  933:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
  934:             foreach my $try_server (@{ $spareshash->{'default'} }) {
  935:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
  936:             }
  937:         }
  938:     }
  939:     return;
  940: }
  941: 
  942: # -------------------------------- ask if server already has a session for user
  943: sub has_user_session {
  944:     my ($lonid,$udom,$uname) = @_;
  945:     my $result = &reply(join(':','userhassession',
  946: 			     map {&escape($_)} ($udom,$uname)),$lonid);
  947:     return 1 if ($result eq 'ok');
  948: 
  949:     return 0;
  950: }
  951: 
  952: # --------- determine least loaded server in a user's domain which allows login
  953: 
  954: sub choose_server {
  955:     my ($udom,$checkloginvia) = @_;
  956:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
  957:     my %servers = &get_servers($udom);
  958:     my $lowest_load = 30000;
  959:     my ($login_host,$hostname,$portal_path,$isredirect);
  960:     foreach my $lonhost (keys(%servers)) {
  961:         my $loginvia;
  962:         if ($checkloginvia) {
  963:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
  964:             if ($loginvia) {
  965:                 my ($server,$path) = split(/:/,$loginvia);
  966:                 ($login_host, $lowest_load) =
  967:                     &compare_server_load($server, $login_host, $lowest_load);
  968:                 if ($login_host eq $server) {
  969:                     $portal_path = $path;
  970:                     $isredirect = 1;
  971:                 }
  972:             } else {
  973:                 ($login_host, $lowest_load) =
  974:                     &compare_server_load($lonhost, $login_host, $lowest_load);
  975:                 if ($login_host eq $lonhost) {
  976:                     $portal_path = '';
  977:                     $isredirect = ''; 
  978:                 }
  979:             }
  980:         } else {
  981:             ($login_host, $lowest_load) =
  982:                 &compare_server_load($lonhost, $login_host, $lowest_load);
  983:         }
  984:     }
  985:     if ($login_host ne '') {
  986:         $hostname = &hostname($login_host);
  987:     }
  988:     return ($login_host,$hostname,$portal_path,$isredirect);
  989: }
  990: 
  991: # --------------------------------------------- Try to change a user's password
  992: 
  993: sub changepass {
  994:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
  995:     $currentpass = &escape($currentpass);
  996:     $newpass     = &escape($newpass);
  997:     my $lonhost = $perlvar{'lonHostID'};
  998:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
  999: 		       $server);
 1000:     if (! $answer) {
 1001: 	&logthis("No reply on password change request to $server ".
 1002: 		 "by $uname in domain $udom.");
 1003:     } elsif ($answer =~ "^ok") {
 1004:         &logthis("$uname in $udom successfully changed their password ".
 1005: 		 "on $server.");
 1006:     } elsif ($answer =~ "^pwchange_failure") {
 1007: 	&logthis("$uname in $udom was unable to change their password ".
 1008: 		 "on $server.  The action was blocked by either lcpasswd ".
 1009: 		 "or pwchange");
 1010:     } elsif ($answer =~ "^non_authorized") {
 1011:         &logthis("$uname in $udom did not get their password correct when ".
 1012: 		 "attempting to change it on $server.");
 1013:     } elsif ($answer =~ "^auth_mode_error") {
 1014:         &logthis("$uname in $udom attempted to change their password despite ".
 1015: 		 "not being locally or internally authenticated on $server.");
 1016:     } elsif ($answer =~ "^unknown_user") {
 1017:         &logthis("$uname in $udom attempted to change their password ".
 1018: 		 "on $server but were unable to because $server is not ".
 1019: 		 "their home server.");
 1020:     } elsif ($answer =~ "^refused") {
 1021: 	&logthis("$server refused to change $uname in $udom password because ".
 1022: 		 "it was sent an unencrypted request to change the password.");
 1023:     } elsif ($answer =~ "invalid_client") {
 1024:         &logthis("$server refused to change $uname in $udom password because ".
 1025:                  "it was a reset by e-mail originating from an invalid server.");
 1026:     }
 1027:     return $answer;
 1028: }
 1029: 
 1030: # ----------------------- Try to determine user's current authentication scheme
 1031: 
 1032: sub queryauthenticate {
 1033:     my ($uname,$udom)=@_;
 1034:     my $uhome=&homeserver($uname,$udom);
 1035:     if (!$uhome) {
 1036: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
 1037: 	return 'no_host';
 1038:     }
 1039:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
 1040:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
 1041: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1042:     }
 1043:     return $answer;
 1044: }
 1045: 
 1046: # --------- Try to authenticate user from domain's lib servers (first this one)
 1047: 
 1048: sub authenticate {
 1049:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
 1050:     $upass=&escape($upass);
 1051:     $uname= &LONCAPA::clean_username($uname);
 1052:     my $uhome=&homeserver($uname,$udom,1);
 1053:     my $newhome;
 1054:     if ((!$uhome) || ($uhome eq 'no_host')) {
 1055: # Maybe the machine was offline and only re-appeared again recently?
 1056:         &reconlonc();
 1057: # One more
 1058: 	$uhome=&homeserver($uname,$udom,1);
 1059:         if (($uhome eq 'no_host') && $checkdefauth) {
 1060:             if (defined(&domain($udom,'primary'))) {
 1061:                 $newhome=&domain($udom,'primary');
 1062:             }
 1063:             if ($newhome ne '') {
 1064:                 $uhome = $newhome;
 1065:             }
 1066:         }
 1067: 	if ((!$uhome) || ($uhome eq 'no_host')) {
 1068: 	    &logthis("User $uname at $udom is unknown in authenticate");
 1069: 	    return 'no_host';
 1070:         }
 1071:     }
 1072:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
 1073:     if ($answer eq 'authorized') {
 1074:         if ($newhome) {
 1075:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
 1076:             return 'no_account_on_host'; 
 1077:         } else {
 1078:             &logthis("User $uname at $udom authorized by $uhome");
 1079:             return $uhome;
 1080:         }
 1081:     }
 1082:     if ($answer eq 'non_authorized') {
 1083: 	&logthis("User $uname at $udom rejected by $uhome");
 1084: 	return 'no_host'; 
 1085:     }
 1086:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1087:     return 'no_host';
 1088: }
 1089: 
 1090: sub can_host_session {
 1091:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
 1092:     my $canhost = 1;
 1093:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
 1094:     if (ref($remotesessions) eq 'HASH') {
 1095:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
 1096:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
 1097:                 $canhost = 0;
 1098:             } else {
 1099:                 $canhost = 1;
 1100:             }
 1101:         }
 1102:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
 1103:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
 1104:                 $canhost = 1;
 1105:             } else {
 1106:                 $canhost = 0;
 1107:             }
 1108:         }
 1109:         if ($canhost) {
 1110:             if ($remotesessions->{'version'} ne '') {
 1111:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
 1112:                 if ($reqmajor ne '' && $reqminor ne '') {
 1113:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
 1114:                         my $major = $1;
 1115:                         my $minor = $2;
 1116:                         if (($major < $reqmajor ) ||
 1117:                             (($major == $reqmajor) && ($minor < $reqminor))) {
 1118:                             $canhost = 0;
 1119:                         }
 1120:                     } else {
 1121:                         $canhost = 0;
 1122:                     }
 1123:                 }
 1124:             }
 1125:         }
 1126:     }
 1127:     if ($canhost) {
 1128:         if (ref($hostedsessions) eq 'HASH') {
 1129:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1130:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
 1131:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
 1132:                 if (($uint_dom ne '') && 
 1133:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
 1134:                     $canhost = 0;
 1135:                 } else {
 1136:                     $canhost = 1;
 1137:                 }
 1138:             }
 1139:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
 1140:                 if (($uint_dom ne '') && 
 1141:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
 1142:                     $canhost = 1;
 1143:                 } else {
 1144:                     $canhost = 0;
 1145:                 }
 1146:             }
 1147:         }
 1148:     }
 1149:     return $canhost;
 1150: }
 1151: 
 1152: sub spare_can_host {
 1153:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
 1154:     my $canhost=1;
 1155:     my @intdoms;
 1156:     my $internet_names = &Apache::lonnet::get_internet_names($try_server);
 1157:     if (ref($internet_names) eq 'ARRAY') {
 1158:         @intdoms = @{$internet_names};
 1159:     }
 1160:     unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
 1161:         my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
 1162:         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
 1163:         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
 1164:         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
 1165:         $canhost = &can_host_session($udom,$try_server,$remoterev,
 1166:                                      $remotesessions,
 1167:                                      $defdomdefaults{'hostedsessions'});
 1168:     }
 1169:     return $canhost;
 1170: }
 1171: 
 1172: sub this_host_spares {
 1173:     my ($dom) = @_;
 1174:     my ($dom_in_use,$lonhost_in_use,$result);
 1175:     my @hosts = &current_machine_ids();
 1176:     foreach my $lonhost (@hosts) {
 1177:         if (&host_domain($lonhost) eq $dom) {
 1178:             $dom_in_use = $dom;
 1179:             $lonhost_in_use = $lonhost;
 1180:             last;
 1181:         }
 1182:     }
 1183:     if ($dom_in_use ne '') {
 1184:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1185:     }
 1186:     if (ref($result) ne 'HASH') {
 1187:         $lonhost_in_use = $perlvar{'lonHostID'};
 1188:         $dom_in_use = &host_domain($lonhost_in_use);
 1189:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1190:         if (ref($result) ne 'HASH') {
 1191:             $result = \%spareid;
 1192:         }
 1193:     }
 1194:     return $result;
 1195: }
 1196: 
 1197: sub spares_for_offload  {
 1198:     my ($dom_in_use,$lonhost_in_use) = @_;
 1199:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
 1200:     if (defined($cached)) {
 1201:         return $result;
 1202:     } else {
 1203:         my $cachetime = 60*60*24;
 1204:         my %domconfig =
 1205:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
 1206:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
 1207:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
 1208:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
 1209:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
 1210:                 }
 1211:             }
 1212:         }
 1213:     }
 1214:     return;
 1215: }
 1216: 
 1217: sub get_lonbalancer_config {
 1218:     my ($servers) = @_;
 1219:     my ($currbalancer,$currtargets);
 1220:     if (ref($servers) eq 'HASH') {
 1221:         foreach my $server (keys(%{$servers})) {
 1222:             my %what = (
 1223:                          spareid => 1,
 1224:                          perlvar => 1,
 1225:                        );
 1226:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
 1227:             if ($result eq 'ok') {
 1228:                 if (ref($returnhash) eq 'HASH') {
 1229:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
 1230:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
 1231:                             $currbalancer = $server;
 1232:                             $currtargets = {};
 1233:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
 1234:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
 1235:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
 1236:                                 }
 1237:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
 1238:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
 1239:                                 }
 1240:                             }
 1241:                             last;
 1242:                         }
 1243:                     }
 1244:                 }
 1245:             }
 1246:         }
 1247:     }
 1248:     return ($currbalancer,$currtargets);
 1249: }
 1250: 
 1251: sub check_loadbalancing {
 1252:     my ($uname,$udom) = @_;
 1253:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
 1254:         $rule_in_effect,$offloadto,$otherserver);
 1255:     my $lonhost = $perlvar{'lonHostID'};
 1256:     my @hosts = &current_machine_ids();
 1257:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1258:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
 1259:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
 1260:     my $serverhomedom = &host_domain($lonhost);
 1261: 
 1262:     my $cachetime = 60*60*24;
 1263: 
 1264:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1265:         $dom_in_use = $udom;
 1266:         $homeintdom = 1;
 1267:     } else {
 1268:         $dom_in_use = $serverhomedom;
 1269:     }
 1270:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
 1271:     unless (defined($cached)) {
 1272:         my %domconfig =
 1273:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
 1274:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1275:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1276:         }
 1277:     }
 1278:     if (ref($result) eq 'HASH') {
 1279:         ($is_balancer,$currtargets,$currrules) = 
 1280:             &check_balancer_result($result,@hosts);
 1281:         if ($is_balancer) {
 1282:             if (ref($currrules) eq 'HASH') {
 1283:                 if ($homeintdom) {
 1284:                     if ($uname ne '') {
 1285:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
 1286:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
 1287:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
 1288:                                 $rule_in_effect = $currrules->{'_LC_author'};
 1289:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
 1290:                                 $rule_in_effect = $currrules->{'_LC_adv'}
 1291:                             }
 1292:                         }
 1293:                         if ($rule_in_effect eq '') {
 1294:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
 1295:                             if ($userenv{'inststatus'} ne '') {
 1296:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
 1297:                                 my ($othertitle,$usertypes,$types) =
 1298:                                     &Apache::loncommon::sorted_inst_types($udom);
 1299:                                 if (ref($types) eq 'ARRAY') {
 1300:                                     foreach my $type (@{$types}) {
 1301:                                         if (grep(/^\Q$type\E$/,@statuses)) {
 1302:                                             if (exists($currrules->{$type})) {
 1303:                                                 $rule_in_effect = $currrules->{$type};
 1304:                                             }
 1305:                                         }
 1306:                                     }
 1307:                                 }
 1308:                             } else {
 1309:                                 if (exists($currrules->{'default'})) {
 1310:                                     $rule_in_effect = $currrules->{'default'};
 1311:                                 }
 1312:                             }
 1313:                         }
 1314:                     } else {
 1315:                         if (exists($currrules->{'default'})) {
 1316:                             $rule_in_effect = $currrules->{'default'};
 1317:                         }
 1318:                     }
 1319:                 } else {
 1320:                     if ($currrules->{'_LC_external'} ne '') {
 1321:                         $rule_in_effect = $currrules->{'_LC_external'};
 1322:                     }
 1323:                 }
 1324:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1325:                                                        $uname,$udom);
 1326:             }
 1327:         }
 1328:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
 1329:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
 1330:         unless (defined($cached)) {
 1331:             my %domconfig =
 1332:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
 1333:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1334:                 $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1335:             }
 1336:         }
 1337:         if (ref($result) eq 'HASH') {
 1338:             ($is_balancer,$currtargets,$currrules) = 
 1339:                 &check_balancer_result($result,@hosts);
 1340:             if ($is_balancer) {
 1341:                 if (ref($currrules) eq 'HASH') {
 1342:                     if ($currrules->{'_LC_internetdom'} ne '') {
 1343:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
 1344:                     }
 1345:                 }
 1346:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1347:                                                        $uname,$udom);
 1348:             }
 1349:         } else {
 1350:             if ($perlvar{'lonBalancer'} eq 'yes') {
 1351:                 $is_balancer = 1;
 1352:                 $offloadto = &this_host_spares($dom_in_use);
 1353:             }
 1354:         }
 1355:     } else {
 1356:         if ($perlvar{'lonBalancer'} eq 'yes') {
 1357:             $is_balancer = 1;
 1358:             $offloadto = &this_host_spares($dom_in_use);
 1359:         }
 1360:     }
 1361:     if ($is_balancer) {
 1362:         my $lowest_load = 30000;
 1363:         if (ref($offloadto) eq 'HASH') {
 1364:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
 1365:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
 1366:                     ($otherserver,$lowest_load) =
 1367:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1368:                 }
 1369:             }
 1370:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
 1371: 
 1372:             if (!$found_server) {
 1373:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
 1374:                     foreach my $try_server (@{$offloadto->{'default'}}) {
 1375:                         ($otherserver,$lowest_load) =
 1376:                             &compare_server_load($try_server,$otherserver,$lowest_load);
 1377:                     }
 1378:                 }
 1379:             }
 1380:         } elsif (ref($offloadto) eq 'ARRAY') {
 1381:             if (@{$offloadto} == 1) {
 1382:                 $otherserver = $offloadto->[0];
 1383:             } elsif (@{$offloadto} > 1) {
 1384:                 foreach my $try_server (@{$offloadto}) {
 1385:                     ($otherserver,$lowest_load) =
 1386:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1387:                 }
 1388:             }
 1389:         }
 1390:         if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
 1391:             $is_balancer = 0;
 1392:             if ($uname ne '' && $udom ne '') {
 1393:                 if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
 1394:                     
 1395:                     &appenv({'user.loadbalexempt'     => $lonhost,  
 1396:                              'user.loadbalcheck.time' => time});
 1397:                 }
 1398:             }
 1399:         }
 1400:     }
 1401:     return ($is_balancer,$otherserver);
 1402: }
 1403: 
 1404: sub check_balancer_result {
 1405:     my ($result,@hosts) = @_;
 1406:     my ($is_balancer,$currtargets,$currrules);
 1407:     if (ref($result) eq 'HASH') {
 1408:         if ($result->{'lonhost'} ne '') {
 1409:             my $currbalancer = $result->{'lonhost'};
 1410:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
 1411:                 $is_balancer = 1;
 1412:                 $currtargets = $result->{'targets'};
 1413:                 $currrules = $result->{'rules'};
 1414:             }
 1415:         } else {
 1416:             foreach my $key (keys(%{$result})) {
 1417:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
 1418:                     (ref($result->{$key}) eq 'HASH')) {
 1419:                     $is_balancer = 1;
 1420:                     $currrules = $result->{$key}{'rules'};
 1421:                     $currtargets = $result->{$key}{'targets'};
 1422:                     last;
 1423:                 }
 1424:             }
 1425:         }
 1426:     }
 1427:     return ($is_balancer,$currtargets,$currrules);
 1428: }
 1429: 
 1430: sub get_loadbalancer_targets {
 1431:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
 1432:     my $offloadto;
 1433:     if ($rule_in_effect eq 'none') {
 1434:         return [$perlvar{'lonHostID'}];
 1435:     } elsif ($rule_in_effect eq '') {
 1436:         $offloadto = $currtargets;
 1437:     } else {
 1438:         if ($rule_in_effect eq 'homeserver') {
 1439:             my $homeserver = &homeserver($uname,$udom);
 1440:             if ($homeserver ne 'no_host') {
 1441:                 $offloadto = [$homeserver];
 1442:             }
 1443:         } elsif ($rule_in_effect eq 'externalbalancer') {
 1444:             my %domconfig =
 1445:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
 1446:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1447:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
 1448:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
 1449:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
 1450:                     }
 1451:                 }
 1452:             } else {
 1453:                 my %servers = &internet_dom_servers($udom);
 1454:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
 1455:                 if (&hostname($remotebalancer) ne '') {
 1456:                     $offloadto = [$remotebalancer];
 1457:                 }
 1458:             }
 1459:         } elsif (&hostname($rule_in_effect) ne '') {
 1460:             $offloadto = [$rule_in_effect];
 1461:         }
 1462:     }
 1463:     return $offloadto;
 1464: }
 1465: 
 1466: sub internet_dom_servers {
 1467:     my ($dom) = @_;
 1468:     my (%uniqservers,%servers);
 1469:     my $primaryserver = &hostname(&domain($dom,'primary'));
 1470:     my @machinedoms = &machine_domains($primaryserver);
 1471:     foreach my $mdom (@machinedoms) {
 1472:         my %currservers = %servers;
 1473:         my %server = &get_servers($mdom);
 1474:         %servers = (%currservers,%server);
 1475:     }
 1476:     my %by_hostname;
 1477:     foreach my $id (keys(%servers)) {
 1478:         push(@{$by_hostname{$servers{$id}}},$id);
 1479:     }
 1480:     foreach my $hostname (sort(keys(%by_hostname))) {
 1481:         if (@{$by_hostname{$hostname}} > 1) {
 1482:             my $match = 0;
 1483:             foreach my $id (@{$by_hostname{$hostname}}) {
 1484:                 if (&host_domain($id) eq $dom) {
 1485:                     $uniqservers{$id} = $hostname;
 1486:                     $match = 1;
 1487:                 }
 1488:             }
 1489:             unless ($match) {
 1490:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1491:             }
 1492:         } else {
 1493:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1494:         }
 1495:     }
 1496:     return %uniqservers;
 1497: }
 1498: 
 1499: # ---------------------- Find the homebase for a user from domain's lib servers
 1500: 
 1501: my %homecache;
 1502: sub homeserver {
 1503:     my ($uname,$udom,$ignoreBadCache)=@_;
 1504:     my $index="$uname:$udom";
 1505: 
 1506:     if (exists($homecache{$index})) { return $homecache{$index}; }
 1507: 
 1508:     my %servers = &get_servers($udom,'library');
 1509:     foreach my $tryserver (keys(%servers)) {
 1510:         next if ($ignoreBadCache ne 'true' && 
 1511: 		 exists($badServerCache{$tryserver}));
 1512: 
 1513: 	my $answer=reply("home:$udom:$uname",$tryserver);
 1514: 	if ($answer eq 'found') {
 1515: 	    delete($badServerCache{$tryserver}); 
 1516: 	    return $homecache{$index}=$tryserver;
 1517: 	} elsif ($answer eq 'no_host') {
 1518: 	    $badServerCache{$tryserver}=1;
 1519: 	}
 1520:     }    
 1521:     return 'no_host';
 1522: }
 1523: 
 1524: # ------------------------------------- Find the usernames behind a list of IDs
 1525: 
 1526: sub idget {
 1527:     my ($udom,@ids)=@_;
 1528:     my %returnhash=();
 1529:     
 1530:     my %servers = &get_servers($udom,'library');
 1531:     foreach my $tryserver (keys(%servers)) {
 1532: 	my $idlist=join('&',@ids);
 1533: 	$idlist=~tr/A-Z/a-z/; 
 1534: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
 1535: 	my @answer=();
 1536: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
 1537: 	    @answer=split(/\&/,$reply);
 1538: 	}                    ;
 1539: 	my $i;
 1540: 	for ($i=0;$i<=$#ids;$i++) {
 1541: 	    if ($answer[$i]) {
 1542: 		$returnhash{$ids[$i]}=$answer[$i];
 1543: 	    } 
 1544: 	}
 1545:     } 
 1546:     return %returnhash;
 1547: }
 1548: 
 1549: # ------------------------------------- Find the IDs behind a list of usernames
 1550: 
 1551: sub idrget {
 1552:     my ($udom,@unames)=@_;
 1553:     my %returnhash=();
 1554:     foreach my $uname (@unames) {
 1555:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
 1556:     }
 1557:     return %returnhash;
 1558: }
 1559: 
 1560: # ------------------------------- Store away a list of names and associated IDs
 1561: 
 1562: sub idput {
 1563:     my ($udom,%ids)=@_;
 1564:     my %servers=();
 1565:     foreach my $uname (keys(%ids)) {
 1566: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
 1567:         my $uhom=&homeserver($uname,$udom);
 1568:         if ($uhom ne 'no_host') {
 1569:             my $id=&escape($ids{$uname});
 1570:             $id=~tr/A-Z/a-z/;
 1571:             my $esc_unam=&escape($uname);
 1572: 	    if ($servers{$uhom}) {
 1573: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
 1574:             } else {
 1575:                 $servers{$uhom}=$id.'='.$esc_unam;
 1576:             }
 1577:         }
 1578:     }
 1579:     foreach my $server (keys(%servers)) {
 1580:         &critical('idput:'.$udom.':'.$servers{$server},$server);
 1581:     }
 1582: }
 1583: 
 1584: # ---------------------------------------- Delete unwanted IDs from ids.db file 
 1585: 
 1586: sub iddel {
 1587:     my ($udom,$idshashref,$uhome)=@_;
 1588:     my %result=();
 1589:     unless (ref($idshashref) eq 'HASH') {
 1590:         return %result;
 1591:     }
 1592:     my %servers=();
 1593:     while (my ($id,$uname) = each(%{$idshashref})) {
 1594:         my $uhom;
 1595:         if ($uhome) {
 1596:             $uhom = $uhome;
 1597:         } else {
 1598:             $uhom=&homeserver($uname,$udom);
 1599:         }
 1600:         if ($uhom ne 'no_host') {
 1601:             if ($servers{$uhom}) {
 1602:                 $servers{$uhom}.='&'.&escape($id);
 1603:             } else {
 1604:                 $servers{$uhom}=&escape($id);
 1605:             }
 1606:         }
 1607:     }
 1608:     foreach my $server (keys(%servers)) {
 1609:         $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
 1610:     }
 1611:     return %result;
 1612: }
 1613: 
 1614: # ------------------------------dump from db file owned by domainconfig user
 1615: sub dump_dom {
 1616:     my ($namespace, $udom, $regexp) = @_;
 1617: 
 1618:     $udom ||= $env{'user.domain'};
 1619: 
 1620:     return () unless $udom;
 1621: 
 1622:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
 1623: }
 1624: 
 1625: # ------------------------------------------ get items from domain db files   
 1626: 
 1627: sub get_dom {
 1628:     my ($namespace,$storearr,$udom,$uhome)=@_;
 1629:     my $items='';
 1630:     foreach my $item (@$storearr) {
 1631:         $items.=&escape($item).'&';
 1632:     }
 1633:     $items=~s/\&$//;
 1634:     if (!$udom) {
 1635:         $udom=$env{'user.domain'};
 1636:         if (defined(&domain($udom,'primary'))) {
 1637:             $uhome=&domain($udom,'primary');
 1638:         } else {
 1639:             undef($uhome);
 1640:         }
 1641:     } else {
 1642:         if (!$uhome) {
 1643:             if (defined(&domain($udom,'primary'))) {
 1644:                 $uhome=&domain($udom,'primary');
 1645:             }
 1646:         }
 1647:     }
 1648:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1649:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
 1650:         my %returnhash;
 1651:         if ($rep eq '' || $rep =~ /^error: 2 /) {
 1652:             return %returnhash;
 1653:         }
 1654:         my @pairs=split(/\&/,$rep);
 1655:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 1656:             return @pairs;
 1657:         }
 1658:         my $i=0;
 1659:         foreach my $item (@$storearr) {
 1660:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
 1661:             $i++;
 1662:         }
 1663:         return %returnhash;
 1664:     } else {
 1665:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
 1666:     }
 1667: }
 1668: 
 1669: # -------------------------------------------- put items in domain db files 
 1670: 
 1671: sub put_dom {
 1672:     my ($namespace,$storehash,$udom,$uhome)=@_;
 1673:     if (!$udom) {
 1674:         $udom=$env{'user.domain'};
 1675:         if (defined(&domain($udom,'primary'))) {
 1676:             $uhome=&domain($udom,'primary');
 1677:         } else {
 1678:             undef($uhome);
 1679:         }
 1680:     } else {
 1681:         if (!$uhome) {
 1682:             if (defined(&domain($udom,'primary'))) {
 1683:                 $uhome=&domain($udom,'primary');
 1684:             }
 1685:         }
 1686:     } 
 1687:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1688:         my $items='';
 1689:         foreach my $item (keys(%$storehash)) {
 1690:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 1691:         }
 1692:         $items=~s/\&$//;
 1693:         return &reply("putdom:$udom:$namespace:$items",$uhome);
 1694:     } else {
 1695:         &logthis("put_dom failed - no homeserver and/or domain");
 1696:     }
 1697: }
 1698: 
 1699: # --------------------- newput for items in db file owned by domainconfig user
 1700: sub newput_dom {
 1701:     my ($namespace,$storehash,$udom) = @_;
 1702:     my $result;
 1703:     if (!$udom) {
 1704:         $udom=$env{'user.domain'};
 1705:     }
 1706:     if ($udom) {
 1707:         my $uname = &get_domainconfiguser($udom);
 1708:         $result = &newput($namespace,$storehash,$udom,$uname);
 1709:     }
 1710:     return $result;
 1711: }
 1712: 
 1713: # --------------------- delete for items in db file owned by domainconfig user
 1714: sub del_dom {
 1715:     my ($namespace,$storearr,$udom)=@_;
 1716:     if (ref($storearr) eq 'ARRAY') {
 1717:         if (!$udom) {
 1718:             $udom=$env{'user.domain'};
 1719:         }
 1720:         if ($udom) {
 1721:             my $uname = &get_domainconfiguser($udom); 
 1722:             return &del($namespace,$storearr,$udom,$uname);
 1723:         }
 1724:     }
 1725: }
 1726: 
 1727: # ----------------------------------construct domainconfig user for a domain 
 1728: sub get_domainconfiguser {
 1729:     my ($udom) = @_;
 1730:     return $udom.'-domainconfig';
 1731: }
 1732: 
 1733: sub retrieve_inst_usertypes {
 1734:     my ($udom) = @_;
 1735:     my (%returnhash,@order);
 1736:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 1737:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
 1738:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
 1739:         %returnhash = %{$domdefs{'inststatustypes'}};
 1740:         @order = @{$domdefs{'inststatusorder'}};
 1741:     } else {
 1742:         if (defined(&domain($udom,'primary'))) {
 1743:             my $uhome=&domain($udom,'primary');
 1744:             my $rep=&reply("inst_usertypes:$udom",$uhome);
 1745:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
 1746:                 &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
 1747:                 return (\%returnhash,\@order);
 1748:             }
 1749:             my ($hashitems,$orderitems) = split(/:/,$rep); 
 1750:             my @pairs=split(/\&/,$hashitems);
 1751:             foreach my $item (@pairs) {
 1752:                 my ($key,$value)=split(/=/,$item,2);
 1753:                 $key = &unescape($key);
 1754:                 next if ($key =~ /^error: 2 /);
 1755:                 $returnhash{$key}=&thaw_unescape($value);
 1756:             }
 1757:             my @esc_order = split(/\&/,$orderitems);
 1758:             foreach my $item (@esc_order) {
 1759:                 push(@order,&unescape($item));
 1760:             }
 1761:         } else {
 1762:             &logthis("get_dom failed - no primary domain server for $udom");
 1763:         }
 1764:     }
 1765:     return (\%returnhash,\@order);
 1766: }
 1767: 
 1768: sub is_domainimage {
 1769:     my ($url) = @_;
 1770:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
 1771:         if (&domain($1) ne '') {
 1772:             return '1';
 1773:         }
 1774:     }
 1775:     return;
 1776: }
 1777: 
 1778: sub inst_directory_query {
 1779:     my ($srch) = @_;
 1780:     my $udom = $srch->{'srchdomain'};
 1781:     my %results;
 1782:     my $homeserver = &domain($udom,'primary');
 1783:     my $outcome;
 1784:     if ($homeserver ne '') {
 1785: 	my $queryid=&reply("querysend:instdirsearch:".
 1786: 			   &escape($srch->{'srchby'}).':'.
 1787: 			   &escape($srch->{'srchterm'}).':'.
 1788: 			   &escape($srch->{'srchtype'}),$homeserver);
 1789: 	my $host=&hostname($homeserver);
 1790: 	if ($queryid !~/^\Q$host\E\_/) {
 1791: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1792: 	    return;
 1793: 	}
 1794: 	my $response = &get_query_reply($queryid);
 1795: 	my $maxtries = 5;
 1796: 	my $tries = 1;
 1797: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1798: 	    $response = &get_query_reply($queryid);
 1799: 	    $tries ++;
 1800: 	}
 1801: 
 1802:         if (!&error($response) && $response ne 'refused') {
 1803:             if ($response eq 'unavailable') {
 1804:                 $outcome = $response;
 1805:             } else {
 1806:                 $outcome = 'ok';
 1807:                 my @matches = split(/\n/,$response);
 1808:                 foreach my $match (@matches) {
 1809:                     my ($key,$value) = split(/=/,$match);
 1810:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 1811:                 }
 1812:             }
 1813:         }
 1814:     }
 1815:     return ($outcome,%results);
 1816: }
 1817: 
 1818: sub usersearch {
 1819:     my ($srch) = @_;
 1820:     my $dom = $srch->{'srchdomain'};
 1821:     my %results;
 1822:     my %libserv = &all_library();
 1823:     my $query = 'usersearch';
 1824:     foreach my $tryserver (keys(%libserv)) {
 1825:         if (&host_domain($tryserver) eq $dom) {
 1826:             my $host=&hostname($tryserver);
 1827:             my $queryid=
 1828:                 &reply("querysend:".&escape($query).':'.
 1829:                        &escape($srch->{'srchby'}).':'.
 1830:                        &escape($srch->{'srchtype'}).':'.
 1831:                        &escape($srch->{'srchterm'}),$tryserver);
 1832:             if ($queryid !~/^\Q$host\E\_/) {
 1833:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 1834:                 next;
 1835:             }
 1836:             my $reply = &get_query_reply($queryid);
 1837:             my $maxtries = 1;
 1838:             my $tries = 1;
 1839:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 1840:                 $reply = &get_query_reply($queryid);
 1841:                 $tries ++;
 1842:             }
 1843:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 1844:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 1845:             } else {
 1846:                 my @matches;
 1847:                 if ($reply =~ /\n/) {
 1848:                     @matches = split(/\n/,$reply);
 1849:                 } else {
 1850:                     @matches = split(/\&/,$reply);
 1851:                 }
 1852:                 foreach my $match (@matches) {
 1853:                     my ($uname,$udom,%userhash);
 1854:                     foreach my $entry (split(/:/,$match)) {
 1855:                         my ($key,$value) =
 1856:                             map {&unescape($_);} split(/=/,$entry);
 1857:                         $userhash{$key} = $value;
 1858:                         if ($key eq 'username') {
 1859:                             $uname = $value;
 1860:                         } elsif ($key eq 'domain') {
 1861:                             $udom = $value;
 1862:                         }
 1863:                     }
 1864:                     $results{$uname.':'.$udom} = \%userhash;
 1865:                 }
 1866:             }
 1867:         }
 1868:     }
 1869:     return %results;
 1870: }
 1871: 
 1872: sub get_instuser {
 1873:     my ($udom,$uname,$id) = @_;
 1874:     my $homeserver = &domain($udom,'primary');
 1875:     my ($outcome,%results);
 1876:     if ($homeserver ne '') {
 1877:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 1878:                            &escape($id).':'.&escape($udom),$homeserver);
 1879:         my $host=&hostname($homeserver);
 1880:         if ($queryid !~/^\Q$host\E\_/) {
 1881:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1882:             return;
 1883:         }
 1884:         my $response = &get_query_reply($queryid);
 1885:         my $maxtries = 5;
 1886:         my $tries = 1;
 1887:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1888:             $response = &get_query_reply($queryid);
 1889:             $tries ++;
 1890:         }
 1891:         if (!&error($response) && $response ne 'refused') {
 1892:             if ($response eq 'unavailable') {
 1893:                 $outcome = $response;
 1894:             } else {
 1895:                 $outcome = 'ok';
 1896:                 my @matches = split(/\n/,$response);
 1897:                 foreach my $match (@matches) {
 1898:                     my ($key,$value) = split(/=/,$match);
 1899:                     $results{&unescape($key)} = &thaw_unescape($value);
 1900:                 }
 1901:             }
 1902:         }
 1903:     }
 1904:     my %userinfo;
 1905:     if (ref($results{$uname}) eq 'HASH') {
 1906:         %userinfo = %{$results{$uname}};
 1907:     } 
 1908:     return ($outcome,%userinfo);
 1909: }
 1910: 
 1911: sub inst_rulecheck {
 1912:     my ($udom,$uname,$id,$item,$rules) = @_;
 1913:     my %returnhash;
 1914:     if ($udom ne '') {
 1915:         if (ref($rules) eq 'ARRAY') {
 1916:             @{$rules} = map {&escape($_);} (@{$rules});
 1917:             my $rulestr = join(':',@{$rules});
 1918:             my $homeserver=&domain($udom,'primary');
 1919:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1920:                 my $response;
 1921:                 if ($item eq 'username') {                
 1922:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 1923:                                               ':'.&escape($uname).':'.$rulestr,
 1924:                                               $homeserver));
 1925:                 } elsif ($item eq 'id') {
 1926:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 1927:                                               ':'.&escape($id).':'.$rulestr,
 1928:                                               $homeserver));
 1929:                 } elsif ($item eq 'selfcreate') {
 1930:                     $response=&unescape(&reply('instselfcreatecheck:'.
 1931:                                                &escape($udom).':'.&escape($uname).
 1932:                                               ':'.$rulestr,$homeserver));
 1933:                 }
 1934:                 if ($response ne 'refused') {
 1935:                     my @pairs=split(/\&/,$response);
 1936:                     foreach my $item (@pairs) {
 1937:                         my ($key,$value)=split(/=/,$item,2);
 1938:                         $key = &unescape($key);
 1939:                         next if ($key =~ /^error: 2 /);
 1940:                         $returnhash{$key}=&thaw_unescape($value);
 1941:                     }
 1942:                 }
 1943:             }
 1944:         }
 1945:     }
 1946:     return %returnhash;
 1947: }
 1948: 
 1949: sub inst_userrules {
 1950:     my ($udom,$check) = @_;
 1951:     my (%ruleshash,@ruleorder);
 1952:     if ($udom ne '') {
 1953:         my $homeserver=&domain($udom,'primary');
 1954:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1955:             my $response;
 1956:             if ($check eq 'id') {
 1957:                 $response=&reply('instidrules:'.&escape($udom),
 1958:                                  $homeserver);
 1959:             } elsif ($check eq 'email') {
 1960:                 $response=&reply('instemailrules:'.&escape($udom),
 1961:                                  $homeserver);
 1962:             } else {
 1963:                 $response=&reply('instuserrules:'.&escape($udom),
 1964:                                  $homeserver);
 1965:             }
 1966:             if (($response ne 'refused') && ($response ne 'error') && 
 1967:                 ($response ne 'unknown_cmd') && 
 1968:                 ($response ne 'no_such_host')) {
 1969:                 my ($hashitems,$orderitems) = split(/:/,$response);
 1970:                 my @pairs=split(/\&/,$hashitems);
 1971:                 foreach my $item (@pairs) {
 1972:                     my ($key,$value)=split(/=/,$item,2);
 1973:                     $key = &unescape($key);
 1974:                     next if ($key =~ /^error: 2 /);
 1975:                     $ruleshash{$key}=&thaw_unescape($value);
 1976:                 }
 1977:                 my @esc_order = split(/\&/,$orderitems);
 1978:                 foreach my $item (@esc_order) {
 1979:                     push(@ruleorder,&unescape($item));
 1980:                 }
 1981:             }
 1982:         }
 1983:     }
 1984:     return (\%ruleshash,\@ruleorder);
 1985: }
 1986: 
 1987: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 1988: 
 1989: sub get_domain_defaults {
 1990:     my ($domain,$ignore_cache) = @_;
 1991:     return if (($domain eq '') || ($domain eq 'public'));
 1992:     my $cachetime = 60*60*24;
 1993:     unless ($ignore_cache) {
 1994:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 1995:         if (defined($cached)) {
 1996:             if (ref($result) eq 'HASH') {
 1997:                 return %{$result};
 1998:             }
 1999:         }
 2000:     }
 2001:     my %domdefaults;
 2002:     my %domconfig =
 2003:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
 2004:                                   'requestcourses','inststatus',
 2005:                                   'coursedefaults','usersessions',
 2006:                                   'requestauthor'],$domain);
 2007:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 2008:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 2009:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 2010:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 2011:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 2012:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
 2013:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
 2014:     } else {
 2015:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 2016:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 2017:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 2018:     }
 2019:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 2020:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 2021:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 2022:         } else {
 2023:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 2024:         }
 2025:         my @usertools = ('aboutme','blog','webdav','portfolio');
 2026:         foreach my $item (@usertools) {
 2027:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 2028:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 2029:             }
 2030:         }
 2031:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
 2032:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
 2033:         }
 2034:     }
 2035:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 2036:         foreach my $item ('official','unofficial','community') {
 2037:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
 2038:         }
 2039:     }
 2040:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
 2041:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
 2042:     }
 2043:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
 2044:         foreach my $item ('inststatustypes','inststatusorder') {
 2045:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
 2046:         }
 2047:     }
 2048:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
 2049:         $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
 2050:         if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
 2051:             $domdefaults{'officialcredits'} = $domconfig{'coursedefaults'}{'coursecredits'}{'official'};
 2052:             $domdefaults{'unofficialcredits'} = $domconfig{'coursedefaults'}{'coursecredits'}{'unofficial'};
 2053:         }
 2054:         if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
 2055:             $domdefaults{'officialquota'} = $domconfig{'coursedefaults'}{'uploadquota'}{'official'};
 2056:             $domdefaults{'unofficialquota'} = $domconfig{'coursedefaults'}{'uploadquota'}{'unofficial'};
 2057:             $domdefaults{'communityquota'} = $domconfig{'coursedefaults'}{'uploadquota'}{'community'};           
 2058:         }
 2059:     }
 2060:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
 2061:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
 2062:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
 2063:         }
 2064:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
 2065:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
 2066:         }
 2067:     }
 2068:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
 2069:     return %domdefaults;
 2070: }
 2071: 
 2072: # --------------------------------------------------- Assign a key to a student
 2073: 
 2074: sub assign_access_key {
 2075: #
 2076: # a valid key looks like uname:udom#comments
 2077: # comments are being appended
 2078: #
 2079:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 2080:     $kdom=
 2081:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 2082:     $knum=
 2083:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 2084:     $cdom=
 2085:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2086:     $cnum=
 2087:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2088:     $udom=$env{'user.name'} unless (defined($udom));
 2089:     $uname=$env{'user.domain'} unless (defined($uname));
 2090:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 2091:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 2092:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 2093:                                                   # assigned to this person
 2094:                                                   # - this should not happen,
 2095:                                                   # unless something went wrong
 2096:                                                   # the first time around
 2097: # ready to assign
 2098:         $logentry=$1.'; '.$logentry;
 2099:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 2100:                                                  $kdom,$knum) eq 'ok') {
 2101: # key now belongs to user
 2102: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 2103:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 2104:                 &appenv({'environment.'.$envkey => $ckey});
 2105:                 return 'ok';
 2106:             } else {
 2107:                 return 
 2108:   'error: Count not permanently assign key, will need to be re-entered later.';
 2109: 	    }
 2110:         } else {
 2111:             return 'error: Could not assign key, try again later.';
 2112:         }
 2113:     } elsif (!$existing{$ckey}) {
 2114: # the key does not exist
 2115: 	return 'error: The key does not exist';
 2116:     } else {
 2117: # the key is somebody else's
 2118: 	return 'error: The key is already in use';
 2119:     }
 2120: }
 2121: 
 2122: # ------------------------------------------ put an additional comment on a key
 2123: 
 2124: sub comment_access_key {
 2125: #
 2126: # a valid key looks like uname:udom#comments
 2127: # comments are being appended
 2128: #
 2129:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 2130:     $cdom=
 2131:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2132:     $cnum=
 2133:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2134:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2135:     if ($existing{$ckey}) {
 2136:         $existing{$ckey}.='; '.$logentry;
 2137: # ready to assign
 2138:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 2139:                                                  $cdom,$cnum) eq 'ok') {
 2140: 	    return 'ok';
 2141:         } else {
 2142: 	    return 'error: Count not store comment.';
 2143:         }
 2144:     } else {
 2145: # the key does not exist
 2146: 	return 'error: The key does not exist';
 2147:     }
 2148: }
 2149: 
 2150: # ------------------------------------------------------ Generate a set of keys
 2151: 
 2152: sub generate_access_keys {
 2153:     my ($number,$cdom,$cnum,$logentry)=@_;
 2154:     $cdom=
 2155:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2156:     $cnum=
 2157:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2158:     unless (&allowed('mky',$cdom)) { return 0; }
 2159:     unless (($cdom) && ($cnum)) { return 0; }
 2160:     if ($number>10000) { return 0; }
 2161:     sleep(2); # make sure don't get same seed twice
 2162:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 2163:     my $total=0;
 2164:     for (my $i=1;$i<=$number;$i++) {
 2165:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 2166:                   sprintf("%lx",int(100000*rand)).'-'.
 2167:                   sprintf("%lx",int(100000*rand));
 2168:        $newkey=~s/1/g/g; # folks mix up 1 and l
 2169:        $newkey=~s/0/h/g; # and also 0 and O
 2170:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 2171:        if ($existing{$newkey}) {
 2172:            $i--;
 2173:        } else {
 2174: 	  if (&put('accesskeys',
 2175:               { $newkey => '# generated '.localtime().
 2176:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 2177:                            '; '.$logentry },
 2178: 		   $cdom,$cnum) eq 'ok') {
 2179:               $total++;
 2180: 	  }
 2181:        }
 2182:     }
 2183:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 2184:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 2185:     return $total;
 2186: }
 2187: 
 2188: # ------------------------------------------------------- Validate an accesskey
 2189: 
 2190: sub validate_access_key {
 2191:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 2192:     $cdom=
 2193:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2194:     $cnum=
 2195:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2196:     $udom=$env{'user.domain'} unless (defined($udom));
 2197:     $uname=$env{'user.name'} unless (defined($uname));
 2198:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2199:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 2200: }
 2201: 
 2202: # ------------------------------------- Find the section of student in a course
 2203: sub devalidate_getsection_cache {
 2204:     my ($udom,$unam,$courseid)=@_;
 2205:     my $hashid="$udom:$unam:$courseid";
 2206:     &devalidate_cache_new('getsection',$hashid);
 2207: }
 2208: 
 2209: sub courseid_to_courseurl {
 2210:     my ($courseid) = @_;
 2211:     #already url style courseid
 2212:     return $courseid if ($courseid =~ m{^/});
 2213: 
 2214:     if (exists($env{'course.'.$courseid.'.num'})) {
 2215: 	my $cnum = $env{'course.'.$courseid.'.num'};
 2216: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 2217: 	return "/$cdom/$cnum";
 2218:     }
 2219: 
 2220:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 2221:     if (exists($courseinfo{'num'})) {
 2222: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 2223:     }
 2224: 
 2225:     return undef;
 2226: }
 2227: 
 2228: sub getsection {
 2229:     my ($udom,$unam,$courseid)=@_;
 2230:     my $cachetime=1800;
 2231: 
 2232:     my $hashid="$udom:$unam:$courseid";
 2233:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 2234:     if (defined($cached)) { return $result; }
 2235: 
 2236:     my %Pending; 
 2237:     my %Expired;
 2238:     #
 2239:     # Each role can either have not started yet (pending), be active, 
 2240:     #    or have expired.
 2241:     #
 2242:     # If there is an active role, we are done.
 2243:     #
 2244:     # If there is more than one role which has not started yet, 
 2245:     #     choose the one which will start sooner
 2246:     # If there is one role which has not started yet, return it.
 2247:     #
 2248:     # If there is more than one expired role, choose the one which ended last.
 2249:     # If there is a role which has expired, return it.
 2250:     #
 2251:     $courseid = &courseid_to_courseurl($courseid);
 2252:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 2253:     foreach my $key (keys(%roleshash)) {
 2254:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 2255:         my $section=$1;
 2256:         if ($key eq $courseid.'_st') { $section=''; }
 2257:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 2258:         my $now=time;
 2259:         if (defined($end) && $end && ($now > $end)) {
 2260:             $Expired{$end}=$section;
 2261:             next;
 2262:         }
 2263:         if (defined($start) && $start && ($now < $start)) {
 2264:             $Pending{$start}=$section;
 2265:             next;
 2266:         }
 2267:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 2268:     }
 2269:     #
 2270:     # Presumedly there will be few matching roles from the above
 2271:     # loop and the sorting time will be negligible.
 2272:     if (scalar(keys(%Pending))) {
 2273:         my ($time) = sort {$a <=> $b} keys(%Pending);
 2274:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 2275:     } 
 2276:     if (scalar(keys(%Expired))) {
 2277:         my @sorted = sort {$a <=> $b} keys(%Expired);
 2278:         my $time = pop(@sorted);
 2279:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 2280:     }
 2281:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 2282: }
 2283: 
 2284: sub save_cache {
 2285:     &purge_remembered();
 2286:     #&Apache::loncommon::validate_page();
 2287:     undef(%env);
 2288:     undef($env_loaded);
 2289: }
 2290: 
 2291: my $to_remember=-1;
 2292: my %remembered;
 2293: my %accessed;
 2294: my $kicks=0;
 2295: my $hits=0;
 2296: sub make_key {
 2297:     my ($name,$id) = @_;
 2298:     if (length($id) > 65 
 2299: 	&& length(&escape($id)) > 200) {
 2300: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 2301:     }
 2302:     return &escape($name.':'.$id);
 2303: }
 2304: 
 2305: sub devalidate_cache_new {
 2306:     my ($name,$id,$debug) = @_;
 2307:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 2308:     $id=&make_key($name,$id);
 2309:     $memcache->delete($id);
 2310:     delete($remembered{$id});
 2311:     delete($accessed{$id});
 2312: }
 2313: 
 2314: sub is_cached_new {
 2315:     my ($name,$id,$debug) = @_;
 2316:     $id=&make_key($name,$id);
 2317:     if (exists($remembered{$id})) {
 2318: 	if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
 2319: 	$accessed{$id}=[&gettimeofday()];
 2320: 	$hits++;
 2321: 	return ($remembered{$id},1);
 2322:     }
 2323:     my $value = $memcache->get($id);
 2324:     if (!(defined($value))) {
 2325: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 2326: 	return (undef,undef);
 2327:     }
 2328:     if ($value eq '__undef__') {
 2329: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 2330: 	$value=undef;
 2331:     }
 2332:     &make_room($id,$value,$debug);
 2333:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 2334:     return ($value,1);
 2335: }
 2336: 
 2337: sub do_cache_new {
 2338:     my ($name,$id,$value,$time,$debug) = @_;
 2339:     $id=&make_key($name,$id);
 2340:     my $setvalue=$value;
 2341:     if (!defined($setvalue)) {
 2342: 	$setvalue='__undef__';
 2343:     }
 2344:     if (!defined($time) ) {
 2345: 	$time=600;
 2346:     }
 2347:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 2348:     my $result = $memcache->set($id,$setvalue,$time);
 2349:     if (! $result) {
 2350: 	&logthis("caching of id -> $id  failed");
 2351: 	$memcache->disconnect_all();
 2352:     }
 2353:     # need to make a copy of $value
 2354:     &make_room($id,$value,$debug);
 2355:     return $value;
 2356: }
 2357: 
 2358: sub make_room {
 2359:     my ($id,$value,$debug)=@_;
 2360: 
 2361:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
 2362:                                     : $value;
 2363:     if ($to_remember<0) { return; }
 2364:     $accessed{$id}=[&gettimeofday()];
 2365:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 2366:     my $to_kick;
 2367:     my $max_time=0;
 2368:     foreach my $other (keys(%accessed)) {
 2369: 	if (&tv_interval($accessed{$other}) > $max_time) {
 2370: 	    $to_kick=$other;
 2371: 	    $max_time=&tv_interval($accessed{$other});
 2372: 	}
 2373:     }
 2374:     delete($remembered{$to_kick});
 2375:     delete($accessed{$to_kick});
 2376:     $kicks++;
 2377:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 2378:     return;
 2379: }
 2380: 
 2381: sub purge_remembered {
 2382:     #&logthis("Tossing ".scalar(keys(%remembered)));
 2383:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 2384:     undef(%remembered);
 2385:     undef(%accessed);
 2386: }
 2387: # ------------------------------------- Read an entry from a user's environment
 2388: 
 2389: sub userenvironment {
 2390:     my ($udom,$unam,@what)=@_;
 2391:     my $items;
 2392:     foreach my $item (@what) {
 2393:         $items.=&escape($item).'&';
 2394:     }
 2395:     $items=~s/\&$//;
 2396:     my %returnhash=();
 2397:     my $uhome = &homeserver($unam,$udom);
 2398:     unless ($uhome eq 'no_host') {
 2399:         my @answer=split(/\&/, 
 2400:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
 2401:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
 2402:             return %returnhash;
 2403:         }
 2404:         my $i;
 2405:         for ($i=0;$i<=$#what;$i++) {
 2406: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
 2407:         }
 2408:     }
 2409:     return %returnhash;
 2410: }
 2411: 
 2412: # ---------------------------------------------------------- Get a studentphoto
 2413: sub studentphoto {
 2414:     my ($udom,$unam,$ext) = @_;
 2415:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 2416:     if (defined($env{'request.course.id'})) {
 2417:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 2418:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 2419:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 2420:             } else {
 2421:                 my ($result,$perm_reqd)=
 2422: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 2423:                 if ($result eq 'ok') {
 2424:                     if (!($perm_reqd eq 'yes')) {
 2425:                         return(&retrievestudentphoto($udom,$unam,$ext));
 2426:                     }
 2427:                 }
 2428:             }
 2429:         }
 2430:     } else {
 2431:         my ($result,$perm_reqd) = 
 2432: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 2433:         if ($result eq 'ok') {
 2434:             if (!($perm_reqd eq 'yes')) {
 2435:                 return(&retrievestudentphoto($udom,$unam,$ext));
 2436:             }
 2437:         }
 2438:     }
 2439:     return '/adm/lonKaputt/lonlogo_broken.gif';
 2440: }
 2441: 
 2442: sub retrievestudentphoto {
 2443:     my ($udom,$unam,$ext,$type) = @_;
 2444:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 2445:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 2446:     if ($ret eq 'ok') {
 2447:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 2448:         if ($type eq 'thumbnail') {
 2449:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 2450:         }
 2451:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 2452:         return $tokenurl;
 2453:     } else {
 2454:         if ($type eq 'thumbnail') {
 2455:             return '/adm/lonKaputt/genericstudent_tn.gif';
 2456:         } else { 
 2457:             return '/adm/lonKaputt/lonlogo_broken.gif';
 2458:         }
 2459:     }
 2460: }
 2461: 
 2462: # -------------------------------------------------------------------- New chat
 2463: 
 2464: sub chatsend {
 2465:     my ($newentry,$anon,$group)=@_;
 2466:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 2467:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2468:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 2469:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 2470: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 2471: 		   &escape($newentry)).':'.$group,$chome);
 2472: }
 2473: 
 2474: # ------------------------------------------ Find current version of a resource
 2475: 
 2476: sub getversion {
 2477:     my $fname=&clutter(shift);
 2478:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
 2479:     return &currentversion(&filelocation('',$fname));
 2480: }
 2481: 
 2482: sub currentversion {
 2483:     my $fname=shift;
 2484:     my $author=$fname;
 2485:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2486:     my ($udom,$uname)=split(/\//,$author);
 2487:     my $home=&homeserver($uname,$udom);
 2488:     if ($home eq 'no_host') { 
 2489:         return -1; 
 2490:     }
 2491:     my $answer=&reply("currentversion:$fname",$home);
 2492:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 2493: 	return -1;
 2494:     }
 2495:     return $answer;
 2496: }
 2497: 
 2498: #
 2499: # Return special version number of resource if set by override, empty otherwise
 2500: #
 2501: sub usedversion {
 2502:     my $fname=shift;
 2503:     unless ($fname) { $fname=$env{'request.uri'}; }
 2504:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
 2505:     if ($urlversion) { return $urlversion; }
 2506:     return '';
 2507: }
 2508: 
 2509: # ----------------------------- Subscribe to a resource, return URL if possible
 2510: 
 2511: sub subscribe {
 2512:     my $fname=shift;
 2513:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 2514:     $fname=~s/[\n\r]//g;
 2515:     my $author=$fname;
 2516:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2517:     my ($udom,$uname)=split(/\//,$author);
 2518:     my $home=homeserver($uname,$udom);
 2519:     if ($home eq 'no_host') {
 2520:         return 'not_found';
 2521:     }
 2522:     my $answer=reply("sub:$fname",$home);
 2523:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 2524: 	$answer.=' by '.$home;
 2525:     }
 2526:     return $answer;
 2527: }
 2528:     
 2529: # -------------------------------------------------------------- Replicate file
 2530: 
 2531: sub repcopy {
 2532:     my $filename=shift;
 2533:     $filename=~s/\/+/\//g;
 2534:     my $londocroot = $perlvar{'lonDocRoot'};
 2535:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
 2536:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
 2537:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
 2538: 	$filename=~m{^/*(uploaded|editupload)/}) {
 2539: 	return &repcopy_userfile($filename);
 2540:     }
 2541:     $filename=~s/[\n\r]//g;
 2542:     my $transname="$filename.in.transfer";
 2543: # FIXME: this should flock
 2544:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 2545:     my $remoteurl=subscribe($filename);
 2546:     if ($remoteurl =~ /^con_lost by/) {
 2547: 	   &logthis("Subscribe returned $remoteurl: $filename");
 2548:            return 'unavailable';
 2549:     } elsif ($remoteurl eq 'not_found') {
 2550: 	   #&logthis("Subscribe returned not_found: $filename");
 2551: 	   return 'not_found';
 2552:     } elsif ($remoteurl =~ /^rejected by/) {
 2553: 	   &logthis("Subscribe returned $remoteurl: $filename");
 2554:            return 'forbidden';
 2555:     } elsif ($remoteurl eq 'directory') {
 2556:            return 'ok';
 2557:     } else {
 2558:         my $author=$filename;
 2559:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2560:         my ($udom,$uname)=split(/\//,$author);
 2561:         my $home=homeserver($uname,$udom);
 2562:         unless ($home eq $perlvar{'lonHostID'}) {
 2563:            my @parts=split(/\//,$filename);
 2564:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 2565:            if ($path ne "$londocroot/res") {
 2566:                &logthis("Malconfiguration for replication: $filename");
 2567: 	       return 'bad_request';
 2568:            }
 2569:            my $count;
 2570:            for ($count=5;$count<$#parts;$count++) {
 2571:                $path.="/$parts[$count]";
 2572:                if ((-e $path)!=1) {
 2573: 		   mkdir($path,0777);
 2574:                }
 2575:            }
 2576:            my $ua=new LWP::UserAgent;
 2577:            my $request=new HTTP::Request('GET',"$remoteurl");
 2578:            my $response=$ua->request($request,$transname);
 2579:            if ($response->is_error()) {
 2580: 	       unlink($transname);
 2581:                my $message=$response->status_line;
 2582:                &logthis("<font color=\"blue\">WARNING:"
 2583:                        ." LWP get: $message: $filename</font>");
 2584:                return 'unavailable';
 2585:            } else {
 2586: 	       if ($remoteurl!~/\.meta$/) {
 2587:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 2588:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
 2589:                   if ($mresponse->is_error()) {
 2590: 		      unlink($filename.'.meta');
 2591:                       &logthis(
 2592:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 2593:                   }
 2594: 	       }
 2595:                rename($transname,$filename);
 2596:                return 'ok';
 2597:            }
 2598:        }
 2599:     }
 2600: }
 2601: 
 2602: # ------------------------------------------------ Get server side include body
 2603: sub ssi_body {
 2604:     my ($filelink,%form)=@_;
 2605:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 2606:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 2607:     }
 2608:     my $output='';
 2609:     my $response;
 2610:     if ($filelink=~/^https?\:/) {
 2611:        ($output,$response)=&externalssi($filelink);
 2612:     } else {
 2613:        $filelink .= $filelink=~/\?/ ? '&' : '?';
 2614:        $filelink .= 'inhibitmenu=yes';
 2615:        ($output,$response)=&ssi($filelink,%form);
 2616:     }
 2617:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 2618:     $output=~s/^.*?\<body[^\>]*\>//si;
 2619:     $output=~s/\<\/body\s*\>.*?$//si;
 2620:     if (wantarray) {
 2621:         return ($output, $response);
 2622:     } else {
 2623:         return $output;
 2624:     }
 2625: }
 2626: 
 2627: # --------------------------------------------------------- Server Side Include
 2628: 
 2629: sub absolute_url {
 2630:     my ($host_name) = @_;
 2631:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 2632:     if ($host_name eq '') {
 2633: 	$host_name = $ENV{'SERVER_NAME'};
 2634:     }
 2635:     return $protocol.$host_name;
 2636: }
 2637: 
 2638: #
 2639: #   Server side include.
 2640: # Parameters:
 2641: #  fn     Possibly encrypted resource name/id.
 2642: #  form   Hash that describes how the rendering should be done
 2643: #         and other things.
 2644: # Returns:
 2645: #   Scalar context: The content of the response.
 2646: #   Array context:  2 element list of the content and the full response object.
 2647: #     
 2648: sub ssi {
 2649: 
 2650:     my ($fn,%form)=@_;
 2651:     my $ua=new LWP::UserAgent;
 2652:     my $request;
 2653: 
 2654:     $form{'no_update_last_known'}=1;
 2655:     &Apache::lonenc::check_encrypt(\$fn);
 2656:     if (%form) {
 2657:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 2658:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
 2659:     } else {
 2660:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 2661:     }
 2662: 
 2663:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 2664:     my $response= $ua->request($request);
 2665:     my $content = $response->content;
 2666: 
 2667: 
 2668:     if (wantarray) {
 2669: 	return ($content, $response);
 2670:     } else {
 2671: 	return $content;
 2672:     }
 2673: }
 2674: 
 2675: sub externalssi {
 2676:     my ($url)=@_;
 2677:     my $ua=new LWP::UserAgent;
 2678:     my $request=new HTTP::Request('GET',$url);
 2679:     my $response=$ua->request($request);
 2680:     if (wantarray) {
 2681:         return ($response->content, $response);
 2682:     } else {
 2683:         return $response->content;
 2684:     }
 2685: }
 2686: 
 2687: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 2688: 
 2689: sub allowuploaded {
 2690:     my ($srcurl,$url)=@_;
 2691:     $url=&clutter(&declutter($url));
 2692:     my $dir=$url;
 2693:     $dir=~s/\/[^\/]+$//;
 2694:     my %httpref=();
 2695:     my $httpurl=&hreflocation('',$url);
 2696:     $httpref{'httpref.'.$httpurl}=$srcurl;
 2697:     &Apache::lonnet::appenv(\%httpref);
 2698: }
 2699: 
 2700: #
 2701: # Determine if the current user should be able to edit a particular resource,
 2702: # when viewing in course context.
 2703: # (a) When viewing resource used to determine if "Edit" item is included in 
 2704: #     Functions.
 2705: # (b) When displaying folder contents in course editor, used to determine if
 2706: #     "Edit" link will be displayed alongside resource.
 2707: #
 2708: #  input: six args -- filename (decluttered), course number, course domain,
 2709: #                   url, symb (if registered) and group (if this is a group
 2710: #                   item -- e.g., bulletin board, group page etc.).
 2711: #  output: array of five scalars -- 
 2712: #          $cfile -- url for file editing if editable on current server
 2713: #          $home -- homeserver of resource (i.e., for author if published,
 2714: #                                           or course if uploaded.).
 2715: #          $switchserver --  1 if server switch will be needed.
 2716: #          $forceedit -- 1 if icon/link should be to go to edit mode 
 2717: #          $forceview -- 1 if icon/link should be to go to view mode
 2718: #
 2719: 
 2720: sub can_edit_resource {
 2721:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
 2722:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
 2723: #
 2724: # For aboutme pages user can only edit his/her own.
 2725: #
 2726:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
 2727:         my ($sdom,$sname) = ($1,$2);
 2728:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
 2729:             $home = $env{'user.home'};
 2730:             $cfile = $resurl;
 2731:             if ($env{'form.forceedit'}) {
 2732:                 $forceview = 1;
 2733:             } else {
 2734:                 $forceedit = 1;
 2735:             }
 2736:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
 2737:         } else {
 2738:             return;
 2739:         }
 2740:     }
 2741: 
 2742:     if ($env{'request.course.id'}) {
 2743:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
 2744:         if ($group ne '') {
 2745: # if this is a group homepage or group bulletin board, check group privs
 2746:             my $allowed = 0;
 2747:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
 2748:                 if ((&allowed('mdg',$env{'request.course.id'}.
 2749:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 2750:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 2751:                     $allowed = 1;
 2752:                 }
 2753:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
 2754:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 2755:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 2756:                     $allowed = 1;
 2757:                 }
 2758:             }
 2759:             if ($allowed) {
 2760:                 $home=&homeserver($cnum,$cdom);
 2761:                 if ($env{'form.forceedit'}) {
 2762:                     $forceview = 1;
 2763:                 } else {
 2764:                     $forceedit = 1;
 2765:                 }
 2766:                 $cfile = $resurl;
 2767:             } else {
 2768:                 return;
 2769:             }
 2770:         } else {
 2771:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
 2772:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
 2773:                     return;
 2774:                 }
 2775:             } elsif (!$crsedit) {
 2776: #
 2777: # No edit allowed where CC has switched to student role.
 2778: #
 2779:                 return;
 2780:             }
 2781:         }
 2782:     }
 2783: 
 2784:     if ($file ne '') {
 2785:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
 2786:             if (&is_course_upload($file,$cnum,$cdom)) {
 2787:                 $uploaded = 1;
 2788:                 $incourse = 1;
 2789:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
 2790:                     $cfile = &hreflocation('',$file);
 2791:                     if ($env{'form.forceedit'}) {
 2792:                         $forceview = 1;
 2793:                     } else {
 2794:                         $forceedit = 1;
 2795:                     }
 2796:                 }
 2797:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
 2798:                 $incourse = 1;
 2799:                 if ($env{'form.forceedit'}) {
 2800:                     $forceview = 1;
 2801:                 } else {
 2802:                     $forceedit = 1;
 2803:                 }
 2804:                 $cfile = $resurl;
 2805:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
 2806:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
 2807:                     $incourse = 1;
 2808:                     if ($env{'form.forceedit'}) {
 2809:                         $forceview = 1;
 2810:                     } else {
 2811:                         $forceedit = 1;
 2812:                     }
 2813:                     $cfile = $resurl;
 2814:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
 2815:                     $incourse = 1;
 2816:                     $cfile = $resurl.'/smpedit';
 2817:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
 2818:                     $incourse = 1;
 2819:                     if ($env{'form.forceedit'}) {
 2820:                         $forceview = 1;
 2821:                     } else {
 2822:                         $forceedit = 1;
 2823:                     }
 2824:                     $cfile = $resurl;
 2825:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 2826:                     $incourse = 1;
 2827:                     if ($env{'form.forceedit'}) {
 2828:                         $forceview = 1;
 2829:                     } else {
 2830:                         $forceedit = 1;
 2831:                     }
 2832:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 2833:                 }
 2834:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
 2835:                 my $template = '/res/lib/templates/simpleproblem.problem';
 2836:                 if (&is_on_map($template)) { 
 2837:                     $incourse = 1;
 2838:                     $forceview = 1;
 2839:                     $cfile = $template;
 2840:                 }
 2841:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 2842:                     $incourse = 1;
 2843:                     if ($env{'form.forceedit'}) {
 2844:                         $forceview = 1;
 2845:                     } else {
 2846:                         $forceedit = 1;
 2847:                     }
 2848:                     $cfile = $resurl;
 2849:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
 2850:                 $incourse = 1;
 2851:                 $forceview = 1;
 2852:                 if ($symb) {
 2853:                     my ($map,$id,$res)=&decode_symb($symb);
 2854:                     $env{'request.symb'} = $symb;
 2855:                     $cfile = &clutter($res);
 2856:                 } else {
 2857:                     $cfile = $env{'form.suppurl'};
 2858:                     $cfile =~ s{^http://}{};
 2859:                     $cfile = '/adm/wrapper/ext/'.$cfile;
 2860:                 }
 2861:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 2862:                 if ($env{'form.forceedit'}) {
 2863:                     $forceview = 1;
 2864:                 } else {
 2865:                     $forceedit = 1;
 2866:                 }
 2867:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 2868:             }
 2869:         }
 2870:         if ($uploaded || $incourse) {
 2871:             $home=&homeserver($cnum,$cdom);
 2872:         } elsif ($file !~ m{/$}) {
 2873:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
 2874:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
 2875:             # Check that the user has permission to edit this resource
 2876:             my $setpriv = 1;
 2877:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
 2878:             if (defined($cfudom)) {
 2879:                 $home=&homeserver($cfuname,$cfudom);
 2880:                 $cfile=$file;
 2881:             }
 2882:         }
 2883:         if (($cfile ne '') && (!$incourse || $uploaded) && 
 2884:             (($home ne '') && ($home ne 'no_host'))) {
 2885:             my @ids=&current_machine_ids();
 2886:             unless (grep(/^\Q$home\E$/,@ids)) {
 2887:                 $switchserver=1;
 2888:             }
 2889:         }
 2890:     }
 2891:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
 2892: }
 2893: 
 2894: sub is_course_upload {
 2895:     my ($file,$cnum,$cdom) = @_;
 2896:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
 2897:     $uploadpath =~ s{^\/}{};
 2898:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
 2899:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
 2900:         return 1;
 2901:     }
 2902:     return;
 2903: }
 2904: 
 2905: sub in_course {
 2906:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
 2907:     if ($hideprivileged) {
 2908:         my $skipuser;
 2909:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
 2910:         my @possdoms = ($cdom);  
 2911:         if ($coursehash{'checkforpriv'}) { 
 2912:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
 2913:         }
 2914:         if (&privileged($uname,$udom,\@possdoms)) {
 2915:             $skipuser = 1;
 2916:             if ($coursehash{'nothideprivileged'}) {
 2917:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 2918:                     my $user;
 2919:                     if ($item =~ /:/) {
 2920:                         $user = $item;
 2921:                     } else {
 2922:                         $user = join(':',split(/[\@]/,$item));
 2923:                     }
 2924:                     if ($user eq $uname.':'.$udom) {
 2925:                         undef($skipuser);
 2926:                         last;
 2927:                     }
 2928:                 }
 2929:             }
 2930:             if ($skipuser) {
 2931:                 return 0;
 2932:             }
 2933:         }
 2934:     }
 2935:     $type ||= 'any';
 2936:     if (!defined($cdom) || !defined($cnum)) {
 2937:         my $cid  = $env{'request.course.id'};
 2938:         $cdom = $env{'course.'.$cid.'.domain'};
 2939:         $cnum = $env{'course.'.$cid.'.num'};
 2940:     }
 2941:     my $typesref;
 2942:     if (($type eq 'any') || ($type eq 'all')) {
 2943:         $typesref = ['active','previous','future'];
 2944:     } elsif ($type eq 'previous' || $type eq 'future') {
 2945:         $typesref = [$type];
 2946:     }
 2947:     my %roles = &get_my_roles($uname,$udom,'userroles',
 2948:                               $typesref,undef,[$cdom]);
 2949:     my ($tmp) = keys(%roles);
 2950:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
 2951:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
 2952:     if (@course_roles > 0) {
 2953:         return 1;
 2954:     }
 2955:     return 0;
 2956: }
 2957: 
 2958: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 2959: # input: action, courseID, current domain, intended
 2960: #        path to file, source of file, instruction to parse file for objects,
 2961: #        ref to hash for embedded objects,
 2962: #        ref to hash for codebase of java objects.
 2963: #        reference to scalar to accommodate mime type determined
 2964: #          from File::MMagic if $parser = parse.
 2965: #
 2966: # output: url to file (if action was uploaddoc), 
 2967: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 2968: #
 2969: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 2970: # course.
 2971: #
 2972: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2973: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 2974: #          course's home server.
 2975: #
 2976: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 2977: #          be copied from $source (current location) to 
 2978: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2979: #         and will then be copied to
 2980: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 2981: #         course's home server.
 2982: #
 2983: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2984: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 2985: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2986: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 2987: #         in course's home server.
 2988: #
 2989: 
 2990: sub process_coursefile {
 2991:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
 2992:         $mimetype)=@_;
 2993:     my $fetchresult;
 2994:     my $home=&homeserver($docuname,$docudom);
 2995:     if ($action eq 'propagate') {
 2996:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2997: 			     $home);
 2998:     } else {
 2999:         my $fpath = '';
 3000:         my $fname = $file;
 3001:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3002:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3003:         my $filepath = &build_filepath($fpath);
 3004:         if ($action eq 'copy') {
 3005:             if ($source eq '') {
 3006:                 $fetchresult = 'no source file';
 3007:                 return $fetchresult;
 3008:             } else {
 3009:                 my $destination = $filepath.'/'.$fname;
 3010:                 rename($source,$destination);
 3011:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3012:                                  $home);
 3013:             }
 3014:         } elsif ($action eq 'uploaddoc') {
 3015:             open(my $fh,'>'.$filepath.'/'.$fname);
 3016:             print $fh $env{'form.'.$source};
 3017:             close($fh);
 3018:             if ($parser eq 'parse') {
 3019:                 my $mm = new File::MMagic;
 3020:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
 3021:                 if ($type eq 'text/html') {
 3022:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 3023:                     unless ($parse_result eq 'ok') {
 3024:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 3025:                     }
 3026:                 }
 3027:                 if (ref($mimetype)) {
 3028:                     $$mimetype = $type;
 3029:                 } 
 3030:             }
 3031:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3032:                                  $home);
 3033:             if ($fetchresult eq 'ok') {
 3034:                 return '/uploaded/'.$fpath.'/'.$fname;
 3035:             } else {
 3036:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3037:                         ' to host '.$home.': '.$fetchresult);
 3038:                 return '/adm/notfound.html';
 3039:             }
 3040:         }
 3041:     }
 3042:     unless ( $fetchresult eq 'ok') {
 3043:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3044:              ' to host '.$home.': '.$fetchresult);
 3045:     }
 3046:     return $fetchresult;
 3047: }
 3048: 
 3049: sub build_filepath {
 3050:     my ($fpath) = @_;
 3051:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 3052:     unless ($fpath eq '') {
 3053:         my @parts=split('/',$fpath);
 3054:         foreach my $part (@parts) {
 3055:             $filepath.= '/'.$part;
 3056:             if ((-e $filepath)!=1) {
 3057:                 mkdir($filepath,0777);
 3058:             }
 3059:         }
 3060:     }
 3061:     return $filepath;
 3062: }
 3063: 
 3064: sub store_edited_file {
 3065:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 3066:     my $file = $primary_url;
 3067:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 3068:     my $fpath = '';
 3069:     my $fname = $file;
 3070:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3071:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3072:     my $filepath = &build_filepath($fpath);
 3073:     open(my $fh,'>'.$filepath.'/'.$fname);
 3074:     print $fh $content;
 3075:     close($fh);
 3076:     my $home=&homeserver($docuname,$docudom);
 3077:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3078: 			  $home);
 3079:     if ($$fetchresult eq 'ok') {
 3080:         return '/uploaded/'.$fpath.'/'.$fname;
 3081:     } else {
 3082:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3083: 		 ' to host '.$home.': '.$$fetchresult);
 3084:         return '/adm/notfound.html';
 3085:     }
 3086: }
 3087: 
 3088: sub clean_filename {
 3089:     my ($fname,$args)=@_;
 3090: # Replace Windows backslashes by forward slashes
 3091:     $fname=~s/\\/\//g;
 3092:     if (!$args->{'keep_path'}) {
 3093:         # Get rid of everything but the actual filename
 3094: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 3095:     }
 3096: # Replace spaces by underscores
 3097:     $fname=~s/\s+/\_/g;
 3098: # Replace all other weird characters by nothing
 3099:     $fname=~s{[^/\w\.\-]}{}g;
 3100: # Replace all .\d. sequences with _\d. so they no longer look like version
 3101: # numbers
 3102:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 3103:     return $fname;
 3104: }
 3105: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
 3106: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
 3107: # image with the same aspect ratio as the original, but with dimensions which do 
 3108: # not exceed $resizewidth and $resizeheight.
 3109:  
 3110: sub resizeImage {
 3111:     my ($img_path,$resizewidth,$resizeheight) = @_;
 3112:     my $ima = Image::Magick->new;
 3113:     my $resized;
 3114:     if (-e $img_path) {
 3115:         $ima->Read($img_path);
 3116:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
 3117:             my $width = $ima->Get('width');
 3118:             my $height = $ima->Get('height');
 3119:             if ($width > $resizewidth) {
 3120: 	        my $factor = $width/$resizewidth;
 3121:                 my $newheight = $height/$factor;
 3122:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
 3123:                 $resized = 1;
 3124:             }
 3125:         }
 3126:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
 3127:             my $width = $ima->Get('width');
 3128:             my $height = $ima->Get('height');
 3129:             if ($height > $resizeheight) {
 3130:                 my $factor = $height/$resizeheight;
 3131:                 my $newwidth = $width/$factor;
 3132:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
 3133:                 $resized = 1;
 3134:             }
 3135:         }
 3136:         if ($resized) {
 3137:             $ima->Write($img_path);
 3138:         }
 3139:     }
 3140:     return;
 3141: }
 3142: 
 3143: # --------------- Take an uploaded file and put it into the userfiles directory
 3144: # input: $formname - the contents of the file are in $env{"form.$formname"}
 3145: #                    the desired filename is in $env{"form.$formname.filename"}
 3146: #        $context - possible values: coursedoc, existingfile, overwrite, 
 3147: #                                    canceloverwrite, or ''. 
 3148: #                   if 'coursedoc': upload to the current course
 3149: #                   if 'existingfile': write file to tmp/overwrites directory 
 3150: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
 3151: #                   $context is passed as argument to &finishuserfileupload
 3152: #        $subdir - directory in userfile to store the file into
 3153: #        $parser - instruction to parse file for objects ($parser = parse)    
 3154: #        $allfiles - reference to hash for embedded objects
 3155: #        $codebase - reference to hash for codebase of java objects
 3156: #        $desuname - username for permanent storage of uploaded file
 3157: #        $dsetudom - domain for permanaent storage of uploaded file
 3158: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 3159: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 3160: #        $resizewidth - width (pixels) to which to resize uploaded image
 3161: #        $resizeheight - height (pixels) to which to resize uploaded image
 3162: #        $mimetype - reference to scalar to accommodate mime type determined
 3163: #                    from File::MMagic.
 3164: # 
 3165: # output: url of file in userspace, or error: <message> 
 3166: #             or /adm/notfound.html if failure to upload occurse
 3167: 
 3168: sub userfileupload {
 3169:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
 3170:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
 3171:     if (!defined($subdir)) { $subdir='unknown'; }
 3172:     my $fname=$env{'form.'.$formname.'.filename'};
 3173:     $fname=&clean_filename($fname);
 3174:     # See if there is anything left
 3175:     unless ($fname) { return 'error: no uploaded file'; }
 3176:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
 3177:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
 3178:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
 3179:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3180:         my $now = time;
 3181:         my $filepath;
 3182:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
 3183:              $filepath = 'tmp/helprequests/'.$now;
 3184:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
 3185:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 3186:                          '_'.$env{'user.domain'}.'/pending';
 3187:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3188:             my ($docuname,$docudom);
 3189:             if ($destudom) {
 3190:                 $docudom = $destudom;
 3191:             } else {
 3192:                 $docudom = $env{'user.domain'};
 3193:             }
 3194:             if ($destuname) {
 3195:                 $docuname = $destuname;
 3196:             } else {
 3197:                 $docuname = $env{'user.name'};
 3198:             }
 3199:             if (exists($env{'form.group'})) {
 3200:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3201:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3202:             }
 3203:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
 3204:             if ($context eq 'canceloverwrite') {
 3205:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
 3206:                 if (-e  $tempfile) {
 3207:                     my @info = stat($tempfile);
 3208:                     if ($info[9] eq $env{'form.timestamp'}) {
 3209:                         unlink($tempfile);
 3210:                     }
 3211:                 }
 3212:                 return;
 3213:             }
 3214:         }
 3215:         # Create the directory if not present
 3216:         my @parts=split(/\//,$filepath);
 3217:         my $fullpath = $perlvar{'lonDaemons'};
 3218:         for (my $i=0;$i<@parts;$i++) {
 3219:             $fullpath .= '/'.$parts[$i];
 3220:             if ((-e $fullpath)!=1) {
 3221:                 mkdir($fullpath,0777);
 3222:             }
 3223:         }
 3224:         open(my $fh,'>'.$fullpath.'/'.$fname);
 3225:         print $fh $env{'form.'.$formname};
 3226:         close($fh);
 3227:         if ($context eq 'existingfile') {
 3228:             my @info = stat($fullpath.'/'.$fname);
 3229:             return ($fullpath.'/'.$fname,$info[9]);
 3230:         } else {
 3231:             return $fullpath.'/'.$fname;
 3232:         }
 3233:     }
 3234:     if ($subdir eq 'scantron') {
 3235:         $fname = 'scantron_orig_'.$fname;
 3236:     } else {
 3237:         $fname="$subdir/$fname";
 3238:     }
 3239:     if ($context eq 'coursedoc') {
 3240: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3241: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3242:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 3243:             return &finishuserfileupload($docuname,$docudom,
 3244: 					 $formname,$fname,$parser,$allfiles,
 3245: 					 $codebase,$thumbwidth,$thumbheight,
 3246:                                          $resizewidth,$resizeheight,$context,$mimetype);
 3247:         } else {
 3248:             if ($env{'form.folder'}) {
 3249:                 $fname=$env{'form.folder'}.'/'.$fname;
 3250:             }
 3251:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 3252: 				       $fname,$formname,$parser,
 3253: 				       $allfiles,$codebase,$mimetype);
 3254:         }
 3255:     } elsif (defined($destuname)) {
 3256:         my $docuname=$destuname;
 3257:         my $docudom=$destudom;
 3258: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 3259: 				     $parser,$allfiles,$codebase,
 3260:                                      $thumbwidth,$thumbheight,
 3261:                                      $resizewidth,$resizeheight,$context,$mimetype);
 3262:     } else {
 3263:         my $docuname=$env{'user.name'};
 3264:         my $docudom=$env{'user.domain'};
 3265:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
 3266:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3267:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3268:         }
 3269: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 3270: 				     $parser,$allfiles,$codebase,
 3271:                                      $thumbwidth,$thumbheight,
 3272:                                      $resizewidth,$resizeheight,$context,$mimetype);
 3273:     }
 3274: }
 3275: 
 3276: sub finishuserfileupload {
 3277:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 3278:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
 3279:     my $path=$docudom.'/'.$docuname.'/';
 3280:     my $filepath=$perlvar{'lonDocRoot'};
 3281:   
 3282:     my ($fnamepath,$file,$fetchthumb);
 3283:     $file=$fname;
 3284:     if ($fname=~m|/|) {
 3285:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 3286: 	$path.=$fnamepath.'/';
 3287:     }
 3288:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 3289:     my $count;
 3290:     for ($count=4;$count<=$#parts;$count++) {
 3291:         $filepath.="/$parts[$count]";
 3292:         if ((-e $filepath)!=1) {
 3293: 	    mkdir($filepath,0777);
 3294:         }
 3295:     }
 3296: 
 3297: # Save the file
 3298:     {
 3299: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
 3300: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 3301: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 3302: 	    return '/adm/notfound.html';
 3303: 	}
 3304:         if ($context eq 'overwrite') {
 3305:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
 3306:             my $target = $filepath.'/'.$file;
 3307:             if (-e $source) {
 3308:                 my @info = stat($source);
 3309:                 if ($info[9] eq $env{'form.timestamp'}) {   
 3310:                     unless (&File::Copy::move($source,$target)) {
 3311:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
 3312:                         return "Moving from $source failed";
 3313:                     }
 3314:                 } else {
 3315:                     return "Temporary file: $source had unexpected date/time for last modification";
 3316:                 }
 3317:             } else {
 3318:                 return "Temporary file: $source missing";
 3319:             }
 3320:         } elsif (!print FH ($env{'form.'.$formname})) {
 3321: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 3322: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 3323: 	    return '/adm/notfound.html';
 3324: 	}
 3325: 	close(FH);
 3326:         if ($resizewidth && $resizeheight) {
 3327:             my $mm = new File::MMagic;
 3328:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
 3329:             if ($mime_type =~ m{^image/}) {
 3330: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
 3331:             }  
 3332: 	}
 3333:     }
 3334:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
 3335:         if (ref($mimetype)) {
 3336:             if ($$mimetype eq '') {
 3337:                 my $mm = new File::MMagic;
 3338:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
 3339:                 $$mimetype = $type;
 3340:             }
 3341:         }
 3342:     }
 3343:     if ($parser eq 'parse') {
 3344:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
 3345:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
 3346:                                                        $allfiles,$codebase);
 3347:             unless ($parse_result eq 'ok') {
 3348:                 &logthis('Failed to parse '.$filepath.$file.
 3349: 	   	         ' for embedded media: '.$parse_result); 
 3350:             }
 3351:         }
 3352:     }
 3353:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 3354:         my $input = $filepath.'/'.$file;
 3355:         my $output = $filepath.'/'.'tn-'.$file;
 3356:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 3357:         system("convert -sample $thumbsize $input $output");
 3358:         if (-e $filepath.'/'.'tn-'.$file) {
 3359:             $fetchthumb  = 1; 
 3360:         }
 3361:     }
 3362:  
 3363: # Notify homeserver to grep it
 3364: #
 3365:     my $docuhome=&homeserver($docuname,$docudom);	
 3366:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 3367:     if ($fetchresult eq 'ok') {
 3368:         if ($fetchthumb) {
 3369:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 3370:             if ($thumbresult ne 'ok') {
 3371:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 3372:                          $docuhome.': '.$thumbresult);
 3373:             }
 3374:         }
 3375: #
 3376: # Return the URL to it
 3377:         return '/uploaded/'.$path.$file;
 3378:     } else {
 3379:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 3380: 		 ': '.$fetchresult);
 3381:         return '/adm/notfound.html';
 3382:     }
 3383: }
 3384: 
 3385: sub extract_embedded_items {
 3386:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 3387:     my @state = ();
 3388:     my (%lastids,%related,%shockwave,%flashvars);
 3389:     my %javafiles = (
 3390:                       codebase => '',
 3391:                       code => '',
 3392:                       archive => ''
 3393:                     );
 3394:     my %mediafiles = (
 3395:                       src => '',
 3396:                       movie => '',
 3397:                      );
 3398:     my $p;
 3399:     if ($content) {
 3400:         $p = HTML::LCParser->new($content);
 3401:     } else {
 3402:         $p = HTML::LCParser->new($fullpath);
 3403:     }
 3404:     while (my $t=$p->get_token()) {
 3405: 	if ($t->[0] eq 'S') {
 3406: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 3407: 	    push(@state, $tagname);
 3408:             if (lc($tagname) eq 'allow') {
 3409:                 &add_filetype($allfiles,$attr->{'src'},'src');
 3410:             }
 3411: 	    if (lc($tagname) eq 'img') {
 3412: 		&add_filetype($allfiles,$attr->{'src'},'src');
 3413: 	    }
 3414: 	    if (lc($tagname) eq 'a') {
 3415:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
 3416:                     &add_filetype($allfiles,$attr->{'href'},'href');
 3417:                 }
 3418: 	    }
 3419:             if (lc($tagname) eq 'script') {
 3420:                 my $src;
 3421:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 3422:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 3423:                 } else {
 3424:                     if ($attr->{'src'} ne '') {
 3425:                         $src = $attr->{'src'};
 3426:                         &add_filetype($allfiles,$src,'src');
 3427:                     }
 3428:                 }
 3429:                 my $text = $p->get_trimmed_text();
 3430:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
 3431:                     my @swfargs = split(/,/,$1);
 3432:                     foreach my $item (@swfargs) {
 3433:                         $item =~ s/["']//g;
 3434:                         $item =~ s/^\s+//;
 3435:                         $item =~ s/\s+$//;
 3436:                     }
 3437:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
 3438:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
 3439:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
 3440:                         } else {
 3441:                             $related{$swfargs[0]} = [$swfargs[2]];
 3442:                         }
 3443:                     }
 3444:                 }
 3445:             }
 3446:             if (lc($tagname) eq 'link') {
 3447:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 3448:                     &add_filetype($allfiles,$attr->{'href'},'href');
 3449:                 }
 3450:             }
 3451: 	    if (lc($tagname) eq 'object' ||
 3452: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 3453: 		foreach my $item (keys(%javafiles)) {
 3454: 		    $javafiles{$item} = '';
 3455: 		}
 3456:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
 3457:                     $lastids{lc($tagname)} = $attr->{'id'};
 3458:                 }
 3459: 	    }
 3460: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 3461: 		my $name = lc($attr->{'name'});
 3462: 		foreach my $item (keys(%javafiles)) {
 3463: 		    if ($name eq $item) {
 3464: 			$javafiles{$item} = $attr->{'value'};
 3465: 			last;
 3466: 		    }
 3467: 		}
 3468:                 my $pathfrom;
 3469: 		foreach my $item (keys(%mediafiles)) {
 3470: 		    if ($name eq $item) {
 3471:                         $pathfrom = $attr->{'value'};
 3472:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
 3473: 			&add_filetype($allfiles,$pathfrom,$name);
 3474: 			last;
 3475: 		    }
 3476: 		}
 3477:                 if ($name eq 'flashvars') {
 3478:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
 3479:                 }
 3480:                 if ($pathfrom ne '') {
 3481:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
 3482:                                          $pathfrom);
 3483:                 }
 3484: 	    }
 3485: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 3486: 		foreach my $item (keys(%javafiles)) {
 3487: 		    if ($attr->{$item}) {
 3488: 			$javafiles{$item} = $attr->{$item};
 3489: 			last;
 3490: 		    }
 3491: 		}
 3492: 		foreach my $item (keys(%mediafiles)) {
 3493: 		    if ($attr->{$item}) {
 3494: 			&add_filetype($allfiles,$attr->{$item},$item);
 3495: 			last;
 3496: 		    }
 3497: 		}
 3498:                 if (lc($tagname) eq 'embed') {
 3499:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
 3500:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
 3501:                                              $attr->{'src'});
 3502:                     }
 3503:                 }
 3504: 	    }
 3505:             if ($t->[4] =~ m{/>$}) {
 3506:                 pop(@state);  
 3507:             }
 3508: 	} elsif ($t->[0] eq 'E') {
 3509: 	    my ($tagname) = ($t->[1]);
 3510: 	    if ($javafiles{'codebase'} ne '') {
 3511: 		$javafiles{'codebase'} .= '/';
 3512: 	    }  
 3513: 	    if (lc($tagname) eq 'applet' ||
 3514: 		lc($tagname) eq 'object' ||
 3515: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 3516: 		) {
 3517: 		foreach my $item (keys(%javafiles)) {
 3518: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 3519: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 3520: 			&add_filetype($allfiles,$file,$item);
 3521: 		    }
 3522: 		}
 3523: 	    } 
 3524: 	    pop @state;
 3525: 	}
 3526:     }
 3527:     foreach my $id (sort(keys(%flashvars))) {
 3528:         if ($shockwave{$id} ne '') {
 3529:             my @pairs = split(/\&/,$flashvars{$id});
 3530:             foreach my $pair (@pairs) {
 3531:                 my ($key,$value) = split(/\=/,$pair);
 3532:                 if ($key eq 'thumb') {
 3533:                     &add_filetype($allfiles,$value,$key);
 3534:                 } elsif ($key eq 'content') {
 3535:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
 3536:                     my ($ext) = ($value =~ /\.([^.]+)$/);
 3537:                     if ($ext ne '') {
 3538:                         &add_filetype($allfiles,$path.$value,$ext);
 3539:                     }
 3540:                 }
 3541:             }
 3542:         }
 3543:     }
 3544:     return 'ok';
 3545: }
 3546: 
 3547: sub add_filetype {
 3548:     my ($allfiles,$file,$type)=@_;
 3549:     if (exists($allfiles->{$file})) {
 3550: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 3551: 	    push(@{$allfiles->{$file}}, &escape($type));
 3552: 	}
 3553:     } else {
 3554: 	@{$allfiles->{$file}} = (&escape($type));
 3555:     }
 3556: }
 3557: 
 3558: sub embedded_dependency {
 3559:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
 3560:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
 3561:         if (($identifier ne '') &&
 3562:             (ref($related->{$identifier}) eq 'ARRAY') &&
 3563:             ($pathfrom ne '')) {
 3564:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
 3565:             foreach my $dep (@{$related->{$identifier}}) {
 3566:                 &add_filetype($allfiles,$path.$dep,'object');
 3567:             }
 3568:         }
 3569:     }
 3570:     return;
 3571: }
 3572: 
 3573: sub removeuploadedurl {
 3574:     my ($url)=@_;	
 3575:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 3576:     return &removeuserfile($uname,$udom,$fname);
 3577: }
 3578: 
 3579: sub removeuserfile {
 3580:     my ($docuname,$docudom,$fname)=@_;
 3581:     my $home=&homeserver($docuname,$docudom);    
 3582:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 3583:     if ($result eq 'ok') {	
 3584:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 3585:             my $metafile = $fname.'.meta';
 3586:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 3587: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 3588:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 3589:             my $sqlresult = 
 3590:                 &update_portfolio_table($docuname,$docudom,$file,
 3591:                                         'portfolio_metadata',$group,
 3592:                                         'delete');
 3593:         }
 3594:     }
 3595:     return $result;
 3596: }
 3597: 
 3598: sub mkdiruserfile {
 3599:     my ($docuname,$docudom,$dir)=@_;
 3600:     my $home=&homeserver($docuname,$docudom);
 3601:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 3602: }
 3603: 
 3604: sub renameuserfile {
 3605:     my ($docuname,$docudom,$old,$new)=@_;
 3606:     my $home=&homeserver($docuname,$docudom);
 3607:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 3608:                         &escape("$old").':'.&escape("$new"),$home);
 3609:     if ($result eq 'ok') {
 3610:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 3611:             my $oldmeta = $old.'.meta';
 3612:             my $newmeta = $new.'.meta';
 3613:             my $metaresult = 
 3614:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 3615: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 3616:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 3617:             my $sqlresult = 
 3618:                 &update_portfolio_table($docuname,$docudom,$file,
 3619:                                         'portfolio_metadata',$group,
 3620:                                         'delete');
 3621:         }
 3622:     }
 3623:     return $result;
 3624: }
 3625: 
 3626: # ------------------------------------------------------------------------- Log
 3627: 
 3628: sub log {
 3629:     my ($dom,$nam,$hom,$what)=@_;
 3630:     return critical("log:$dom:$nam:$what",$hom);
 3631: }
 3632: 
 3633: # ------------------------------------------------------------------ Course Log
 3634: #
 3635: # This routine flushes several buffers of non-mission-critical nature
 3636: #
 3637: 
 3638: sub flushcourselogs {
 3639:     &logthis('Flushing log buffers');
 3640: #
 3641: # course logs
 3642: # This is a log of all transactions in a course, which can be used
 3643: # for data mining purposes
 3644: #
 3645: # It also collects the courseid database, which lists last transaction
 3646: # times and course titles for all courseids
 3647: #
 3648:     my %courseidbuffer=();
 3649:     foreach my $crsid (keys(%courselogs)) {
 3650:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 3651: 		          &escape($courselogs{$crsid}),
 3652: 		          $coursehombuf{$crsid}) eq 'ok') {
 3653: 	    delete $courselogs{$crsid};
 3654:         } else {
 3655:             &logthis('Failed to flush log buffer for '.$crsid);
 3656:             if (length($courselogs{$crsid})>40000) {
 3657:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 3658:                         " exceeded maximum size, deleting.</font>");
 3659:                delete $courselogs{$crsid};
 3660:             }
 3661:         }
 3662:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 3663:             'description' => $coursedescrbuf{$crsid},
 3664:             'inst_code'    => $courseinstcodebuf{$crsid},
 3665:             'type'        => $coursetypebuf{$crsid},
 3666:             'owner'       => $courseownerbuf{$crsid},
 3667:         };
 3668:     }
 3669: #
 3670: # Write course id database (reverse lookup) to homeserver of courses 
 3671: # Is used in pickcourse
 3672: #
 3673:     foreach my $crs_home (keys(%courseidbuffer)) {
 3674:         my $response = &courseidput(&host_domain($crs_home),
 3675:                                     $courseidbuffer{$crs_home},
 3676:                                     $crs_home,'timeonly');
 3677:     }
 3678: #
 3679: # File accesses
 3680: # Writes to the dynamic metadata of resources to get hit counts, etc.
 3681: #
 3682:     foreach my $entry (keys(%accesshash)) {
 3683:         if ($entry =~ /___count$/) {
 3684:             my ($dom,$name);
 3685:             ($dom,$name,undef)=
 3686: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 3687:             if (! defined($dom) || $dom eq '' || 
 3688:                 ! defined($name) || $name eq '') {
 3689:                 my $cid = $env{'request.course.id'};
 3690:                 $dom  = $env{'request.'.$cid.'.domain'};
 3691:                 $name = $env{'request.'.$cid.'.num'};
 3692:             }
 3693:             my $value = $accesshash{$entry};
 3694:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 3695:             my %temphash=($url => $value);
 3696:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 3697:             if ($result eq 'ok') {
 3698:                 delete $accesshash{$entry};
 3699:             }
 3700:         } else {
 3701:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 3702:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
 3703:             my %temphash=($entry => $accesshash{$entry});
 3704:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 3705:                 delete $accesshash{$entry};
 3706:             }
 3707:         }
 3708:     }
 3709: #
 3710: # Roles
 3711: # Reverse lookup of user roles for course faculty/staff and co-authorship
 3712: #
 3713:     foreach my $entry (keys(%userrolehash)) {
 3714:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 3715: 	    split(/\:/,$entry);
 3716:         if (&Apache::lonnet::put('nohist_userroles',
 3717:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 3718:                 $rudom,$runame) eq 'ok') {
 3719: 	    delete $userrolehash{$entry};
 3720:         }
 3721:     }
 3722: #
 3723: # Reverse lookup of domain roles (dc, ad, li, sc, au)
 3724: #
 3725:     my %domrolebuffer = ();
 3726:     foreach my $entry (keys(%domainrolehash)) {
 3727:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 3728:         if ($domrolebuffer{$rudom}) {
 3729:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 3730:                       '='.&escape($domainrolehash{$entry});
 3731:         } else {
 3732:             $domrolebuffer{$rudom}.=&escape($entry).
 3733:                       '='.&escape($domainrolehash{$entry});
 3734:         }
 3735:         delete $domainrolehash{$entry};
 3736:     }
 3737:     foreach my $dom (keys(%domrolebuffer)) {
 3738: 	my %servers = &get_servers($dom,'library');
 3739: 	foreach my $tryserver (keys(%servers)) {
 3740: 	    unless (&reply('domroleput:'.$dom.':'.
 3741: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
 3742: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 3743: 	    }
 3744:         }
 3745:     }
 3746:     $dumpcount++;
 3747: }
 3748: 
 3749: sub courselog {
 3750:     my $what=shift;
 3751:     $what=time.':'.$what;
 3752:     unless ($env{'request.course.id'}) { return ''; }
 3753:     $coursedombuf{$env{'request.course.id'}}=
 3754:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 3755:     $coursenumbuf{$env{'request.course.id'}}=
 3756:        $env{'course.'.$env{'request.course.id'}.'.num'};
 3757:     $coursehombuf{$env{'request.course.id'}}=
 3758:        $env{'course.'.$env{'request.course.id'}.'.home'};
 3759:     $coursedescrbuf{$env{'request.course.id'}}=
 3760:        $env{'course.'.$env{'request.course.id'}.'.description'};
 3761:     $courseinstcodebuf{$env{'request.course.id'}}=
 3762:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 3763:     $courseownerbuf{$env{'request.course.id'}}=
 3764:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 3765:     $coursetypebuf{$env{'request.course.id'}}=
 3766:        $env{'course.'.$env{'request.course.id'}.'.type'};
 3767:     if (defined $courselogs{$env{'request.course.id'}}) {
 3768: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 3769:     } else {
 3770: 	$courselogs{$env{'request.course.id'}}.=$what;
 3771:     }
 3772:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 3773: 	&flushcourselogs();
 3774:     }
 3775: }
 3776: 
 3777: sub courseacclog {
 3778:     my $fnsymb=shift;
 3779:     unless ($env{'request.course.id'}) { return ''; }
 3780:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 3781:     if ($fnsymb=~/$LONCAPA::assess_re/) {
 3782:         $what.=':POST';
 3783:         # FIXME: Probably ought to escape things....
 3784: 	foreach my $key (keys(%env)) {
 3785:             if ($key=~/^form\.(.*)/) {
 3786:                 my $formitem = $1;
 3787:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 3788:                     $what.=':'.$formitem.'='.$env{$key};
 3789:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 3790:                     $what.=':'.$formitem.'='.$env{$key};
 3791:                 }
 3792:             }
 3793:         }
 3794:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 3795:         # FIXME: We should not be depending on a form parameter that someone
 3796:         # editing lonsearchcat.pm might change in the future.
 3797:         if ($env{'form.phase'} eq 'course_search') {
 3798:             $what.= ':POST';
 3799:             # FIXME: Probably ought to escape things....
 3800:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 3801:                                  'crsdiscuss') {
 3802:                 $what.=':'.$element.'='.$env{'form.'.$element};
 3803:             }
 3804:         }
 3805:     }
 3806:     &courselog($what);
 3807: }
 3808: 
 3809: sub countacc {
 3810:     my $url=&declutter(shift);
 3811:     return if (! defined($url) || $url eq '');
 3812:     unless ($env{'request.course.id'}) { return ''; }
 3813: #
 3814: # Mark that this url was used in this course
 3815: #
 3816:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 3817: #
 3818: # Increase the access count for this resource in this child process
 3819: #
 3820:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 3821:     $accesshash{$key}++;
 3822: }
 3823: 
 3824: sub linklog {
 3825:     my ($from,$to)=@_;
 3826:     $from=&declutter($from);
 3827:     $to=&declutter($to);
 3828:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 3829:     $accesshash{$to.'___'.$from.'___goto'}=1;
 3830: }
 3831: 
 3832: sub statslog {
 3833:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
 3834:     if ($users<2) { return; }
 3835:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
 3836:             'course'       => $env{'request.course.id'},
 3837:             'sections'     => '"all"',
 3838:             'num_students' => $users,
 3839:             'part'         => $part,
 3840:             'symb'         => $symb,
 3841:             'mean_tries'   => $av_attempts,
 3842:             'deg_of_diff'  => $degdiff});
 3843:     foreach my $key (keys(%dynstore)) {
 3844:         $accesshash{$key}=$dynstore{$key};
 3845:     }
 3846: }
 3847:   
 3848: sub userrolelog {
 3849:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 3850:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
 3851:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 3852:        $userrolehash
 3853:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 3854:                     =$tend.':'.$tstart;
 3855:     }
 3856:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
 3857:        $userrolehash
 3858:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 3859:                     =$tend.':'.$tstart;
 3860:     }
 3861:     if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
 3862:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 3863:        $domainrolehash
 3864:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 3865:                     = $tend.':'.$tstart;
 3866:     }
 3867: }
 3868: 
 3869: sub courserolelog {
 3870:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 3871:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 3872:         my $cdom = $1;
 3873:         my $cnum = $2;
 3874:         my $sec = $3;
 3875:         my $namespace = 'rolelog';
 3876:         my %storehash = (
 3877:                            role    => $trole,
 3878:                            start   => $tstart,
 3879:                            end     => $tend,
 3880:                            selfenroll => $selfenroll,
 3881:                            context    => $context,
 3882:                         );
 3883:         if ($trole eq 'gr') {
 3884:             $namespace = 'groupslog';
 3885:             $storehash{'group'} = $sec;
 3886:         } else {
 3887:             $storehash{'section'} = $sec;
 3888:         }
 3889:         &write_log('course',$namespace,\%storehash,$delflag,$username,
 3890:                    $domain,$cnum,$cdom);
 3891:         if (($trole ne 'st') || ($sec ne '')) {
 3892:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 3893:         }
 3894:     }
 3895:     return;
 3896: }
 3897: 
 3898: sub domainrolelog {
 3899:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 3900:     if ($area =~ m{^/($match_domain)/$}) {
 3901:         my $cdom = $1;
 3902:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
 3903:         my $namespace = 'rolelog';
 3904:         my %storehash = (
 3905:                            role    => $trole,
 3906:                            start   => $tstart,
 3907:                            end     => $tend,
 3908:                            context => $context,
 3909:                         );
 3910:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
 3911:                    $domain,$domconfiguser,$cdom);
 3912:     }
 3913:     return;
 3914: 
 3915: }
 3916: 
 3917: sub coauthorrolelog {
 3918:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 3919:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
 3920:         my $audom = $1;
 3921:         my $auname = $2;
 3922:         my $namespace = 'rolelog';
 3923:         my %storehash = (
 3924:                            role    => $trole,
 3925:                            start   => $tstart,
 3926:                            end     => $tend,
 3927:                            context => $context,
 3928:                         );
 3929:         &write_log('author',$namespace,\%storehash,$delflag,$username,
 3930:                    $domain,$auname,$audom);
 3931:     }
 3932:     return;
 3933: }
 3934: 
 3935: sub get_course_adv_roles {
 3936:     my ($cid,$codes) = @_;
 3937:     $cid=$env{'request.course.id'} unless (defined($cid));
 3938:     my %coursehash=&coursedescription($cid);
 3939:     my $crstype = &Apache::loncommon::course_type($cid);
 3940:     my %nothide=();
 3941:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3942:         if ($user !~ /:/) {
 3943: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 3944:         } else {
 3945:             $nothide{$user}=1;
 3946:         }
 3947:     }
 3948:     my @possdoms = ($coursehash{'domain'});
 3949:     if ($coursehash{'checkforpriv'}) {
 3950:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
 3951:     }
 3952:     my %returnhash=();
 3953:     my %dumphash=
 3954:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 3955:     my $now=time;
 3956:     my %privileged;
 3957:     foreach my $entry (keys(%dumphash)) {
 3958: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 3959:         if (($tstart) && ($tstart<0)) { next; }
 3960:         if (($tend) && ($tend<$now)) { next; }
 3961:         if (($tstart) && ($now<$tstart)) { next; }
 3962:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 3963: 	if ($username eq '' || $domain eq '') { next; }
 3964:         if ((&privileged($username,$domain,\@possdoms)) &&
 3965:             (!$nothide{$username.':'.$domain})) { next; }
 3966: 	if ($role eq 'cr') { next; }
 3967:         if ($codes) {
 3968:             if ($section) { $role .= ':'.$section; }
 3969:             if ($returnhash{$role}) {
 3970:                 $returnhash{$role}.=','.$username.':'.$domain;
 3971:             } else {
 3972:                 $returnhash{$role}=$username.':'.$domain;
 3973:             }
 3974:         } else {
 3975:             my $key=&plaintext($role,$crstype);
 3976:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 3977:             if ($returnhash{$key}) {
 3978: 	        $returnhash{$key}.=','.$username.':'.$domain;
 3979:             } else {
 3980:                 $returnhash{$key}=$username.':'.$domain;
 3981:             }
 3982:         }
 3983:     }
 3984:     return %returnhash;
 3985: }
 3986: 
 3987: sub get_my_roles {
 3988:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 3989:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 3990:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 3991:     my (%dumphash,%nothide);
 3992:     if ($context eq 'userroles') {
 3993:         %dumphash = &dump('roles',$udom,$uname);
 3994:     } else {
 3995:         %dumphash = &dump('nohist_userroles',$udom,$uname);
 3996:         if ($hidepriv) {
 3997:             my %coursehash=&coursedescription($udom.'_'.$uname);
 3998:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3999:                 if ($user !~ /:/) {
 4000:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 4001:                 } else {
 4002:                     $nothide{$user} = 1;
 4003:                 }
 4004:             }
 4005:         }
 4006:     }
 4007:     my %returnhash=();
 4008:     my $now=time;
 4009:     my %privileged;
 4010:     foreach my $entry (keys(%dumphash)) {
 4011:         my ($role,$tend,$tstart);
 4012:         if ($context eq 'userroles') {
 4013:             next if ($entry =~ /^rolesdef/);
 4014: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 4015:         } else {
 4016:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 4017:         }
 4018:         if (($tstart) && ($tstart<0)) { next; }
 4019:         my $status = 'active';
 4020:         if (($tend) && ($tend<=$now)) {
 4021:             $status = 'previous';
 4022:         } 
 4023:         if (($tstart) && ($now<$tstart)) {
 4024:             $status = 'future';
 4025:         }
 4026:         if (ref($types) eq 'ARRAY') {
 4027:             if (!grep(/^\Q$status\E$/,@{$types})) {
 4028:                 next;
 4029:             } 
 4030:         } else {
 4031:             if ($status ne 'active') {
 4032:                 next;
 4033:             }
 4034:         }
 4035:         my ($rolecode,$username,$domain,$section,$area);
 4036:         if ($context eq 'userroles') {
 4037:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
 4038:             (undef,$domain,$username,$section) = split(/\//,$area);
 4039:         } else {
 4040:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 4041:         }
 4042:         if (ref($roledoms) eq 'ARRAY') {
 4043:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 4044:                 next;
 4045:             }
 4046:         }
 4047:         if (ref($roles) eq 'ARRAY') {
 4048:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 4049:                 if ($role =~ /^cr\//) {
 4050:                     if (!grep(/^cr$/,@{$roles})) {
 4051:                         next;
 4052:                     }
 4053:                 } elsif ($role =~ /^gr\//) {
 4054:                     if (!grep(/^gr$/,@{$roles})) {
 4055:                         next;
 4056:                     }
 4057:                 } else {
 4058:                     next;
 4059:                 }
 4060:             }
 4061:         }
 4062:         if ($hidepriv) {
 4063:             my @privroles = ('dc','su');
 4064:             if ($context eq 'userroles') {
 4065:                 next if (grep(/^\Q$role\E$/,@privroles));
 4066:             } else {
 4067:                 my $possdoms = [$domain];
 4068:                 if (ref($roledoms) eq 'ARRAY') {
 4069:                    push(@{$possdoms},@{$roledoms}); 
 4070:                 }
 4071:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
 4072:                     if (!$nothide{$username.':'.$domain}) {
 4073:                         next;
 4074:                     }
 4075:                 }
 4076:             }
 4077:         }
 4078:         if ($withsec) {
 4079:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 4080:                 $tstart.':'.$tend;
 4081:         } else {
 4082:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 4083:         }
 4084:     }
 4085:     return %returnhash;
 4086: }
 4087: 
 4088: # ----------------------------------------------------- Frontpage Announcements
 4089: #
 4090: #
 4091: 
 4092: sub postannounce {
 4093:     my ($server,$text)=@_;
 4094:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 4095:     unless ($text=~/\w/) { $text=''; }
 4096:     return &reply('setannounce:'.&escape($text),$server);
 4097: }
 4098: 
 4099: sub getannounce {
 4100: 
 4101:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 4102: 	my $announcement='';
 4103: 	while (my $line = <$fh>) { $announcement .= $line; }
 4104: 	close($fh);
 4105: 	if ($announcement=~/\w/) { 
 4106: 	    return 
 4107:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 4108:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 4109: 	} else {
 4110: 	    return '';
 4111: 	}
 4112:     } else {
 4113: 	return '';
 4114:     }
 4115: }
 4116: 
 4117: # ---------------------------------------------------------- Course ID routines
 4118: # Deal with domain's nohist_courseid.db files
 4119: #
 4120: 
 4121: sub courseidput {
 4122:     my ($domain,$storehash,$coursehome,$caller) = @_;
 4123:     return unless (ref($storehash) eq 'HASH');
 4124:     my $outcome;
 4125:     if ($caller eq 'timeonly') {
 4126:         my $cids = '';
 4127:         foreach my $item (keys(%$storehash)) {
 4128:             $cids.=&escape($item).'&';
 4129:         }
 4130:         $cids=~s/\&$//;
 4131:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 4132:                           $coursehome);       
 4133:     } else {
 4134:         my $items = '';
 4135:         foreach my $item (keys(%$storehash)) {
 4136:             $items.= &escape($item).'='.
 4137:                      &freeze_escape($$storehash{$item}).'&';
 4138:         }
 4139:         $items=~s/\&$//;
 4140:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 4141:                           $coursehome);
 4142:     }
 4143:     if ($outcome eq 'unknown_cmd') {
 4144:         my $what;
 4145:         foreach my $cid (keys(%$storehash)) {
 4146:             $what .= &escape($cid).'=';
 4147:             foreach my $item ('description','inst_code','owner','type') {
 4148:                 $what .= &escape($storehash->{$cid}{$item}).':';
 4149:             }
 4150:             $what =~ s/\:$/&/;
 4151:         }
 4152:         $what =~ s/\&$//;  
 4153:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 4154:     } else {
 4155:         return $outcome;
 4156:     }
 4157: }
 4158: 
 4159: sub courseiddump {
 4160:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 4161:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 4162:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
 4163:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
 4164:     my $as_hash = 1;
 4165:     my %returnhash;
 4166:     if (!$domfilter) { $domfilter=''; }
 4167:     my %libserv = &all_library();
 4168:     foreach my $tryserver (keys(%libserv)) {
 4169:         if ( (  $hostidflag == 1 
 4170: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 4171: 	     || (!defined($hostidflag)) ) {
 4172: 
 4173: 	    if (($domfilter eq '') ||
 4174: 		(&host_domain($tryserver) eq $domfilter)) {
 4175:                 my $rep;
 4176:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
 4177:                     $rep = LONCAPA::Lond::dump_course_id_handler(
 4178:                         join(":", (&host_domain($tryserver), $sincefilter, 
 4179:                                 &escape($descfilter), &escape($instcodefilter), 
 4180:                                 &escape($ownerfilter), &escape($coursefilter),
 4181:                                 &escape($typefilter), &escape($regexp_ok), 
 4182:                                 $as_hash, &escape($selfenrollonly), 
 4183:                                 &escape($catfilter), $showhidden, $caller, 
 4184:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
 4185:                                 &escape($createdbefore), &escape($createdafter), 
 4186:                                 &escape($creationcontext), $domcloner)));
 4187:                 } else {
 4188:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
 4189:                              $sincefilter.':'.&escape($descfilter).':'.
 4190:                              &escape($instcodefilter).':'.&escape($ownerfilter).
 4191:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
 4192:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
 4193:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
 4194:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
 4195:                              &escape($cc_clone).':'.$cloneonly.':'.
 4196:                              &escape($createdbefore).':'.&escape($createdafter).':'.
 4197:                              &escape($creationcontext).':'.$domcloner,
 4198:                              $tryserver);
 4199:                 }
 4200:                      
 4201:                 my @pairs=split(/\&/,$rep);
 4202:                 foreach my $item (@pairs) {
 4203:                     my ($key,$value)=split(/\=/,$item,2);
 4204:                     $key = &unescape($key);
 4205:                     next if ($key =~ /^error: 2 /);
 4206:                     my $result = &thaw_unescape($value);
 4207:                     if (ref($result) eq 'HASH') {
 4208:                         $returnhash{$key}=$result;
 4209:                     } else {
 4210:                         my @responses = split(/:/,$value);
 4211:                         my @items = ('description','inst_code','owner','type');
 4212:                         for (my $i=0; $i<@responses; $i++) {
 4213:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 4214:                         }
 4215:                     }
 4216:                 }
 4217:             }
 4218:         }
 4219:     }
 4220:     return %returnhash;
 4221: }
 4222: 
 4223: sub courselastaccess {
 4224:     my ($cdom,$cnum,$hostidref) = @_;
 4225:     my %returnhash;
 4226:     if ($cdom && $cnum) {
 4227:         my $chome = &homeserver($cnum,$cdom);
 4228:         if ($chome ne 'no_host') {
 4229:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
 4230:             &extract_lastaccess(\%returnhash,$rep);
 4231:         }
 4232:     } else {
 4233:         if (!$cdom) { $cdom=''; }
 4234:         my %libserv = &all_library();
 4235:         foreach my $tryserver (keys(%libserv)) {
 4236:             if (ref($hostidref) eq 'ARRAY') {
 4237:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
 4238:             } 
 4239:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
 4240:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
 4241:                 &extract_lastaccess(\%returnhash,$rep);
 4242:             }
 4243:         }
 4244:     }
 4245:     return %returnhash;
 4246: }
 4247: 
 4248: sub extract_lastaccess {
 4249:     my ($returnhash,$rep) = @_;
 4250:     if (ref($returnhash) eq 'HASH') {
 4251:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
 4252:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
 4253:                  $rep eq '') {
 4254:             my @pairs=split(/\&/,$rep);
 4255:             foreach my $item (@pairs) {
 4256:                 my ($key,$value)=split(/\=/,$item,2);
 4257:                 $key = &unescape($key);
 4258:                 next if ($key =~ /^error: 2 /);
 4259:                 $returnhash->{$key} = &thaw_unescape($value);
 4260:             }
 4261:         }
 4262:     }
 4263:     return;
 4264: }
 4265: 
 4266: # ---------------------------------------------------------- DC e-mail
 4267: 
 4268: sub dcmailput {
 4269:     my ($domain,$msgid,$message,$server)=@_;
 4270:     my $status = &Apache::lonnet::critical(
 4271:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 4272:        &escape($message),$server);
 4273:     return $status;
 4274: }
 4275: 
 4276: sub dcmaildump {
 4277:     my ($dom,$startdate,$enddate,$senders) = @_;
 4278:     my %returnhash=();
 4279: 
 4280:     if (defined(&domain($dom,'primary'))) {
 4281:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 4282:                                                          &escape($enddate).':';
 4283: 	my @esc_senders=map { &escape($_)} @$senders;
 4284: 	$cmd.=&escape(join('&',@esc_senders));
 4285: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 4286:             my ($key,$value) = split(/\=/,$line,2);
 4287:             if (($key) && ($value)) {
 4288:                 $returnhash{&unescape($key)} = &unescape($value);
 4289:             }
 4290:         }
 4291:     }
 4292:     return %returnhash;
 4293: }
 4294: # ---------------------------------------------------------- Domain roles
 4295: 
 4296: sub get_domain_roles {
 4297:     my ($dom,$roles,$startdate,$enddate)=@_;
 4298:     if ((!defined($startdate)) || ($startdate eq '')) {
 4299:         $startdate = '.';
 4300:     }
 4301:     if ((!defined($enddate)) || ($enddate eq '')) {
 4302:         $enddate = '.';
 4303:     }
 4304:     my $rolelist;
 4305:     if (ref($roles) eq 'ARRAY') {
 4306:         $rolelist = join('&',@{$roles});
 4307:     }
 4308:     my %personnel = ();
 4309: 
 4310:     my %servers = &get_servers($dom,'library');
 4311:     foreach my $tryserver (keys(%servers)) {
 4312: 	%{$personnel{$tryserver}}=();
 4313: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 4314: 					    &escape($startdate).':'.
 4315: 					    &escape($enddate).':'.
 4316: 					    &escape($rolelist), $tryserver))) {
 4317: 	    my ($key,$value) = split(/\=/,$line,2);
 4318: 	    if (($key) && ($value)) {
 4319: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 4320: 	    }
 4321: 	}
 4322:     }
 4323:     return %personnel;
 4324: }
 4325: 
 4326: # ----------------------------------------------------------- Interval timing 
 4327: 
 4328: {
 4329: # Caches needed for speedup of navmaps
 4330: # We don't want to cache this for very long at all (5 seconds at most)
 4331: # 
 4332: # The user for whom we cache
 4333: my $cachedkey='';
 4334: # The cached times for this user
 4335: my %cachedtimes=();
 4336: # When this was last done
 4337: my $cachedtime=();
 4338: 
 4339: sub load_all_first_access {
 4340:     my ($uname,$udom)=@_;
 4341:     if (($cachedkey eq $uname.':'.$udom) &&
 4342:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
 4343:         return;
 4344:     }
 4345:     $cachedtime=time;
 4346:     $cachedkey=$uname.':'.$udom;
 4347:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
 4348: }
 4349: 
 4350: sub get_first_access {
 4351:     my ($type,$argsymb,$argmap)=@_;
 4352:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 4353:     if ($argsymb) { $symb=$argsymb; }
 4354:     my ($map,$id,$res)=&decode_symb($symb);
 4355:     if ($argmap) { $map = $argmap; }
 4356:     if ($type eq 'course') {
 4357: 	$res='course';
 4358:     } elsif ($type eq 'map') {
 4359: 	$res=&symbread($map);
 4360:     } else {
 4361: 	$res=$symb;
 4362:     }
 4363:     &load_all_first_access($uname,$udom);
 4364:     return $cachedtimes{"$courseid\0$res"};
 4365: }
 4366: 
 4367: sub set_first_access {
 4368:     my ($type,$interval)=@_;
 4369:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 4370:     my ($map,$id,$res)=&decode_symb($symb);
 4371:     if ($type eq 'course') {
 4372: 	$res='course';
 4373:     } elsif ($type eq 'map') {
 4374: 	$res=&symbread($map);
 4375:     } else {
 4376: 	$res=$symb;
 4377:     }
 4378:     $cachedkey='';
 4379:     my $firstaccess=&get_first_access($type,$symb,$map);
 4380:     if (!$firstaccess) {
 4381:         my $start = time;
 4382: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
 4383:                           $udom,$uname);
 4384:         if ($putres eq 'ok') {
 4385:             &put('timerinterval',{"$courseid\0$res"=>$interval},
 4386:                  $udom,$uname); 
 4387:             &appenv(
 4388:                      {
 4389:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
 4390:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
 4391:                      }
 4392:                   );
 4393:         }
 4394:         return $putres;
 4395:     }
 4396:     return 'already_set';
 4397: }
 4398: }
 4399: # --------------------------------------------- Set Expire Date for Spreadsheet
 4400: 
 4401: sub expirespread {
 4402:     my ($uname,$udom,$stype,$usymb)=@_;
 4403:     my $cid=$env{'request.course.id'}; 
 4404:     if ($cid) {
 4405:        my $now=time;
 4406:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 4407:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 4408:                             $env{'course.'.$cid.'.num'}.
 4409: 	        	    ':nohist_expirationdates:'.
 4410:                             &escape($key).'='.$now,
 4411:                             $env{'course.'.$cid.'.home'})
 4412:     }
 4413:     return 'ok';
 4414: }
 4415: 
 4416: # ----------------------------------------------------- Devalidate Spreadsheets
 4417: 
 4418: sub devalidate {
 4419:     my ($symb,$uname,$udom)=@_;
 4420:     my $cid=$env{'request.course.id'}; 
 4421:     if ($cid) {
 4422:         # delete the stored spreadsheets for
 4423:         # - the student level sheet of this user in course's homespace
 4424:         # - the assessment level sheet for this resource 
 4425:         #   for this user in user's homespace
 4426: 	# - current conditional state info
 4427: 	my $key=$uname.':'.$udom.':';
 4428:         my $status=
 4429: 	    &del('nohist_calculatedsheets',
 4430: 		 [$key.'studentcalc:'],
 4431: 		 $env{'course.'.$cid.'.domain'},
 4432: 		 $env{'course.'.$cid.'.num'})
 4433: 		.' '.
 4434: 	    &del('nohist_calculatedsheets_'.$cid,
 4435: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 4436:         unless ($status eq 'ok ok') {
 4437:            &logthis('Could not devalidate spreadsheet '.
 4438:                     $uname.' at '.$udom.' for '.
 4439: 		    $symb.': '.$status);
 4440:         }
 4441: 	&delenv('user.state.'.$cid);
 4442:     }
 4443: }
 4444: 
 4445: sub get_scalar {
 4446:     my ($string,$end) = @_;
 4447:     my $value;
 4448:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 4449: 	$value = $1;
 4450:     } elsif ($$string =~ s/^([^&]*?)&//) {
 4451: 	$value = $1;
 4452:     }
 4453:     return &unescape($value);
 4454: }
 4455: 
 4456: sub array2str {
 4457:   my (@array) = @_;
 4458:   my $result=&arrayref2str(\@array);
 4459:   $result=~s/^__ARRAY_REF__//;
 4460:   $result=~s/__END_ARRAY_REF__$//;
 4461:   return $result;
 4462: }
 4463: 
 4464: sub arrayref2str {
 4465:   my ($arrayref) = @_;
 4466:   my $result='__ARRAY_REF__';
 4467:   foreach my $elem (@$arrayref) {
 4468:     if(ref($elem) eq 'ARRAY') {
 4469:       $result.=&arrayref2str($elem).'&';
 4470:     } elsif(ref($elem) eq 'HASH') {
 4471:       $result.=&hashref2str($elem).'&';
 4472:     } elsif(ref($elem)) {
 4473:       #print("Got a ref of ".(ref($elem))." skipping.");
 4474:     } else {
 4475:       $result.=&escape($elem).'&';
 4476:     }
 4477:   }
 4478:   $result=~s/\&$//;
 4479:   $result .= '__END_ARRAY_REF__';
 4480:   return $result;
 4481: }
 4482: 
 4483: sub hash2str {
 4484:   my (%hash) = @_;
 4485:   my $result=&hashref2str(\%hash);
 4486:   $result=~s/^__HASH_REF__//;
 4487:   $result=~s/__END_HASH_REF__$//;
 4488:   return $result;
 4489: }
 4490: 
 4491: sub hashref2str {
 4492:   my ($hashref)=@_;
 4493:   my $result='__HASH_REF__';
 4494:   foreach my $key (sort(keys(%$hashref))) {
 4495:     if (ref($key) eq 'ARRAY') {
 4496:       $result.=&arrayref2str($key).'=';
 4497:     } elsif (ref($key) eq 'HASH') {
 4498:       $result.=&hashref2str($key).'=';
 4499:     } elsif (ref($key)) {
 4500:       $result.='=';
 4501:       #print("Got a ref of ".(ref($key))." skipping.");
 4502:     } else {
 4503: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
 4504:     }
 4505: 
 4506:     if(ref($hashref->{$key}) eq 'ARRAY') {
 4507:       $result.=&arrayref2str($hashref->{$key}).'&';
 4508:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 4509:       $result.=&hashref2str($hashref->{$key}).'&';
 4510:     } elsif(ref($hashref->{$key})) {
 4511:        $result.='&';
 4512:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 4513:     } else {
 4514:       $result.=&escape($hashref->{$key}).'&';
 4515:     }
 4516:   }
 4517:   $result=~s/\&$//;
 4518:   $result .= '__END_HASH_REF__';
 4519:   return $result;
 4520: }
 4521: 
 4522: sub str2hash {
 4523:     my ($string)=@_;
 4524:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 4525:     return %$hash;
 4526: }
 4527: 
 4528: sub str2hashref {
 4529:   my ($string) = @_;
 4530: 
 4531:   my %hash;
 4532: 
 4533:   if($string !~ /^__HASH_REF__/) {
 4534:       if (! ($string eq '' || !defined($string))) {
 4535: 	  $hash{'error'}='Not hash reference';
 4536:       }
 4537:       return (\%hash, $string);
 4538:   }
 4539: 
 4540:   $string =~ s/^__HASH_REF__//;
 4541: 
 4542:   while($string !~ /^__END_HASH_REF__/) {
 4543:       #key
 4544:       my $key='';
 4545:       if($string =~ /^__HASH_REF__/) {
 4546:           ($key, $string)=&str2hashref($string);
 4547:           if(defined($key->{'error'})) {
 4548:               $hash{'error'}='Bad data';
 4549:               return (\%hash, $string);
 4550:           }
 4551:       } elsif($string =~ /^__ARRAY_REF__/) {
 4552:           ($key, $string)=&str2arrayref($string);
 4553:           if($key->[0] eq 'Array reference error') {
 4554:               $hash{'error'}='Bad data';
 4555:               return (\%hash, $string);
 4556:           }
 4557:       } else {
 4558:           $string =~ s/^(.*?)=//;
 4559: 	  $key=&unescape($1);
 4560:       }
 4561:       $string =~ s/^=//;
 4562: 
 4563:       #value
 4564:       my $value='';
 4565:       if($string =~ /^__HASH_REF__/) {
 4566:           ($value, $string)=&str2hashref($string);
 4567:           if(defined($value->{'error'})) {
 4568:               $hash{'error'}='Bad data';
 4569:               return (\%hash, $string);
 4570:           }
 4571:       } elsif($string =~ /^__ARRAY_REF__/) {
 4572:           ($value, $string)=&str2arrayref($string);
 4573:           if($value->[0] eq 'Array reference error') {
 4574:               $hash{'error'}='Bad data';
 4575:               return (\%hash, $string);
 4576:           }
 4577:       } else {
 4578: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 4579:       }
 4580:       $string =~ s/^&//;
 4581: 
 4582:       $hash{$key}=$value;
 4583:   }
 4584: 
 4585:   $string =~ s/^__END_HASH_REF__//;
 4586: 
 4587:   return (\%hash, $string);
 4588: }
 4589: 
 4590: sub str2array {
 4591:     my ($string)=@_;
 4592:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 4593:     return @$array;
 4594: }
 4595: 
 4596: sub str2arrayref {
 4597:   my ($string) = @_;
 4598:   my @array;
 4599: 
 4600:   if($string !~ /^__ARRAY_REF__/) {
 4601:       if (! ($string eq '' || !defined($string))) {
 4602: 	  $array[0]='Array reference error';
 4603:       }
 4604:       return (\@array, $string);
 4605:   }
 4606: 
 4607:   $string =~ s/^__ARRAY_REF__//;
 4608: 
 4609:   while($string !~ /^__END_ARRAY_REF__/) {
 4610:       my $value='';
 4611:       if($string =~ /^__HASH_REF__/) {
 4612:           ($value, $string)=&str2hashref($string);
 4613:           if(defined($value->{'error'})) {
 4614:               $array[0] ='Array reference error';
 4615:               return (\@array, $string);
 4616:           }
 4617:       } elsif($string =~ /^__ARRAY_REF__/) {
 4618:           ($value, $string)=&str2arrayref($string);
 4619:           if($value->[0] eq 'Array reference error') {
 4620:               $array[0] ='Array reference error';
 4621:               return (\@array, $string);
 4622:           }
 4623:       } else {
 4624: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 4625:       }
 4626:       $string =~ s/^&//;
 4627: 
 4628:       push(@array, $value);
 4629:   }
 4630: 
 4631:   $string =~ s/^__END_ARRAY_REF__//;
 4632: 
 4633:   return (\@array, $string);
 4634: }
 4635: 
 4636: # -------------------------------------------------------------------Temp Store
 4637: 
 4638: sub tmpreset {
 4639:   my ($symb,$namespace,$domain,$stuname) = @_;
 4640:   if (!$symb) {
 4641:     $symb=&symbread();
 4642:     if (!$symb) { $symb= $env{'request.url'}; }
 4643:   }
 4644:   $symb=escape($symb);
 4645: 
 4646:   if (!$namespace) { $namespace=$env{'request.state'}; }
 4647:   $namespace=~s/\//\_/g;
 4648:   $namespace=~s/\W//g;
 4649: 
 4650:   if (!$domain) { $domain=$env{'user.domain'}; }
 4651:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4652:   if ($domain eq 'public' && $stuname eq 'public') {
 4653:       $stuname=$ENV{'REMOTE_ADDR'};
 4654:   }
 4655:   my $path=LONCAPA::tempdir();
 4656:   my %hash;
 4657:   if (tie(%hash,'GDBM_File',
 4658: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4659: 	  &GDBM_WRCREAT(),0640)) {
 4660:     foreach my $key (keys(%hash)) {
 4661:       if ($key=~ /:$symb/) {
 4662: 	delete($hash{$key});
 4663:       }
 4664:     }
 4665:   }
 4666: }
 4667: 
 4668: sub tmpstore {
 4669:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4670: 
 4671:   if (!$symb) {
 4672:     $symb=&symbread();
 4673:     if (!$symb) { $symb= $env{'request.url'}; }
 4674:   }
 4675:   $symb=escape($symb);
 4676: 
 4677:   if (!$namespace) {
 4678:     # I don't think we would ever want to store this for a course.
 4679:     # it seems this will only be used if we don't have a course.
 4680:     #$namespace=$env{'request.course.id'};
 4681:     #if (!$namespace) {
 4682:       $namespace=$env{'request.state'};
 4683:     #}
 4684:   }
 4685:   $namespace=~s/\//\_/g;
 4686:   $namespace=~s/\W//g;
 4687:   if (!$domain) { $domain=$env{'user.domain'}; }
 4688:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4689:   if ($domain eq 'public' && $stuname eq 'public') {
 4690:       $stuname=$ENV{'REMOTE_ADDR'};
 4691:   }
 4692:   my $now=time;
 4693:   my %hash;
 4694:   my $path=LONCAPA::tempdir();
 4695:   if (tie(%hash,'GDBM_File',
 4696: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4697: 	  &GDBM_WRCREAT(),0640)) {
 4698:     $hash{"version:$symb"}++;
 4699:     my $version=$hash{"version:$symb"};
 4700:     my $allkeys=''; 
 4701:     foreach my $key (keys(%$storehash)) {
 4702:       $allkeys.=$key.':';
 4703:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 4704:     }
 4705:     $hash{"$version:$symb:timestamp"}=$now;
 4706:     $allkeys.='timestamp';
 4707:     $hash{"$version:keys:$symb"}=$allkeys;
 4708:     if (untie(%hash)) {
 4709:       return 'ok';
 4710:     } else {
 4711:       return "error:$!";
 4712:     }
 4713:   } else {
 4714:     return "error:$!";
 4715:   }
 4716: }
 4717: 
 4718: # -----------------------------------------------------------------Temp Restore
 4719: 
 4720: sub tmprestore {
 4721:   my ($symb,$namespace,$domain,$stuname) = @_;
 4722: 
 4723:   if (!$symb) {
 4724:     $symb=&symbread();
 4725:     if (!$symb) { $symb= $env{'request.url'}; }
 4726:   }
 4727:   $symb=escape($symb);
 4728: 
 4729:   if (!$namespace) { $namespace=$env{'request.state'}; }
 4730: 
 4731:   if (!$domain) { $domain=$env{'user.domain'}; }
 4732:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4733:   if ($domain eq 'public' && $stuname eq 'public') {
 4734:       $stuname=$ENV{'REMOTE_ADDR'};
 4735:   }
 4736:   my %returnhash;
 4737:   $namespace=~s/\//\_/g;
 4738:   $namespace=~s/\W//g;
 4739:   my %hash;
 4740:   my $path=LONCAPA::tempdir();
 4741:   if (tie(%hash,'GDBM_File',
 4742: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4743: 	  &GDBM_READER(),0640)) {
 4744:     my $version=$hash{"version:$symb"};
 4745:     $returnhash{'version'}=$version;
 4746:     my $scope;
 4747:     for ($scope=1;$scope<=$version;$scope++) {
 4748:       my $vkeys=$hash{"$scope:keys:$symb"};
 4749:       my @keys=split(/:/,$vkeys);
 4750:       my $key;
 4751:       $returnhash{"$scope:keys"}=$vkeys;
 4752:       foreach $key (@keys) {
 4753: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 4754: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 4755:       }
 4756:     }
 4757:     if (!(untie(%hash))) {
 4758:       return "error:$!";
 4759:     }
 4760:   } else {
 4761:     return "error:$!";
 4762:   }
 4763:   return %returnhash;
 4764: }
 4765: 
 4766: # ----------------------------------------------------------------------- Store
 4767: 
 4768: sub store {
 4769:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4770:     my $home='';
 4771: 
 4772:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4773: 
 4774:     $symb=&symbclean($symb);
 4775:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 4776: 
 4777:     if (!$domain) { $domain=$env{'user.domain'}; }
 4778:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4779: 
 4780:     &devalidate($symb,$stuname,$domain);
 4781: 
 4782:     $symb=escape($symb);
 4783:     if (!$namespace) { 
 4784:        unless ($namespace=$env{'request.course.id'}) { 
 4785:           return ''; 
 4786:        } 
 4787:     }
 4788:     if (!$home) { $home=$env{'user.home'}; }
 4789: 
 4790:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 4791:     $$storehash{'host'}=$perlvar{'lonHostID'};
 4792: 
 4793:     my $namevalue='';
 4794:     foreach my $key (keys(%$storehash)) {
 4795:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4796:     }
 4797:     $namevalue=~s/\&$//;
 4798:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 4799:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 4800: }
 4801: 
 4802: # -------------------------------------------------------------- Critical Store
 4803: 
 4804: sub cstore {
 4805:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4806:     my $home='';
 4807: 
 4808:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4809: 
 4810:     $symb=&symbclean($symb);
 4811:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 4812: 
 4813:     if (!$domain) { $domain=$env{'user.domain'}; }
 4814:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4815: 
 4816:     &devalidate($symb,$stuname,$domain);
 4817: 
 4818:     $symb=escape($symb);
 4819:     if (!$namespace) { 
 4820:        unless ($namespace=$env{'request.course.id'}) { 
 4821:           return ''; 
 4822:        } 
 4823:     }
 4824:     if (!$home) { $home=$env{'user.home'}; }
 4825: 
 4826:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 4827:     $$storehash{'host'}=$perlvar{'lonHostID'};
 4828: 
 4829:     my $namevalue='';
 4830:     foreach my $key (keys(%$storehash)) {
 4831:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4832:     }
 4833:     $namevalue=~s/\&$//;
 4834:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 4835:     return critical
 4836:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 4837: }
 4838: 
 4839: # --------------------------------------------------------------------- Restore
 4840: 
 4841: sub restore {
 4842:     my ($symb,$namespace,$domain,$stuname) = @_;
 4843:     my $home='';
 4844: 
 4845:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4846: 
 4847:     if (!$symb) {
 4848:         return if ($namespace eq 'courserequests');
 4849:         unless ($symb=escape(&symbread())) { return ''; }
 4850:     } else {
 4851:         unless ($namespace eq 'courserequests') {
 4852:             $symb=&escape(&symbclean($symb));
 4853:         }
 4854:     }
 4855:     if (!$namespace) { 
 4856:        unless ($namespace=$env{'request.course.id'}) { 
 4857:           return ''; 
 4858:        } 
 4859:     }
 4860:     if (!$domain) { $domain=$env{'user.domain'}; }
 4861:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4862:     if (!$home) { $home=$env{'user.home'}; }
 4863:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 4864: 
 4865:     my %returnhash=();
 4866:     foreach my $line (split(/\&/,$answer)) {
 4867: 	my ($name,$value)=split(/\=/,$line);
 4868:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 4869:     }
 4870:     my $version;
 4871:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 4872:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 4873:           $returnhash{$item}=$returnhash{$version.':'.$item};
 4874:        }
 4875:     }
 4876:     return %returnhash;
 4877: }
 4878: 
 4879: # ---------------------------------------------------------- Course Description
 4880: #
 4881: #  
 4882: 
 4883: sub coursedescription {
 4884:     my ($courseid,$args)=@_;
 4885:     $courseid=~s/^\///;
 4886:     $courseid=~s/\_/\//g;
 4887:     my ($cdomain,$cnum)=split(/\//,$courseid);
 4888:     my $chome=&homeserver($cnum,$cdomain);
 4889:     my $normalid=$cdomain.'_'.$cnum;
 4890:     # need to always cache even if we get errors otherwise we keep 
 4891:     # trying and trying and trying to get the course description.
 4892:     my %envhash=();
 4893:     my %returnhash=();
 4894:     
 4895:     my $expiretime=600;
 4896:     if ($env{'request.course.id'} eq $normalid) {
 4897: 	$expiretime=120;
 4898:     }
 4899: 
 4900:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 4901:     if (!$args->{'freshen_cache'}
 4902: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 4903: 	foreach my $key (keys(%env)) {
 4904: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 4905: 	    my ($setting) = $1;
 4906: 	    $returnhash{$setting} = $env{$key};
 4907: 	}
 4908: 	return %returnhash;
 4909:     }
 4910: 
 4911:     # get the data again
 4912: 
 4913:     if (!$args->{'one_time'}) {
 4914: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 4915:     }
 4916: 
 4917:     if ($chome ne 'no_host') {
 4918:        %returnhash=&dump('environment',$cdomain,$cnum);
 4919:        if (!exists($returnhash{'con_lost'})) {
 4920: 	   my $username = $env{'user.name'}; # Defult username
 4921: 	   if(defined $args->{'user'}) {
 4922: 	       $username = $args->{'user'};
 4923: 	   }
 4924:            $returnhash{'home'}= $chome;
 4925: 	   $returnhash{'domain'} = $cdomain;
 4926: 	   $returnhash{'num'} = $cnum;
 4927:            if (!defined($returnhash{'type'})) {
 4928:                $returnhash{'type'} = 'Course';
 4929:            }
 4930:            while (my ($name,$value) = each %returnhash) {
 4931:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 4932:            }
 4933:            $returnhash{'url'}=&clutter($returnhash{'url'});
 4934:            $returnhash{'fn'}=LONCAPA::tempdir() .
 4935: 	       $username.'_'.$cdomain.'_'.$cnum;
 4936:            $envhash{'course.'.$normalid.'.home'}=$chome;
 4937:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 4938:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 4939:        }
 4940:     }
 4941:     if (!$args->{'one_time'}) {
 4942: 	&appenv(\%envhash);
 4943:     }
 4944:     return %returnhash;
 4945: }
 4946: 
 4947: sub update_released_required {
 4948:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
 4949:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
 4950:         $cid = $env{'request.course.id'};
 4951:         $cdom = $env{'course.'.$cid.'.domain'};
 4952:         $cnum = $env{'course.'.$cid.'.num'};
 4953:         $chome = $env{'course.'.$cid.'.home'};
 4954:     }
 4955:     if ($needsrelease) {
 4956:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
 4957:         my $needsupdate;
 4958:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
 4959:             $needsupdate = 1;
 4960:         } else {
 4961:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
 4962:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
 4963:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
 4964:                 $needsupdate = 1;
 4965:             }
 4966:         }
 4967:         if ($needsupdate) {
 4968:             my %needshash = (
 4969:                              'internal.releaserequired' => $needsrelease,
 4970:                             );
 4971:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
 4972:             if ($putresult eq 'ok') {
 4973:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
 4974:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 4975:                 if (ref($crsinfo{$cid}) eq 'HASH') {
 4976:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
 4977:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
 4978:                 }
 4979:             }
 4980:         }
 4981:     }
 4982:     return;
 4983: }
 4984: 
 4985: # -------------------------------------------------See if a user is privileged
 4986: 
 4987: sub privileged {
 4988:     my ($username,$domain,$possdomains,$possroles)=@_;
 4989:     my $now = time;
 4990:     my $roles;
 4991:     if (ref($possroles) eq 'ARRAY') {
 4992:         $roles = $possroles; 
 4993:     } else {
 4994:         $roles = ['dc','su'];
 4995:     }
 4996:     if (ref($possdomains) eq 'ARRAY') {
 4997:         my %privileged = &privileged_by_domain($possdomains,$roles);
 4998:         foreach my $dom (@{$possdomains}) {
 4999:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
 5000:                 (ref($privileged{$dom}) eq 'HASH')) {
 5001:                 foreach my $role (@{$roles}) {
 5002:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 5003:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
 5004:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
 5005:                             return 1 unless (($end && $end < $now) ||
 5006:                                              ($start && $start > $now));
 5007:                         }
 5008:                     }
 5009:                 }
 5010:             }
 5011:         }
 5012:     } else {
 5013:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
 5014:         my $now = time;
 5015: 
 5016:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys %rolesdump}) {
 5017:             my ($trole, $tend, $tstart) = split(/_/, $role);
 5018:             if (grep(/^\Q$trole\E$/,@{$roles})) {
 5019:                 return 1 unless ($tend && $tend < $now) 
 5020:                         or ($tstart && $tstart > $now);
 5021:             }
 5022:         }
 5023:     }
 5024:     return 0;
 5025: }
 5026: 
 5027: sub privileged_by_domain {
 5028:     my ($domains,$roles) = @_;
 5029:     my %privileged = ();
 5030:     my $cachetime = 60*60*24;
 5031:     my $now = time;
 5032:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
 5033:         return %privileged;
 5034:     }
 5035:     foreach my $dom (@{$domains}) {
 5036:         next if (ref($privileged{$dom}) eq 'HASH');
 5037:         my $needroles;
 5038:         foreach my $role (@{$roles}) {
 5039:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
 5040:             if (defined($cached)) {
 5041:                 if (ref($result) eq 'HASH') {
 5042:                     $privileged{$dom}{$role} = $result;
 5043:                 }
 5044:             } else {
 5045:                 $needroles = 1;
 5046:             }
 5047:         }
 5048:         if ($needroles) {
 5049:             my %dompersonnel = &get_domain_roles($dom,$roles);
 5050:             $privileged{$dom} = {};
 5051:             foreach my $server (keys(%dompersonnel)) {
 5052:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 5053:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
 5054:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
 5055:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
 5056:                         next if ($end && $end < $now);
 5057:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
 5058:                             $dompersonnel{$server}{$item};
 5059:                     }
 5060:                 }
 5061:             }
 5062:             if (ref($privileged{$dom}) eq 'HASH') {
 5063:                 foreach my $role (@{$roles}) {
 5064:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 5065:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
 5066:                     } else {
 5067:                         my %hash = ();
 5068:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
 5069:                     }
 5070:                 }
 5071:             }
 5072:         }
 5073:     }
 5074:     return %privileged;
 5075: }
 5076: 
 5077: # -------------------------------------------------------- Get user privileges
 5078: 
 5079: sub rolesinit {
 5080:     my ($domain, $username) = @_;
 5081:     my %userroles = ('user.login.time' => time);
 5082:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
 5083: 
 5084:     # firstaccess and timerinterval are related to timed maps/resources. 
 5085:     # also, blocking can be triggered by an activating timer
 5086:     # it's saved in the user's %env.
 5087:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
 5088:     my %timerinterval = &dump('timerinterval', $domain, $username);
 5089:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
 5090:         %timerintchk, %timerintenv);
 5091: 
 5092:     foreach my $key (keys(%firstaccess)) {
 5093:         my ($cid, $rest) = split(/\0/, $key);
 5094:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
 5095:     }
 5096: 
 5097:     foreach my $key (keys(%timerinterval)) {
 5098:         my ($cid,$rest) = split(/\0/,$key);
 5099:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
 5100:     }
 5101: 
 5102:     my %allroles=();
 5103:     my %allgroups=();
 5104: 
 5105:     for my $area (grep { ! /^rolesdef_/ } keys %rolesdump) {
 5106:         my $role = $rolesdump{$area};
 5107:         $area =~ s/\_\w\w$//;
 5108: 
 5109:         my ($trole, $tend, $tstart, $group_privs);
 5110: 
 5111:         if ($role =~ /^cr/) {
 5112:         # Custom role, defined by a user 
 5113:         # e.g., user.role.cr/msu/smith/mynewrole
 5114:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 5115:                 $trole = $1;
 5116:                 ($tend, $tstart) = split('_', $2);
 5117:             } else {
 5118:                 $trole = $role;
 5119:             }
 5120:         } elsif ($role =~ m|^gr/|) {
 5121:         # Role of member in a group, defined within a course/community
 5122:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
 5123:             ($trole, $tend, $tstart) = split(/_/, $role);
 5124:             next if $tstart eq '-1';
 5125:             ($trole, $group_privs) = split(/\//, $trole);
 5126:             $group_privs = &unescape($group_privs);
 5127:         } else {
 5128:         # Just a normal role, defined in roles.tab
 5129:             ($trole, $tend, $tstart) = split(/_/,$role);
 5130:         }
 5131: 
 5132:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 5133:                  $username);
 5134:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 5135: 
 5136:         # role expired or not available yet?
 5137:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
 5138:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
 5139: 
 5140:         next if $area eq '' or $trole eq '';
 5141: 
 5142:         my $spec = "$trole.$area";
 5143:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
 5144: 
 5145:         if ($trole =~ /^cr\//) {
 5146:         # Custom role, defined by a user
 5147:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 5148:         } elsif ($trole eq 'gr') {
 5149:         # Role of a member in a group, defined within a course/community
 5150:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 5151:             next;
 5152:         } else {
 5153:         # Normal role, defined in roles.tab
 5154:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 5155:         }
 5156: 
 5157:         my $cid = $tdomain.'_'.$trest;
 5158:         unless ($firstaccchk{$cid}) {
 5159:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
 5160:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
 5161:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
 5162:                         $coursetimerstarts{$cid}{$item}; 
 5163:                 }
 5164:             }
 5165:             $firstaccchk{$cid} = 1;
 5166:         }
 5167:         unless ($timerintchk{$cid}) {
 5168:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
 5169:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
 5170:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
 5171:                        $coursetimerintervals{$cid}{$item};
 5172:                 }
 5173:             }
 5174:             $timerintchk{$cid} = 1;
 5175:         }
 5176:     }
 5177: 
 5178:     @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
 5179:         \%allroles, \%allgroups);
 5180:     $env{'user.adv'} = $userroles{'user.adv'};
 5181: 
 5182:     return (\%userroles,\%firstaccenv,\%timerintenv);
 5183: }
 5184: 
 5185: sub set_arearole {
 5186:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
 5187:     unless ($nolog) {
 5188: # log the associated role with the area
 5189:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 5190:     }
 5191:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 5192: }
 5193: 
 5194: sub custom_roleprivs {
 5195:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 5196:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 5197:     my $homsvr=homeserver($rauthor,$rdomain);
 5198:     if (&hostname($homsvr) ne '') {
 5199:         my ($rdummy,$roledef)=
 5200:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 5201:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 5202:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 5203:             if (defined($syspriv)) {
 5204:                 if ($trest =~ /^$match_community$/) {
 5205:                     $syspriv =~ s/bre\&S//; 
 5206:                 }
 5207:                 $$allroles{'cm./'}.=':'.$syspriv;
 5208:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 5209:             }
 5210:             if ($tdomain ne '') {
 5211:                 if (defined($dompriv)) {
 5212:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 5213:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 5214:                 }
 5215:                 if (($trest ne '') && (defined($coursepriv))) {
 5216:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 5217:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 5218:                 }
 5219:             }
 5220:         }
 5221:     }
 5222: }
 5223: 
 5224: sub group_roleprivs {
 5225:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 5226:     my $access = 1;
 5227:     my $now = time;
 5228:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 5229:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 5230:     if ($access) {
 5231:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 5232:         $$allgroups{$course}{$group} .=':'.$group_privs;
 5233:     }
 5234: }
 5235: 
 5236: sub standard_roleprivs {
 5237:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 5238:     if (defined($pr{$trole.':s'})) {
 5239:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 5240:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 5241:     }
 5242:     if ($tdomain ne '') {
 5243:         if (defined($pr{$trole.':d'})) {
 5244:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 5245:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 5246:         }
 5247:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 5248:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 5249:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 5250:         }
 5251:     }
 5252: }
 5253: 
 5254: sub set_userprivs {
 5255:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
 5256:     my $author=0;
 5257:     my $adv=0;
 5258:     my %grouproles = ();
 5259:     if (keys(%{$allgroups}) > 0) {
 5260:         my @groupkeys; 
 5261:         foreach my $role (keys(%{$allroles})) {
 5262:             push(@groupkeys,$role);
 5263:         }
 5264:         if (ref($groups_roles) eq 'HASH') {
 5265:             foreach my $key (keys(%{$groups_roles})) {
 5266:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
 5267:                     push(@groupkeys,$key);
 5268:                 }
 5269:             }
 5270:         }
 5271:         if (@groupkeys > 0) {
 5272:             foreach my $role (@groupkeys) {
 5273:                 my ($trole,$area,$sec,$extendedarea);
 5274:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 5275:                     $trole = $1;
 5276:                     $area = $2;
 5277:                     $sec = $3;
 5278:                     $extendedarea = $area.$sec;
 5279:                     if (exists($$allgroups{$area})) {
 5280:                         foreach my $group (keys(%{$$allgroups{$area}})) {
 5281:                             my $spec = $trole.'.'.$extendedarea;
 5282:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
 5283:                                                 $$allgroups{$area}{$group};
 5284:                         }
 5285:                     }
 5286:                 }
 5287:             }
 5288:         }
 5289:     }
 5290:     foreach my $group (keys(%grouproles)) {
 5291:         $$allroles{$group} = $grouproles{$group};
 5292:     }
 5293:     foreach my $role (keys(%{$allroles})) {
 5294:         my %thesepriv;
 5295:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 5296:         foreach my $item (split(/:/,$$allroles{$role})) {
 5297:             if ($item ne '') {
 5298:                 my ($privilege,$restrictions)=split(/&/,$item);
 5299:                 if ($restrictions eq '') {
 5300:                     $thesepriv{$privilege}='F';
 5301:                 } elsif ($thesepriv{$privilege} ne 'F') {
 5302:                     $thesepriv{$privilege}.=$restrictions;
 5303:                 }
 5304:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 5305:             }
 5306:         }
 5307:         my $thesestr='';
 5308:         foreach my $priv (sort(keys(%thesepriv))) {
 5309: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 5310: 	}
 5311:         $userroles->{'user.priv.'.$role} = $thesestr;
 5312:     }
 5313:     return ($author,$adv);
 5314: }
 5315: 
 5316: sub role_status {
 5317:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 5318:     my @pwhere = ();
 5319:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 5320:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
 5321:         unless (!defined($$role) || $$role eq '') {
 5322:             $$where=join('.',@pwhere);
 5323:             $$trolecode=$$role.'.'.$$where;
 5324:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 5325:             $$tstatus='is';
 5326:             if ($$tstart && $$tstart>$update) {
 5327:                 $$tstatus='future';
 5328:                 if ($$tstart<$now) {
 5329:                     if ($$tstart && $$tstart>$refresh) {
 5330:                         if (($$where ne '') && ($$role ne '')) {
 5331:                             my (%allroles,%allgroups,$group_privs,
 5332:                                 %groups_roles,@rolecodes);
 5333:                             my %userroles = (
 5334:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 5335:                             );
 5336:                             @rolecodes = ('cm'); 
 5337:                             my $spec=$$role.'.'.$$where;
 5338:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 5339:                             if ($$role =~ /^cr\//) {
 5340:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 5341:                                 push(@rolecodes,'cr');
 5342:                             } elsif ($$role eq 'gr') {
 5343:                                 push(@rolecodes,$$role);
 5344:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 5345:                                                     $env{'user.name'});
 5346:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
 5347:                                 (undef,my $group_privs) = split(/\//,$trole);
 5348:                                 $group_privs = &unescape($group_privs);
 5349:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 5350:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
 5351:                                 &get_groups_roles($tdomain,$trest,
 5352:                                                   \%course_roles,\@rolecodes,
 5353:                                                   \%groups_roles);
 5354:                             } else {
 5355:                                 push(@rolecodes,$$role);
 5356:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 5357:                             }
 5358:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
 5359:                             &appenv(\%userroles,\@rolecodes);
 5360:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 5361:                         }
 5362:                     }
 5363:                     $$tstatus = 'is';
 5364:                 }
 5365:             }
 5366:             if ($$tend) {
 5367:                 if ($$tend<$update) {
 5368:                     $$tstatus='expired';
 5369:                 } elsif ($$tend<$now) {
 5370:                     $$tstatus='will_not';
 5371:                 }
 5372:             }
 5373:         }
 5374:     }
 5375: }
 5376: 
 5377: sub get_groups_roles {
 5378:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
 5379:     return unless((ref($cdom_courseroles) eq 'HASH') && 
 5380:                   (ref($rolecodes) eq 'ARRAY') && 
 5381:                   (ref($groups_roles) eq 'HASH')); 
 5382:     if (keys(%{$cdom_courseroles}) > 0) {
 5383:         my ($cnum) = ($rest =~ /^($match_courseid)/);
 5384:         if ($cdom ne '' && $cnum ne '') {
 5385:             foreach my $key (keys(%{$cdom_courseroles})) {
 5386:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
 5387:                     my $crsrole = $1;
 5388:                     my $crssec = $2;
 5389:                     if ($crsrole =~ /^cr/) {
 5390:                         unless (grep(/^cr$/,@{$rolecodes})) {
 5391:                             push(@{$rolecodes},'cr');
 5392:                         }
 5393:                     } else {
 5394:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
 5395:                             push(@{$rolecodes},$crsrole);
 5396:                         }
 5397:                     }
 5398:                     my $rolekey = "$crsrole./$cdom/$cnum";
 5399:                     if ($crssec ne '') {
 5400:                         $rolekey .= "/$crssec";
 5401:                     }
 5402:                     $rolekey .= './';
 5403:                     $groups_roles->{$rolekey} = $rolecodes;
 5404:                 }
 5405:             }
 5406:         }
 5407:     }
 5408:     return;
 5409: }
 5410: 
 5411: sub delete_env_groupprivs {
 5412:     my ($where,$courseroles,$possroles) = @_;
 5413:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
 5414:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
 5415:     unless (ref($courseroles->{$udom}) eq 'HASH') {
 5416:         %{$courseroles->{$udom}} =
 5417:             &get_my_roles('','','userroles',['active'],
 5418:                           $possroles,[$udom],1);
 5419:     }
 5420:     if (ref($courseroles->{$udom}) eq 'HASH') {
 5421:         foreach my $item (keys(%{$courseroles->{$udom}})) {
 5422:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
 5423:             my $area = '/'.$cdom.'/'.$cnum;
 5424:             my $privkey = "user.priv.$crsrole.$area";
 5425:             if ($crssec ne '') {
 5426:                 $privkey .= '/'.$crssec;
 5427:             }
 5428:             $privkey .= ".$area/$group";
 5429:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
 5430:         }
 5431:     }
 5432:     return;
 5433: }
 5434: 
 5435: sub check_adhoc_privs {
 5436:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
 5437:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 5438:     my $setprivs;
 5439:     if ($env{$cckey}) {
 5440:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 5441:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 5442:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 5443:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
 5444:             $setprivs = 1;
 5445:         }
 5446:     } else {
 5447:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
 5448:         $setprivs = 1;
 5449:     }
 5450:     return $setprivs;
 5451: }
 5452: 
 5453: sub set_adhoc_privileges {
 5454: # role can be cc or ca
 5455:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
 5456:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 5457:     my $spec = $role.'.'.$area;
 5458:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 5459:                                   $env{'user.name'},1);
 5460:     my %ccrole = ();
 5461:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
 5462:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
 5463:     &appenv(\%userroles,[$role,'cm']);
 5464:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 5465:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
 5466:         &appenv( {'request.role'        => $spec,
 5467:                   'request.role.domain' => $dcdom,
 5468:                   'request.course.sec'  => ''
 5469:                  }
 5470:                );
 5471:         my $tadv=0;
 5472:         if (&allowed('adv') eq 'F') { $tadv=1; }
 5473:         &appenv({'request.role.adv'    => $tadv});
 5474:     }
 5475: }
 5476: 
 5477: # --------------------------------------------------------------- get interface
 5478: 
 5479: sub get {
 5480:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5481:    my $items='';
 5482:    foreach my $item (@$storearr) {
 5483:        $items.=&escape($item).'&';
 5484:    }
 5485:    $items=~s/\&$//;
 5486:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5487:    if (!$uname) { $uname=$env{'user.name'}; }
 5488:    my $uhome=&homeserver($uname,$udomain);
 5489: 
 5490:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 5491:    my @pairs=split(/\&/,$rep);
 5492:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 5493:      return @pairs;
 5494:    }
 5495:    my %returnhash=();
 5496:    my $i=0;
 5497:    foreach my $item (@$storearr) {
 5498:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 5499:       $i++;
 5500:    }
 5501:    return %returnhash;
 5502: }
 5503: 
 5504: # --------------------------------------------------------------- del interface
 5505: 
 5506: sub del {
 5507:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5508:    my $items='';
 5509:    foreach my $item (@$storearr) {
 5510:        $items.=&escape($item).'&';
 5511:    }
 5512: 
 5513:    $items=~s/\&$//;
 5514:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5515:    if (!$uname) { $uname=$env{'user.name'}; }
 5516:    my $uhome=&homeserver($uname,$udomain);
 5517:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 5518: }
 5519: 
 5520: # -------------------------------------------------------------- dump interface
 5521: 
 5522: sub unserialize {
 5523:     my ($rep, $escapedkeys) = @_;
 5524: 
 5525:     return {} if $rep =~ /^error/;
 5526: 
 5527:     my %returnhash=();
 5528: 	foreach my $item (split /\&/, $rep) {
 5529: 	    my ($key, $value) = split(/=/, $item, 2);
 5530: 	    $key = unescape($key) unless $escapedkeys;
 5531: 	    next if $key =~ /^error: 2 /;
 5532: 	    $returnhash{$key} = Apache::lonnet::thaw_unescape($value);
 5533: 	}
 5534:     #return %returnhash;
 5535:     return \%returnhash;
 5536: }        
 5537: 
 5538: # see Lond::dump_with_regexp
 5539: # if $escapedkeys hash keys won't get unescaped.
 5540: sub dump {
 5541:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
 5542:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5543:     if (!$uname) { $uname=$env{'user.name'}; }
 5544:     my $uhome=&homeserver($uname,$udomain);
 5545: 
 5546:     my $reply;
 5547:     if (grep { $_ eq $uhome } current_machine_ids()) {
 5548:         # user is hosted on this machine
 5549:         $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
 5550:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
 5551:         return %{unserialize($reply, $escapedkeys)};
 5552:     }
 5553:     if ($regexp) {
 5554: 	$regexp=&escape($regexp);
 5555:     } else {
 5556: 	$regexp='.';
 5557:     }
 5558:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 5559:     my @pairs=split(/\&/,$rep);
 5560:     my %returnhash=();
 5561:     if (!($rep =~ /^error/ )) {
 5562: 	foreach my $item (@pairs) {
 5563: 	    my ($key,$value)=split(/=/,$item,2);
 5564:         $key = unescape($key) unless $escapedkeys;
 5565:         #$key = &unescape($key);
 5566: 	    next if ($key =~ /^error: 2 /);
 5567: 	    $returnhash{$key}=&thaw_unescape($value);
 5568: 	}
 5569:     }
 5570:     return %returnhash;
 5571: }
 5572: 
 5573: 
 5574: # --------------------------------------------------------- dumpstore interface
 5575: 
 5576: sub dumpstore {
 5577:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 5578:    # same as dump but keys must be escaped. They may contain colon separated
 5579:    # lists of values that may themself contain colons (e.g. symbs).
 5580:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
 5581: }
 5582: 
 5583: # -------------------------------------------------------------- keys interface
 5584: 
 5585: sub getkeys {
 5586:    my ($namespace,$udomain,$uname)=@_;
 5587:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5588:    if (!$uname) { $uname=$env{'user.name'}; }
 5589:    my $uhome=&homeserver($uname,$udomain);
 5590:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 5591:    my @keyarray=();
 5592:    foreach my $key (split(/\&/,$rep)) {
 5593:       next if ($key =~ /^error: 2 /);
 5594:       push(@keyarray,&unescape($key));
 5595:    }
 5596:    return @keyarray;
 5597: }
 5598: 
 5599: # --------------------------------------------------------------- currentdump
 5600: sub currentdump {
 5601:    my ($courseid,$sdom,$sname)=@_;
 5602:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 5603:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 5604:    $sname    = $env{'user.name'}         if (! defined($sname));
 5605:    my $uhome = &homeserver($sname,$sdom);
 5606:    my $rep;
 5607: 
 5608:    if (grep { $_ eq $uhome } current_machine_ids()) {
 5609:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
 5610:                    $courseid)));
 5611:    } else {
 5612:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 5613:    }
 5614: 
 5615:    return if ($rep =~ /^(error:|no_such_host)/);
 5616:    #
 5617:    my %returnhash=();
 5618:    #
 5619:    if ($rep eq "unknown_cmd") { 
 5620:        # an old lond will not know currentdump
 5621:        # Do a dump and make it look like a currentdump
 5622:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 5623:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 5624:        my %hash = @tmp;
 5625:        @tmp=();
 5626:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 5627:    } else {
 5628:        my @pairs=split(/\&/,$rep);
 5629:        foreach my $pair (@pairs) {
 5630:            my ($key,$value)=split(/=/,$pair,2);
 5631:            my ($symb,$param) = split(/:/,$key);
 5632:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 5633:                                                         &thaw_unescape($value);
 5634:        }
 5635:    }
 5636:    return %returnhash;
 5637: }
 5638: 
 5639: sub convert_dump_to_currentdump{
 5640:     my %hash = %{shift()};
 5641:     my %returnhash;
 5642:     # Code ripped from lond, essentially.  The only difference
 5643:     # here is the unescaping done by lonnet::dump().  Conceivably
 5644:     # we might run in to problems with parameter names =~ /^v\./
 5645:     while (my ($key,$value) = each(%hash)) {
 5646:         my ($v,$symb,$param) = split(/:/,$key);
 5647: 	$symb  = &unescape($symb);
 5648: 	$param = &unescape($param);
 5649:         next if ($v eq 'version' || $symb eq 'keys');
 5650:         next if (exists($returnhash{$symb}) &&
 5651:                  exists($returnhash{$symb}->{$param}) &&
 5652:                  $returnhash{$symb}->{'v.'.$param} > $v);
 5653:         $returnhash{$symb}->{$param}=$value;
 5654:         $returnhash{$symb}->{'v.'.$param}=$v;
 5655:     }
 5656:     #
 5657:     # Remove all of the keys in the hashes which keep track of
 5658:     # the version of the parameter.
 5659:     while (my ($symb,$param_hash) = each(%returnhash)) {
 5660:         # use a foreach because we are going to delete from the hash.
 5661:         foreach my $key (keys(%$param_hash)) {
 5662:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 5663:         }
 5664:     }
 5665:     return \%returnhash;
 5666: }
 5667: 
 5668: # ------------------------------------------------------ critical inc interface
 5669: 
 5670: sub cinc {
 5671:     return &inc(@_,'critical');
 5672: }
 5673: 
 5674: # --------------------------------------------------------------- inc interface
 5675: 
 5676: sub inc {
 5677:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 5678:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5679:     if (!$uname) { $uname=$env{'user.name'}; }
 5680:     my $uhome=&homeserver($uname,$udomain);
 5681:     my $items='';
 5682:     if (! ref($store)) {
 5683:         # got a single value, so use that instead
 5684:         $items = &escape($store).'=&';
 5685:     } elsif (ref($store) eq 'SCALAR') {
 5686:         $items = &escape($$store).'=&';        
 5687:     } elsif (ref($store) eq 'ARRAY') {
 5688:         $items = join('=&',map {&escape($_);} @{$store});
 5689:     } elsif (ref($store) eq 'HASH') {
 5690:         while (my($key,$value) = each(%{$store})) {
 5691:             $items.= &escape($key).'='.&escape($value).'&';
 5692:         }
 5693:     }
 5694:     $items=~s/\&$//;
 5695:     if ($critical) {
 5696: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 5697:     } else {
 5698: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 5699:     }
 5700: }
 5701: 
 5702: # --------------------------------------------------------------- put interface
 5703: 
 5704: sub put {
 5705:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5706:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5707:    if (!$uname) { $uname=$env{'user.name'}; }
 5708:    my $uhome=&homeserver($uname,$udomain);
 5709:    my $items='';
 5710:    foreach my $item (keys(%$storehash)) {
 5711:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5712:    }
 5713:    $items=~s/\&$//;
 5714:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 5715: }
 5716: 
 5717: # ------------------------------------------------------------ newput interface
 5718: 
 5719: sub newput {
 5720:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5721:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5722:    if (!$uname) { $uname=$env{'user.name'}; }
 5723:    my $uhome=&homeserver($uname,$udomain);
 5724:    my $items='';
 5725:    foreach my $key (keys(%$storehash)) {
 5726:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 5727:    }
 5728:    $items=~s/\&$//;
 5729:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 5730: }
 5731: 
 5732: # ---------------------------------------------------------  putstore interface
 5733: 
 5734: sub putstore {
 5735:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 5736:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5737:    if (!$uname) { $uname=$env{'user.name'}; }
 5738:    my $uhome=&homeserver($uname,$udomain);
 5739:    my $items='';
 5740:    foreach my $key (keys(%$storehash)) {
 5741:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 5742:    }
 5743:    $items=~s/\&$//;
 5744:    my $esc_symb=&escape($symb);
 5745:    my $esc_v=&escape($version);
 5746:    my $reply =
 5747:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 5748: 	      $uhome);
 5749:    if ($reply eq 'unknown_cmd') {
 5750:        # gfall back to way things use to be done
 5751:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 5752: 			    $uname);
 5753:    }
 5754:    return $reply;
 5755: }
 5756: 
 5757: sub old_putstore {
 5758:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 5759:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5760:     if (!$uname) { $uname=$env{'user.name'}; }
 5761:     my $uhome=&homeserver($uname,$udomain);
 5762:     my %newstorehash;
 5763:     foreach my $item (keys(%$storehash)) {
 5764: 	my $key = $version.':'.&escape($symb).':'.$item;
 5765: 	$newstorehash{$key} = $storehash->{$item};
 5766:     }
 5767:     my $items='';
 5768:     my %allitems = ();
 5769:     foreach my $item (keys(%newstorehash)) {
 5770: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 5771: 	    my $key = $1.':keys:'.$2;
 5772: 	    $allitems{$key} .= $3.':';
 5773: 	}
 5774: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 5775:     }
 5776:     foreach my $item (keys(%allitems)) {
 5777: 	$allitems{$item} =~ s/\:$//;
 5778: 	$items.= $item.'='.$allitems{$item}.'&';
 5779:     }
 5780:     $items=~s/\&$//;
 5781:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 5782: }
 5783: 
 5784: # ------------------------------------------------------ critical put interface
 5785: 
 5786: sub cput {
 5787:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5788:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5789:    if (!$uname) { $uname=$env{'user.name'}; }
 5790:    my $uhome=&homeserver($uname,$udomain);
 5791:    my $items='';
 5792:    foreach my $item (keys(%$storehash)) {
 5793:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5794:    }
 5795:    $items=~s/\&$//;
 5796:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 5797: }
 5798: 
 5799: # -------------------------------------------------------------- eget interface
 5800: 
 5801: sub eget {
 5802:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5803:    my $items='';
 5804:    foreach my $item (@$storearr) {
 5805:        $items.=&escape($item).'&';
 5806:    }
 5807:    $items=~s/\&$//;
 5808:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5809:    if (!$uname) { $uname=$env{'user.name'}; }
 5810:    my $uhome=&homeserver($uname,$udomain);
 5811:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 5812:    my @pairs=split(/\&/,$rep);
 5813:    my %returnhash=();
 5814:    my $i=0;
 5815:    foreach my $item (@$storearr) {
 5816:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 5817:       $i++;
 5818:    }
 5819:    return %returnhash;
 5820: }
 5821: 
 5822: # ------------------------------------------------------------ tmpput interface
 5823: sub tmpput {
 5824:     my ($storehash,$server,$context)=@_;
 5825:     my $items='';
 5826:     foreach my $item (keys(%$storehash)) {
 5827: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5828:     }
 5829:     $items=~s/\&$//;
 5830:     if (defined($context)) {
 5831:         $items .= ':'.&escape($context);
 5832:     }
 5833:     return &reply("tmpput:$items",$server);
 5834: }
 5835: 
 5836: # ------------------------------------------------------------ tmpget interface
 5837: sub tmpget {
 5838:     my ($token,$server)=@_;
 5839:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 5840:     my $rep=&reply("tmpget:$token",$server);
 5841:     my %returnhash;
 5842:     foreach my $item (split(/\&/,$rep)) {
 5843: 	my ($key,$value)=split(/=/,$item);
 5844:         next if ($key =~ /^error: 2 /);
 5845: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 5846:     }
 5847:     return %returnhash;
 5848: }
 5849: 
 5850: # ------------------------------------------------------------ tmpdel interface
 5851: sub tmpdel {
 5852:     my ($token,$server)=@_;
 5853:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 5854:     return &reply("tmpdel:$token",$server);
 5855: }
 5856: 
 5857: # ------------------------------------------------------------ get_timebased_id 
 5858: 
 5859: sub get_timebased_id {
 5860:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
 5861:         $maxtries) = @_;
 5862:     my ($newid,$error,$dellock);
 5863:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
 5864:         return ('','ok','invalid call to get suffix');
 5865:     }
 5866: 
 5867: # set defaults for any optional args for which values were not supplied
 5868:     if ($who eq '') {
 5869:         $who = $env{'user.name'}.':'.$env{'user.domain'};
 5870:     }
 5871:     if (!$locktries) {
 5872:         $locktries = 3;
 5873:     }
 5874:     if (!$maxtries) {
 5875:         $maxtries = 10;
 5876:     }
 5877:     
 5878:     if (($cdom eq '') || ($cnum eq '')) {
 5879:         if ($env{'request.course.id'}) {
 5880:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5881:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5882:         }
 5883:         if (($cdom eq '') || ($cnum eq '')) {
 5884:             return ('','ok','call to get suffix not in course context');
 5885:         }
 5886:     }
 5887: 
 5888: # construct locking item
 5889:     my $lockhash = {
 5890:                       $prefix."\0".'locked_'.$keyid => $who,
 5891:                    };
 5892:     my $tries = 0;
 5893: 
 5894: # attempt to get lock on nohist_$namespace file
 5895:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 5896:     while (($gotlock ne 'ok') && $tries <$locktries) {
 5897:         $tries ++;
 5898:         sleep 1;
 5899:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 5900:     }
 5901: 
 5902: # attempt to get unique identifier, based on current timestamp
 5903:     if ($gotlock eq 'ok') {
 5904:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
 5905:         my $id = time;
 5906:         $newid = $id;
 5907:         my $idtries = 0;
 5908:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
 5909:             if ($idtype eq 'concat') {
 5910:                 $newid = $id.$idtries;
 5911:             } else {
 5912:                 $newid ++;
 5913:             }
 5914:             $idtries ++;
 5915:         }
 5916:         if (!exists($inuse{$prefix."\0".$newid})) {
 5917:             my %new_item =  (
 5918:                               $prefix."\0".$newid => $who,
 5919:                             );
 5920:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
 5921:                                                  $cdom,$cnum);
 5922:             if ($putresult ne 'ok') {
 5923:                 undef($newid);
 5924:                 $error = 'error saving new item: '.$putresult;
 5925:             }
 5926:         } else {
 5927:              $error = ('error: no unique suffix available for the new item ');
 5928:         }
 5929: #  remove lock
 5930:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
 5931:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
 5932:     } else {
 5933:         $error = "error: could not obtain lockfile\n";
 5934:         $dellock = 'ok';
 5935:     }
 5936:     return ($newid,$dellock,$error);
 5937: }
 5938: 
 5939: # -------------------------------------------------- portfolio access checking
 5940: 
 5941: sub portfolio_access {
 5942:     my ($requrl) = @_;
 5943:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 5944:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
 5945:     if ($result) {
 5946:         my %setters;
 5947:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 5948:             my ($startblock,$endblock) =
 5949:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 5950:             if ($startblock && $endblock) {
 5951:                 return 'B';
 5952:             }
 5953:         } else {
 5954:             my ($startblock,$endblock) =
 5955:                 &Apache::loncommon::blockcheck(\%setters,'port');
 5956:             if ($startblock && $endblock) {
 5957:                 return 'B';
 5958:             }
 5959:         }
 5960:     }
 5961:     if ($result eq 'ok') {
 5962:        return 'F';
 5963:     } elsif ($result =~ /^[^:]+:guest_/) {
 5964:        return 'A';
 5965:     }
 5966:     return '';
 5967: }
 5968: 
 5969: sub get_portfolio_access {
 5970:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
 5971: 
 5972:     if (!ref($access_hash)) {
 5973: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 5974: 	my %access_controls = &get_access_controls($current_perms,$group,
 5975: 						   $file_name);
 5976: 	$access_hash = $access_controls{$file_name};
 5977:     }
 5978: 
 5979:     my ($public,$guest,@domains,@users,@courses,@groups);
 5980:     my $now = time;
 5981:     if (ref($access_hash) eq 'HASH') {
 5982:         foreach my $key (keys(%{$access_hash})) {
 5983:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 5984:             if ($start > $now) {
 5985:                 next;
 5986:             }
 5987:             if ($end && $end<$now) {
 5988:                 next;
 5989:             }
 5990:             if ($scope eq 'public') {
 5991:                 $public = $key;
 5992:                 last;
 5993:             } elsif ($scope eq 'guest') {
 5994:                 $guest = $key;
 5995:             } elsif ($scope eq 'domains') {
 5996:                 push(@domains,$key);
 5997:             } elsif ($scope eq 'users') {
 5998:                 push(@users,$key);
 5999:             } elsif ($scope eq 'course') {
 6000:                 push(@courses,$key);
 6001:             } elsif ($scope eq 'group') {
 6002:                 push(@groups,$key);
 6003:             }
 6004:         }
 6005:         if ($public) {
 6006:             return 'ok';
 6007:         }
 6008:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 6009:             if ($guest) {
 6010:                 return $guest;
 6011:             }
 6012:         } else {
 6013:             if (@domains > 0) {
 6014:                 foreach my $domkey (@domains) {
 6015:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 6016:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 6017:                             return 'ok';
 6018:                         }
 6019:                     }
 6020:                 }
 6021:             }
 6022:             if (@users > 0) {
 6023:                 foreach my $userkey (@users) {
 6024:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 6025:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 6026:                             if (ref($item) eq 'HASH') {
 6027:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 6028:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 6029:                                     return 'ok';
 6030:                                 }
 6031:                             }
 6032:                         }
 6033:                     } 
 6034:                 }
 6035:             }
 6036:             my %roleshash;
 6037:             my @courses_and_groups = @courses;
 6038:             push(@courses_and_groups,@groups); 
 6039:             if (@courses_and_groups > 0) {
 6040:                 my (%allgroups,%allroles); 
 6041:                 my ($start,$end,$role,$sec,$group);
 6042:                 foreach my $envkey (%env) {
 6043:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 6044:                         my $cid = $2.'_'.$3; 
 6045:                         if ($1 eq 'gr') {
 6046:                             $group = $4;
 6047:                             $allgroups{$cid}{$group} = $env{$envkey};
 6048:                         } else {
 6049:                             if ($4 eq '') {
 6050:                                 $sec = 'none';
 6051:                             } else {
 6052:                                 $sec = $4;
 6053:                             }
 6054:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 6055:                         }
 6056:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 6057:                         my $cid = $2.'_'.$3;
 6058:                         if ($4 eq '') {
 6059:                             $sec = 'none';
 6060:                         } else {
 6061:                             $sec = $4;
 6062:                         }
 6063:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 6064:                     }
 6065:                 }
 6066:                 if (keys(%allroles) == 0) {
 6067:                     return;
 6068:                 }
 6069:                 foreach my $key (@courses_and_groups) {
 6070:                     my %content = %{$$access_hash{$key}};
 6071:                     my $cnum = $content{'number'};
 6072:                     my $cdom = $content{'domain'};
 6073:                     my $cid = $cdom.'_'.$cnum;
 6074:                     if (!exists($allroles{$cid})) {
 6075:                         next;
 6076:                     }    
 6077:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 6078:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 6079:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 6080:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 6081:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 6082:                         foreach my $role (keys(%{$allroles{$cid}})) {
 6083:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 6084:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 6085:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 6086:                                         if (grep/^all$/,@sections) {
 6087:                                             return 'ok';
 6088:                                         } else {
 6089:                                             if (grep/^$sec$/,@sections) {
 6090:                                                 return 'ok';
 6091:                                             }
 6092:                                         }
 6093:                                     }
 6094:                                 }
 6095:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 6096:                                     if (grep/^none$/,@groups) {
 6097:                                         return 'ok';
 6098:                                     }
 6099:                                 } else {
 6100:                                     if (grep/^all$/,@groups) {
 6101:                                         return 'ok';
 6102:                                     } 
 6103:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 6104:                                         if (grep/^$group$/,@groups) {
 6105:                                             return 'ok';
 6106:                                         }
 6107:                                     }
 6108:                                 } 
 6109:                             }
 6110:                         }
 6111:                     }
 6112:                 }
 6113:             }
 6114:             if ($guest) {
 6115:                 return $guest;
 6116:             }
 6117:         }
 6118:     }
 6119:     return;
 6120: }
 6121: 
 6122: sub course_group_datechecker {
 6123:     my ($dates,$now,$status) = @_;
 6124:     my ($start,$end) = split(/\./,$dates);
 6125:     if (!$start && !$end) {
 6126:         return 'ok';
 6127:     }
 6128:     if (grep/^active$/,@{$status}) {
 6129:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 6130:             return 'ok';
 6131:         }
 6132:     }
 6133:     if (grep/^previous$/,@{$status}) {
 6134:         if ($end > $now ) {
 6135:             return 'ok';
 6136:         }
 6137:     }
 6138:     if (grep/^future$/,@{$status}) {
 6139:         if ($start > $now) {
 6140:             return 'ok';
 6141:         }
 6142:     }
 6143:     return; 
 6144: }
 6145: 
 6146: sub parse_portfolio_url {
 6147:     my ($url) = @_;
 6148: 
 6149:     my ($type,$udom,$unum,$group,$file_name);
 6150:     
 6151:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 6152: 	$type = 1;
 6153:         $udom = $1;
 6154:         $unum = $2;
 6155:         $file_name = $3;
 6156:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 6157: 	$type = 2;
 6158:         $udom = $1;
 6159:         $unum = $2;
 6160:         $group = $3;
 6161:         $file_name = $3.'/'.$4;
 6162:     }
 6163:     if (wantarray) {
 6164: 	return ($type,$udom,$unum,$file_name,$group);
 6165:     }
 6166:     return $type;
 6167: }
 6168: 
 6169: sub is_portfolio_url {
 6170:     my ($url) = @_;
 6171:     return scalar(&parse_portfolio_url($url));
 6172: }
 6173: 
 6174: sub is_portfolio_file {
 6175:     my ($file) = @_;
 6176:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 6177:         return 1;
 6178:     }
 6179:     return;
 6180: }
 6181: 
 6182: sub usertools_access {
 6183:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
 6184:     my ($access,%tools);
 6185:     if ($context eq '') {
 6186:         $context = 'tools';
 6187:     }
 6188:     if ($context eq 'requestcourses') {
 6189:         %tools = (
 6190:                       official   => 1,
 6191:                       unofficial => 1,
 6192:                       community  => 1,
 6193:                  );
 6194:     } elsif ($context eq 'requestauthor') {
 6195:         %tools = (
 6196:                       requestauthor => 1,
 6197:                  );
 6198:     } else {
 6199:         %tools = (
 6200:                       aboutme   => 1,
 6201:                       blog      => 1,
 6202:                       webdav    => 1,
 6203:                       portfolio => 1,
 6204:                  );
 6205:     }
 6206:     return if (!defined($tools{$tool}));
 6207: 
 6208:     if (($udom eq '') || ($uname eq '')) {
 6209:         $udom = $env{'user.domain'};
 6210:         $uname = $env{'user.name'};
 6211:     }
 6212: 
 6213:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 6214:         if ($action ne 'reload') {
 6215:             if ($context eq 'requestcourses') {
 6216:                 return $env{'environment.canrequest.'.$tool};
 6217:             } elsif ($context eq 'requestauthor') {
 6218:                 return $env{'environment.canrequest.author'};
 6219:             } else {
 6220:                 return $env{'environment.availabletools.'.$tool};
 6221:             }
 6222:         }
 6223:     }
 6224: 
 6225:     my ($toolstatus,$inststatus,$envkey);
 6226:     if ($context eq 'requestauthor') {
 6227:         $envkey = $context; 
 6228:     } else {
 6229:         $envkey = $context.'.'.$tool;
 6230:     }
 6231: 
 6232:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 6233:          ($action ne 'reload')) {
 6234:         $toolstatus = $env{'environment.'.$envkey};
 6235:         $inststatus = $env{'environment.inststatus'};
 6236:     } else {
 6237:         if (ref($userenvref) eq 'HASH') {
 6238:             $toolstatus = $userenvref->{$envkey};
 6239:             $inststatus = $userenvref->{'inststatus'};
 6240:         } else {
 6241:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
 6242:             $toolstatus = $userenv{$envkey};
 6243:             $inststatus = $userenv{'inststatus'};
 6244:         }
 6245:     }
 6246: 
 6247:     if ($toolstatus ne '') {
 6248:         if ($toolstatus) {
 6249:             $access = 1;
 6250:         } else {
 6251:             $access = 0;
 6252:         }
 6253:         return $access;
 6254:     }
 6255: 
 6256:     my ($is_adv,%domdef);
 6257:     if (ref($is_advref) eq 'HASH') {
 6258:         $is_adv = $is_advref->{'is_adv'};
 6259:     } else {
 6260:         $is_adv = &is_advanced_user($udom,$uname);
 6261:     }
 6262:     if (ref($domdefref) eq 'HASH') {
 6263:         %domdef = %{$domdefref};
 6264:     } else {
 6265:         %domdef = &get_domain_defaults($udom);
 6266:     }
 6267:     if (ref($domdef{$tool}) eq 'HASH') {
 6268:         if ($is_adv) {
 6269:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 6270:                 if ($domdef{$tool}{'_LC_adv'}) { 
 6271:                     $access = 1;
 6272:                 } else {
 6273:                     $access = 0;
 6274:                 }
 6275:                 return $access;
 6276:             }
 6277:         }
 6278:         if ($inststatus ne '') {
 6279:             my ($hasaccess,$hasnoaccess);
 6280:             foreach my $affiliation (split(/:/,$inststatus)) {
 6281:                 if ($domdef{$tool}{$affiliation} ne '') { 
 6282:                     if ($domdef{$tool}{$affiliation}) {
 6283:                         $hasaccess = 1;
 6284:                     } else {
 6285:                         $hasnoaccess = 1;
 6286:                     }
 6287:                 }
 6288:             }
 6289:             if ($hasaccess || $hasnoaccess) {
 6290:                 if ($hasaccess) {
 6291:                     $access = 1;
 6292:                 } elsif ($hasnoaccess) {
 6293:                     $access = 0; 
 6294:                 }
 6295:                 return $access;
 6296:             }
 6297:         } else {
 6298:             if ($domdef{$tool}{'default'} ne '') {
 6299:                 if ($domdef{$tool}{'default'}) {
 6300:                     $access = 1;
 6301:                 } elsif ($domdef{$tool}{'default'} == 0) {
 6302:                     $access = 0;
 6303:                 }
 6304:                 return $access;
 6305:             }
 6306:         }
 6307:     } else {
 6308:         if (($context eq 'tools') && ($tool ne 'webdav')) {
 6309:             $access = 1;
 6310:         } else {
 6311:             $access = 0;
 6312:         }
 6313:         return $access;
 6314:     }
 6315: }
 6316: 
 6317: sub is_course_owner {
 6318:     my ($cdom,$cnum,$udom,$uname) = @_;
 6319:     if (($udom eq '') || ($uname eq '')) {
 6320:         $udom = $env{'user.domain'};
 6321:         $uname = $env{'user.name'};
 6322:     }
 6323:     unless (($udom eq '') || ($uname eq '')) {
 6324:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
 6325:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
 6326:                 return 1;
 6327:             } else {
 6328:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
 6329:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
 6330:                     return 1;
 6331:                 }
 6332:             }
 6333:         }
 6334:     }
 6335:     return;
 6336: }
 6337: 
 6338: sub is_advanced_user {
 6339:     my ($udom,$uname) = @_;
 6340:     if ($udom ne '' && $uname ne '') {
 6341:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 6342:             if (wantarray) {
 6343:                 return ($env{'user.adv'},$env{'user.author'});
 6344:             } else {
 6345:                 return $env{'user.adv'};
 6346:             }
 6347:         }
 6348:     }
 6349:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 6350:     my %allroles;
 6351:     my ($is_adv,$is_author);
 6352:     foreach my $role (keys(%roleshash)) {
 6353:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 6354:         my $area = '/'.$tdomain.'/'.$trest;
 6355:         if ($sec ne '') {
 6356:             $area .= '/'.$sec;
 6357:         }
 6358:         if (($area ne '') && ($trole ne '')) {
 6359:             my $spec=$trole.'.'.$area;
 6360:             if ($trole =~ /^cr\//) {
 6361:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 6362:             } elsif ($trole ne 'gr') {
 6363:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 6364:             }
 6365:             if ($trole eq 'au') {
 6366:                 $is_author = 1;
 6367:             }
 6368:         }
 6369:     }
 6370:     foreach my $role (keys(%allroles)) {
 6371:         last if ($is_adv);
 6372:         foreach my $item (split(/:/,$allroles{$role})) {
 6373:             if ($item ne '') {
 6374:                 my ($privilege,$restrictions)=split(/&/,$item);
 6375:                 if ($privilege eq 'adv') {
 6376:                     $is_adv = 1;
 6377:                     last;
 6378:                 }
 6379:             }
 6380:         }
 6381:     }
 6382:     if (wantarray) {
 6383:         return ($is_adv,$is_author);
 6384:     }
 6385:     return $is_adv;
 6386: }
 6387: 
 6388: sub check_can_request {
 6389:     my ($dom,$can_request,$request_domains) = @_;
 6390:     my $canreq = 0;
 6391:     my ($types,$typename) = &Apache::loncommon::course_types();
 6392:     my @options = ('approval','validate','autolimit');
 6393:     my $optregex = join('|',@options);
 6394:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
 6395:         foreach my $type (@{$types}) {
 6396:             if (&usertools_access($env{'user.name'},
 6397:                                   $env{'user.domain'},
 6398:                                   $type,undef,'requestcourses')) {
 6399:                 $canreq ++;
 6400:                 if (ref($request_domains) eq 'HASH') {
 6401:                     push(@{$request_domains->{$type}},$env{'user.domain'});
 6402:                 }
 6403:                 if ($dom eq $env{'user.domain'}) {
 6404:                     $can_request->{$type} = 1;
 6405:                 }
 6406:             }
 6407:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
 6408:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
 6409:                 if (@curr > 0) {
 6410:                     foreach my $item (@curr) {
 6411:                         if (ref($request_domains) eq 'HASH') {
 6412:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
 6413:                             if ($otherdom ne '') {
 6414:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
 6415:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
 6416:                                         push(@{$request_domains->{$type}},$otherdom);
 6417:                                     }
 6418:                                 } else {
 6419:                                     push(@{$request_domains->{$type}},$otherdom);
 6420:                                 }
 6421:                             }
 6422:                         }
 6423:                     }
 6424:                     unless($dom eq $env{'user.domain'}) {
 6425:                         $canreq ++;
 6426:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
 6427:                             $can_request->{$type} = 1;
 6428:                         }
 6429:                     }
 6430:                 }
 6431:             }
 6432:         }
 6433:     }
 6434:     return $canreq;
 6435: }
 6436: 
 6437: # ---------------------------------------------- Custom access rule evaluation
 6438: 
 6439: sub customaccess {
 6440:     my ($priv,$uri)=@_;
 6441:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 6442:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 6443:     $udom = &LONCAPA::clean_domain($udom);
 6444:     $ucrs = &LONCAPA::clean_username($ucrs);
 6445:     my $access=0;
 6446:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 6447: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 6448: 	if ($type eq 'user') {
 6449: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 6450: 		my ($tdom,$tuname)=split(m{/},$scope);
 6451: 		if ($tdom) {
 6452: 		    if ($tdom ne $env{'user.domain'}) { next; }
 6453: 		}
 6454: 		if ($tuname) {
 6455: 		    if ($tuname ne $env{'user.name'}) { next; }
 6456: 		}
 6457: 		$access=($effect eq 'allow');
 6458: 		last;
 6459: 	    }
 6460: 	} else {
 6461: 	    if ($role) {
 6462: 		if ($role ne $urole) { next; }
 6463: 	    }
 6464: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 6465: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 6466: 		if ($tdom) {
 6467: 		    if ($tdom ne $udom) { next; }
 6468: 		}
 6469: 		if ($tcrs) {
 6470: 		    if ($tcrs ne $ucrs) { next; }
 6471: 		}
 6472: 		if ($tsec) {
 6473: 		    if ($tsec ne $usec) { next; }
 6474: 		}
 6475: 		$access=($effect eq 'allow');
 6476: 		last;
 6477: 	    }
 6478: 	    if ($realm eq '' && $role eq '') {
 6479: 		$access=($effect eq 'allow');
 6480: 	    }
 6481: 	}
 6482:     }
 6483:     return $access;
 6484: }
 6485: 
 6486: # ------------------------------------------------- Check for a user privilege
 6487: 
 6488: sub allowed {
 6489:     my ($priv,$uri,$symb,$role)=@_;
 6490:     my $ver_orguri=$uri;
 6491:     $uri=&deversion($uri);
 6492:     my $orguri=$uri;
 6493:     $uri=&declutter($uri);
 6494: 
 6495:     if ($priv eq 'evb') {
 6496: # Evade communication block restrictions for specified role in a course
 6497:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 6498:             return $1;
 6499:         } else {
 6500:             return;
 6501:         }
 6502:     }
 6503: 
 6504:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 6505: # Free bre access to adm and meta resources
 6506:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
 6507: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 6508: 	&& ($priv eq 'bre')) {
 6509: 	return 'F';
 6510:     }
 6511: 
 6512: # Free bre access to user's own portfolio contents
 6513:     my ($space,$domain,$name,@dir)=split('/',$uri);
 6514:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 6515: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 6516:         my %setters;
 6517:         my ($startblock,$endblock) = 
 6518:             &Apache::loncommon::blockcheck(\%setters,'port');
 6519:         if ($startblock && $endblock) {
 6520:             return 'B';
 6521:         } else {
 6522:             return 'F';
 6523:         }
 6524:     }
 6525: 
 6526: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 6527:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 6528:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 6529:         if (exists($env{'request.course.id'})) {
 6530:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6531:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 6532:             if (($domain eq $cdom) && ($name eq $cnum)) {
 6533:                 my $courseprivid=$env{'request.course.id'};
 6534:                 $courseprivid=~s/\_/\//;
 6535:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 6536:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 6537:                     return $1; 
 6538:                 } else {
 6539:                     if ($env{'request.course.sec'}) {
 6540:                         $courseprivid.='/'.$env{'request.course.sec'};
 6541:                     }
 6542:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 6543:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 6544:                         return $2;
 6545:                     }
 6546:                 }
 6547:             }
 6548:         }
 6549:     }
 6550: 
 6551: # Free bre to public access
 6552: 
 6553:     if ($priv eq 'bre') {
 6554:         my $copyright=&metadata($uri,'copyright');
 6555: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 6556:            return 'F'; 
 6557:         }
 6558:         if ($copyright eq 'priv') {
 6559:             $uri=~/([^\/]+)\/([^\/]+)\//;
 6560: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 6561: 		return '';
 6562:             }
 6563:         }
 6564:         if ($copyright eq 'domain') {
 6565:             $uri=~/([^\/]+)\/([^\/]+)\//;
 6566: 	    unless (($env{'user.domain'} eq $1) ||
 6567:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 6568: 		return '';
 6569:             }
 6570:         }
 6571:         if ($env{'request.role'}=~ /li\.\//) {
 6572:             # Library role, so allow browsing of resources in this domain.
 6573:             return 'F';
 6574:         }
 6575:         if ($copyright eq 'custom') {
 6576: 	    unless (&customaccess($priv,$uri)) { return ''; }
 6577:         }
 6578:     }
 6579:     # Domain coordinator is trying to create a course
 6580:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 6581:         # uri is the requested domain in this case.
 6582:         # comparison to 'request.role.domain' shows if the user has selected
 6583:         # a role of dc for the domain in question.
 6584:         return 'F' if ($uri eq $env{'request.role.domain'});
 6585:     }
 6586: 
 6587:     my $thisallowed='';
 6588:     my $statecond=0;
 6589:     my $courseprivid='';
 6590: 
 6591:     my $ownaccess;
 6592:     # Community Coordinator or Assistant Co-author browsing resource space.
 6593:     if (($priv eq 'bro') && ($env{'user.author'})) {
 6594:         if ($uri eq '') {
 6595:             $ownaccess = 1;
 6596:         } else {
 6597:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
 6598:                 my $udom = $env{'user.domain'};
 6599:                 my $uname = $env{'user.name'};
 6600:                 if ($uri =~ m{^\Q$udom\E/?$}) {
 6601:                     $ownaccess = 1;
 6602:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
 6603:                     unless ($uri =~ m{\.\./}) {
 6604:                         $ownaccess = 1;
 6605:                     }
 6606:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
 6607:                     my $now = time;
 6608:                     if ($uri =~ m{^([^/]+)/?$}) {
 6609:                         my $adom = $1;
 6610:                         foreach my $key (keys(%env)) {
 6611:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
 6612:                                 my ($start,$end) = split('.',$env{$key});
 6613:                                 if (($now >= $start) && (!$end || $end < $now)) {
 6614:                                     $ownaccess = 1;
 6615:                                     last;
 6616:                                 }
 6617:                             }
 6618:                         }
 6619:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
 6620:                         my $adom = $1;
 6621:                         my $aname = $2;
 6622:                         foreach my $role ('ca','aa') { 
 6623:                             if ($env{"user.role.$role./$adom/$aname"}) {
 6624:                                 my ($start,$end) =
 6625:                                     split('.',$env{"user.role.$role./$adom/$aname"});
 6626:                                 if (($now >= $start) && (!$end || $end < $now)) {
 6627:                                     $ownaccess = 1;
 6628:                                     last;
 6629:                                 }
 6630:                             }
 6631:                         }
 6632:                     }
 6633:                 }
 6634:             }
 6635:         }
 6636:     }
 6637: 
 6638: # Course
 6639: 
 6640:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 6641:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6642:             $thisallowed.=$1;
 6643:         }
 6644:     }
 6645: 
 6646: # Domain
 6647: 
 6648:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 6649:        =~/\Q$priv\E\&([^\:]*)/) {
 6650:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6651:             $thisallowed.=$1;
 6652:         }
 6653:     }
 6654: 
 6655: # User who is not author or co-author might still be able to edit
 6656: # resource of an author in the domain (e.g., if Domain Coordinator).
 6657:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
 6658:         (&allowed('mdc',$env{'request.course.id'}))) {
 6659:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
 6660:             $thisallowed.=$1;
 6661:         }
 6662:     }
 6663: 
 6664: # Course: uri itself is a course
 6665:     my $courseuri=$uri;
 6666:     $courseuri=~s/\_(\d)/\/$1/;
 6667:     $courseuri=~s/^([^\/])/\/$1/;
 6668: 
 6669:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 6670:        =~/\Q$priv\E\&([^\:]*)/) {
 6671:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6672:             $thisallowed.=$1;
 6673:         }
 6674:     }
 6675: 
 6676: # URI is an uploaded document for this course, default permissions don't matter
 6677: # not allowing 'edit' access (editupload) to uploaded course docs
 6678:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 6679: 	$thisallowed='';
 6680:         my ($match)=&is_on_map($uri);
 6681:         if ($match) {
 6682:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 6683:                   =~/\Q$priv\E\&([^\:]*)/) {
 6684:                 my @blockers = &has_comm_blocking($priv,$symb,$uri);
 6685:                 if (@blockers > 0) {
 6686:                     $thisallowed = 'B';
 6687:                 } else {
 6688:                     $thisallowed.=$1;
 6689:                 }
 6690:             }
 6691:         } else {
 6692:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 6693:             if ($refuri) {
 6694:                 if ($refuri =~ m|^/adm/|) {
 6695:                     $thisallowed='F';
 6696:                 } else {
 6697:                     $refuri=&declutter($refuri);
 6698:                     my ($match) = &is_on_map($refuri);
 6699:                     if ($match) {
 6700:                         my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 6701:                         if (@blockers > 0) {
 6702:                             $thisallowed = 'B';
 6703:                         } else {
 6704:                             $thisallowed='F';
 6705:                         }
 6706:                     }
 6707:                 }
 6708:             }
 6709:         }
 6710:     }
 6711: 
 6712:     if ($priv eq 'bre'
 6713: 	&& $thisallowed ne 'F' 
 6714: 	&& $thisallowed ne '2'
 6715: 	&& &is_portfolio_url($uri)) {
 6716: 	$thisallowed = &portfolio_access($uri);
 6717:     }
 6718:     
 6719: # Full access at system, domain or course-wide level? Exit.
 6720:     if ($thisallowed=~/F/) {
 6721: 	return 'F';
 6722:     }
 6723: 
 6724: # If this is generating or modifying users, exit with special codes
 6725: 
 6726:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 6727: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 6728: 	    my ($audom,$auname)=split('/',$uri);
 6729: # no author name given, so this just checks on the general right to make a co-author in this domain
 6730: 	    unless ($auname) { return $thisallowed; }
 6731: # an author name is given, so we are about to actually make a co-author for a certain account
 6732: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 6733: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 6734: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 6735: 	}
 6736: 	return $thisallowed;
 6737:     }
 6738: #
 6739: # Gathered so far: system, domain and course wide privileges
 6740: #
 6741: # Course: See if uri or referer is an individual resource that is part of 
 6742: # the course
 6743: 
 6744:     if ($env{'request.course.id'}) {
 6745: 
 6746:        $courseprivid=$env{'request.course.id'};
 6747:        if ($env{'request.course.sec'}) {
 6748:           $courseprivid.='/'.$env{'request.course.sec'};
 6749:        }
 6750:        $courseprivid=~s/\_/\//;
 6751:        my $checkreferer=1;
 6752:        my ($match,$cond)=&is_on_map($uri);
 6753:        if ($match) {
 6754:            $statecond=$cond;
 6755:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 6756:                =~/\Q$priv\E\&([^\:]*)/) {
 6757:                my $value = $1;
 6758:                if ($priv eq 'bre') {
 6759:                    my @blockers = &has_comm_blocking($priv,$symb,$uri);
 6760:                    if (@blockers > 0) {
 6761:                        $thisallowed = 'B';
 6762:                    } else {
 6763:                        $thisallowed.=$value;
 6764:                    }
 6765:                } else {
 6766:                    $thisallowed.=$value;
 6767:                }
 6768:                $checkreferer=0;
 6769:            }
 6770:        }
 6771:        
 6772:        if ($checkreferer) {
 6773: 	  my $refuri=$env{'httpref.'.$orguri};
 6774:             unless ($refuri) {
 6775:                 foreach my $key (keys(%env)) {
 6776: 		    if ($key=~/^httpref\..*\*/) {
 6777: 			my $pattern=$key;
 6778:                         $pattern=~s/^httpref\.\/res\///;
 6779:                         $pattern=~s/\*/\[\^\/\]\+/g;
 6780:                         $pattern=~s/\//\\\//g;
 6781:                         if ($orguri=~/$pattern/) {
 6782: 			    $refuri=$env{$key};
 6783:                         }
 6784:                     }
 6785:                 }
 6786:             }
 6787: 
 6788:          if ($refuri) { 
 6789: 	  $refuri=&declutter($refuri);
 6790:           my ($match,$cond)=&is_on_map($refuri);
 6791:             if ($match) {
 6792:               my $refstatecond=$cond;
 6793:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 6794:                   =~/\Q$priv\E\&([^\:]*)/) {
 6795:                   my $value = $1;
 6796:                   if ($priv eq 'bre') {
 6797:                       my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 6798:                       if (@blockers > 0) {
 6799:                           $thisallowed = 'B';
 6800:                       } else {
 6801:                           $thisallowed.=$value;
 6802:                       }
 6803:                   } else {
 6804:                       $thisallowed.=$value;
 6805:                   }
 6806:                   $uri=$refuri;
 6807:                   $statecond=$refstatecond;
 6808:               }
 6809:           }
 6810:         }
 6811:        }
 6812:    }
 6813: 
 6814: #
 6815: # Gathered now: all privileges that could apply, and condition number
 6816: # 
 6817: #
 6818: # Full or no access?
 6819: #
 6820: 
 6821:     if ($thisallowed=~/F/) {
 6822: 	return 'F';
 6823:     }
 6824: 
 6825:     unless ($thisallowed) {
 6826:         return '';
 6827:     }
 6828: 
 6829: # Restrictions exist, deal with them
 6830: #
 6831: #   C:according to course preferences
 6832: #   R:according to resource settings
 6833: #   L:unless locked
 6834: #   X:according to user session state
 6835: #
 6836: 
 6837: # Possibly locked functionality, check all courses
 6838: # Locks might take effect only after 10 minutes cache expiration for other
 6839: # courses, and 2 minutes for current course
 6840: 
 6841:     my $envkey;
 6842:     if ($thisallowed=~/L/) {
 6843:         foreach $envkey (keys(%env)) {
 6844:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 6845:                my $courseid=$2;
 6846:                my $roleid=$1.'.'.$2;
 6847:                $courseid=~s/^\///;
 6848:                my $expiretime=600;
 6849:                if ($env{'request.role'} eq $roleid) {
 6850: 		  $expiretime=120;
 6851:                }
 6852: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 6853:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 6854:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 6855: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 6856:                }
 6857:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 6858:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 6859: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 6860:                        &log($env{'user.domain'},$env{'user.name'},
 6861:                             $env{'user.home'},
 6862:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 6863:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 6864:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 6865: 		       return '';
 6866:                    }
 6867:                }
 6868:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 6869:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 6870: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 6871:                        &log($env{'user.domain'},$env{'user.name'},
 6872:                             $env{'user.home'},
 6873:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 6874:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 6875:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 6876: 		       return '';
 6877:                    }
 6878:                }
 6879: 	   }
 6880:        }
 6881:     }
 6882:    
 6883: #
 6884: # Rest of the restrictions depend on selected course
 6885: #
 6886: 
 6887:     unless ($env{'request.course.id'}) {
 6888: 	if ($thisallowed eq 'A') {
 6889: 	    return 'A';
 6890:         } elsif ($thisallowed eq 'B') {
 6891:             return 'B';
 6892: 	} else {
 6893: 	    return '1';
 6894: 	}
 6895:     }
 6896: 
 6897: #
 6898: # Now user is definitely in a course
 6899: #
 6900: 
 6901: 
 6902: # Course preferences
 6903: 
 6904:    if ($thisallowed=~/C/) {
 6905:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 6906:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 6907:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 6908: 	   =~/\Q$rolecode\E/) {
 6909: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 6910: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 6911: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 6912: 			$env{'request.course.id'});
 6913: 	   }
 6914:            return '';
 6915:        }
 6916: 
 6917:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 6918: 	   =~/\Q$unamedom\E/) {
 6919: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 6920: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 6921: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 6922: 			$env{'request.course.id'});
 6923: 	   }
 6924:            return '';
 6925:        }
 6926:    }
 6927: 
 6928: # Resource preferences
 6929: 
 6930:    if ($thisallowed=~/R/) {
 6931:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 6932:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 6933: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 6934: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 6935: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 6936: 	   }
 6937: 	   return '';
 6938:        }
 6939:    }
 6940: 
 6941: # Restricted by state or randomout?
 6942: 
 6943:    if ($thisallowed=~/X/) {
 6944:       if ($env{'acc.randomout'}) {
 6945: 	 if (!$symb) { $symb=&symbread($uri,1); }
 6946:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 6947:             return ''; 
 6948:          }
 6949:       }
 6950:       if (&condval($statecond)) {
 6951: 	 return '2';
 6952:       } else {
 6953:          return '';
 6954:       }
 6955:    }
 6956: 
 6957:     if ($thisallowed eq 'A') {
 6958: 	return 'A';
 6959:     } elsif ($thisallowed eq 'B') {
 6960:         return 'B';
 6961:     }
 6962:    return 'F';
 6963: }
 6964: 
 6965: # ------------------------------------------- Check construction space access
 6966: 
 6967: sub constructaccess {
 6968:     my ($url,$setpriv)=@_;
 6969: 
 6970: # We do not allow editing of previous versions of files
 6971:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
 6972: 
 6973: # Get username and domain from URL
 6974:     my ($ownername,$ownerdomain,$ownerhome);
 6975: 
 6976:     ($ownerdomain,$ownername) =
 6977:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)/});
 6978: 
 6979: # The URL does not really point to any authorspace, forget it
 6980:     unless (($ownername) && ($ownerdomain)) { return ''; }
 6981: 
 6982: # Now we need to see if the user has access to the authorspace of
 6983: # $ownername at $ownerdomain
 6984: 
 6985:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
 6986: # Real author for this?
 6987:        $ownerhome = $env{'user.home'};
 6988:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
 6989:           return ($ownername,$ownerdomain,$ownerhome);
 6990:        }
 6991:     } else {
 6992: # Co-author for this?
 6993:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
 6994:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
 6995:             $ownerhome = &homeserver($ownername,$ownerdomain);
 6996:             return ($ownername,$ownerdomain,$ownerhome);
 6997:         }
 6998:     }
 6999: 
 7000: # We don't have any access right now. If we are not possibly going to do anything about this,
 7001: # we might as well leave
 7002:    unless ($setpriv) { return ''; }
 7003: 
 7004: # Backdoor access?
 7005:     my $allowed=&allowed('eco',$ownerdomain);
 7006: # Nope
 7007:     unless ($allowed) { return ''; }
 7008: # Looks like we may have access, but could be locked by the owner of the construction space
 7009:     if ($allowed eq 'U') {
 7010:         my %blocked=&get('environment',['domcoord.author'],
 7011:                          $ownerdomain,$ownername);
 7012: # Is blocked by owner
 7013:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
 7014:     }
 7015:     if (($allowed eq 'F') || ($allowed eq 'U')) {
 7016: # Grant temporary access
 7017:         my $then=$env{'user.login.time'};
 7018:         my $update=$env{'user.update.time'};
 7019:         if (!$update) { $update = $then; }
 7020:         my $refresh=$env{'user.refresh.time'};
 7021:         if (!$refresh) { $refresh = $update; }
 7022:         my $now = time;
 7023:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
 7024:                            $now,'ca','constructaccess');
 7025:         $ownerhome = &homeserver($ownername,$ownerdomain);
 7026:         return($ownername,$ownerdomain,$ownerhome);
 7027:     }
 7028: # No business here
 7029:     return '';
 7030: }
 7031: 
 7032: sub get_comm_blocks {
 7033:     my ($cdom,$cnum) = @_;
 7034:     if ($cdom eq '' || $cnum eq '') {
 7035:         return unless ($env{'request.course.id'});
 7036:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7037:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7038:     }
 7039:     my %commblocks;
 7040:     my $hashid=$cdom.'_'.$cnum;
 7041:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
 7042:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
 7043:         %commblocks = %{$blocksref};
 7044:     } else {
 7045:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
 7046:         my $cachetime = 600;
 7047:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
 7048:     }
 7049:     return %commblocks;
 7050: }
 7051: 
 7052: sub has_comm_blocking {
 7053:     my ($priv,$symb,$uri,$blocks) = @_;
 7054:     return unless ($env{'request.course.id'});
 7055:     return unless ($priv eq 'bre');
 7056:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 7057:     my %commblocks;
 7058:     if (ref($blocks) eq 'HASH') {
 7059:         %commblocks = %{$blocks};
 7060:     } else {
 7061:         %commblocks = &get_comm_blocks();
 7062:     }
 7063:     return unless (keys(%commblocks) > 0);
 7064:     if (!$symb) { $symb=&symbread($uri,1); }
 7065:     my ($map,$resid,undef)=&decode_symb($symb);
 7066:     my %tocheck = (
 7067:                     maps      => $map,
 7068:                     resources => $symb,
 7069:                   );
 7070:     my @blockers;
 7071:     my $now = time;
 7072:     my $navmap = Apache::lonnavmaps::navmap->new();
 7073:     foreach my $block (keys(%commblocks)) {
 7074:         if ($block =~ /^(\d+)____(\d+)$/) {
 7075:             my ($start,$end) = ($1,$2);
 7076:             if ($start <= $now && $end >= $now) {
 7077:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 7078:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 7079:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 7080:                             if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
 7081:                                 unless (grep(/^\Q$block\E$/,@blockers)) {
 7082:                                     push(@blockers,$block);
 7083:                                 }
 7084:                             }
 7085:                         }
 7086:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 7087:                             if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
 7088:                                 unless (grep(/^\Q$block\E$/,@blockers)) {  
 7089:                                     push(@blockers,$block);
 7090:                                 }
 7091:                             }
 7092:                         }
 7093:                     }
 7094:                 }
 7095:             }
 7096:         } elsif ($block =~ /^firstaccess____(.+)$/) {
 7097:             my $item = $1;
 7098:             my @to_test;
 7099:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 7100:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 7101:                     my $check_interval;
 7102:                     if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
 7103:                         my @interval;
 7104:                         my $type = 'map';
 7105:                         if ($item eq 'course') {
 7106:                             $type = 'course';
 7107:                             @interval=&EXT("resource.0.interval");
 7108:                         } else {
 7109:                             if ($item =~ /___\d+___/) {
 7110:                                 $type = 'resource';
 7111:                                 @interval=&EXT("resource.0.interval",$item);
 7112:                                 if (ref($navmap)) {                        
 7113:                                     my $res = $navmap->getBySymb($item); 
 7114:                                     push(@to_test,$res);
 7115:                                 }
 7116:                             } else {
 7117:                                 my $mapsymb = &symbread($item,1);
 7118:                                 if ($mapsymb) {
 7119:                                     if (ref($navmap)) {
 7120:                                         my $mapres = $navmap->getBySymb($mapsymb);
 7121:                                         @to_test = $mapres->retrieveResources($mapres,undef,0,1);
 7122:                                         foreach my $res (@to_test) {
 7123:                                             my $symb = $res->symb();
 7124:                                             next if ($symb eq $mapsymb);
 7125:                                             if ($symb ne '') {
 7126:                                                 @interval=&EXT("resource.0.interval",$symb);
 7127:                                                 last;
 7128:                                             }
 7129:                                         }
 7130:                                     }
 7131:                                 }
 7132:                             }
 7133:                         }
 7134:                         if ($interval[0] =~ /\d+/) {
 7135:                             my $first_access;
 7136:                             if ($type eq 'resource') {
 7137:                                 $first_access=&get_first_access($interval[1],$item);
 7138:                             } elsif ($type eq 'map') {
 7139:                                 $first_access=&get_first_access($interval[1],undef,$item);
 7140:                             } else {
 7141:                                 $first_access=&get_first_access($interval[1]);
 7142:                             }
 7143:                             if ($first_access) {
 7144:                                 my $timesup = $first_access+$interval[0];
 7145:                                 if ($timesup > $now) {
 7146:                                     foreach my $res (@to_test) {
 7147:                                         if ($res->is_problem()) {
 7148:                                             if ($res->completable()) {
 7149:                                                 unless (grep(/^\Q$block\E$/,@blockers)) {
 7150:                                                     push(@blockers,$block);
 7151:                                                 }
 7152:                                                 last;
 7153:                                             }
 7154:                                         }
 7155:                                     }
 7156:                                 }
 7157:                             }
 7158:                         }
 7159:                     }
 7160:                 }
 7161:             }
 7162:         }
 7163:     }
 7164:     return @blockers;
 7165: }
 7166: 
 7167: sub check_docs_block {
 7168:     my ($docsblock,$tocheck) =@_;
 7169:     if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
 7170:         return;
 7171:     }
 7172:     if (ref($docsblock->{'maps'}) eq 'HASH') {
 7173:         if ($tocheck->{'maps'}) {
 7174:             if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
 7175:                 return 1;
 7176:             }
 7177:         }
 7178:     }
 7179:     if (ref($docsblock->{'resources'}) eq 'HASH') {
 7180:         if ($tocheck->{'resources'}) {
 7181:             if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
 7182:                 return 1;
 7183:             }
 7184:         }
 7185:     }
 7186:     return;
 7187: }
 7188: 
 7189: #
 7190: #   Removes the versino from a URI and
 7191: #   splits it in to its filename and path to the filename.
 7192: #   Seems like File::Basename could have done this more clearly.
 7193: #   Parameters:
 7194: #      $uri   - input URI
 7195: #   Returns:
 7196: #     Two element list consisting of 
 7197: #     $pathname  - the URI up to and excluding the trailing /
 7198: #     $filename  - The part of the URI following the last /
 7199: #  NOTE:
 7200: #    Another realization of this is simply:
 7201: #    use File::Basename;
 7202: #    ...
 7203: #    $uri = shift;
 7204: #    $filename = basename($uri);
 7205: #    $path     = dirname($uri);
 7206: #    return ($filename, $path);
 7207: #
 7208: #     The implementation below is probably faster however.
 7209: #
 7210: sub split_uri_for_cond {
 7211:     my $uri=&deversion(&declutter(shift));
 7212:     my @uriparts=split(/\//,$uri);
 7213:     my $filename=pop(@uriparts);
 7214:     my $pathname=join('/',@uriparts);
 7215:     return ($pathname,$filename);
 7216: }
 7217: # --------------------------------------------------- Is a resource on the map?
 7218: 
 7219: sub is_on_map {
 7220:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 7221:     #Trying to find the conditional for the file
 7222:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 7223: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 7224:     if ($match) {
 7225: 	return (1,$1);
 7226:     } else {
 7227: 	return (0,0);
 7228:     }
 7229: }
 7230: 
 7231: # --------------------------------------------------------- Get symb from alias
 7232: 
 7233: sub get_symb_from_alias {
 7234:     my $symb=shift;
 7235:     my ($map,$resid,$url)=&decode_symb($symb);
 7236: # Already is a symb
 7237:     if ($url) { return $symb; }
 7238: # Must be an alias
 7239:     my $aliassymb='';
 7240:     my %bighash;
 7241:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7242:                             &GDBM_READER(),0640)) {
 7243:         my $rid=$bighash{'mapalias_'.$symb};
 7244: 	if ($rid) {
 7245: 	    my ($mapid,$resid)=split(/\./,$rid);
 7246: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 7247: 				    $resid,$bighash{'src_'.$rid});
 7248: 	}
 7249:         untie %bighash;
 7250:     }
 7251:     return $aliassymb;
 7252: }
 7253: 
 7254: # ----------------------------------------------------------------- Define Role
 7255: 
 7256: sub definerole {
 7257:   if (allowed('mcr','/')) {
 7258:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 7259:     foreach my $role (split(':',$sysrole)) {
 7260: 	my ($crole,$cqual)=split(/\&/,$role);
 7261:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 7262:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 7263: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 7264:                return "refused:s:$crole&$cqual"; 
 7265:             }
 7266:         }
 7267:     }
 7268:     foreach my $role (split(':',$domrole)) {
 7269: 	my ($crole,$cqual)=split(/\&/,$role);
 7270:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 7271:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 7272: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 7273:                return "refused:d:$crole&$cqual"; 
 7274:             }
 7275:         }
 7276:     }
 7277:     foreach my $role (split(':',$courole)) {
 7278: 	my ($crole,$cqual)=split(/\&/,$role);
 7279:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 7280:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 7281: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 7282:                return "refused:c:$crole&$cqual"; 
 7283:             }
 7284:         }
 7285:     }
 7286:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 7287:                 "$env{'user.domain'}:$env{'user.name'}:".
 7288: 	        "rolesdef_$rolename=".
 7289:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 7290:     return reply($command,$env{'user.home'});
 7291:   } else {
 7292:     return 'refused';
 7293:   }
 7294: }
 7295: 
 7296: # ---------------- Make a metadata query against the network of library servers
 7297: 
 7298: sub metadata_query {
 7299:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
 7300:     my %rhash;
 7301:     my %libserv = &all_library();
 7302:     my @server_list = (defined($server_array) ? @$server_array
 7303:                                               : keys(%libserv) );
 7304:     for my $server (@server_list) {
 7305:         my $domains = ''; 
 7306:         if (ref($domains_hash) eq 'HASH') {
 7307:             $domains = $domains_hash->{$server}; 
 7308:         }
 7309: 	unless ($custom or $customshow) {
 7310: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
 7311: 	    $rhash{$server}=$reply;
 7312: 	}
 7313: 	else {
 7314: 	    my $reply=&reply("querysend:".&escape($query).':'.
 7315: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
 7316: 			     $server);
 7317: 	    $rhash{$server}=$reply;
 7318: 	}
 7319:     }
 7320:     return \%rhash;
 7321: }
 7322: 
 7323: # ----------------------------------------- Send log queries and wait for reply
 7324: 
 7325: sub log_query {
 7326:     my ($uname,$udom,$query,%filters)=@_;
 7327:     my $uhome=&homeserver($uname,$udom);
 7328:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 7329:     my $uhost=&hostname($uhome);
 7330:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 7331:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 7332:                        $uhome);
 7333:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 7334:     return get_query_reply($queryid);
 7335: }
 7336: 
 7337: # -------------------------- Update MySQL table for portfolio file
 7338: 
 7339: sub update_portfolio_table {
 7340:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 7341:     if ($group ne '') {
 7342:         $file_name =~s /^\Q$group\E//;
 7343:     }
 7344:     my $homeserver = &homeserver($uname,$udom);
 7345:     my $queryid=
 7346:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 7347:                ':'.&escape($file_name).':'.$action,$homeserver);
 7348:     my $reply = &get_query_reply($queryid);
 7349:     return $reply;
 7350: }
 7351: 
 7352: # -------------------------- Update MySQL allusers table
 7353: 
 7354: sub update_allusers_table {
 7355:     my ($uname,$udom,$names) = @_;
 7356:     my $homeserver = &homeserver($uname,$udom);
 7357:     my $queryid=
 7358:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 7359:                'lastname='.&escape($names->{'lastname'}).'%%'.
 7360:                'firstname='.&escape($names->{'firstname'}).'%%'.
 7361:                'middlename='.&escape($names->{'middlename'}).'%%'.
 7362:                'generation='.&escape($names->{'generation'}).'%%'.
 7363:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 7364:                'id='.&escape($names->{'id'}),$homeserver);
 7365:     return;
 7366: }
 7367: 
 7368: # ------- Request retrieval of institutional classlists for course(s)
 7369: 
 7370: sub fetch_enrollment_query {
 7371:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 7372:     my $homeserver;
 7373:     my $maxtries = 1;
 7374:     if ($context eq 'automated') {
 7375:         $homeserver = $perlvar{'lonHostID'};
 7376:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 7377:     } else {
 7378:         $homeserver = &homeserver($cnum,$dom);
 7379:     }
 7380:     my $host=&hostname($homeserver);
 7381:     my $cmd = '';
 7382:     foreach my $affiliate (keys(%{$affiliatesref})) {
 7383:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 7384:     }
 7385:     $cmd =~ s/%%$//;
 7386:     $cmd = &escape($cmd);
 7387:     my $query = 'fetchenrollment';
 7388:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 7389:     unless ($queryid=~/^\Q$host\E\_/) { 
 7390:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 7391:         return 'error: '.$queryid;
 7392:     }
 7393:     my $reply = &get_query_reply($queryid);
 7394:     my $tries = 1;
 7395:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 7396:         $reply = &get_query_reply($queryid);
 7397:         $tries ++;
 7398:     }
 7399:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 7400:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 7401:     } else {
 7402:         my @responses = split(/:/,$reply);
 7403:         if ($homeserver eq $perlvar{'lonHostID'}) {
 7404:             foreach my $line (@responses) {
 7405:                 my ($key,$value) = split(/=/,$line,2);
 7406:                 $$replyref{$key} = $value;
 7407:             }
 7408:         } else {
 7409:             my $pathname = LONCAPA::tempdir();
 7410:             foreach my $line (@responses) {
 7411:                 my ($key,$value) = split(/=/,$line);
 7412:                 $$replyref{$key} = $value;
 7413:                 if ($value > 0) {
 7414:                     foreach my $item (@{$$affiliatesref{$key}}) {
 7415:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 7416:                         my $destname = $pathname.'/'.$filename;
 7417:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 7418:                         if ($xml_classlist =~ /^error/) {
 7419:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 7420:                         } else {
 7421:                             if ( open(FILE,">$destname") ) {
 7422:                                 print FILE &unescape($xml_classlist);
 7423:                                 close(FILE);
 7424:                             } else {
 7425:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 7426:                             }
 7427:                         }
 7428:                     }
 7429:                 }
 7430:             }
 7431:         }
 7432:         return 'ok';
 7433:     }
 7434:     return 'error';
 7435: }
 7436: 
 7437: sub get_query_reply {
 7438:     my $queryid=shift;
 7439:     my $replyfile=LONCAPA::tempdir().$queryid;
 7440:     my $reply='';
 7441:     for (1..100) {
 7442: 	sleep 2;
 7443:         if (-e $replyfile.'.end') {
 7444: 	    if (open(my $fh,$replyfile)) {
 7445: 		$reply = join('',<$fh>);
 7446: 		close($fh);
 7447: 	   } else { return 'error: reply_file_error'; }
 7448:            return &unescape($reply);
 7449: 	}
 7450:     }
 7451:     return 'timeout:'.$queryid;
 7452: }
 7453: 
 7454: sub courselog_query {
 7455: #
 7456: # possible filters:
 7457: # url: url or symb
 7458: # username
 7459: # domain
 7460: # action: view, submit, grade
 7461: # start: timestamp
 7462: # end: timestamp
 7463: #
 7464:     my (%filters)=@_;
 7465:     unless ($env{'request.course.id'}) { return 'no_course'; }
 7466:     if ($filters{'url'}) {
 7467: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 7468:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 7469:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 7470:     }
 7471:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7472:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7473:     return &log_query($cname,$cdom,'courselog',%filters);
 7474: }
 7475: 
 7476: sub userlog_query {
 7477: #
 7478: # possible filters:
 7479: # action: log check role
 7480: # start: timestamp
 7481: # end: timestamp
 7482: #
 7483:     my ($uname,$udom,%filters)=@_;
 7484:     return &log_query($uname,$udom,'userlog',%filters);
 7485: }
 7486: 
 7487: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 7488: 
 7489: sub auto_run {
 7490:     my ($cnum,$cdom) = @_;
 7491:     my $response = 0;
 7492:     my $settings;
 7493:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 7494:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 7495:         $settings = $domconfig{'autoenroll'};
 7496:         if ($settings->{'run'} eq '1') {
 7497:             $response = 1;
 7498:         }
 7499:     } else {
 7500:         my $homeserver;
 7501:         if (&is_course($cdom,$cnum)) {
 7502:             $homeserver = &homeserver($cnum,$cdom);
 7503:         } else {
 7504:             $homeserver = &domain($cdom,'primary');
 7505:         }
 7506:         if ($homeserver ne 'no_host') {
 7507:             $response = &reply('autorun:'.$cdom,$homeserver);
 7508:         }
 7509:     }
 7510:     return $response;
 7511: }
 7512: 
 7513: sub auto_get_sections {
 7514:     my ($cnum,$cdom,$inst_coursecode) = @_;
 7515:     my $homeserver;
 7516:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
 7517:         $homeserver = &homeserver($cnum,$cdom);
 7518:     }
 7519:     if (!defined($homeserver)) { 
 7520:         if ($cdom =~ /^$match_domain$/) {
 7521:             $homeserver = &domain($cdom,'primary');
 7522:         }
 7523:     }
 7524:     my @secs;
 7525:     if (defined($homeserver)) {
 7526:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 7527:         unless ($response eq 'refused') {
 7528:             @secs = split(/:/,$response);
 7529:         }
 7530:     }
 7531:     return @secs;
 7532: }
 7533: 
 7534: sub auto_new_course {
 7535:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
 7536:     my $homeserver = &homeserver($cnum,$cdom);
 7537:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
 7538:     return $response;
 7539: }
 7540: 
 7541: sub auto_validate_courseID {
 7542:     my ($cnum,$cdom,$inst_course_id) = @_;
 7543:     my $homeserver = &homeserver($cnum,$cdom);
 7544:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 7545:     return $response;
 7546: }
 7547: 
 7548: sub auto_validate_instcode {
 7549:     my ($cnum,$cdom,$instcode,$owner) = @_;
 7550:     my ($homeserver,$response);
 7551:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 7552:         $homeserver = &homeserver($cnum,$cdom);
 7553:     }
 7554:     if (!defined($homeserver)) {
 7555:         if ($cdom =~ /^$match_domain$/) {
 7556:             $homeserver = &domain($cdom,'primary');
 7557:         }
 7558:     }
 7559:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
 7560:                         &escape($instcode).':'.&escape($owner),$homeserver));
 7561:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
 7562:     return ($outcome,$description,$defaultcredits);
 7563: }
 7564: 
 7565: sub auto_create_password {
 7566:     my ($cnum,$cdom,$authparam,$udom) = @_;
 7567:     my ($homeserver,$response);
 7568:     my $create_passwd = 0;
 7569:     my $authchk = '';
 7570:     if ($udom =~ /^$match_domain$/) {
 7571:         $homeserver = &domain($udom,'primary');
 7572:     }
 7573:     if ($homeserver eq '') {
 7574:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 7575:             $homeserver = &homeserver($cnum,$cdom);
 7576:         }
 7577:     }
 7578:     if ($homeserver eq '') {
 7579:         $authchk = 'nodomain';
 7580:     } else {
 7581:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 7582:         if ($response eq 'refused') {
 7583:             $authchk = 'refused';
 7584:         } else {
 7585:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 7586:         }
 7587:     }
 7588:     return ($authparam,$create_passwd,$authchk);
 7589: }
 7590: 
 7591: sub auto_photo_permission {
 7592:     my ($cnum,$cdom,$students) = @_;
 7593:     my $homeserver = &homeserver($cnum,$cdom);
 7594:     my ($outcome,$perm_reqd,$conditions) = 
 7595: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 7596:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 7597: 	return (undef,undef);
 7598:     }
 7599:     return ($outcome,$perm_reqd,$conditions);
 7600: }
 7601: 
 7602: sub auto_checkphotos {
 7603:     my ($uname,$udom,$pid) = @_;
 7604:     my $homeserver = &homeserver($uname,$udom);
 7605:     my ($result,$resulttype);
 7606:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 7607: 				   &escape($uname).':'.&escape($pid),
 7608: 				   $homeserver));
 7609:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 7610: 	return (undef,undef);
 7611:     }
 7612:     if ($outcome) {
 7613:         ($result,$resulttype) = split(/:/,$outcome);
 7614:     } 
 7615:     return ($result,$resulttype);
 7616: }
 7617: 
 7618: sub auto_photochoice {
 7619:     my ($cnum,$cdom) = @_;
 7620:     my $homeserver = &homeserver($cnum,$cdom);
 7621:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 7622: 						       &escape($cdom),
 7623: 						       $homeserver)));
 7624:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 7625: 	return (undef,undef);
 7626:     }
 7627:     return ($update,$comment);
 7628: }
 7629: 
 7630: sub auto_photoupdate {
 7631:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 7632:     my $homeserver = &homeserver($cnum,$dom);
 7633:     my $host=&hostname($homeserver);
 7634:     my $cmd = '';
 7635:     my $maxtries = 1;
 7636:     foreach my $affiliate (keys(%{$affiliatesref})) {
 7637:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 7638:     }
 7639:     $cmd =~ s/%%$//;
 7640:     $cmd = &escape($cmd);
 7641:     my $query = 'institutionalphotos';
 7642:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 7643:     unless ($queryid=~/^\Q$host\E\_/) {
 7644:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 7645:         return 'error: '.$queryid;
 7646:     }
 7647:     my $reply = &get_query_reply($queryid);
 7648:     my $tries = 1;
 7649:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 7650:         $reply = &get_query_reply($queryid);
 7651:         $tries ++;
 7652:     }
 7653:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 7654:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 7655:     } else {
 7656:         my @responses = split(/:/,$reply);
 7657:         my $outcome = shift(@responses); 
 7658:         foreach my $item (@responses) {
 7659:             my ($key,$value) = split(/=/,$item);
 7660:             $$photo{$key} = $value;
 7661:         }
 7662:         return $outcome;
 7663:     }
 7664:     return 'error';
 7665: }
 7666: 
 7667: sub auto_instcode_format {
 7668:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 7669: 	$cat_order) = @_;
 7670:     my $courses = '';
 7671:     my @homeservers;
 7672:     if ($caller eq 'global') {
 7673: 	my %servers = &get_servers($codedom,'library');
 7674: 	foreach my $tryserver (keys(%servers)) {
 7675: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7676: 		push(@homeservers,$tryserver);
 7677: 	    }
 7678:         }
 7679:     } elsif ($caller eq 'requests') {
 7680:         if ($codedom =~ /^$match_domain$/) {
 7681:             my $chome = &domain($codedom,'primary');
 7682:             unless ($chome eq 'no_host') {
 7683:                 push(@homeservers,$chome);
 7684:             }
 7685:         }
 7686:     } else {
 7687:         push(@homeservers,&homeserver($caller,$codedom));
 7688:     }
 7689:     foreach my $code (keys(%{$instcodes})) {
 7690:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 7691:     }
 7692:     chop($courses);
 7693:     my $ok_response = 0;
 7694:     my $response;
 7695:     while (@homeservers > 0 && $ok_response == 0) {
 7696:         my $server = shift(@homeservers); 
 7697:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 7698:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 7699:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 7700: 		split(/:/,$response);
 7701:             %{$codes} = (%{$codes},&str2hash($codes_str));
 7702:             push(@{$codetitles},&str2array($codetitles_str));
 7703:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 7704:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 7705:             $ok_response = 1;
 7706:         }
 7707:     }
 7708:     if ($ok_response) {
 7709:         return 'ok';
 7710:     } else {
 7711:         return $response;
 7712:     }
 7713: }
 7714: 
 7715: sub auto_instcode_defaults {
 7716:     my ($domain,$returnhash,$code_order) = @_;
 7717:     my @homeservers;
 7718: 
 7719:     my %servers = &get_servers($domain,'library');
 7720:     foreach my $tryserver (keys(%servers)) {
 7721: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7722: 	    push(@homeservers,$tryserver);
 7723: 	}
 7724:     }
 7725: 
 7726:     my $response;
 7727:     foreach my $server (@homeservers) {
 7728:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 7729:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 7730: 	
 7731: 	foreach my $pair (split(/\&/,$response)) {
 7732: 	    my ($name,$value)=split(/\=/,$pair);
 7733: 	    if ($name eq 'code_order') {
 7734: 		@{$code_order} = split(/\&/,&unescape($value));
 7735: 	    } else {
 7736: 		$returnhash->{&unescape($name)}=&unescape($value);
 7737: 	    }
 7738: 	}
 7739: 	return 'ok';
 7740:     }
 7741: 
 7742:     return $response;
 7743: }
 7744: 
 7745: sub auto_possible_instcodes {
 7746:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
 7747:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
 7748:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 7749:         return;
 7750:     }
 7751:     my (@homeservers,$uhome);
 7752:     if (defined(&domain($domain,'primary'))) {
 7753:         $uhome=&domain($domain,'primary');
 7754:         push(@homeservers,&domain($domain,'primary'));
 7755:     } else {
 7756:         my %servers = &get_servers($domain,'library');
 7757:         foreach my $tryserver (keys(%servers)) {
 7758:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7759:                 push(@homeservers,$tryserver);
 7760:             }
 7761:         }
 7762:     }
 7763:     my $response;
 7764:     foreach my $server (@homeservers) {
 7765:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
 7766:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 7767:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
 7768:             split(':',$response);
 7769:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
 7770:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
 7771:         foreach my $item (split('&',$cat_title)) {   
 7772:             my ($name,$value)=split('=',$item);
 7773:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
 7774:         }
 7775:         foreach my $item (split('&',$cat_order)) {
 7776:             my ($name,$value)=split('=',$item);
 7777:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
 7778:         }
 7779:         return 'ok';
 7780:     }
 7781:     return $response;
 7782: }
 7783: 
 7784: sub auto_courserequest_checks {
 7785:     my ($dom) = @_;
 7786:     my ($homeserver,%validations);
 7787:     if ($dom =~ /^$match_domain$/) {
 7788:         $homeserver = &domain($dom,'primary');
 7789:     }
 7790:     unless ($homeserver eq 'no_host') {
 7791:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
 7792:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 7793:             my @items = split(/&/,$response);
 7794:             foreach my $item (@items) {
 7795:                 my ($key,$value) = split('=',$item);
 7796:                 $validations{&unescape($key)} = &thaw_unescape($value);
 7797:             }
 7798:         }
 7799:     }
 7800:     return %validations; 
 7801: }
 7802: 
 7803: sub auto_courserequest_validation {
 7804:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
 7805:     my ($homeserver,$response);
 7806:     if ($dom =~ /^$match_domain$/) {
 7807:         $homeserver = &domain($dom,'primary');
 7808:     }
 7809:     unless ($homeserver eq 'no_host') {  
 7810:           
 7811:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
 7812:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
 7813:                                     ':'.&escape($instcode).':'.&escape($instseclist),
 7814:                                     $homeserver));
 7815:     }
 7816:     return $response;
 7817: }
 7818: 
 7819: sub auto_validate_class_sec {
 7820:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 7821:     my $homeserver = &homeserver($cnum,$cdom);
 7822:     my $ownerlist;
 7823:     if (ref($owners) eq 'ARRAY') {
 7824:         $ownerlist = join(',',@{$owners});
 7825:     } else {
 7826:         $ownerlist = $owners;
 7827:     }
 7828:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 7829:                         &escape($ownerlist).':'.$cdom,$homeserver);
 7830:     return $response;
 7831: }
 7832: 
 7833: # ------------------------------------------------------- Course Group routines
 7834: 
 7835: sub get_coursegroups {
 7836:     my ($cdom,$cnum,$group,$namespace) = @_;
 7837:     return(&dump($namespace,$cdom,$cnum,$group));
 7838: }
 7839: 
 7840: sub modify_coursegroup {
 7841:     my ($cdom,$cnum,$groupsettings) = @_;
 7842:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 7843: }
 7844: 
 7845: sub toggle_coursegroup_status {
 7846:     my ($cdom,$cnum,$group,$action) = @_;
 7847:     my ($from_namespace,$to_namespace);
 7848:     if ($action eq 'delete') {
 7849:         $from_namespace = 'coursegroups';
 7850:         $to_namespace = 'deleted_groups';
 7851:     } else {
 7852:         $from_namespace = 'deleted_groups';
 7853:         $to_namespace = 'coursegroups';
 7854:     }
 7855:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 7856:     if (my $tmp = &error(%curr_group)) {
 7857:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 7858:         return ('read error',$tmp);
 7859:     } else {
 7860:         my %savedsettings = %curr_group; 
 7861:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 7862:         my $deloutcome;
 7863:         if ($result eq 'ok') {
 7864:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 7865:         } else {
 7866:             return ('write error',$result);
 7867:         }
 7868:         if ($deloutcome eq 'ok') {
 7869:             return 'ok';
 7870:         } else {
 7871:             return ('delete error',$deloutcome);
 7872:         }
 7873:     }
 7874: }
 7875: 
 7876: sub modify_group_roles {
 7877:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 7878:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 7879:     my $role = 'gr/'.&escape($userprivs);
 7880:     my ($uname,$udom) = split(/:/,$user);
 7881:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 7882:     if ($result eq 'ok') {
 7883:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 7884:     }
 7885:     return $result;
 7886: }
 7887: 
 7888: sub modify_coursegroup_membership {
 7889:     my ($cdom,$cnum,$membership) = @_;
 7890:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 7891:     return $result;
 7892: }
 7893: 
 7894: sub get_active_groups {
 7895:     my ($udom,$uname,$cdom,$cnum) = @_;
 7896:     my $now = time;
 7897:     my %groups = ();
 7898:     foreach my $key (keys(%env)) {
 7899:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 7900:             my ($start,$end) = split(/\./,$env{$key});
 7901:             if (($end!=0) && ($end<$now)) { next; }
 7902:             if (($start!=0) && ($start>$now)) { next; }
 7903:             if ($1 eq $cdom && $2 eq $cnum) {
 7904:                 $groups{$3} = $env{$key} ;
 7905:             }
 7906:         }
 7907:     }
 7908:     return %groups;
 7909: }
 7910: 
 7911: sub get_group_membership {
 7912:     my ($cdom,$cnum,$group) = @_;
 7913:     return(&dump('groupmembership',$cdom,$cnum,$group));
 7914: }
 7915: 
 7916: sub get_users_groups {
 7917:     my ($udom,$uname,$courseid) = @_;
 7918:     my @usersgroups;
 7919:     my $cachetime=1800;
 7920: 
 7921:     my $hashid="$udom:$uname:$courseid";
 7922:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 7923:     if (defined($cached)) {
 7924:         @usersgroups = split(/:/,$grouplist);
 7925:     } else {  
 7926:         $grouplist = '';
 7927:         my $courseurl = &courseid_to_courseurl($courseid);
 7928:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 7929:         my $access_end = $env{'course.'.$courseid.
 7930:                               '.default_enrollment_end_date'};
 7931:         my $now = time;
 7932:         foreach my $key (keys(%roleshash)) {
 7933:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 7934:                 my $group = $1;
 7935:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 7936:                     my $start = $2;
 7937:                     my $end = $1;
 7938:                     if ($start == -1) { next; } # deleted from group
 7939:                     if (($start!=0) && ($start>$now)) { next; }
 7940:                     if (($end!=0) && ($end<$now)) {
 7941:                         if ($access_end && $access_end < $now) {
 7942:                             if ($access_end - $end < 86400) {
 7943:                                 push(@usersgroups,$group);
 7944:                             }
 7945:                         }
 7946:                         next;
 7947:                     }
 7948:                     push(@usersgroups,$group);
 7949:                 }
 7950:             }
 7951:         }
 7952:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 7953:         $grouplist = join(':',@usersgroups);
 7954:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 7955:     }
 7956:     return @usersgroups;
 7957: }
 7958: 
 7959: sub devalidate_getgroups_cache {
 7960:     my ($udom,$uname,$cdom,$cnum)=@_;
 7961:     my $courseid = $cdom.'_'.$cnum;
 7962: 
 7963:     my $hashid="$udom:$uname:$courseid";
 7964:     &devalidate_cache_new('getgroups',$hashid);
 7965: }
 7966: 
 7967: # ------------------------------------------------------------------ Plain Text
 7968: 
 7969: sub plaintext {
 7970:     my ($short,$type,$cid,$forcedefault) = @_;
 7971:     if ($short =~ m{^cr/}) {
 7972: 	return (split('/',$short))[-1];
 7973:     }
 7974:     if (!defined($cid)) {
 7975:         $cid = $env{'request.course.id'};
 7976:     }
 7977:     my %rolenames = (
 7978:                       Course    => 'std',
 7979:                       Community => 'alt1',
 7980:                     );
 7981:     if ($cid ne '') {
 7982:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
 7983:             unless ($forcedefault) {
 7984:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
 7985:                 &Apache::lonlocal::mt_escape(\$roletext);
 7986:                 return &Apache::lonlocal::mt($roletext);
 7987:             }
 7988:         }
 7989:     }
 7990:     if ((defined($type)) && (defined($rolenames{$type})) &&
 7991:         (defined($rolenames{$type})) && 
 7992:         (defined($prp{$short}{$rolenames{$type}}))) {
 7993:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 7994:     } elsif ($cid ne '') {
 7995:         my $crstype = $env{'course.'.$cid.'.type'};
 7996:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
 7997:             (defined($prp{$short}{$rolenames{$crstype}}))) {
 7998:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
 7999:         }
 8000:     }
 8001:     return &Apache::lonlocal::mt($prp{$short}{'std'});
 8002: }
 8003: 
 8004: # ----------------------------------------------------------------- Assign Role
 8005: 
 8006: sub assignrole {
 8007:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
 8008:         $context)=@_;
 8009:     my $mrole;
 8010:     if ($role =~ /^cr\//) {
 8011:         my $cwosec=$url;
 8012:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 8013: 	unless (&allowed('ccr',$cwosec)) {
 8014:            my $refused = 1;
 8015:            if ($context eq 'requestcourses') {
 8016:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 8017:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
 8018:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
 8019:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 8020:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 8021:                            if ($crsenv{'internal.courseowner'} eq
 8022:                                $env{'user.name'}.':'.$env{'user.domain'}) {
 8023:                                $refused = '';
 8024:                            }
 8025:                        }
 8026:                    }
 8027:                }
 8028:            }
 8029:            if ($refused) {
 8030:                &logthis('Refused custom assignrole: '.
 8031:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
 8032:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
 8033:                return 'refused';
 8034:            }
 8035:         }
 8036:         $mrole='cr';
 8037:     } elsif ($role =~ /^gr\//) {
 8038:         my $cwogrp=$url;
 8039:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 8040:         unless (&allowed('mdg',$cwogrp)) {
 8041:             &logthis('Refused group assignrole: '.
 8042:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 8043:                     $env{'user.name'}.' at '.$env{'user.domain'});
 8044:             return 'refused';
 8045:         }
 8046:         $mrole='gr';
 8047:     } else {
 8048:         my $cwosec=$url;
 8049:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 8050:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 8051:             my $refused;
 8052:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 8053:                 if (!(&allowed('c'.$role,$url))) {
 8054:                     $refused = 1;
 8055:                 }
 8056:             } else {
 8057:                 $refused = 1;
 8058:             }
 8059:             if ($refused) {
 8060:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 8061:                 if (!$selfenroll && $context eq 'course') {
 8062:                     my %crsenv;
 8063:                     if ($role eq 'cc' || $role eq 'co') {
 8064:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 8065:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
 8066:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
 8067:                                 if ($crsenv{'internal.courseowner'} eq 
 8068:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 8069:                                     $refused = '';
 8070:                                 }
 8071:                             }
 8072:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
 8073:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
 8074:                                 if ($crsenv{'internal.courseowner'} eq 
 8075:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 8076:                                     $refused = '';
 8077:                                 }
 8078:                             }
 8079:                         }
 8080:                     }
 8081:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 8082:                     $refused = '';
 8083:                 } elsif ($context eq 'requestcourses') {
 8084:                     my @possroles = ('st','ta','ep','in','cc','co');
 8085:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
 8086:                         my $wrongcc;
 8087:                         if ($cnum =~ /^$match_community$/) {
 8088:                             $wrongcc = 1 if ($role eq 'cc');
 8089:                         } else {
 8090:                             $wrongcc = 1 if ($role eq 'co');
 8091:                         }
 8092:                         unless ($wrongcc) {
 8093:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 8094:                             if ($crsenv{'internal.courseowner'} eq 
 8095:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
 8096:                                 $refused = '';
 8097:                             }
 8098:                         }
 8099:                     }
 8100:                 } elsif ($context eq 'requestauthor') {
 8101:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
 8102:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
 8103:                         if ($env{'environment.requestauthor'} eq 'automatic') {
 8104:                             $refused = '';
 8105:                         } else {
 8106:                             my %domdefaults = &get_domain_defaults($udom);
 8107:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
 8108:                                 my $checkbystatus;
 8109:                                 if ($env{'user.adv'}) { 
 8110:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
 8111:                                     if ($disposition eq 'automatic') {
 8112:                                         $refused = '';
 8113:                                     } elsif ($disposition eq '') {
 8114:                                         $checkbystatus = 1;
 8115:                                     } 
 8116:                                 } else {
 8117:                                     $checkbystatus = 1;
 8118:                                 }
 8119:                                 if ($checkbystatus) {
 8120:                                     if ($env{'environment.inststatus'}) {
 8121:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
 8122:                                         foreach my $type (@inststatuses) {
 8123:                                             if (($type ne '') &&
 8124:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
 8125:                                                 $refused = '';
 8126:                                             }
 8127:                                         }
 8128:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
 8129:                                         $refused = '';
 8130:                                     }
 8131:                                 }
 8132:                             }
 8133:                         }
 8134:                     }
 8135:                 }
 8136:                 if ($refused) {
 8137:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 8138:                              ' '.$role.' '.$end.' '.$start.' by '.
 8139: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
 8140:                     return 'refused';
 8141:                 }
 8142:             }
 8143:         } elsif ($role eq 'au') {
 8144:             if ($url ne '/'.$udom.'/') {
 8145:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
 8146:                          ' to assign author role for '.$uname.':'.$udom.
 8147:                          ' in domain: '.$url.' refused (wrong domain).');
 8148:                 return 'refused';
 8149:             }
 8150:         }
 8151:         $mrole=$role;
 8152:     }
 8153:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 8154:                 "$udom:$uname:$url".'_'."$mrole=$role";
 8155:     if ($end) { $command.='_'.$end; }
 8156:     if ($start) {
 8157: 	if ($end) { 
 8158:            $command.='_'.$start; 
 8159:         } else {
 8160:            $command.='_0_'.$start;
 8161:         }
 8162:     }
 8163:     my $origstart = $start;
 8164:     my $origend = $end;
 8165:     my $delflag;
 8166: # actually delete
 8167:     if ($deleteflag) {
 8168: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 8169: # modify command to delete the role
 8170:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 8171:                 "$udom:$uname:$url".'_'."$mrole";
 8172: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 8173: # set start and finish to negative values for userrolelog
 8174:            $start=-1;
 8175:            $end=-1;
 8176:            $delflag = 1;
 8177:         }
 8178:     }
 8179: # send command
 8180:     my $answer=&reply($command,&homeserver($uname,$udom));
 8181: # log new user role if status is ok
 8182:     if ($answer eq 'ok') {
 8183: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 8184:         if (($role eq 'cc') || ($role eq 'in') ||
 8185:             ($role eq 'ep') || ($role eq 'ad') ||
 8186:             ($role eq 'ta') || ($role eq 'st') ||
 8187:             ($role=~/^cr/) || ($role eq 'gr') ||
 8188:             ($role eq 'co')) {
 8189: # for course roles, perform group memberships changes triggered by role change.
 8190:             unless ($role =~ /^gr/) {
 8191:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 8192:                                                  $origstart,$selfenroll,$context);
 8193:             }
 8194:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 8195:                            $selfenroll,$context);
 8196:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
 8197:                  ($role eq 'au') || ($role eq 'dc')) {
 8198:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 8199:                            $context);
 8200:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
 8201:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 8202:                              $context); 
 8203:         }
 8204:         if ($role eq 'cc') {
 8205:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
 8206:         }
 8207:     }
 8208:     return $answer;
 8209: }
 8210: 
 8211: sub autoupdate_coowners {
 8212:     my ($url,$end,$start,$uname,$udom) = @_;
 8213:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
 8214:     if (($cdom ne '') && ($cnum ne '')) {
 8215:         my $now = time;
 8216:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
 8217:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
 8218:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
 8219:             my $instcode = $coursehash{'internal.coursecode'};
 8220:             if ($instcode ne '') {
 8221:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
 8222:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
 8223:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
 8224:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
 8225:                         if ($result eq 'valid') {
 8226:                             if ($coursehash{'internal.co-owners'}) {
 8227:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 8228:                                     push(@newcoowners,$coowner);
 8229:                                 }
 8230:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
 8231:                                     push(@newcoowners,$uname.':'.$udom);
 8232:                                 }
 8233:                                 @newcoowners = sort(@newcoowners);
 8234:                             } else {
 8235:                                 push(@newcoowners,$uname.':'.$udom);
 8236:                             }
 8237:                         } else {
 8238:                             if ($coursehash{'internal.co-owners'}) {
 8239:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 8240:                                     unless ($coowner eq $uname.':'.$udom) {
 8241:                                         push(@newcoowners,$coowner);
 8242:                                     }
 8243:                                 }
 8244:                                 unless (@newcoowners > 0) {
 8245:                                     $delcoowners = 1;
 8246:                                     $coowners = '';
 8247:                                 }
 8248:                             }
 8249:                         }
 8250:                         if (@newcoowners || $delcoowners) {
 8251:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
 8252:                                             $delcoowners,@newcoowners);
 8253:                         }
 8254:                     }
 8255:                 }
 8256:             }
 8257:         }
 8258:     }
 8259: }
 8260: 
 8261: sub store_coowners {
 8262:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
 8263:     my $cid = $cdom.'_'.$cnum;
 8264:     my ($coowners,$delresult,$putresult);
 8265:     if (@newcoowners) {
 8266:         $coowners = join(',',@newcoowners);
 8267:         my %coownershash = (
 8268:                             'internal.co-owners' => $coowners,
 8269:                            );
 8270:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
 8271:         if ($putresult eq 'ok') {
 8272:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
 8273:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
 8274:             }
 8275:         }
 8276:     }
 8277:     if ($delcoowners) {
 8278:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
 8279:         if ($delresult eq 'ok') {
 8280:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
 8281:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
 8282:             }
 8283:         }
 8284:     }
 8285:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
 8286:         my %crsinfo =
 8287:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 8288:         if (ref($crsinfo{$cid}) eq 'HASH') {
 8289:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
 8290:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
 8291:         }
 8292:     }
 8293: }
 8294: 
 8295: # -------------------------------------------------- Modify user authentication
 8296: # Overrides without validation
 8297: 
 8298: sub modifyuserauth {
 8299:     my ($udom,$uname,$umode,$upass)=@_;
 8300:     my $uhome=&homeserver($uname,$udom);
 8301:     unless (&allowed('mau',$udom)) { return 'refused'; }
 8302:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 8303:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 8304:              ' in domain '.$env{'request.role.domain'});  
 8305:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 8306: 		     &escape($upass),$uhome);
 8307:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 8308:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 8309:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 8310:     &log($udom,,$uname,$uhome,
 8311:         'Authentication changed by '.$env{'user.domain'}.', '.
 8312:                                      $env{'user.name'}.', '.$umode.
 8313:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 8314:     unless ($reply eq 'ok') {
 8315:         &logthis('Authentication mode error: '.$reply);
 8316: 	return 'error: '.$reply;
 8317:     }   
 8318:     return 'ok';
 8319: }
 8320: 
 8321: # --------------------------------------------------------------- Modify a user
 8322: 
 8323: sub modifyuser {
 8324:     my ($udom,    $uname, $uid,
 8325:         $umode,   $upass, $first,
 8326:         $middle,  $last,  $gene,
 8327:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
 8328:     $udom= &LONCAPA::clean_domain($udom);
 8329:     $uname=&LONCAPA::clean_username($uname);
 8330:     my $showcandelete = 'none';
 8331:     if (ref($candelete) eq 'ARRAY') {
 8332:         if (@{$candelete} > 0) {
 8333:             $showcandelete = join(', ',@{$candelete});
 8334:         }
 8335:     }
 8336:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 8337:              $umode.', '.$first.', '.$middle.', '.
 8338: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
 8339:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 8340:                                      ' desiredhome not specified'). 
 8341:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 8342:              ' in domain '.$env{'request.role.domain'});
 8343:     my $uhome=&homeserver($uname,$udom,'true');
 8344:     my $newuser;
 8345:     if ($uhome eq 'no_host') {
 8346:         $newuser = 1;
 8347:     }
 8348: # ----------------------------------------------------------------- Create User
 8349:     if (($uhome eq 'no_host') && 
 8350: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 8351:         my $unhome='';
 8352:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 8353:             $unhome = $desiredhome;
 8354: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 8355: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 8356:         } else { # load balancing routine for determining $unhome
 8357:             my $loadm=10000000;
 8358: 	    my %servers = &get_servers($udom,'library');
 8359: 	    foreach my $tryserver (keys(%servers)) {
 8360: 		my $answer=reply('load',$tryserver);
 8361: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 8362: 		    $loadm=$answer;
 8363: 		    $unhome=$tryserver;
 8364: 		}
 8365: 	    }
 8366:         }
 8367:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 8368: 	    return 'error: unable to find a home server for '.$uname.
 8369:                    ' in domain '.$udom;
 8370:         }
 8371:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 8372:                          &escape($upass),$unhome);
 8373: 	unless ($reply eq 'ok') {
 8374:             return 'error: '.$reply;
 8375:         }   
 8376:         $uhome=&homeserver($uname,$udom,'true');
 8377:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 8378: 	    return 'error: unable verify users home machine.';
 8379:         }
 8380:     }   # End of creation of new user
 8381: # ---------------------------------------------------------------------- Add ID
 8382:     if ($uid) {
 8383:        $uid=~tr/A-Z/a-z/;
 8384:        my %uidhash=&idrget($udom,$uname);
 8385:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 8386:          && (!$forceid)) {
 8387: 	  unless ($uid eq $uidhash{$uname}) {
 8388: 	      return 'error: user id "'.$uid.'" does not match '.
 8389:                   'current user id "'.$uidhash{$uname}.'".';
 8390:           }
 8391:        } else {
 8392: 	  &idput($udom,($uname => $uid));
 8393:        }
 8394:     }
 8395: # -------------------------------------------------------------- Add names, etc
 8396:     my @tmp=&get('environment',
 8397: 		   ['firstname','middlename','lastname','generation','id',
 8398:                     'permanentemail','inststatus'],
 8399: 		   $udom,$uname);
 8400:     my (%names,%oldnames);
 8401:     if ($tmp[0] =~ m/^error:.*/) { 
 8402:         %names=(); 
 8403:     } else {
 8404:         %names = @tmp;
 8405:         %oldnames = %names;
 8406:     }
 8407: #
 8408: # If name, email and/or uid are blank (e.g., because an uploaded file
 8409: # of users did not contain them), do not overwrite existing values
 8410: # unless field is in $candelete array ref.  
 8411: #
 8412: 
 8413:     my @fields = ('firstname','middlename','lastname','generation',
 8414:                   'permanentemail','id');
 8415:     my %newvalues;
 8416:     if (ref($candelete) eq 'ARRAY') {
 8417:         foreach my $field (@fields) {
 8418:             if (grep(/^\Q$field\E$/,@{$candelete})) {
 8419:                 if ($field eq 'firstname') {
 8420:                     $names{$field} = $first;
 8421:                 } elsif ($field eq 'middlename') {
 8422:                     $names{$field} = $middle;
 8423:                 } elsif ($field eq 'lastname') {
 8424:                     $names{$field} = $last;
 8425:                 } elsif ($field eq 'generation') { 
 8426:                     $names{$field} = $gene;
 8427:                 } elsif ($field eq 'permanentemail') {
 8428:                     $names{$field} = $email;
 8429:                 } elsif ($field eq 'id') {
 8430:                     $names{$field}  = $uid;
 8431:                 }
 8432:             }
 8433:         }
 8434:     }
 8435:     if ($first)  { $names{'firstname'}  = $first; }
 8436:     if (defined($middle)) { $names{'middlename'} = $middle; }
 8437:     if ($last)   { $names{'lastname'}   = $last; }
 8438:     if (defined($gene))   { $names{'generation'} = $gene; }
 8439:     if ($email) {
 8440:        $email=~s/[^\w\@\.\-\,]//gs;
 8441:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
 8442:     }
 8443:     if ($uid) { $names{'id'}  = $uid; }
 8444:     if (defined($inststatus)) {
 8445:         $names{'inststatus'} = '';
 8446:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
 8447:         if (ref($usertypes) eq 'HASH') {
 8448:             my @okstatuses; 
 8449:             foreach my $item (split(/:/,$inststatus)) {
 8450:                 if (defined($usertypes->{$item})) {
 8451:                     push(@okstatuses,$item);  
 8452:                 }
 8453:             }
 8454:             if (@okstatuses) {
 8455:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
 8456:             }
 8457:         }
 8458:     }
 8459:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
 8460:                  $umode.', '.$first.', '.$middle.', '.
 8461:                  $last.', '.$gene.', '.$email.', '.$inststatus;
 8462:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
 8463:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
 8464:     } else {
 8465:         $logmsg .= ' during self creation';
 8466:     }
 8467:     my $changed;
 8468:     if ($newuser) {
 8469:         $changed = 1;
 8470:     } else {
 8471:         foreach my $field (@fields) {
 8472:             if ($names{$field} ne $oldnames{$field}) {
 8473:                 $changed = 1;
 8474:                 last;
 8475:             }
 8476:         }
 8477:     }
 8478:     unless ($changed) {
 8479:         $logmsg = 'No changes in user information needed for: '.$logmsg;
 8480:         &logthis($logmsg);
 8481:         return 'ok';
 8482:     }
 8483:     my $reply = &put('environment', \%names, $udom,$uname);
 8484:     if ($reply ne 'ok') { 
 8485:         return 'error: '.$reply;
 8486:     }
 8487:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
 8488:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
 8489:     }
 8490:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
 8491:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 8492:     $logmsg = 'Success modifying user '.$logmsg;
 8493:     &logthis($logmsg);
 8494:     return 'ok';
 8495: }
 8496: 
 8497: # -------------------------------------------------------------- Modify student
 8498: 
 8499: sub modifystudent {
 8500:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 8501:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
 8502:         $selfenroll,$context,$inststatus,$credits)=@_;
 8503:     if (!$cid) {
 8504: 	unless ($cid=$env{'request.course.id'}) {
 8505: 	    return 'not_in_class';
 8506: 	}
 8507:     }
 8508: # --------------------------------------------------------------- Make the user
 8509:     my $reply=&modifyuser
 8510: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 8511:          $desiredhome,$email,$inststatus);
 8512:     unless ($reply eq 'ok') { return $reply; }
 8513:     # This will cause &modify_student_enrollment to get the uid from the
 8514:     # student's environment
 8515:     $uid = undef if (!$forceid);
 8516:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 8517:                                         $gene,$usec,$end,$start,$type,$locktype,
 8518:                                         $cid,$selfenroll,$context,$credits);
 8519:     return $reply;
 8520: }
 8521: 
 8522: sub modify_student_enrollment {
 8523:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
 8524:         $locktype,$cid,$selfenroll,$context,$credits) = @_;
 8525:     my ($cdom,$cnum,$chome);
 8526:     if (!$cid) {
 8527: 	unless ($cid=$env{'request.course.id'}) {
 8528: 	    return 'not_in_class';
 8529: 	}
 8530: 	$cdom=$env{'course.'.$cid.'.domain'};
 8531: 	$cnum=$env{'course.'.$cid.'.num'};
 8532:     } else {
 8533: 	($cdom,$cnum)=split(/_/,$cid);
 8534:     }
 8535:     $chome=$env{'course.'.$cid.'.home'};
 8536:     if (!$chome) {
 8537: 	$chome=&homeserver($cnum,$cdom);
 8538:     }
 8539:     if (!$chome) { return 'unknown_course'; }
 8540:     # Make sure the user exists
 8541:     my $uhome=&homeserver($uname,$udom);
 8542:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 8543: 	return 'error: no such user';
 8544:     }
 8545:     # Get student data if we were not given enough information
 8546:     if (!defined($first)  || $first  eq '' || 
 8547:         !defined($last)   || $last   eq '' || 
 8548:         !defined($uid)    || $uid    eq '' || 
 8549:         !defined($middle) || $middle eq '' || 
 8550:         !defined($gene)   || $gene   eq '') {
 8551:         # They did not supply us with enough data to enroll the student, so
 8552:         # we need to pick up more information.
 8553:         my %tmp = &get('environment',
 8554:                        ['firstname','middlename','lastname', 'generation','id']
 8555:                        ,$udom,$uname);
 8556: 
 8557:         #foreach my $key (keys(%tmp)) {
 8558:         #    &logthis("key $key = ".$tmp{$key});
 8559:         #}
 8560:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 8561:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 8562:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 8563:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 8564:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 8565:     }
 8566:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 8567:     my $user = "$uname:$udom";
 8568:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
 8569:     my $reply=cput('classlist',
 8570: 		   {$user => 
 8571: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits) },
 8572: 		   $cdom,$cnum);
 8573:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
 8574:         &devalidate_getsection_cache($udom,$uname,$cid);
 8575:     } else { 
 8576: 	return 'error: '.$reply;
 8577:     }
 8578:     # Add student role to user
 8579:     my $uurl='/'.$cid;
 8580:     $uurl=~s/\_/\//g;
 8581:     if ($usec) {
 8582: 	$uurl.='/'.$usec;
 8583:     }
 8584:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
 8585:                              $selfenroll,$context);
 8586:     if ($result ne 'ok') {
 8587:         if ($old_entry{$user} ne '') {
 8588:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
 8589:         } else {
 8590:             $reply = &del('classlist',[$user],$cdom,$cnum);
 8591:         }
 8592:     }
 8593:     return $result; 
 8594: }
 8595: 
 8596: sub format_name {
 8597:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 8598:     my $name;
 8599:     if ($first ne 'lastname') {
 8600: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 8601:     } else {
 8602: 	if ($lastname=~/\S/) {
 8603: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 8604: 	    $name=~s/\s+,/,/;
 8605: 	} else {
 8606: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 8607: 	}
 8608:     }
 8609:     $name=~s/^\s+//;
 8610:     $name=~s/\s+$//;
 8611:     $name=~s/\s+/ /g;
 8612:     return $name;
 8613: }
 8614: 
 8615: # ------------------------------------------------- Write to course preferences
 8616: 
 8617: sub writecoursepref {
 8618:     my ($courseid,%prefs)=@_;
 8619:     $courseid=~s/^\///;
 8620:     $courseid=~s/\_/\//g;
 8621:     my ($cdomain,$cnum)=split(/\//,$courseid);
 8622:     my $chome=homeserver($cnum,$cdomain);
 8623:     if (($chome eq '') || ($chome eq 'no_host')) { 
 8624: 	return 'error: no such course';
 8625:     }
 8626:     my $cstring='';
 8627:     foreach my $pref (keys(%prefs)) {
 8628: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 8629:     }
 8630:     $cstring=~s/\&$//;
 8631:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 8632: }
 8633: 
 8634: # ---------------------------------------------------------- Make/modify course
 8635: 
 8636: sub createcourse {
 8637:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 8638:         $course_owner,$crstype,$cnum,$context,$category)=@_;
 8639:     $url=&declutter($url);
 8640:     my $cid='';
 8641:     if ($context eq 'requestcourses') {
 8642:         my $can_create = 0;
 8643:         my ($ownername,$ownerdom) = split(':',$course_owner);
 8644:         if ($udom eq $ownerdom) {
 8645:             if (&usertools_access($ownername,$ownerdom,$category,undef,
 8646:                                   $context)) {
 8647:                 $can_create = 1;
 8648:             }
 8649:         } else {
 8650:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
 8651:                                            $category);
 8652:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
 8653:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
 8654:                 if (@curr > 0) {
 8655:                     my @options = qw(approval validate autolimit);
 8656:                     my $optregex = join('|',@options);
 8657:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
 8658:                         $can_create = 1;
 8659:                     }
 8660:                 }
 8661:             }
 8662:         }
 8663:         if ($can_create) {
 8664:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
 8665:                 unless (&allowed('ccc',$udom)) {
 8666:                     return 'refused'; 
 8667:                 }
 8668:             }
 8669:         } else {
 8670:             return 'refused';
 8671:         }
 8672:     } elsif (!&allowed('ccc',$udom)) {
 8673:         return 'refused';
 8674:     }
 8675: # --------------------------------------------------------------- Get Unique ID
 8676:     my $uname;
 8677:     if ($cnum =~ /^$match_courseid$/) {
 8678:         my $chome=&homeserver($cnum,$udom,'true');
 8679:         if (($chome eq '') || ($chome eq 'no_host')) {
 8680:             $uname = $cnum;
 8681:         } else {
 8682:             $uname = &generate_coursenum($udom,$crstype);
 8683:         }
 8684:     } else {
 8685:         $uname = &generate_coursenum($udom,$crstype);
 8686:     }
 8687:     return $uname if ($uname =~ /^error/);
 8688: # -------------------------------------------------- Check supplied server name
 8689:     if (!defined($course_server)) {
 8690:         if (defined(&domain($udom,'primary'))) {
 8691:             $course_server = &domain($udom,'primary');
 8692:         } else {
 8693:             $course_server = $env{'user.home'}; 
 8694:         }
 8695:     }
 8696:     my %host_servers =
 8697:         &Apache::lonnet::get_servers($udom,'library');
 8698:     unless ($host_servers{$course_server}) {
 8699:         return 'error: invalid home server for course: '.$course_server;
 8700:     }
 8701: # ------------------------------------------------------------- Make the course
 8702:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 8703:                       $course_server);
 8704:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 8705:     my $uhome=&homeserver($uname,$udom,'true');
 8706:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 8707: 	return 'error: no such course';
 8708:     }
 8709: # ----------------------------------------------------------------- Course made
 8710: # log existence
 8711:     my $now = time;
 8712:     my $newcourse = {
 8713:                     $udom.'_'.$uname => {
 8714:                                      description => $description,
 8715:                                      inst_code   => $inst_code,
 8716:                                      owner       => $course_owner,
 8717:                                      type        => $crstype,
 8718:                                      creator     => $env{'user.name'}.':'.
 8719:                                                     $env{'user.domain'},
 8720:                                      created     => $now,
 8721:                                      context     => $context,
 8722:                                                 },
 8723:                     };
 8724:     &courseidput($udom,$newcourse,$uhome,'notime');
 8725: # set toplevel url
 8726:     my $topurl=$url;
 8727:     unless ($nonstandard) {
 8728: # ------------------------------------------ For standard courses, make top url
 8729:         my $mapurl=&clutter($url);
 8730:         if ($mapurl eq '/res/') { $mapurl=''; }
 8731:         $env{'form.initmap'}=(<<ENDINITMAP);
 8732: <map>
 8733: <resource id="1" type="start"></resource>
 8734: <resource id="2" src="$mapurl"></resource>
 8735: <resource id="3" type="finish"></resource>
 8736: <link index="1" from="1" to="2"></link>
 8737: <link index="2" from="2" to="3"></link>
 8738: </map>
 8739: ENDINITMAP
 8740:         $topurl=&declutter(
 8741:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 8742:                           );
 8743:     }
 8744: # ----------------------------------------------------------- Write preferences
 8745:     &writecoursepref($udom.'_'.$uname,
 8746:                      ('description'              => $description,
 8747:                       'url'                      => $topurl,
 8748:                       'internal.creator'         => $env{'user.name'}.':'.
 8749:                                                     $env{'user.domain'},
 8750:                       'internal.created'         => $now,
 8751:                       'internal.creationcontext' => $context)
 8752:                     );
 8753:     return '/'.$udom.'/'.$uname;
 8754: }
 8755: 
 8756: # ------------------------------------------------------------------- Create ID
 8757: sub generate_coursenum {
 8758:     my ($udom,$crstype) = @_;
 8759:     my $domdesc = &domain($udom);
 8760:     return 'error: invalid domain' if ($domdesc eq '');
 8761:     my $first;
 8762:     if ($crstype eq 'Community') {
 8763:         $first = '0';
 8764:     } else {
 8765:         $first = int(1+rand(9)); 
 8766:     } 
 8767:     my $uname=$first.
 8768:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 8769:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
 8770:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 8771: # ----------------------------------------------- Make sure that does not exist
 8772:     my $uhome=&homeserver($uname,$udom,'true');
 8773:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
 8774:         if ($crstype eq 'Community') {
 8775:             $first = '0';
 8776:         } else {
 8777:             $first = int(1+rand(9));
 8778:         }
 8779:         $uname=$first.
 8780:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 8781:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
 8782:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 8783:         $uhome=&homeserver($uname,$udom,'true');
 8784:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
 8785:             return 'error: unable to generate unique course-ID';
 8786:         }
 8787:     }
 8788:     return $uname;
 8789: }
 8790: 
 8791: sub is_course {
 8792:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
 8793:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
 8794: 
 8795:     return unless $cdom and $cnum;
 8796: 
 8797:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
 8798:         '.');
 8799: 
 8800:     return unless(exists($courses{$cdom.'_'.$cnum}));
 8801:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
 8802: }
 8803: 
 8804: sub store_userdata {
 8805:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
 8806:     my $result;
 8807:     if ($datakey ne '') {
 8808:         if (ref($storehash) eq 'HASH') {
 8809:             if ($udom eq '' || $uname eq '') {
 8810:                 $udom = $env{'user.domain'};
 8811:                 $uname = $env{'user.name'};
 8812:             }
 8813:             my $uhome=&homeserver($uname,$udom);
 8814:             if (($uhome eq '') || ($uhome eq 'no_host')) {
 8815:                 $result = 'error: no_host';
 8816:             } else {
 8817:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
 8818:                 $storehash->{'host'} = $perlvar{'lonHostID'};
 8819: 
 8820:                 my $namevalue='';
 8821:                 foreach my $key (keys(%{$storehash})) {
 8822:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 8823:                 }
 8824:                 $namevalue=~s/\&$//;
 8825:                 unless ($namespace eq 'courserequests') {
 8826:                     $datakey = &escape($datakey);
 8827:                 }
 8828:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
 8829:                                   $namevalue,$uhome);
 8830:             }
 8831:         } else {
 8832:             $result = 'error: data to store was not a hash reference'; 
 8833:         }
 8834:     } else {
 8835:         $result= 'error: invalid requestkey'; 
 8836:     }
 8837:     return $result;
 8838: }
 8839: 
 8840: # ---------------------------------------------------------- Assign Custom Role
 8841: 
 8842: sub assigncustomrole {
 8843:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
 8844:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 8845:                        $end,$start,$deleteflag,$selfenroll,$context);
 8846: }
 8847: 
 8848: # ----------------------------------------------------------------- Revoke Role
 8849: 
 8850: sub revokerole {
 8851:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
 8852:     my $now=time;
 8853:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
 8854: }
 8855: 
 8856: # ---------------------------------------------------------- Revoke Custom Role
 8857: 
 8858: sub revokecustomrole {
 8859:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
 8860:     my $now=time;
 8861:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 8862:            $deleteflag,$selfenroll,$context);
 8863: }
 8864: 
 8865: # ------------------------------------------------------------ Disk usage
 8866: sub diskusage {
 8867:     my ($udom,$uname,$directorypath,$getpropath)=@_;
 8868:     $directorypath =~ s/\/$//;
 8869:     my $listing=&reply('du2:'.&escape($directorypath).':'
 8870:                        .&escape($getpropath).':'.&escape($uname).':'
 8871:                        .&escape($udom),homeserver($uname,$udom));
 8872:     if ($listing eq 'unknown_cmd') {
 8873:         if ($getpropath) {
 8874:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
 8875:         }
 8876:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
 8877:     }
 8878:     return $listing;
 8879: }
 8880: 
 8881: sub is_locked {
 8882:     my ($file_name, $domain, $user, $which) = @_;
 8883:     my @check;
 8884:     my $is_locked;
 8885:     push (@check,$file_name);
 8886:     my %locked = &get('file_permissions',\@check,
 8887: 		      $env{'user.domain'},$env{'user.name'});
 8888:     my ($tmp)=keys(%locked);
 8889:     if ($tmp=~/^error:/) { undef(%locked); }
 8890:     
 8891:     if (ref($locked{$file_name}) eq 'ARRAY') {
 8892:         $is_locked = 'false';
 8893:         foreach my $entry (@{$locked{$file_name}}) {
 8894:            if (ref($entry) eq 'ARRAY') {
 8895:                $is_locked = 'true';
 8896:                if (ref($which) eq 'ARRAY') {
 8897:                    push(@{$which},$entry);
 8898:                } else {
 8899:                    last;
 8900:                }
 8901:            }
 8902:        }
 8903:     } else {
 8904:         $is_locked = 'false';
 8905:     }
 8906:     return $is_locked;
 8907: }
 8908: 
 8909: sub declutter_portfile {
 8910:     my ($file) = @_;
 8911:     $file =~ s{^(/portfolio/|portfolio/)}{/};
 8912:     return $file;
 8913: }
 8914: 
 8915: # ------------------------------------------------------------- Mark as Read Only
 8916: 
 8917: sub mark_as_readonly {
 8918:     my ($domain,$user,$files,$what) = @_;
 8919:     my %current_permissions = &dump('file_permissions',$domain,$user);
 8920:     my ($tmp)=keys(%current_permissions);
 8921:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 8922:     foreach my $file (@{$files}) {
 8923: 	$file = &declutter_portfile($file);
 8924:         push(@{$current_permissions{$file}},$what);
 8925:     }
 8926:     &put('file_permissions',\%current_permissions,$domain,$user);
 8927:     return;
 8928: }
 8929: 
 8930: # ------------------------------------------------------------Save Selected Files
 8931: 
 8932: sub save_selected_files {
 8933:     my ($user, $path, @files) = @_;
 8934:     my $filename = $user."savedfiles";
 8935:     my @other_files = &files_not_in_path($user, $path);
 8936:     open (OUT, '>'.$tmpdir.$filename);
 8937:     foreach my $file (@files) {
 8938:         print (OUT $env{'form.currentpath'}.$file."\n");
 8939:     }
 8940:     foreach my $file (@other_files) {
 8941:         print (OUT $file."\n");
 8942:     }
 8943:     close (OUT);
 8944:     return 'ok';
 8945: }
 8946: 
 8947: sub clear_selected_files {
 8948:     my ($user) = @_;
 8949:     my $filename = $user."savedfiles";
 8950:     open (OUT, '>'.LONCAPA::tempdir().$filename);
 8951:     print (OUT undef);
 8952:     close (OUT);
 8953:     return ("ok");    
 8954: }
 8955: 
 8956: sub files_in_path {
 8957:     my ($user, $path) = @_;
 8958:     my $filename = $user."savedfiles";
 8959:     my %return_files;
 8960:     open (IN, '<'.LONCAPA::tempdir().$filename);
 8961:     while (my $line_in = <IN>) {
 8962:         chomp ($line_in);
 8963:         my @paths_and_file = split (m!/!, $line_in);
 8964:         my $file_part = pop (@paths_and_file);
 8965:         my $path_part = join ('/', @paths_and_file);
 8966:         $path_part.='/';
 8967:         my $path_and_file = $path_part.$file_part;
 8968:         if ($path_part eq $path) {
 8969:             $return_files{$file_part}= 'selected';
 8970:         }
 8971:     }
 8972:     close (IN);
 8973:     return (\%return_files);
 8974: }
 8975: 
 8976: # called in portfolio select mode, to show files selected NOT in current directory
 8977: sub files_not_in_path {
 8978:     my ($user, $path) = @_;
 8979:     my $filename = $user."savedfiles";
 8980:     my @return_files;
 8981:     my $path_part;
 8982:     open(IN, '<'.LONCAPA::.$filename);
 8983:     while (my $line = <IN>) {
 8984:         #ok, I know it's clunky, but I want it to work
 8985:         my @paths_and_file = split(m|/|, $line);
 8986:         my $file_part = pop(@paths_and_file);
 8987:         chomp($file_part);
 8988:         my $path_part = join('/', @paths_and_file);
 8989:         $path_part .= '/';
 8990:         my $path_and_file = $path_part.$file_part;
 8991:         if ($path_part ne $path) {
 8992:             push(@return_files, ($path_and_file));
 8993:         }
 8994:     }
 8995:     close(OUT);
 8996:     return (@return_files);
 8997: }
 8998: 
 8999: #----------------------------------------------Get portfolio file permissions
 9000: 
 9001: sub get_portfile_permissions {
 9002:     my ($domain,$user) = @_;
 9003:     my %current_permissions = &dump('file_permissions',$domain,$user);
 9004:     my ($tmp)=keys(%current_permissions);
 9005:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 9006:     return \%current_permissions;
 9007: }
 9008: 
 9009: #---------------------------------------------Get portfolio file access controls
 9010: 
 9011: sub get_access_controls {
 9012:     my ($current_permissions,$group,$file) = @_;
 9013:     my %access;
 9014:     my $real_file = $file;
 9015:     $file =~ s/\.meta$//;
 9016:     if (defined($file)) {
 9017:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
 9018:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
 9019:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
 9020:             }
 9021:         }
 9022:     } else {
 9023:         foreach my $key (keys(%{$current_permissions})) {
 9024:             if ($key =~ /\0accesscontrol$/) {
 9025:                 if (defined($group)) {
 9026:                     if ($key !~ m-^\Q$group\E/-) {
 9027:                         next;
 9028:                     }
 9029:                 }
 9030:                 my ($fullpath) = split(/\0/,$key);
 9031:                 if (ref($$current_permissions{$key}) eq 'HASH') {
 9032:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
 9033:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
 9034:                     }
 9035:                 }
 9036:             }
 9037:         }
 9038:     }
 9039:     return %access;
 9040: }
 9041: 
 9042: sub modify_access_controls {
 9043:     my ($file_name,$changes,$domain,$user)=@_;
 9044:     my ($outcome,$deloutcome);
 9045:     my %store_permissions;
 9046:     my %new_values;
 9047:     my %new_control;
 9048:     my %translation;
 9049:     my @deletions = ();
 9050:     my $now = time;
 9051:     if (exists($$changes{'activate'})) {
 9052:         if (ref($$changes{'activate'}) eq 'HASH') {
 9053:             my @newitems = sort(keys(%{$$changes{'activate'}}));
 9054:             my $numnew = scalar(@newitems);
 9055:             for (my $i=0; $i<$numnew; $i++) {
 9056:                 my $newkey = $newitems[$i];
 9057:                 my $newid = &Apache::loncommon::get_cgi_id();
 9058:                 if ($newkey =~ /^\d+:/) { 
 9059:                     $newkey =~ s/^(\d+)/$newid/;
 9060:                     $translation{$1} = $newid;
 9061:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
 9062:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
 9063:                     $translation{$1} = $newid;
 9064:                 }
 9065:                 $new_values{$file_name."\0".$newkey} = 
 9066:                                           $$changes{'activate'}{$newitems[$i]};
 9067:                 $new_control{$newkey} = $now;
 9068:             }
 9069:         }
 9070:     }
 9071:     my %todelete;
 9072:     my %changed_items;
 9073:     foreach my $action ('delete','update') {
 9074:         if (exists($$changes{$action})) {
 9075:             if (ref($$changes{$action}) eq 'HASH') {
 9076:                 foreach my $key (keys(%{$$changes{$action}})) {
 9077:                     my ($itemnum) = ($key =~ /^([^:]+):/);
 9078:                     if ($action eq 'delete') { 
 9079:                         $todelete{$itemnum} = 1;
 9080:                     } else {
 9081:                         $changed_items{$itemnum} = $key;
 9082:                     }
 9083:                 }
 9084:             }
 9085:         }
 9086:     }
 9087:     # get lock on access controls for file.
 9088:     my $lockhash = {
 9089:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
 9090:                                                        ':'.$env{'user.domain'},
 9091:                    }; 
 9092:     my $tries = 0;
 9093:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 9094:    
 9095:     while (($gotlock ne 'ok') && $tries <3) {
 9096:         $tries ++;
 9097:         sleep 1;
 9098:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 9099:     }
 9100:     if ($gotlock eq 'ok') {
 9101:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
 9102:         my ($tmp)=keys(%curr_permissions);
 9103:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
 9104:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
 9105:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
 9106:             if (ref($curr_controls) eq 'HASH') {
 9107:                 foreach my $control_item (keys(%{$curr_controls})) {
 9108:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
 9109:                     if (defined($todelete{$itemnum})) {
 9110:                         push(@deletions,$file_name."\0".$control_item);
 9111:                     } else {
 9112:                         if (defined($changed_items{$itemnum})) {
 9113:                             $new_control{$changed_items{$itemnum}} = $now;
 9114:                             push(@deletions,$file_name."\0".$control_item);
 9115:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
 9116:                         } else {
 9117:                             $new_control{$control_item} = $$curr_controls{$control_item};
 9118:                         }
 9119:                     }
 9120:                 }
 9121:             }
 9122:         }
 9123:         my ($group);
 9124:         if (&is_course($domain,$user)) {
 9125:             ($group,my $file) = split(/\//,$file_name,2);
 9126:         }
 9127:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
 9128:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
 9129:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
 9130:         #  remove lock
 9131:         my @del_lock = ($file_name."\0".'locked_access_records');
 9132:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
 9133:         my $sqlresult =
 9134:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
 9135:                                     $group);
 9136:     } else {
 9137:         $outcome = "error: could not obtain lockfile\n";  
 9138:     }
 9139:     return ($outcome,$deloutcome,\%new_values,\%translation);
 9140: }
 9141: 
 9142: sub make_public_indefinitely {
 9143:     my ($requrl) = @_;
 9144:     my $now = time;
 9145:     my $action = 'activate';
 9146:     my $aclnum = 0;
 9147:     if (&is_portfolio_url($requrl)) {
 9148:         my (undef,$udom,$unum,$file_name,$group) =
 9149:             &parse_portfolio_url($requrl);
 9150:         my $current_perms = &get_portfile_permissions($udom,$unum);
 9151:         my %access_controls = &get_access_controls($current_perms,
 9152:                                                    $group,$file_name);
 9153:         foreach my $key (keys(%{$access_controls{$file_name}})) {
 9154:             my ($num,$scope,$end,$start) = 
 9155:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 9156:             if ($scope eq 'public') {
 9157:                 if ($start <= $now && $end == 0) {
 9158:                     $action = 'none';
 9159:                 } else {
 9160:                     $action = 'update';
 9161:                     $aclnum = $num;
 9162:                 }
 9163:                 last;
 9164:             }
 9165:         }
 9166:         if ($action eq 'none') {
 9167:              return 'ok';
 9168:         } else {
 9169:             my %changes;
 9170:             my $newend = 0;
 9171:             my $newstart = $now;
 9172:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
 9173:             $changes{$action}{$newkey} = {
 9174:                 type => 'public',
 9175:                 time => {
 9176:                     start => $newstart,
 9177:                     end   => $newend,
 9178:                 },
 9179:             };
 9180:             my ($outcome,$deloutcome,$new_values,$translation) =
 9181:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
 9182:             return $outcome;
 9183:         }
 9184:     } else {
 9185:         return 'invalid';
 9186:     }
 9187: }
 9188: 
 9189: #------------------------------------------------------Get Marked as Read Only
 9190: 
 9191: sub get_marked_as_readonly {
 9192:     my ($domain,$user,$what,$group) = @_;
 9193:     my $current_permissions = &get_portfile_permissions($domain,$user);
 9194:     my @readonly_files;
 9195:     my $cmp1=$what;
 9196:     if (ref($what)) { $cmp1=join('',@{$what}) };
 9197:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 9198:         if (defined($group)) {
 9199:             if ($file_name !~ m-^\Q$group\E/-) {
 9200:                 next;
 9201:             }
 9202:         }
 9203:         if (ref($value) eq "ARRAY"){
 9204:             foreach my $stored_what (@{$value}) {
 9205:                 my $cmp2=$stored_what;
 9206:                 if (ref($stored_what) eq 'ARRAY') {
 9207:                     $cmp2=join('',@{$stored_what});
 9208:                 }
 9209:                 if ($cmp1 eq $cmp2) {
 9210:                     push(@readonly_files, $file_name);
 9211:                     last;
 9212:                 } elsif (!defined($what)) {
 9213:                     push(@readonly_files, $file_name);
 9214:                     last;
 9215:                 }
 9216:             }
 9217:         }
 9218:     }
 9219:     return @readonly_files;
 9220: }
 9221: #-----------------------------------------------------------Get Marked as Read Only Hash
 9222: 
 9223: sub get_marked_as_readonly_hash {
 9224:     my ($current_permissions,$group,$what) = @_;
 9225:     my %readonly_files;
 9226:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 9227:         if (defined($group)) {
 9228:             if ($file_name !~ m-^\Q$group\E/-) {
 9229:                 next;
 9230:             }
 9231:         }
 9232:         if (ref($value) eq "ARRAY"){
 9233:             foreach my $stored_what (@{$value}) {
 9234:                 if (ref($stored_what) eq 'ARRAY') {
 9235:                     foreach my $lock_descriptor(@{$stored_what}) {
 9236:                         if ($lock_descriptor eq 'graded') {
 9237:                             $readonly_files{$file_name} = 'graded';
 9238:                         } elsif ($lock_descriptor eq 'handback') {
 9239:                             $readonly_files{$file_name} = 'handback';
 9240:                         } else {
 9241:                             if (!exists($readonly_files{$file_name})) {
 9242:                                 $readonly_files{$file_name} = 'locked';
 9243:                             }
 9244:                         }
 9245:                     }
 9246:                 } 
 9247:             }
 9248:         } 
 9249:     }
 9250:     return %readonly_files;
 9251: }
 9252: # ------------------------------------------------------------ Unmark as Read Only
 9253: 
 9254: sub unmark_as_readonly {
 9255:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
 9256:     # for portfolio submissions, $what contains [$symb,$crsid] 
 9257:     my ($domain,$user,$what,$file_name,$group) = @_;
 9258:     $file_name = &declutter_portfile($file_name);
 9259:     my $symb_crs = $what;
 9260:     if (ref($what)) { $symb_crs=join('',@$what); }
 9261:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
 9262:     my ($tmp)=keys(%current_permissions);
 9263:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 9264:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
 9265:     foreach my $file (@readonly_files) {
 9266: 	my $clean_file = &declutter_portfile($file);
 9267: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
 9268: 	my $current_locks = $current_permissions{$file};
 9269:         my @new_locks;
 9270:         my @del_keys;
 9271:         if (ref($current_locks) eq "ARRAY"){
 9272:             foreach my $locker (@{$current_locks}) {
 9273:                 my $compare=$locker;
 9274:                 if (ref($locker) eq 'ARRAY') {
 9275:                     $compare=join('',@{$locker});
 9276:                     if ($compare ne $symb_crs) {
 9277:                         push(@new_locks, $locker);
 9278:                     }
 9279:                 }
 9280:             }
 9281:             if (scalar(@new_locks) > 0) {
 9282:                 $current_permissions{$file} = \@new_locks;
 9283:             } else {
 9284:                 push(@del_keys, $file);
 9285:                 &del('file_permissions',\@del_keys, $domain, $user);
 9286:                 delete($current_permissions{$file});
 9287:             }
 9288:         }
 9289:     }
 9290:     &put('file_permissions',\%current_permissions,$domain,$user);
 9291:     return;
 9292: }
 9293: 
 9294: # ------------------------------------------------------------ Directory lister
 9295: 
 9296: sub dirlist {
 9297:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
 9298:     $uri=~s/^\///;
 9299:     $uri=~s/\/$//;
 9300:     my ($udom, $uname);
 9301:     if ($getuserdir) {
 9302:         $udom = $userdomain;
 9303:         $uname = $username;
 9304:     } else {
 9305:         (undef,$udom,$uname)=split(/\//,$uri);
 9306:         if(defined($userdomain)) {
 9307:             $udom = $userdomain;
 9308:         }
 9309:         if(defined($username)) {
 9310:             $uname = $username;
 9311:         }
 9312:     }
 9313:     my ($dirRoot,$listing,@listing_results);
 9314: 
 9315:     $dirRoot = $perlvar{'lonDocRoot'};
 9316:     if (defined($getpropath)) {
 9317:         $dirRoot = &propath($udom,$uname);
 9318:         $dirRoot =~ s/\/$//;
 9319:     } elsif (defined($getuserdir)) {
 9320:         my $subdir=$uname.'__';
 9321:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 9322:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
 9323:                    ."/$udom/$subdir/$uname";
 9324:     } elsif (defined($alternateRoot)) {
 9325:         $dirRoot = $alternateRoot;
 9326:     }
 9327: 
 9328:     if($udom) {
 9329:         if($uname) {
 9330:             my $uhome = &homeserver($uname,$udom);
 9331:             if ($uhome eq 'no_host') {
 9332:                 return ([],'no_host');
 9333:             }
 9334:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
 9335:                               .$getuserdir.':'.&escape($dirRoot)
 9336:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
 9337:             if ($listing eq 'unknown_cmd') {
 9338:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
 9339:             } else {
 9340:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 9341:             }
 9342:             if ($listing eq 'unknown_cmd') {
 9343:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
 9344:                 @listing_results = split(/:/,$listing);
 9345:             } else {
 9346:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 9347:             }
 9348:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
 9349:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
 9350:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
 9351:                 return ([],$listing);
 9352:             } else {
 9353:                 return (\@listing_results);
 9354:             }
 9355:         } elsif(!$alternateRoot) {
 9356:             my (%allusers,%listerror);
 9357: 	    my %servers = &get_servers($udom,'library');
 9358:  	    foreach my $tryserver (keys(%servers)) {
 9359:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
 9360:                                   &escape($udom),$tryserver);
 9361:                 if ($listing eq 'unknown_cmd') {
 9362: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
 9363: 				      $udom, $tryserver);
 9364:                 } else {
 9365:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
 9366:                 }
 9367: 		if ($listing eq 'unknown_cmd') {
 9368: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 9369: 				      $udom, $tryserver);
 9370: 		    @listing_results = split(/:/,$listing);
 9371: 		} else {
 9372: 		    @listing_results =
 9373: 			map { &unescape($_); } split(/:/,$listing);
 9374: 		}
 9375:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
 9376:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
 9377:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
 9378:                     $listerror{$tryserver} = $listing;
 9379:                 } else {
 9380: 		    foreach my $line (@listing_results) {
 9381: 			my ($entry) = split(/&/,$line,2);
 9382: 			$allusers{$entry} = 1;
 9383: 		    }
 9384: 		}
 9385:             }
 9386:             my @alluserslist=();
 9387:             foreach my $user (sort(keys(%allusers))) {
 9388:                 push(@alluserslist,$user.'&user');
 9389:             }
 9390:             return (\@alluserslist);
 9391:         } else {
 9392:             return ([],'missing username');
 9393:         }
 9394:     } elsif(!defined($getpropath)) {
 9395:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
 9396:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
 9397:         return (\@all_domains);
 9398:     } else {
 9399:         return ([],'missing domain');
 9400:     }
 9401: }
 9402: 
 9403: # --------------------------------------------- GetFileTimestamp
 9404: # This function utilizes dirlist and returns the date stamp for
 9405: # when it was last modified.  It will also return an error of -1
 9406: # if an error occurs
 9407: 
 9408: sub GetFileTimestamp {
 9409:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
 9410:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
 9411:     $studentName   = &LONCAPA::clean_username($studentName);
 9412:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
 9413:                                     undef,$getuserdir);
 9414:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
 9415:         return -1;
 9416:     }
 9417:     if (ref($fileref) eq 'ARRAY') {
 9418:         my @stats = split('&',$fileref->[0]);
 9419:         # @stats contains first the filename, then the stat output
 9420:         return $stats[10]; # so this is 10 instead of 9.
 9421:     } else {
 9422:         return -1;
 9423:     }
 9424: }
 9425: 
 9426: sub stat_file {
 9427:     my ($uri) = @_;
 9428:     $uri = &clutter_with_no_wrapper($uri);
 9429: 
 9430:     my ($udom,$uname,$file);
 9431:     if ($uri =~ m-^/(uploaded|editupload)/-) {
 9432: 	($udom,$uname,$file) =
 9433: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
 9434: 	$file = 'userfiles/'.$file;
 9435:     }
 9436:     if ($uri =~ m-^/res/-) {
 9437: 	($udom,$uname) = 
 9438: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
 9439: 	$file = $uri;
 9440:     }
 9441: 
 9442:     if (!$udom || !$uname || !$file) {
 9443: 	# unable to handle the uri
 9444: 	return ();
 9445:     }
 9446:     my $getpropath;
 9447:     if ($file =~ /^userfiles\//) {
 9448:         $getpropath = 1;
 9449:     }
 9450:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
 9451:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
 9452:         return ();
 9453:     } else {
 9454:         if (ref($listref) eq 'ARRAY') {
 9455:             my @stats = split('&',$listref->[0]);
 9456: 	    shift(@stats); #filename is first
 9457: 	    return @stats;
 9458:         }
 9459:     }
 9460:     return ();
 9461: }
 9462: 
 9463: # -------------------------------------------------------- Value of a Condition
 9464: 
 9465: # gets the value of a specific preevaluated condition
 9466: #    stored in the string  $env{user.state.<cid>}
 9467: # or looks up a condition reference in the bighash and if if hasn't
 9468: # already been evaluated recurses into docondval to get the value of
 9469: # the condition, then memoizing it to 
 9470: #   $env{user.state.<cid>.<condition>}
 9471: sub directcondval {
 9472:     my $number=shift;
 9473:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
 9474: 	&Apache::lonuserstate::evalstate();
 9475:     }
 9476:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
 9477: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
 9478:     } elsif ($number =~ /^_/) {
 9479: 	my $sub_condition;
 9480: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 9481: 		&GDBM_READER(),0640)) {
 9482: 	    $sub_condition=$bighash{'conditions'.$number};
 9483: 	    untie(%bighash);
 9484: 	}
 9485: 	my $value = &docondval($sub_condition);
 9486: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
 9487: 	return $value;
 9488:     }
 9489:     if ($env{'user.state.'.$env{'request.course.id'}}) {
 9490:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
 9491:     } else {
 9492:        return 2;
 9493:     }
 9494: }
 9495: 
 9496: # get the collection of conditions for this resource
 9497: sub condval {
 9498:     my $condidx=shift;
 9499:     my $allpathcond='';
 9500:     foreach my $cond (split(/\|/,$condidx)) {
 9501: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
 9502: 	    $allpathcond.=
 9503: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
 9504: 	}
 9505:     }
 9506:     $allpathcond=~s/\|$//;
 9507:     return &docondval($allpathcond);
 9508: }
 9509: 
 9510: #evaluates an expression of conditions
 9511: sub docondval {
 9512:     my ($allpathcond) = @_;
 9513:     my $result=0;
 9514:     if ($env{'request.course.id'}
 9515: 	&& defined($allpathcond)) {
 9516: 	my $operand='|';
 9517: 	my @stack;
 9518: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
 9519: 	    if ($chunk eq '(') {
 9520: 		push @stack,($operand,$result);
 9521: 	    } elsif ($chunk eq ')') {
 9522: 		my $before=pop @stack;
 9523: 		if (pop @stack eq '&') {
 9524: 		    $result=$result>$before?$before:$result;
 9525: 		} else {
 9526: 		    $result=$result>$before?$result:$before;
 9527: 		}
 9528: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
 9529: 		$operand=$chunk;
 9530: 	    } else {
 9531: 		my $new=directcondval($chunk);
 9532: 		if ($operand eq '&') {
 9533: 		    $result=$result>$new?$new:$result;
 9534: 		} else {
 9535: 		    $result=$result>$new?$result:$new;
 9536: 		}
 9537: 	    }
 9538: 	}
 9539:     }
 9540:     return $result;
 9541: }
 9542: 
 9543: # ---------------------------------------------------- Devalidate courseresdata
 9544: 
 9545: sub devalidatecourseresdata {
 9546:     my ($coursenum,$coursedomain)=@_;
 9547:     my $hashid=$coursenum.':'.$coursedomain;
 9548:     &devalidate_cache_new('courseres',$hashid);
 9549: }
 9550: 
 9551: 
 9552: # --------------------------------------------------- Course Resourcedata Query
 9553: #
 9554: #  Parameters:
 9555: #      $coursenum    - Number of the course.
 9556: #      $coursedomain - Domain at which the course was created.
 9557: #  Returns:
 9558: #     A hash of the course parameters along (I think) with timestamps
 9559: #     and version info.
 9560: 
 9561: sub get_courseresdata {
 9562:     my ($coursenum,$coursedomain)=@_;
 9563:     my $coursehom=&homeserver($coursenum,$coursedomain);
 9564:     my $hashid=$coursenum.':'.$coursedomain;
 9565:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
 9566:     my %dumpreply;
 9567:     unless (defined($cached)) {
 9568: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 9569: 	$result=\%dumpreply;
 9570: 	my ($tmp) = keys(%dumpreply);
 9571: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 9572: 	    &do_cache_new('courseres',$hashid,$result,600);
 9573: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 9574: 	    return $tmp;
 9575: 	} elsif ($tmp =~ /^(error)/) {
 9576: 	    $result=undef;
 9577: 	    &do_cache_new('courseres',$hashid,$result,600);
 9578: 	}
 9579:     }
 9580:     return $result;
 9581: }
 9582: 
 9583: sub devalidateuserresdata {
 9584:     my ($uname,$udom)=@_;
 9585:     my $hashid="$udom:$uname";
 9586:     &devalidate_cache_new('userres',$hashid);
 9587: }
 9588: 
 9589: sub get_userresdata {
 9590:     my ($uname,$udom)=@_;
 9591:     #most student don\'t have any data set, check if there is some data
 9592:     if (&EXT_cache_status($udom,$uname)) { return undef; }
 9593: 
 9594:     my $hashid="$udom:$uname";
 9595:     my ($result,$cached)=&is_cached_new('userres',$hashid);
 9596:     if (!defined($cached)) {
 9597: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
 9598: 	$result=\%resourcedata;
 9599: 	&do_cache_new('userres',$hashid,$result,600);
 9600:     }
 9601:     my ($tmp)=keys(%$result);
 9602:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
 9603: 	return $result;
 9604:     }
 9605:     #error 2 occurs when the .db doesn't exist
 9606:     if ($tmp!~/error: 2 /) {
 9607: 	&logthis("<font color=\"blue\">WARNING:".
 9608: 		 " Trying to get resource data for ".
 9609: 		 $uname." at ".$udom.": ".
 9610: 		 $tmp."</font>");
 9611:     } elsif ($tmp=~/error: 2 /) {
 9612: 	#&EXT_cache_set($udom,$uname);
 9613: 	&do_cache_new('userres',$hashid,undef,600);
 9614: 	undef($tmp); # not really an error so don't send it back
 9615:     }
 9616:     return $tmp;
 9617: }
 9618: #----------------------------------------------- resdata - return resource data
 9619: #  Purpose:
 9620: #    Return resource data for either users or for a course.
 9621: #  Parameters:
 9622: #     $name      - Course/user name.
 9623: #     $domain    - Name of the domain the user/course is registered on.
 9624: #     $type      - Type of thing $name is (must be 'course' or 'user'
 9625: #     @which     - Array of names of resources desired.
 9626: #  Returns:
 9627: #     The value of the first reasource in @which that is found in the
 9628: #     resource hash.
 9629: #  Exceptional Conditions:
 9630: #     If the $type passed in is not valid (not the string 'course' or 
 9631: #     'user', an undefined  reference is returned.
 9632: #     If none of the resources are found, an undef is returned
 9633: sub resdata {
 9634:     my ($name,$domain,$type,@which)=@_;
 9635:     my $result;
 9636:     if ($type eq 'course') {
 9637: 	$result=&get_courseresdata($name,$domain);
 9638:     } elsif ($type eq 'user') {
 9639: 	$result=&get_userresdata($name,$domain);
 9640:     }
 9641:     if (!ref($result)) { return $result; }    
 9642:     foreach my $item (@which) {
 9643: 	if (defined($result->{$item->[0]})) {
 9644: 	    return [$result->{$item->[0]},$item->[1]];
 9645: 	}
 9646:     }
 9647:     return undef;
 9648: }
 9649: 
 9650: sub get_numsuppfiles {
 9651:     my ($cnum,$cdom,$ignorecache)=@_;
 9652:     my $hashid=$cnum.':'.$cdom;
 9653:     my ($suppcount,$cached);
 9654:     unless ($ignorecache) {
 9655:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
 9656:     }
 9657:     unless (defined($cached)) {
 9658:         my $chome=&homeserver($cnum,$cdom);
 9659:         unless ($chome eq 'no_host') {
 9660:             ($suppcount,my $errors) = (0,0);
 9661:             my $suppmap = 'supplemental.sequence';
 9662:             ($suppcount,$errors) = 
 9663:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
 9664:         }
 9665:         &do_cache_new('suppcount',$hashid,$suppcount,600);
 9666:     }
 9667:     return $suppcount;
 9668: }
 9669: 
 9670: #
 9671: # EXT resource caching routines
 9672: #
 9673: 
 9674: sub clear_EXT_cache_status {
 9675:     &delenv('cache.EXT.');
 9676: }
 9677: 
 9678: sub EXT_cache_status {
 9679:     my ($target_domain,$target_user) = @_;
 9680:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 9681:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
 9682:         # We know already the user has no data
 9683:         return 1;
 9684:     } else {
 9685:         return 0;
 9686:     }
 9687: }
 9688: 
 9689: sub EXT_cache_set {
 9690:     my ($target_domain,$target_user) = @_;
 9691:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 9692:     #&appenv({$cachename => time});
 9693: }
 9694: 
 9695: # --------------------------------------------------------- Value of a Variable
 9696: sub EXT {
 9697: 
 9698:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
 9699:     unless ($varname) { return ''; }
 9700:     #get real user name/domain, courseid and symb
 9701:     my $courseid;
 9702:     my $publicuser;
 9703:     if ($symbparm) {
 9704: 	$symbparm=&get_symb_from_alias($symbparm);
 9705:     }
 9706:     if (!($uname && $udom)) {
 9707:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
 9708:       if (!$symbparm) {	$symbparm=$cursymb; }
 9709:     } else {
 9710: 	$courseid=$env{'request.course.id'};
 9711:     }
 9712:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 9713:     my $rest;
 9714:     if (defined($therest[0])) {
 9715:        $rest=join('.',@therest);
 9716:     } else {
 9717:        $rest='';
 9718:     }
 9719: 
 9720:     my $qualifierrest=$qualifier;
 9721:     if ($rest) { $qualifierrest.='.'.$rest; }
 9722:     my $spacequalifierrest=$space;
 9723:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 9724:     if ($realm eq 'user') {
 9725: # --------------------------------------------------------------- user.resource
 9726: 	if ($space eq 'resource') {
 9727: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
 9728: 		  || defined($Apache::lonhomework::parsing_a_task))
 9729: 		 &&
 9730: 		 ($symbparm eq &symbread()) ) {	
 9731: 		# if we are in the middle of processing the resource the
 9732: 		# get the value we are planning on committing
 9733:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
 9734:                     return $Apache::lonhomework::results{$qualifierrest};
 9735:                 } else {
 9736:                     return $Apache::lonhomework::history{$qualifierrest};
 9737:                 }
 9738: 	    } else {
 9739: 		my %restored;
 9740: 		if ($publicuser || $env{'request.state'} eq 'construct') {
 9741: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
 9742: 		} else {
 9743: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
 9744: 		}
 9745: 		return $restored{$qualifierrest};
 9746: 	    }
 9747: # ----------------------------------------------------------------- user.access
 9748:         } elsif ($space eq 'access') {
 9749: 	    # FIXME - not supporting calls for a specific user
 9750:             return &allowed($qualifier,$rest);
 9751: # ------------------------------------------ user.preferences, user.environment
 9752:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 9753: 	    if (($uname eq $env{'user.name'}) &&
 9754: 		($udom eq $env{'user.domain'})) {
 9755: 		return $env{join('.',('environment',$qualifierrest))};
 9756: 	    } else {
 9757: 		my %returnhash;
 9758: 		if (!$publicuser) {
 9759: 		    %returnhash=&userenvironment($udom,$uname,
 9760: 						 $qualifierrest);
 9761: 		}
 9762: 		return $returnhash{$qualifierrest};
 9763: 	    }
 9764: # ----------------------------------------------------------------- user.course
 9765:         } elsif ($space eq 'course') {
 9766: 	    # FIXME - not supporting calls for a specific user
 9767:             return $env{join('.',('request.course',$qualifier))};
 9768: # ------------------------------------------------------------------- user.role
 9769:         } elsif ($space eq 'role') {
 9770: 	    # FIXME - not supporting calls for a specific user
 9771:             my ($role,$where)=split(/\./,$env{'request.role'});
 9772:             if ($qualifier eq 'value') {
 9773: 		return $role;
 9774:             } elsif ($qualifier eq 'extent') {
 9775:                 return $where;
 9776:             }
 9777: # ----------------------------------------------------------------- user.domain
 9778:         } elsif ($space eq 'domain') {
 9779:             return $udom;
 9780: # ------------------------------------------------------------------- user.name
 9781:         } elsif ($space eq 'name') {
 9782:             return $uname;
 9783: # ---------------------------------------------------- Any other user namespace
 9784:         } else {
 9785: 	    my %reply;
 9786: 	    if (!$publicuser) {
 9787: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
 9788: 	    }
 9789: 	    return $reply{$qualifierrest};
 9790:         }
 9791:     } elsif ($realm eq 'query') {
 9792: # ---------------------------------------------- pull stuff out of query string
 9793:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 9794: 						[$spacequalifierrest]);
 9795: 	return $env{'form.'.$spacequalifierrest}; 
 9796:    } elsif ($realm eq 'request') {
 9797: # ------------------------------------------------------------- request.browser
 9798:         if ($space eq 'browser') {
 9799:             return $env{'browser.'.$qualifier};
 9800: # ------------------------------------------------------------ request.filename
 9801:         } else {
 9802:             return $env{'request.'.$spacequalifierrest};
 9803:         }
 9804:     } elsif ($realm eq 'course') {
 9805: # ---------------------------------------------------------- course.description
 9806:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
 9807:     } elsif ($realm eq 'resource') {
 9808: 
 9809: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
 9810: 	    if (!$symbparm) { $symbparm=&symbread(); }
 9811: 	}
 9812: 
 9813:         if ($qualifier eq '') {
 9814: 	    if ($space eq 'title') {
 9815: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
 9816: 	        return &gettitle($symbparm);
 9817: 	    }
 9818: 	
 9819: 	    if ($space eq 'map') {
 9820: 	        my ($map) = &decode_symb($symbparm);
 9821: 	        return &symbread($map);
 9822: 	    }
 9823:             if ($space eq 'maptitle') {
 9824:                 my ($map) = &decode_symb($symbparm);
 9825:                 return &gettitle($map);
 9826:             }
 9827: 	    if ($space eq 'filename') {
 9828: 	        if ($symbparm) {
 9829: 		    return &clutter((&decode_symb($symbparm))[2]);
 9830: 	        }
 9831: 	        return &hreflocation('',$env{'request.filename'});
 9832: 	    }
 9833: 
 9834:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
 9835:                 if ($space eq 'visibleparts') {
 9836:                     my $navmap = Apache::lonnavmaps::navmap->new();
 9837:                     my $item;
 9838:                     if (ref($navmap)) {
 9839:                         my $res = $navmap->getBySymb($symbparm);
 9840:                         my $parts = $res->parts();
 9841:                         if (ref($parts) eq 'ARRAY') {
 9842:                             $item = join(',',@{$parts});
 9843:                         }
 9844:                         undef($navmap);
 9845:                     }
 9846:                     return $item;
 9847:                 }
 9848:             }
 9849:         }
 9850: 
 9851: 	my ($section, $group, @groups);
 9852: 	my ($courselevelm,$courselevel);
 9853:         if (($courseid eq '') && ($cid)) {
 9854:             $courseid = $cid;
 9855:         }
 9856: 	if (($symbparm && $courseid) && 
 9857: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
 9858: 
 9859: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
 9860: 
 9861: # ----------------------------------------------------- Cascading lookup scheme
 9862: 	    my $symbp=$symbparm;
 9863: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
 9864: 
 9865: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
 9866: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
 9867: 
 9868: 	    if (($env{'user.name'} eq $uname) &&
 9869: 		($env{'user.domain'} eq $udom)) {
 9870: 		$section=$env{'request.course.sec'};
 9871:                 @groups = split(/:/,$env{'request.course.groups'});  
 9872:                 @groups=&sort_course_groups($courseid,@groups); 
 9873: 	    } else {
 9874: 		if (! defined($usection)) {
 9875: 		    $section=&getsection($udom,$uname,$courseid);
 9876: 		} else {
 9877: 		    $section = $usection;
 9878: 		}
 9879:                 @groups = &get_users_groups($udom,$uname,$courseid);
 9880: 	    }
 9881: 
 9882: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
 9883: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
 9884: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
 9885: 
 9886: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
 9887: 	    my $courselevelr=$courseid.'.'.$symbparm;
 9888: 	    $courselevelm=$courseid.'.'.$mapparm;
 9889: 
 9890: # ----------------------------------------------------------- first, check user
 9891: 
 9892: 	    my $userreply=&resdata($uname,$udom,'user',
 9893: 				       ([$courselevelr,'resource'],
 9894: 					[$courselevelm,'map'     ],
 9895: 					[$courselevel, 'course'  ]));
 9896: 	    if (defined($userreply)) { return &get_reply($userreply); }
 9897: 
 9898: # ------------------------------------------------ second, check some of course
 9899:             my $coursereply;
 9900:             if (@groups > 0) {
 9901:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
 9902:                                        $mapparm,$spacequalifierrest);
 9903:                 if (defined($coursereply)) { return &get_reply($coursereply); }
 9904:             }
 9905: 
 9906: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 9907: 				  $env{'course.'.$courseid.'.domain'},
 9908: 				  'course',
 9909: 				  ([$seclevelr,   'resource'],
 9910: 				   [$seclevelm,   'map'     ],
 9911: 				   [$seclevel,    'course'  ],
 9912: 				   [$courselevelr,'resource']));
 9913: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 9914: 
 9915: # ------------------------------------------------------ third, check map parms
 9916: 	    my %parmhash=();
 9917: 	    my $thisparm='';
 9918: 	    if (tie(%parmhash,'GDBM_File',
 9919: 		    $env{'request.course.fn'}.'_parms.db',
 9920: 		    &GDBM_READER(),0640)) {
 9921: 		$thisparm=$parmhash{$symbparm};
 9922: 		untie(%parmhash);
 9923: 	    }
 9924: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
 9925: 	}
 9926: # ------------------------------------------ fourth, look in resource metadata
 9927: 
 9928: 	$spacequalifierrest=~s/\./\_/;
 9929: 	my $filename;
 9930: 	if (!$symbparm) { $symbparm=&symbread(); }
 9931: 	if ($symbparm) {
 9932: 	    $filename=(&decode_symb($symbparm))[2];
 9933: 	} else {
 9934: 	    $filename=$env{'request.filename'};
 9935: 	}
 9936: 	my $metadata=&metadata($filename,$spacequalifierrest);
 9937: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 9938: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
 9939: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 9940: 
 9941: # ---------------------------------------------- fourth, look in rest of course
 9942: 	if ($symbparm && defined($courseid) && 
 9943: 	    $courseid eq $env{'request.course.id'}) {
 9944: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 9945: 				     $env{'course.'.$courseid.'.domain'},
 9946: 				     'course',
 9947: 				     ([$courselevelm,'map'   ],
 9948: 				      [$courselevel, 'course']));
 9949: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 9950: 	}
 9951: # ------------------------------------------------------------------ Cascade up
 9952: 	unless ($space eq '0') {
 9953: 	    my @parts=split(/_/,$space);
 9954: 	    my $id=pop(@parts);
 9955: 	    my $part=join('_',@parts);
 9956: 	    if ($part eq '') { $part='0'; }
 9957: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
 9958: 				 $symbparm,$udom,$uname,$section,1);
 9959: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
 9960: 	}
 9961: 	if ($recurse) { return undef; }
 9962: 	my $pack_def=&packages_tab_default($filename,$varname);
 9963: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
 9964: # ---------------------------------------------------- Any other user namespace
 9965:     } elsif ($realm eq 'environment') {
 9966: # ----------------------------------------------------------------- environment
 9967: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
 9968: 	    return $env{'environment.'.$spacequalifierrest};
 9969: 	} else {
 9970: 	    if ($uname eq 'anonymous' && $udom eq '') {
 9971: 		return '';
 9972: 	    }
 9973: 	    my %returnhash=&userenvironment($udom,$uname,
 9974: 					    $spacequalifierrest);
 9975: 	    return $returnhash{$spacequalifierrest};
 9976: 	}
 9977:     } elsif ($realm eq 'system') {
 9978: # ----------------------------------------------------------------- system.time
 9979: 	if ($space eq 'time') {
 9980: 	    return time;
 9981:         }
 9982:     } elsif ($realm eq 'server') {
 9983: # ----------------------------------------------------------------- system.time
 9984: 	if ($space eq 'name') {
 9985: 	    return $ENV{'SERVER_NAME'};
 9986:         }
 9987:     }
 9988:     return '';
 9989: }
 9990: 
 9991: sub get_reply {
 9992:     my ($reply_value) = @_;
 9993:     if (ref($reply_value) eq 'ARRAY') {
 9994:         if (wantarray) {
 9995: 	    return @$reply_value;
 9996:         }
 9997:         return $reply_value->[0];
 9998:     } else {
 9999:         return $reply_value;
10000:     }
10001: }
10002: 
10003: sub check_group_parms {
10004:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
10005:     my @groupitems = ();
10006:     my $resultitem;
10007:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
10008:     foreach my $group (@{$groups}) {
10009:         foreach my $level (@levels) {
10010:              my $item = $courseid.'.['.$group.'].'.$level->[0];
10011:              push(@groupitems,[$item,$level->[1]]);
10012:         }
10013:     }
10014:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
10015:                             $env{'course.'.$courseid.'.domain'},
10016:                                      'course',@groupitems);
10017:     return $coursereply;
10018: }
10019: 
10020: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
10021:     my ($courseid,@groups) = @_;
10022:     @groups = sort(@groups);
10023:     return @groups;
10024: }
10025: 
10026: sub packages_tab_default {
10027:     my ($uri,$varname)=@_;
10028:     my (undef,$part,$name)=split(/\./,$varname);
10029: 
10030:     my (@extension,@specifics,$do_default);
10031:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
10032: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
10033: 	if ($pack_type eq 'default') {
10034: 	    $do_default=1;
10035: 	} elsif ($pack_type eq 'extension') {
10036: 	    push(@extension,[$package,$pack_type,$pack_part]);
10037: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
10038: 	    # only look at packages defaults for packages that this id is
10039: 	    push(@specifics,[$package,$pack_type,$pack_part]);
10040: 	}
10041:     }
10042:     # first look for a package that matches the requested part id
10043:     foreach my $package (@specifics) {
10044: 	my (undef,$pack_type,$pack_part)=@{$package};
10045: 	next if ($pack_part ne $part);
10046: 	if (defined($packagetab{"$pack_type&$name&default"})) {
10047: 	    return $packagetab{"$pack_type&$name&default"};
10048: 	}
10049:     }
10050:     # look for any possible matching non extension_ package
10051:     foreach my $package (@specifics) {
10052: 	my (undef,$pack_type,$pack_part)=@{$package};
10053: 	if (defined($packagetab{"$pack_type&$name&default"})) {
10054: 	    return $packagetab{"$pack_type&$name&default"};
10055: 	}
10056: 	if ($pack_type eq 'part') { $pack_part='0'; }
10057: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
10058: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
10059: 	}
10060:     }
10061:     # look for any posible extension_ match
10062:     foreach my $package (@extension) {
10063: 	my ($package,$pack_type)=@{$package};
10064: 	if (defined($packagetab{"$pack_type&$name&default"})) {
10065: 	    return $packagetab{"$pack_type&$name&default"};
10066: 	}
10067: 	if (defined($packagetab{$package."&$name&default"})) {
10068: 	    return $packagetab{$package."&$name&default"};
10069: 	}
10070:     }
10071:     # look for a global default setting
10072:     if ($do_default && defined($packagetab{"default&$name&default"})) {
10073: 	return $packagetab{"default&$name&default"};
10074:     }
10075:     return undef;
10076: }
10077: 
10078: sub add_prefix_and_part {
10079:     my ($prefix,$part)=@_;
10080:     my $keyroot;
10081:     if (defined($prefix) && $prefix !~ /^__/) {
10082: 	# prefix that has a part already
10083: 	$keyroot=$prefix;
10084:     } elsif (defined($prefix)) {
10085: 	# prefix that is missing a part
10086: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
10087:     } else {
10088: 	# no prefix at all
10089: 	if (defined($part)) { $keyroot='_'.$part; }
10090:     }
10091:     return $keyroot;
10092: }
10093: 
10094: # ---------------------------------------------------------------- Get metadata
10095: 
10096: my %metaentry;
10097: my %importedpartids;
10098: sub metadata {
10099:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
10100:     $uri=&declutter($uri);
10101:     # if it is a non metadata possible uri return quickly
10102:     if (($uri eq '') || 
10103: 	(($uri =~ m|^/*adm/|) && 
10104: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
10105:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
10106: 	return undef;
10107:     }
10108:     if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) 
10109: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
10110: 	return undef;
10111:     }
10112:     my $filename=$uri;
10113:     $uri=~s/\.meta$//;
10114: #
10115: # Is the metadata already cached?
10116: # Look at timestamp of caching
10117: # Everything is cached by the main uri, libraries are never directly cached
10118: #
10119:     if (!defined($liburi)) {
10120: 	my ($result,$cached)=&is_cached_new('meta',$uri);
10121: 	if (defined($cached)) { return $result->{':'.$what}; }
10122:     }
10123:     {
10124: # Imported parts would go here
10125:         my %importedids=();
10126:         my @origfileimportpartids=();
10127:         my $importedparts=0;
10128: #
10129: # Is this a recursive call for a library?
10130: #
10131: #	if (! exists($metacache{$uri})) {
10132: #	    $metacache{$uri}={};
10133: #	}
10134: 	my $cachetime = 60*60;
10135:         if ($liburi) {
10136: 	    $liburi=&declutter($liburi);
10137:             $filename=$liburi;
10138:         } else {
10139: 	    &devalidate_cache_new('meta',$uri);
10140: 	    undef(%metaentry);
10141: 	}
10142:         my %metathesekeys=();
10143:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
10144: 	my $metastring;
10145: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
10146: 	    my $which = &hreflocation('','/'.($liburi || $uri));
10147: 	    $metastring = 
10148: 		&Apache::lonnet::ssi_body($which,
10149: 					  ('grade_target' => 'meta'));
10150: 	    $cachetime = 1; # only want this cached in the child not long term
10151: 	} elsif (($uri !~ m -^(editupload)/-) && 
10152:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
10153: 	    my $file=&filelocation('',&clutter($filename));
10154: 	    #push(@{$metaentry{$uri.'.file'}},$file);
10155: 	    $metastring=&getfile($file);
10156: 	}
10157:         my $parser=HTML::LCParser->new(\$metastring);
10158:         my $token;
10159:         undef %metathesekeys;
10160:         while ($token=$parser->get_token) {
10161: 	    if ($token->[0] eq 'S') {
10162: 		if (defined($token->[2]->{'package'})) {
10163: #
10164: # This is a package - get package info
10165: #
10166: 		    my $package=$token->[2]->{'package'};
10167: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10168: 		    if (defined($token->[2]->{'id'})) { 
10169: 			$keyroot.='_'.$token->[2]->{'id'}; 
10170: 		    }
10171: 		    if ($metaentry{':packages'}) {
10172: 			$metaentry{':packages'}.=','.$package.$keyroot;
10173: 		    } else {
10174: 			$metaentry{':packages'}=$package.$keyroot;
10175: 		    }
10176: 		    foreach my $pack_entry (keys(%packagetab)) {
10177: 			my $part=$keyroot;
10178: 			$part=~s/^\_//;
10179: 			if ($pack_entry=~/^\Q$package\E\&/ || 
10180: 			    $pack_entry=~/^\Q$package\E_0\&/) {
10181: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
10182: 			    # ignore package.tab specified default values
10183:                             # here &package_tab_default() will fetch those
10184: 			    if ($subp eq 'default') { next; }
10185: 			    my $value=$packagetab{$pack_entry};
10186: 			    my $unikey;
10187: 			    if ($pack =~ /_0$/) {
10188: 				$unikey='parameter_0_'.$name;
10189: 				$part=0;
10190: 			    } else {
10191: 				$unikey='parameter'.$keyroot.'_'.$name;
10192: 			    }
10193: 			    if ($subp eq 'display') {
10194: 				$value.=' [Part: '.$part.']';
10195: 			    }
10196: 			    $metaentry{':'.$unikey.'.part'}=$part;
10197: 			    $metathesekeys{$unikey}=1;
10198: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10199: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
10200: 			    }
10201: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
10202: 				$metaentry{':'.$unikey}=
10203: 				    $metaentry{':'.$unikey.'.default'};
10204: 			    }
10205: 			}
10206: 		    }
10207: 		} else {
10208: #
10209: # This is not a package - some other kind of start tag
10210: #
10211: 		    my $entry=$token->[1];
10212: 		    my $unikey='';
10213: 
10214: 		    if ($entry eq 'import') {
10215: #
10216: # Importing a library here
10217: #
10218:                         my $location=$parser->get_text('/import');
10219:                         my $dir=$filename;
10220:                         $dir=~s|[^/]*$||;
10221:                         $location=&filelocation($dir,$location);
10222:                        
10223:                         my $importmode=$token->[2]->{'importmode'};
10224:                         if ($importmode eq 'problem') {
10225: # Import as problem/response
10226:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10227:                         } elsif ($importmode eq 'part') {
10228: # Import as part(s)
10229:                            $importedparts=1;
10230: # We need to get the original file and the imported file to get the part order correct
10231: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
10232: # Load and inspect original file
10233:                            if ($#origfileimportpartids<0) {
10234:                               undef(%importedpartids);
10235:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
10236:                               my $origfile=&getfile($origfilelocation);
10237:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10238:                            }
10239: 
10240: # Load and inspect imported file
10241:                            my $impfile=&getfile($location);
10242:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10243:                            if ($#impfilepartids>=0) {
10244: # This problem had parts
10245:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
10246:                            } else {
10247: # Importing by turning a single problem into a problem part
10248: # It gets the import-tags ID as part-ID
10249:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
10250:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
10251:                            }
10252:                         } else {
10253: # Normal import
10254:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10255:                            if (defined($token->[2]->{'id'})) {
10256:                               $unikey.='_'.$token->[2]->{'id'};
10257:                            }
10258:                         }
10259: 
10260: 			if ($depthcount<20) {
10261: 			    my $metadata = 
10262: 				&metadata($uri,'keys', $location,$unikey,
10263: 					  $depthcount+1);
10264: 			    foreach my $meta (split(',',$metadata)) {
10265: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
10266: 				$metathesekeys{$meta}=1;
10267: 			    }
10268: 			
10269:                         }
10270: 		    } else {
10271: #
10272: # Not importing, some other kind of non-package, non-library start tag
10273: # 
10274:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
10275:                         if (defined($token->[2]->{'id'})) {
10276:                             $unikey.='_'.$token->[2]->{'id'};
10277:                         }
10278: 			if (defined($token->[2]->{'name'})) { 
10279: 			    $unikey.='_'.$token->[2]->{'name'}; 
10280: 			}
10281: 			$metathesekeys{$unikey}=1;
10282: 			foreach my $param (@{$token->[3]}) {
10283: 			    $metaentry{':'.$unikey.'.'.$param} =
10284: 				$token->[2]->{$param};
10285: 			}
10286: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
10287: 			my $default=$metaentry{':'.$unikey.'.default'};
10288: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
10289: 		 # only ws inside the tag, and not in default, so use default
10290: 		 # as value
10291: 			    $metaentry{':'.$unikey}=$default;
10292: 			} elsif ( $internaltext =~ /\S/ ) {
10293: 		  # something interesting inside the tag
10294: 			    $metaentry{':'.$unikey}=$internaltext;
10295: 			} else {
10296: 		  # no interesting values, don't set a default
10297: 			}
10298: # end of not-a-package not-a-library import
10299: 		    }
10300: # end of not-a-package start tag
10301: 		}
10302: # the next is the end of "start tag"
10303: 	    }
10304: 	}
10305: 	my ($extension) = ($uri =~ /\.(\w+)$/);
10306: 	$extension = lc($extension);
10307: 	if ($extension eq 'htm') { $extension='html'; }
10308: 
10309: 	foreach my $key (keys(%packagetab)) {
10310: 	    #no specific packages #how's our extension
10311: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
10312: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
10313: 					 \%metathesekeys);
10314: 	}
10315: 
10316: 	if (!exists($metaentry{':packages'})
10317: 	    || $packagetab{"import_defaults&extension_$extension"}) {
10318: 	    foreach my $key (keys(%packagetab)) {
10319: 		#no specific packages well let's get default then
10320: 		if ($key!~/^default&/) { next; }
10321: 		&metadata_create_package_def($uri,$key,'default',
10322: 					     \%metathesekeys);
10323: 	    }
10324: 	}
10325: # are there custom rights to evaluate
10326: 	if ($metaentry{':copyright'} eq 'custom') {
10327: 
10328:     #
10329:     # Importing a rights file here
10330:     #
10331: 	    unless ($depthcount) {
10332: 		my $location=$metaentry{':customdistributionfile'};
10333: 		my $dir=$filename;
10334: 		$dir=~s|[^/]*$||;
10335: 		$location=&filelocation($dir,$location);
10336: 		my $rights_metadata =
10337: 		    &metadata($uri,'keys',$location,'_rights',
10338: 			      $depthcount+1);
10339: 		foreach my $rights (split(',',$rights_metadata)) {
10340: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
10341: 		    $metathesekeys{$rights}=1;
10342: 		}
10343: 	    }
10344: 	}
10345: 	# uniqifiy package listing
10346: 	my %seen;
10347: 	my @uniq_packages =
10348: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
10349: 	$metaentry{':packages'} = join(',',@uniq_packages);
10350: 
10351:         if ($importedparts) {
10352: # We had imported parts and need to rebuild partorder
10353:            $metaentry{':partorder'}='';
10354:            $metathesekeys{'partorder'}=1;
10355:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
10356:                if ($origfileimportpartids[$index] eq 'part') {
10357: # original part, part of the problem
10358:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
10359:                } else {
10360: # we have imported parts at this position
10361:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
10362:                }
10363:            }
10364:            $metaentry{':partorder'}=~s/^\,//;
10365:         }
10366: 
10367: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
10368: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
10369: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
10370: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
10371: # this is the end of "was not already recently cached
10372:     }
10373:     return $metaentry{':'.$what};
10374: }
10375: 
10376: sub metadata_create_package_def {
10377:     my ($uri,$key,$package,$metathesekeys)=@_;
10378:     my ($pack,$name,$subp)=split(/\&/,$key);
10379:     if ($subp eq 'default') { next; }
10380:     
10381:     if (defined($metaentry{':packages'})) {
10382: 	$metaentry{':packages'}.=','.$package;
10383:     } else {
10384: 	$metaentry{':packages'}=$package;
10385:     }
10386:     my $value=$packagetab{$key};
10387:     my $unikey;
10388:     $unikey='parameter_0_'.$name;
10389:     $metaentry{':'.$unikey.'.part'}=0;
10390:     $$metathesekeys{$unikey}=1;
10391:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10392: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
10393:     }
10394:     if (defined($metaentry{':'.$unikey.'.default'})) {
10395: 	$metaentry{':'.$unikey}=
10396: 	    $metaentry{':'.$unikey.'.default'};
10397:     }
10398: }
10399: 
10400: sub metadata_generate_part0 {
10401:     my ($metadata,$metacache,$uri) = @_;
10402:     my %allnames;
10403:     foreach my $metakey (keys(%$metadata)) {
10404: 	if ($metakey=~/^parameter\_(.*)/) {
10405: 	  my $part=$$metacache{':'.$metakey.'.part'};
10406: 	  my $name=$$metacache{':'.$metakey.'.name'};
10407: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
10408: 	    $allnames{$name}=$part;
10409: 	  }
10410: 	}
10411:     }
10412:     foreach my $name (keys(%allnames)) {
10413:       $$metadata{"parameter_0_$name"}=1;
10414:       my $key=":parameter_0_$name";
10415:       $$metacache{"$key.part"}='0';
10416:       $$metacache{"$key.name"}=$name;
10417:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
10418: 					   $allnames{$name}.'_'.$name.
10419: 					   '.type'};
10420:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
10421: 			     '.display'};
10422:       my $expr='[Part: '.$allnames{$name}.']';
10423:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
10424:       $$metacache{"$key.display"}=$olddis;
10425:     }
10426: }
10427: 
10428: # ------------------------------------------------------ Devalidate title cache
10429: 
10430: sub devalidate_title_cache {
10431:     my ($url)=@_;
10432:     if (!$env{'request.course.id'}) { return; }
10433:     my $symb=&symbread($url);
10434:     if (!$symb) { return; }
10435:     my $key=$env{'request.course.id'}."\0".$symb;
10436:     &devalidate_cache_new('title',$key);
10437: }
10438: 
10439: # ------------------------------------------------- Get the title of a course
10440: 
10441: sub current_course_title {
10442:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
10443: }
10444: # ------------------------------------------------- Get the title of a resource
10445: 
10446: sub gettitle {
10447:     my $urlsymb=shift;
10448:     my $symb=&symbread($urlsymb);
10449:     if ($symb) {
10450: 	my $key=$env{'request.course.id'}."\0".$symb;
10451: 	my ($result,$cached)=&is_cached_new('title',$key);
10452: 	if (defined($cached)) { 
10453: 	    return $result;
10454: 	}
10455: 	my ($map,$resid,$url)=&decode_symb($symb);
10456: 	my $title='';
10457: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
10458: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
10459: 	} else {
10460: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10461: 		    &GDBM_READER(),0640)) {
10462: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
10463: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
10464: 		untie(%bighash);
10465: 	    }
10466: 	}
10467: 	$title=~s/\&colon\;/\:/gs;
10468: 	if ($title) {
10469: # Remember both $symb and $title for dynamic metadata
10470:             $accesshash{$symb.'___crstitle'}=$title;
10471:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
10472: # Cache this title and then return it
10473: 	    return &do_cache_new('title',$key,$title,600);
10474: 	}
10475: 	$urlsymb=$url;
10476:     }
10477:     my $title=&metadata($urlsymb,'title');
10478:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
10479:     return $title;
10480: }
10481: 
10482: sub get_slot {
10483:     my ($which,$cnum,$cdom)=@_;
10484:     if (!$cnum || !$cdom) {
10485: 	(undef,my $courseid)=&whichuser();
10486: 	$cdom=$env{'course.'.$courseid.'.domain'};
10487: 	$cnum=$env{'course.'.$courseid.'.num'};
10488:     }
10489:     my $key=join("\0",'slots',$cdom,$cnum,$which);
10490:     my %slotinfo;
10491:     if (exists($remembered{$key})) {
10492: 	$slotinfo{$which} = $remembered{$key};
10493:     } else {
10494: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
10495: 	&Apache::lonhomework::showhash(%slotinfo);
10496: 	my ($tmp)=keys(%slotinfo);
10497: 	if ($tmp=~/^error:/) { return (); }
10498: 	$remembered{$key} = $slotinfo{$which};
10499:     }
10500:     if (ref($slotinfo{$which}) eq 'HASH') {
10501: 	return %{$slotinfo{$which}};
10502:     }
10503:     return $slotinfo{$which};
10504: }
10505: 
10506: sub get_reservable_slots {
10507:     my ($cnum,$cdom,$uname,$udom) = @_;
10508:     my $now = time;
10509:     my $reservable_info;
10510:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
10511:     if (exists($remembered{$key})) {
10512:         $reservable_info = $remembered{$key};
10513:     } else {
10514:         my %resv;
10515:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
10516:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
10517:         $reservable_info = \%resv;
10518:         $remembered{$key} = $reservable_info;
10519:     }
10520:     return $reservable_info;
10521: }
10522: 
10523: sub get_course_slots {
10524:     my ($cnum,$cdom) = @_;
10525:     my $hashid=$cnum.':'.$cdom;
10526:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
10527:     if (defined($cached)) {
10528:         if (ref($result) eq 'HASH') {
10529:             return %{$result};
10530:         }
10531:     } else {
10532:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
10533:         my ($tmp) = keys(%slots);
10534:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
10535:             &do_cache_new('allslots',$hashid,\%slots,600);
10536:             return %slots;
10537:         }
10538:     }
10539:     return;
10540: }
10541: 
10542: sub devalidate_slots_cache {
10543:     my ($cnum,$cdom)=@_;
10544:     my $hashid=$cnum.':'.$cdom;
10545:     &devalidate_cache_new('allslots',$hashid);
10546: }
10547: 
10548: sub get_coursechange {
10549:     my ($cdom,$cnum) = @_;
10550:     if ($cdom eq '' || $cnum eq '') {
10551:         return unless ($env{'request.course.id'});
10552:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10553:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10554:     }
10555:     my $hashid=$cdom.'_'.$cnum;
10556:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
10557:     if ((defined($cached)) && ($change ne '')) {
10558:         return $change;
10559:     } else {
10560:         my %crshash;
10561:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
10562:         if ($crshash{'internal.contentchange'} eq '') {
10563:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
10564:             if ($change eq '') {
10565:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
10566:                 $change = $crshash{'internal.created'};
10567:             }
10568:         } else {
10569:             $change = $crshash{'internal.contentchange'};
10570:         }
10571:         my $cachetime = 600;
10572:         &do_cache_new('crschange',$hashid,$change,$cachetime);
10573:     }
10574:     return $change;
10575: }
10576: 
10577: sub devalidate_coursechange_cache {
10578:     my ($cnum,$cdom)=@_;
10579:     my $hashid=$cnum.':'.$cdom;
10580:     &devalidate_cache_new('crschange',$hashid);
10581: }
10582: 
10583: # ------------------------------------------------- Update symbolic store links
10584: 
10585: sub symblist {
10586:     my ($mapname,%newhash)=@_;
10587:     $mapname=&deversion(&declutter($mapname));
10588:     my %hash;
10589:     if (($env{'request.course.fn'}) && (%newhash)) {
10590:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
10591:                       &GDBM_WRCREAT(),0640)) {
10592: 	    foreach my $url (keys(%newhash)) {
10593: 		next if ($url eq 'last_known'
10594: 			 && $env{'form.no_update_last_known'});
10595: 		$hash{declutter($url)}=&encode_symb($mapname,
10596: 						    $newhash{$url}->[1],
10597: 						    $newhash{$url}->[0]);
10598:             }
10599:             if (untie(%hash)) {
10600: 		return 'ok';
10601:             }
10602:         }
10603:     }
10604:     return 'error';
10605: }
10606: 
10607: # --------------------------------------------------------------- Verify a symb
10608: 
10609: sub symbverify {
10610:     my ($symb,$thisurl,$encstate)=@_;
10611:     my $thisfn=$thisurl;
10612:     $thisfn=&declutter($thisfn);
10613: # direct jump to resource in page or to a sequence - will construct own symbs
10614:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
10615: # check URL part
10616:     my ($map,$resid,$url)=&decode_symb($symb);
10617: 
10618:     unless ($url eq $thisfn) { return 0; }
10619: 
10620:     $symb=&symbclean($symb);
10621:     $thisurl=&deversion($thisurl);
10622:     $thisfn=&deversion($thisfn);
10623: 
10624:     my %bighash;
10625:     my $okay=0;
10626: 
10627:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10628:                             &GDBM_READER(),0640)) {
10629:         my $noclutter;
10630:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
10631:             $thisurl =~ s/\?.+$//;
10632:             if ($map =~ m{^uploaded/.+\.page$}) {
10633:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
10634:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
10635:                 $noclutter = 1;
10636:             }
10637:         }
10638:         my $ids;
10639:         if ($noclutter) {
10640:             $ids=$bighash{'ids_'.$thisurl};
10641:         } else {
10642:             $ids=$bighash{'ids_'.&clutter($thisurl)};
10643:         }
10644:         unless ($ids) {
10645:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
10646:             $ids=$bighash{$idkey};
10647:         }
10648:         if ($ids) {
10649: # ------------------------------------------------------------------- Has ID(s)
10650:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
10651:                 $symb =~ s/\?.+$//;
10652:             }
10653: 	    foreach my $id (split(/\,/,$ids)) {
10654: 	       my ($mapid,$resid)=split(/\./,$id);
10655:                if (
10656:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
10657:    eq $symb) {
10658:                    if (ref($encstate)) {
10659:                        $$encstate = $bighash{'encrypted_'.$id};
10660:                    }
10661: 		   if (($env{'request.role.adv'}) ||
10662: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
10663:                        ($thisurl eq '/adm/navmaps')) {
10664: 		       $okay=1;
10665:                        last;
10666: 		   }
10667: 	       }
10668: 	   }
10669:         }
10670: 	untie(%bighash);
10671:     }
10672:     return $okay;
10673: }
10674: 
10675: # --------------------------------------------------------------- Clean-up symb
10676: 
10677: sub symbclean {
10678:     my $symb=shift;
10679:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
10680: # remove version from map
10681:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
10682: 
10683: # remove version from URL
10684:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
10685: 
10686: # remove wrapper
10687: 
10688:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
10689:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
10690:     return $symb;
10691: }
10692: 
10693: # ---------------------------------------------- Split symb to find map and url
10694: 
10695: sub encode_symb {
10696:     my ($map,$resid,$url)=@_;
10697:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
10698: }
10699: 
10700: sub decode_symb {
10701:     my $symb=shift;
10702:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
10703:     my ($map,$resid,$url)=split(/___/,$symb);
10704:     return (&fixversion($map),$resid,&fixversion($url));
10705: }
10706: 
10707: sub fixversion {
10708:     my $fn=shift;
10709:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
10710:     my %bighash;
10711:     my $uri=&clutter($fn);
10712:     my $key=$env{'request.course.id'}.'_'.$uri;
10713: # is this cached?
10714:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
10715:     if (defined($cached)) { return $result; }
10716: # unfortunately not cached, or expired
10717:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10718: 	    &GDBM_READER(),0640)) {
10719:  	if ($bighash{'version_'.$uri}) {
10720:  	    my $version=$bighash{'version_'.$uri};
10721:  	    unless (($version eq 'mostrecent') || 
10722: 		    ($version==&getversion($uri))) {
10723:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
10724:  	    }
10725:  	}
10726:  	untie %bighash;
10727:     }
10728:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
10729: }
10730: 
10731: sub deversion {
10732:     my $url=shift;
10733:     $url=~s/\.\d+\.(\w+)$/\.$1/;
10734:     return $url;
10735: }
10736: 
10737: # ------------------------------------------------------ Return symb list entry
10738: 
10739: sub symbread {
10740:     my ($thisfn,$donotrecurse)=@_;
10741:     my $cache_str;
10742:     if ($thisfn ne '') {
10743:         $cache_str='request.symbread.cached.'.$thisfn;
10744:         if ($env{$cache_str} ne '') {
10745:             return $env{$cache_str};
10746:         }
10747:     } else {
10748: # no filename provided? try from environment
10749:         if ($env{'request.symb'}) {
10750: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
10751: 	}
10752: 	$thisfn=$env{'request.filename'};
10753:     }
10754:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
10755: # is that filename actually a symb? Verify, clean, and return
10756:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
10757: 	if (&symbverify($thisfn,$1)) {
10758: 	    return $env{$cache_str}=&symbclean($thisfn);
10759: 	}
10760:     }
10761:     $thisfn=declutter($thisfn);
10762:     my %hash;
10763:     my %bighash;
10764:     my $syval='';
10765:     if (($env{'request.course.fn'}) && ($thisfn)) {
10766:         my $targetfn = $thisfn;
10767:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
10768:             $targetfn = 'adm/wrapper/'.$thisfn;
10769:         }
10770: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
10771: 	    $targetfn=$1;
10772: 	}
10773:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
10774:                       &GDBM_READER(),0640)) {
10775: 	    $syval=$hash{$targetfn};
10776:             untie(%hash);
10777:         }
10778: # ---------------------------------------------------------- There was an entry
10779:         if ($syval) {
10780: 	    #unless ($syval=~/\_\d+$/) {
10781: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
10782: 		    #&appenv({'request.ambiguous' => $thisfn});
10783: 		    #return $env{$cache_str}='';
10784: 		#}    
10785: 		#$syval.=$1;
10786: 	    #}
10787:         } else {
10788: # ------------------------------------------------------- Was not in symb table
10789:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10790:                             &GDBM_READER(),0640)) {
10791: # ---------------------------------------------- Get ID(s) for current resource
10792:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
10793:               unless ($ids) { 
10794:                  $ids=$bighash{'ids_/'.$thisfn};
10795:               }
10796:               unless ($ids) {
10797: # alias?
10798: 		  $ids=$bighash{'mapalias_'.$thisfn};
10799:               }
10800:               if ($ids) {
10801: # ------------------------------------------------------------------- Has ID(s)
10802:                  my @possibilities=split(/\,/,$ids);
10803:                  if ($#possibilities==0) {
10804: # ----------------------------------------------- There is only one possibility
10805: 		     my ($mapid,$resid)=split(/\./,$ids);
10806: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
10807: 						    $resid,$thisfn);
10808:                  } elsif (!$donotrecurse) {
10809: # ------------------------------------------ There is more than one possibility
10810:                      my $realpossible=0;
10811:                      foreach my $id (@possibilities) {
10812: 			 my $file=$bighash{'src_'.$id};
10813:                          if (&allowed('bre',$file)) {
10814:          		    my ($mapid,$resid)=split(/\./,$id);
10815:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
10816: 				$realpossible++;
10817:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
10818: 						    $resid,$thisfn);
10819:                             }
10820: 			 }
10821:                      }
10822: 		     if ($realpossible!=1) { $syval=''; }
10823:                  } else {
10824:                      $syval='';
10825:                  }
10826: 	      }
10827:               untie(%bighash)
10828:            }
10829:         }
10830:         if ($syval) {
10831: 	    return $env{$cache_str}=$syval;
10832:         }
10833:     }
10834:     &appenv({'request.ambiguous' => $thisfn});
10835:     return $env{$cache_str}='';
10836: }
10837: 
10838: # ---------------------------------------------------------- Return random seed
10839: 
10840: sub numval {
10841:     my $txt=shift;
10842:     $txt=~tr/A-J/0-9/;
10843:     $txt=~tr/a-j/0-9/;
10844:     $txt=~tr/K-T/0-9/;
10845:     $txt=~tr/k-t/0-9/;
10846:     $txt=~tr/U-Z/0-5/;
10847:     $txt=~tr/u-z/0-5/;
10848:     $txt=~s/\D//g;
10849:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
10850:     return int($txt);
10851: }
10852: 
10853: sub numval2 {
10854:     my $txt=shift;
10855:     $txt=~tr/A-J/0-9/;
10856:     $txt=~tr/a-j/0-9/;
10857:     $txt=~tr/K-T/0-9/;
10858:     $txt=~tr/k-t/0-9/;
10859:     $txt=~tr/U-Z/0-5/;
10860:     $txt=~tr/u-z/0-5/;
10861:     $txt=~s/\D//g;
10862:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10863:     my $total;
10864:     foreach my $val (@txts) { $total+=$val; }
10865:     if ($_64bit) { if ($total > 2**32) { return -1; } }
10866:     return int($total);
10867: }
10868: 
10869: sub numval3 {
10870:     use integer;
10871:     my $txt=shift;
10872:     $txt=~tr/A-J/0-9/;
10873:     $txt=~tr/a-j/0-9/;
10874:     $txt=~tr/K-T/0-9/;
10875:     $txt=~tr/k-t/0-9/;
10876:     $txt=~tr/U-Z/0-5/;
10877:     $txt=~tr/u-z/0-5/;
10878:     $txt=~s/\D//g;
10879:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10880:     my $total;
10881:     foreach my $val (@txts) { $total+=$val; }
10882:     if ($_64bit) { $total=(($total<<32)>>32); }
10883:     return $total;
10884: }
10885: 
10886: sub digest {
10887:     my ($data)=@_;
10888:     my $digest=&Digest::MD5::md5($data);
10889:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
10890:     my ($e,$f);
10891:     {
10892:         use integer;
10893:         $e=($a+$b);
10894:         $f=($c+$d);
10895:         if ($_64bit) {
10896:             $e=(($e<<32)>>32);
10897:             $f=(($f<<32)>>32);
10898:         }
10899:     }
10900:     if (wantarray) {
10901: 	return ($e,$f);
10902:     } else {
10903: 	my $g;
10904: 	{
10905: 	    use integer;
10906: 	    $g=($e+$f);
10907: 	    if ($_64bit) {
10908: 		$g=(($g<<32)>>32);
10909: 	    }
10910: 	}
10911: 	return $g;
10912:     }
10913: }
10914: 
10915: sub latest_rnd_algorithm_id {
10916:     return '64bit5';
10917: }
10918: 
10919: sub get_rand_alg {
10920:     my ($courseid)=@_;
10921:     if (!$courseid) { $courseid=(&whichuser())[1]; }
10922:     if ($courseid) {
10923: 	return $env{"course.$courseid.rndseed"};
10924:     }
10925:     return &latest_rnd_algorithm_id();
10926: }
10927: 
10928: sub validCODE {
10929:     my ($CODE)=@_;
10930:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
10931:     return 0;
10932: }
10933: 
10934: sub getCODE {
10935:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
10936:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
10937: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
10938: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
10939: 	return $Apache::lonhomework::history{'resource.CODE'};
10940:     }
10941:     return undef;
10942: }
10943: #
10944: #  Determines the random seed for a specific context:
10945: #
10946: # parameters:
10947: #   symb      - in course context the symb for the seed.
10948: #   course_id - The course id of the form domain_coursenum.
10949: #   domain    - Domain for the user.
10950: #   course    - Course for the user.
10951: #   cenv      - environment of the course.
10952: #
10953: # NOTE:
10954: #   All parameters are picked out of the environment if missing
10955: #   or not defined.
10956: #   If a symb cannot be determined the current time is used instead.
10957: #
10958: #  For a given well defined symb, courside, domain, username,
10959: #  and course environment, the seed is reproducible.
10960: #
10961: sub rndseed {
10962:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
10963:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
10964:     if (!defined($symb)) {
10965: 	unless ($symb=$wsymb) { return time; }
10966:     }
10967:     if (!defined $courseid) { 
10968: 	$courseid=$wcourseid; 
10969:     }
10970:     if (!defined $domain) { $domain=$wdomain; }
10971:     if (!defined $username) { $username=$wusername }
10972: 
10973:     my $which;
10974:     if (defined($cenv->{'rndseed'})) {
10975: 	$which = $cenv->{'rndseed'};
10976:     } else {
10977: 	$which =&get_rand_alg($courseid);
10978:     }
10979:     if (defined(&getCODE())) {
10980: 
10981: 	if ($which eq '64bit5') {
10982: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
10983: 	} elsif ($which eq '64bit4') {
10984: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
10985: 	} else {
10986: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
10987: 	}
10988:     } elsif ($which eq '64bit5') {
10989: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
10990:     } elsif ($which eq '64bit4') {
10991: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
10992:     } elsif ($which eq '64bit3') {
10993: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
10994:     } elsif ($which eq '64bit2') {
10995: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
10996:     } elsif ($which eq '64bit') {
10997: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
10998:     }
10999:     return &rndseed_32bit($symb,$courseid,$domain,$username);
11000: }
11001: 
11002: sub rndseed_32bit {
11003:     my ($symb,$courseid,$domain,$username)=@_;
11004:     {
11005: 	use integer;
11006: 	my $symbchck=unpack("%32C*",$symb) << 27;
11007: 	my $symbseed=numval($symb) << 22;
11008: 	my $namechck=unpack("%32C*",$username) << 17;
11009: 	my $nameseed=numval($username) << 12;
11010: 	my $domainseed=unpack("%32C*",$domain) << 7;
11011: 	my $courseseed=unpack("%32C*",$courseid);
11012: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
11013: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11014: 	#&logthis("rndseed :$num:$symb");
11015: 	if ($_64bit) { $num=(($num<<32)>>32); }
11016: 	return $num;
11017:     }
11018: }
11019: 
11020: sub rndseed_64bit {
11021:     my ($symb,$courseid,$domain,$username)=@_;
11022:     {
11023: 	use integer;
11024: 	my $symbchck=unpack("%32S*",$symb) << 21;
11025: 	my $symbseed=numval($symb) << 10;
11026: 	my $namechck=unpack("%32S*",$username);
11027: 	
11028: 	my $nameseed=numval($username) << 21;
11029: 	my $domainseed=unpack("%32S*",$domain) << 10;
11030: 	my $courseseed=unpack("%32S*",$courseid);
11031: 	
11032: 	my $num1=$symbchck+$symbseed+$namechck;
11033: 	my $num2=$nameseed+$domainseed+$courseseed;
11034: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11035: 	#&logthis("rndseed :$num:$symb");
11036: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11037: 	return "$num1,$num2";
11038:     }
11039: }
11040: 
11041: sub rndseed_64bit2 {
11042:     my ($symb,$courseid,$domain,$username)=@_;
11043:     {
11044: 	use integer;
11045: 	# strings need to be an even # of cahracters long, it it is odd the
11046:         # last characters gets thrown away
11047: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
11048: 	my $symbseed=numval($symb) << 10;
11049: 	my $namechck=unpack("%32S*",$username.' ');
11050: 	
11051: 	my $nameseed=numval($username) << 21;
11052: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
11053: 	my $courseseed=unpack("%32S*",$courseid.' ');
11054: 	
11055: 	my $num1=$symbchck+$symbseed+$namechck;
11056: 	my $num2=$nameseed+$domainseed+$courseseed;
11057: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11058: 	#&logthis("rndseed :$num:$symb");
11059: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11060: 	return "$num1,$num2";
11061:     }
11062: }
11063: 
11064: sub rndseed_64bit3 {
11065:     my ($symb,$courseid,$domain,$username)=@_;
11066:     {
11067: 	use integer;
11068: 	# strings need to be an even # of cahracters long, it it is odd the
11069:         # last characters gets thrown away
11070: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
11071: 	my $symbseed=numval2($symb) << 10;
11072: 	my $namechck=unpack("%32S*",$username.' ');
11073: 	
11074: 	my $nameseed=numval2($username) << 21;
11075: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
11076: 	my $courseseed=unpack("%32S*",$courseid.' ');
11077: 	
11078: 	my $num1=$symbchck+$symbseed+$namechck;
11079: 	my $num2=$nameseed+$domainseed+$courseseed;
11080: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11081: 	#&logthis("rndseed :$num1:$num2:$_64bit");
11082: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11083: 	
11084: 	return "$num1:$num2";
11085:     }
11086: }
11087: 
11088: sub rndseed_64bit4 {
11089:     my ($symb,$courseid,$domain,$username)=@_;
11090:     {
11091: 	use integer;
11092: 	# strings need to be an even # of cahracters long, it it is odd the
11093:         # last characters gets thrown away
11094: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
11095: 	my $symbseed=numval3($symb) << 10;
11096: 	my $namechck=unpack("%32S*",$username.' ');
11097: 	
11098: 	my $nameseed=numval3($username) << 21;
11099: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
11100: 	my $courseseed=unpack("%32S*",$courseid.' ');
11101: 	
11102: 	my $num1=$symbchck+$symbseed+$namechck;
11103: 	my $num2=$nameseed+$domainseed+$courseseed;
11104: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11105: 	#&logthis("rndseed :$num1:$num2:$_64bit");
11106: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11107: 	
11108: 	return "$num1:$num2";
11109:     }
11110: }
11111: 
11112: sub rndseed_64bit5 {
11113:     my ($symb,$courseid,$domain,$username)=@_;
11114:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
11115:     return "$num1:$num2";
11116: }
11117: 
11118: sub rndseed_CODE_64bit {
11119:     my ($symb,$courseid,$domain,$username)=@_;
11120:     {
11121: 	use integer;
11122: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
11123: 	my $symbseed=numval2($symb);
11124: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11125: 	my $CODEseed=numval(&getCODE());
11126: 	my $courseseed=unpack("%32S*",$courseid.' ');
11127: 	my $num1=$symbseed+$CODEchck;
11128: 	my $num2=$CODEseed+$courseseed+$symbchck;
11129: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11130: 	#&logthis("rndseed :$num1:$num2:$symb");
11131: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
11132: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
11133: 	return "$num1:$num2";
11134:     }
11135: }
11136: 
11137: sub rndseed_CODE_64bit4 {
11138:     my ($symb,$courseid,$domain,$username)=@_;
11139:     {
11140: 	use integer;
11141: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
11142: 	my $symbseed=numval3($symb);
11143: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11144: 	my $CODEseed=numval3(&getCODE());
11145: 	my $courseseed=unpack("%32S*",$courseid.' ');
11146: 	my $num1=$symbseed+$CODEchck;
11147: 	my $num2=$CODEseed+$courseseed+$symbchck;
11148: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11149: 	#&logthis("rndseed :$num1:$num2:$symb");
11150: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
11151: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
11152: 	return "$num1:$num2";
11153:     }
11154: }
11155: 
11156: sub rndseed_CODE_64bit5 {
11157:     my ($symb,$courseid,$domain,$username)=@_;
11158:     my $code = &getCODE();
11159:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
11160:     return "$num1:$num2";
11161: }
11162: 
11163: sub setup_random_from_rndseed {
11164:     my ($rndseed)=@_;
11165:     if ($rndseed =~/([,:])/) {
11166: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
11167: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
11168:     } else {
11169: 	&Math::Random::random_set_seed_from_phrase($rndseed);
11170:     }
11171: }
11172: 
11173: sub latest_receipt_algorithm_id {
11174:     return 'receipt3';
11175: }
11176: 
11177: sub recunique {
11178:     my $fucourseid=shift;
11179:     my $unique;
11180:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
11181: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
11182: 	$unique=$env{"course.$fucourseid.internal.encseed"};
11183:     } else {
11184: 	$unique=$perlvar{'lonReceipt'};
11185:     }
11186:     return unpack("%32C*",$unique);
11187: }
11188: 
11189: sub recprefix {
11190:     my $fucourseid=shift;
11191:     my $prefix;
11192:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
11193: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
11194: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
11195:     } else {
11196: 	$prefix=$perlvar{'lonHostID'};
11197:     }
11198:     return unpack("%32C*",$prefix);
11199: }
11200: 
11201: sub ireceipt {
11202:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
11203: 
11204:     my $return =&recprefix($fucourseid).'-';
11205: 
11206:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
11207: 	$env{'request.state'} eq 'construct') {
11208: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
11209: 	return $return;
11210:     }
11211: 
11212:     my $cuname=unpack("%32C*",$funame);
11213:     my $cudom=unpack("%32C*",$fudom);
11214:     my $cucourseid=unpack("%32C*",$fucourseid);
11215:     my $cusymb=unpack("%32C*",$fusymb);
11216:     my $cunique=&recunique($fucourseid);
11217:     my $cpart=unpack("%32S*",$part);
11218:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
11219: 
11220: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
11221: 			       
11222: 	$return.= ($cunique%$cuname+
11223: 		   $cunique%$cudom+
11224: 		   $cusymb%$cuname+
11225: 		   $cusymb%$cudom+
11226: 		   $cucourseid%$cuname+
11227: 		   $cucourseid%$cudom+
11228: 		   $cpart%$cuname+
11229: 		   $cpart%$cudom);
11230:     } else {
11231: 	$return.= ($cunique%$cuname+
11232: 		   $cunique%$cudom+
11233: 		   $cusymb%$cuname+
11234: 		   $cusymb%$cudom+
11235: 		   $cucourseid%$cuname+
11236: 		   $cucourseid%$cudom);
11237:     }
11238:     return $return;
11239: }
11240: 
11241: sub receipt {
11242:     my ($part)=@_;
11243:     my ($symb,$courseid,$domain,$name) = &whichuser();
11244:     return &ireceipt($name,$domain,$courseid,$symb,$part);
11245: }
11246: 
11247: sub whichuser {
11248:     my ($passedsymb)=@_;
11249:     my ($symb,$courseid,$domain,$name,$publicuser);
11250:     if (defined($env{'form.grade_symb'})) {
11251: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
11252: 	my $allowed=&allowed('vgr',$tmp_courseid);
11253: 	if (!$allowed &&
11254: 	    exists($env{'request.course.sec'}) &&
11255: 	    $env{'request.course.sec'} !~ /^\s*$/) {
11256: 	    $allowed=&allowed('vgr',$tmp_courseid.
11257: 			      '/'.$env{'request.course.sec'});
11258: 	}
11259: 	if ($allowed) {
11260: 	    ($symb)=&get_env_multiple('form.grade_symb');
11261: 	    $courseid=$tmp_courseid;
11262: 	    ($domain)=&get_env_multiple('form.grade_domain');
11263: 	    ($name)=&get_env_multiple('form.grade_username');
11264: 	    return ($symb,$courseid,$domain,$name,$publicuser);
11265: 	}
11266:     }
11267:     if (!$passedsymb) {
11268: 	$symb=&symbread();
11269:     } else {
11270: 	$symb=$passedsymb;
11271:     }
11272:     $courseid=$env{'request.course.id'};
11273:     $domain=$env{'user.domain'};
11274:     $name=$env{'user.name'};
11275:     if ($name eq 'public' && $domain eq 'public') {
11276: 	if (!defined($env{'form.username'})) {
11277: 	    $env{'form.username'}.=time.rand(10000000);
11278: 	}
11279: 	$name.=$env{'form.username'};
11280:     }
11281:     return ($symb,$courseid,$domain,$name,$publicuser);
11282: 
11283: }
11284: 
11285: # ------------------------------------------------------------ Serves up a file
11286: # returns either the contents of the file or 
11287: # -1 if the file doesn't exist
11288: #
11289: # if the target is a file that was uploaded via DOCS, 
11290: # a check will be made to see if a current copy exists on the local server,
11291: # if it does this will be served, otherwise a copy will be retrieved from
11292: # the home server for the course and stored in /home/httpd/html/userfiles on
11293: # the local server.   
11294: 
11295: sub getfile {
11296:     my ($file) = @_;
11297:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
11298:     &repcopy($file);
11299:     return &readfile($file);
11300: }
11301: 
11302: sub repcopy_userfile {
11303:     my ($file)=@_;
11304:     my $londocroot = $perlvar{'lonDocRoot'};
11305:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
11306:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
11307:     my ($cdom,$cnum,$filename) = 
11308: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
11309:     my $uri="/uploaded/$cdom/$cnum/$filename";
11310:     if (-e "$file") {
11311: # we already have a local copy, check it out
11312: 	my @fileinfo = stat($file);
11313: 	my $rtncode;
11314: 	my $info;
11315: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
11316: 	if ($lwpresp ne 'ok') {
11317: # there is no such file anymore, even though we had a local copy
11318: 	    if ($rtncode eq '404') {
11319: 		unlink($file);
11320: 	    }
11321: 	    return -1;
11322: 	}
11323: 	if ($info < $fileinfo[9]) {
11324: # nice, the file we have is up-to-date, just say okay
11325: 	    return 'ok';
11326: 	} else {
11327: # the file is outdated, get rid of it
11328: 	    unlink($file);
11329: 	}
11330:     }
11331: # one way or the other, at this point, we don't have the file
11332: # construct the correct path for the file
11333:     my @parts = ($cdom,$cnum); 
11334:     if ($filename =~ m|^(.+)/[^/]+$|) {
11335: 	push @parts, split(/\//,$1);
11336:     }
11337:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
11338:     foreach my $part (@parts) {
11339: 	$path .= '/'.$part;
11340: 	if (!-e $path) {
11341: 	    mkdir($path,0770);
11342: 	}
11343:     }
11344: # now the path exists for sure
11345: # get a user agent
11346:     my $ua=new LWP::UserAgent;
11347:     my $transferfile=$file.'.in.transfer';
11348: # FIXME: this should flock
11349:     if (-e $transferfile) { return 'ok'; }
11350:     my $request;
11351:     $uri=~s/^\///;
11352:     my $homeserver = &homeserver($cnum,$cdom);
11353:     my $protocol = $protocol{$homeserver};
11354:     $protocol = 'http' if ($protocol ne 'https');
11355:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
11356:     my $response=$ua->request($request,$transferfile);
11357: # did it work?
11358:     if ($response->is_error()) {
11359: 	unlink($transferfile);
11360: 	&logthis("Userfile repcopy failed for $uri");
11361: 	return -1;
11362:     }
11363: # worked, rename the transfer file
11364:     rename($transferfile,$file);
11365:     return 'ok';
11366: }
11367: 
11368: sub tokenwrapper {
11369:     my $uri=shift;
11370:     $uri=~s|^https?\://([^/]+)||;
11371:     $uri=~s|^/||;
11372:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
11373:     my $token=$1;
11374:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
11375:     if ($udom && $uname && $file) {
11376: 	$file=~s|(\?\.*)*$||;
11377:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
11378:         my $homeserver = &homeserver($uname,$udom);
11379:         my $protocol = $protocol{$homeserver};
11380:         $protocol = 'http' if ($protocol ne 'https');
11381:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
11382:                (($uri=~/\?/)?'&':'?').'token='.$token.
11383:                                '&tokenissued='.$perlvar{'lonHostID'};
11384:     } else {
11385:         return '/adm/notfound.html';
11386:     }
11387: }
11388: 
11389: # call with reqtype HEAD: get last modification time
11390: # call with reqtype GET: get the file contents
11391: # Do not call this with reqtype GET for large files! It loads everything into memory
11392: #
11393: sub getuploaded {
11394:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
11395:     $uri=~s/^\///;
11396:     my $homeserver = &homeserver($cnum,$cdom);
11397:     my $protocol = $protocol{$homeserver};
11398:     $protocol = 'http' if ($protocol ne 'https');
11399:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
11400:     my $ua=new LWP::UserAgent;
11401:     my $request=new HTTP::Request($reqtype,$uri);
11402:     my $response=$ua->request($request);
11403:     $$rtncode = $response->code;
11404:     if (! $response->is_success()) {
11405: 	return 'failed';
11406:     }      
11407:     if ($reqtype eq 'HEAD') {
11408: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
11409:     } elsif ($reqtype eq 'GET') {
11410: 	$$info = $response->content;
11411:     }
11412:     return 'ok';
11413: }
11414: 
11415: sub readfile {
11416:     my $file = shift;
11417:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
11418:     my $fh;
11419:     open($fh,"<$file");
11420:     my $a='';
11421:     while (my $line = <$fh>) { $a .= $line; }
11422:     return $a;
11423: }
11424: 
11425: sub filelocation {
11426:     my ($dir,$file) = @_;
11427:     my $location;
11428:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
11429: 
11430:     if ($file =~ m-^/adm/-) {
11431: 	$file=~s-^/adm/wrapper/-/-;
11432: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
11433:     }
11434: 
11435:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
11436:         $location = $file;
11437:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
11438:         my ($udom,$uname,$filename)=
11439:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
11440:         my $home=&homeserver($uname,$udom);
11441:         my $is_me=0;
11442:         my @ids=&current_machine_ids();
11443:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
11444:         if ($is_me) {
11445:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
11446:         } else {
11447:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
11448:   	      $udom.'/'.$uname.'/'.$filename;
11449:         }
11450:     } elsif ($file =~ m-^/adm/-) {
11451: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
11452:     } else {
11453:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
11454:         $file=~s:^/(res|priv)/:/:;
11455:         my $space=$1;
11456:         if ( !( $file =~ m:^/:) ) {
11457:             $location = $dir. '/'.$file;
11458:         } else {
11459:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
11460:         }
11461:     }
11462:     $location=~s://+:/:g; # remove duplicate /
11463:     while ($location=~m{/\.\./}) {
11464: 	if ($location =~ m{/[^/]+/\.\./}) {
11465: 	    $location=~ s{/[^/]+/\.\./}{/}g;
11466: 	} else {
11467: 	    $location=~ s{/\.\./}{/}g;
11468: 	}
11469:     } #remove dir/..
11470:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
11471:     return $location;
11472: }
11473: 
11474: sub hreflocation {
11475:     my ($dir,$file)=@_;
11476:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
11477: 	$file=filelocation($dir,$file);
11478:     } elsif ($file=~m-^/adm/-) {
11479: 	$file=~s-^/adm/wrapper/-/-;
11480: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
11481:     }
11482:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
11483: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
11484:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
11485: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
11486: 	        {/uploaded/$1/$2/}x;
11487:     }
11488:     if ($file=~ m{^/userfiles/}) {
11489: 	$file =~ s{^/userfiles/}{/uploaded/};
11490:     }
11491:     return $file;
11492: }
11493: 
11494: 
11495: 
11496: 
11497: 
11498: sub current_machine_domains {
11499:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
11500: }
11501: 
11502: sub machine_domains {
11503:     my ($hostname) = @_;
11504:     my @domains;
11505:     my %hostname = &all_hostnames();
11506:     while( my($id, $name) = each(%hostname)) {
11507: #	&logthis("-$id-$name-$hostname-");
11508: 	if ($hostname eq $name) {
11509: 	    push(@domains,&host_domain($id));
11510: 	}
11511:     }
11512:     return @domains;
11513: }
11514: 
11515: sub current_machine_ids {
11516:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
11517: }
11518: 
11519: sub machine_ids {
11520:     my ($hostname) = @_;
11521:     $hostname ||= &hostname($perlvar{'lonHostID'});
11522:     my @ids;
11523:     my %name_to_host = &all_names();
11524:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
11525: 	return @{ $name_to_host{$hostname} };
11526:     }
11527:     return;
11528: }
11529: 
11530: sub additional_machine_domains {
11531:     my @domains;
11532:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
11533:     while( my $line = <$fh>) {
11534:         $line =~ s/\s//g;
11535:         push(@domains,$line);
11536:     }
11537:     return @domains;
11538: }
11539: 
11540: sub default_login_domain {
11541:     my $domain = $perlvar{'lonDefDomain'};
11542:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
11543:     foreach my $posdom (&current_machine_domains(),
11544:                         &additional_machine_domains()) {
11545:         if (lc($posdom) eq lc($testdomain)) {
11546:             $domain=$posdom;
11547:             last;
11548:         }
11549:     }
11550:     return $domain;
11551: }
11552: 
11553: # ------------------------------------------------------------- Declutters URLs
11554: 
11555: sub declutter {
11556:     my $thisfn=shift;
11557:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
11558:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
11559:     $thisfn=~s/^\///;
11560:     $thisfn=~s|^adm/wrapper/||;
11561:     $thisfn=~s|^adm/coursedocs/showdoc/||;
11562:     $thisfn=~s/^res\///;
11563:     $thisfn=~s/^priv\///;
11564:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
11565:         $thisfn=~s/\?.+$//;
11566:     }
11567:     return $thisfn;
11568: }
11569: 
11570: # ------------------------------------------------------------- Clutter up URLs
11571: 
11572: sub clutter {
11573:     my $thisfn='/'.&declutter(shift);
11574:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
11575: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
11576:        $thisfn='/res'.$thisfn; 
11577:     }
11578:     if ($thisfn !~m|^/adm|) {
11579: 	if ($thisfn =~ m|^/ext/|) {
11580: 	    $thisfn='/adm/wrapper'.$thisfn;
11581: 	} else {
11582: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
11583: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
11584: 	    if ($embstyle eq 'ssi'
11585: 		|| ($embstyle eq 'hdn')
11586: 		|| ($embstyle eq 'rat')
11587: 		|| ($embstyle eq 'prv')
11588: 		|| ($embstyle eq 'ign')) {
11589: 		#do nothing with these
11590: 	    } elsif (($embstyle eq 'img') 
11591: 		|| ($embstyle eq 'emb')
11592: 		|| ($embstyle eq 'wrp')) {
11593: 		$thisfn='/adm/wrapper'.$thisfn;
11594: 	    } elsif ($embstyle eq 'unk'
11595: 		     && $thisfn!~/\.(sequence|page)$/) {
11596: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
11597: 	    } else {
11598: #		&logthis("Got a blank emb style");
11599: 	    }
11600: 	}
11601:     }
11602:     return $thisfn;
11603: }
11604: 
11605: sub clutter_with_no_wrapper {
11606:     my $uri = &clutter(shift);
11607:     if ($uri =~ m-^/adm/-) {
11608: 	$uri =~ s-^/adm/wrapper/-/-;
11609: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
11610:     }
11611:     return $uri;
11612: }
11613: 
11614: sub freeze_escape {
11615:     my ($value)=@_;
11616:     if (ref($value)) {
11617: 	$value=&nfreeze($value);
11618: 	return '__FROZEN__'.&escape($value);
11619:     }
11620:     return &escape($value);
11621: }
11622: 
11623: 
11624: sub thaw_unescape {
11625:     my ($value)=@_;
11626:     if ($value =~ /^__FROZEN__/) {
11627: 	substr($value,0,10,undef);
11628: 	$value=&unescape($value);
11629: 	return &thaw($value);
11630:     }
11631:     return &unescape($value);
11632: }
11633: 
11634: sub correct_line_ends {
11635:     my ($result)=@_;
11636:     $$result =~s/\r\n/\n/mg;
11637:     $$result =~s/\r/\n/mg;
11638: }
11639: # ================================================================ Main Program
11640: 
11641: sub goodbye {
11642:    &logthis("Starting Shut down");
11643: #not converted to using infrastruture and probably shouldn't be
11644:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
11645: #converted
11646: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
11647:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
11648: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
11649: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
11650: #1.1 only
11651: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
11652: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
11653: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
11654: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
11655:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
11656:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
11657:    &logthis(sprintf("%-20s is %s",'hits',$hits));
11658:    &flushcourselogs();
11659:    &logthis("Shutting down");
11660: }
11661: 
11662: sub get_dns {
11663:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
11664:     if (!$ignore_cache) {
11665: 	my ($content,$cached)=
11666: 	    &Apache::lonnet::is_cached_new('dns',$url);
11667: 	if ($cached) {
11668: 	    &$func($content,$hashref);
11669: 	    return;
11670: 	}
11671:     }
11672: 
11673:     my %alldns;
11674:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11675:     foreach my $dns (<$config>) {
11676: 	next if ($dns !~ /^\^(\S*)/x);
11677:         my $line = $1;
11678:         my ($host,$protocol) = split(/:/,$line);
11679:         if ($protocol ne 'https') {
11680:             $protocol = 'http';
11681:         }
11682: 	$alldns{$host} = $protocol;
11683:     }
11684:     while (%alldns) {
11685: 	my ($dns) = keys(%alldns);
11686: 	my $ua=new LWP::UserAgent;
11687:         $ua->timeout(30);
11688: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
11689: 	my $response=$ua->request($request);
11690:         delete($alldns{$dns});
11691: 	next if ($response->is_error());
11692: 	my @content = split("\n",$response->content);
11693: 	unless ($nocache) {
11694: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
11695: 	}
11696: 	&$func(\@content,$hashref);
11697: 	return;
11698:     }
11699:     close($config);
11700:     my $which = (split('/',$url))[3];
11701:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
11702:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
11703:     my @content = <$config>;
11704:     &$func(\@content,$hashref);
11705:     return;
11706: }
11707: 
11708: # ------------------------------------------------------Get DNS checksums file
11709: sub parse_dns_checksums_tab {
11710:     my ($lines,$hashref) = @_;
11711:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
11712:     my $loncaparev = &get_server_loncaparev($machine_dom);
11713:     my ($release,$timestamp) = split(/\-/,$loncaparev);
11714:     my (%chksum,%revnum);
11715:     if (ref($lines) eq 'ARRAY') {
11716:         chomp(@{$lines});
11717:         my $version = shift(@{$lines});
11718:         if ($version eq $release) {  
11719:             foreach my $line (@{$lines}) {
11720:                 my ($file,$version,$shasum) = split(/,/,$line);
11721:                 $chksum{$file} = $shasum;
11722:                 $revnum{$file} = $version;
11723:             }
11724:             if (ref($hashref) eq 'HASH') {
11725:                 %{$hashref} = (
11726:                                 sums     => \%chksum,
11727:                                 versions => \%revnum,
11728:                               );
11729:             }
11730:         }
11731:     }
11732:     return;
11733: }
11734: 
11735: sub fetch_dns_checksums {
11736:     my %checksums;
11737:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
11738:     my $loncaparev = &get_server_loncaparev($machine_dom);
11739:     my ($release,$timestamp) = split(/\-/,$loncaparev);
11740:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
11741:              \%checksums);
11742:     return \%checksums;
11743: }
11744: 
11745: # ------------------------------------------------------------ Read domain file
11746: {
11747:     my $loaded;
11748:     my %domain;
11749: 
11750:     sub parse_domain_tab {
11751: 	my ($lines) = @_;
11752: 	foreach my $line (@$lines) {
11753: 	    next if ($line =~ /^(\#|\s*$ )/x);
11754: 
11755: 	    chomp($line);
11756: 	    my ($name,@elements) = split(/:/,$line,9);
11757: 	    my %this_domain;
11758: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
11759: 			       'lang_def', 'city', 'longi', 'lati',
11760: 			       'primary') {
11761: 		$this_domain{$field} = shift(@elements);
11762: 	    }
11763: 	    $domain{$name} = \%this_domain;
11764: 	}
11765:     }
11766: 
11767:     sub reset_domain_info {
11768: 	undef($loaded);
11769: 	undef(%domain);
11770:     }
11771: 
11772:     sub load_domain_tab {
11773: 	my ($ignore_cache) = @_;
11774: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
11775: 	my $fh;
11776: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
11777: 	    my @lines = <$fh>;
11778: 	    &parse_domain_tab(\@lines);
11779: 	}
11780: 	close($fh);
11781: 	$loaded = 1;
11782:     }
11783: 
11784:     sub domain {
11785: 	&load_domain_tab() if (!$loaded);
11786: 
11787: 	my ($name,$what) = @_;
11788: 	return if ( !exists($domain{$name}) );
11789: 
11790: 	if (!$what) {
11791: 	    return $domain{$name}{'description'};
11792: 	}
11793: 	return $domain{$name}{$what};
11794:     }
11795: 
11796:     sub domain_info {
11797:         &load_domain_tab() if (!$loaded);
11798:         return %domain;
11799:     }
11800: 
11801: }
11802: 
11803: 
11804: # ------------------------------------------------------------- Read hosts file
11805: {
11806:     my %hostname;
11807:     my %hostdom;
11808:     my %libserv;
11809:     my $loaded;
11810:     my %name_to_host;
11811:     my %internetdom;
11812:     my %LC_dns_serv;
11813: 
11814:     sub parse_hosts_tab {
11815: 	my ($file) = @_;
11816: 	foreach my $configline (@$file) {
11817: 	    next if ($configline =~ /^(\#|\s*$ )/x);
11818:             chomp($configline);
11819: 	    if ($configline =~ /^\^/) {
11820:                 if ($configline =~ /^\^([\w.\-]+)/) {
11821:                     $LC_dns_serv{$1} = 1;
11822:                 }
11823:                 next;
11824:             }
11825: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
11826: 	    $name=~s/\s//g;
11827: 	    if ($id && $domain && $role && $name) {
11828: 		$hostname{$id}=$name;
11829: 		push(@{$name_to_host{$name}}, $id);
11830: 		$hostdom{$id}=$domain;
11831: 		if ($role eq 'library') { $libserv{$id}=$name; }
11832:                 if (defined($protocol)) {
11833:                     if ($protocol eq 'https') {
11834:                         $protocol{$id} = $protocol;
11835:                     } else {
11836:                         $protocol{$id} = 'http'; 
11837:                     }
11838:                 } else {
11839:                     $protocol{$id} = 'http';
11840:                 }
11841:                 if (defined($intdom)) {
11842:                     $internetdom{$id} = $intdom;
11843:                 }
11844: 	    }
11845: 	}
11846:     }
11847:     
11848:     sub reset_hosts_info {
11849: 	&purge_remembered();
11850: 	&reset_domain_info();
11851: 	&reset_hosts_ip_info();
11852: 	undef(%name_to_host);
11853: 	undef(%hostname);
11854: 	undef(%hostdom);
11855: 	undef(%libserv);
11856: 	undef($loaded);
11857:     }
11858: 
11859:     sub load_hosts_tab {
11860: 	my ($ignore_cache) = @_;
11861: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
11862: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11863: 	my @config = <$config>;
11864: 	&parse_hosts_tab(\@config);
11865: 	close($config);
11866: 	$loaded=1;
11867:     }
11868: 
11869:     sub hostname {
11870: 	&load_hosts_tab() if (!$loaded);
11871: 
11872: 	my ($lonid) = @_;
11873: 	return $hostname{$lonid};
11874:     }
11875: 
11876:     sub all_hostnames {
11877: 	&load_hosts_tab() if (!$loaded);
11878: 
11879: 	return %hostname;
11880:     }
11881: 
11882:     sub all_names {
11883: 	&load_hosts_tab() if (!$loaded);
11884: 
11885: 	return %name_to_host;
11886:     }
11887: 
11888:     sub all_host_domain {
11889:         &load_hosts_tab() if (!$loaded);
11890:         return %hostdom;
11891:     }
11892: 
11893:     sub is_library {
11894: 	&load_hosts_tab() if (!$loaded);
11895: 
11896: 	return exists($libserv{$_[0]});
11897:     }
11898: 
11899:     sub all_library {
11900: 	&load_hosts_tab() if (!$loaded);
11901: 
11902: 	return %libserv;
11903:     }
11904: 
11905:     sub unique_library {
11906: 	#2x reverse removes all hostnames that appear more than once
11907:         my %unique = reverse &all_library();
11908:         return reverse %unique;
11909:     }
11910: 
11911:     sub get_servers {
11912: 	&load_hosts_tab() if (!$loaded);
11913: 
11914: 	my ($domain,$type) = @_;
11915: 	my %possible_hosts = ($type eq 'library') ? %libserv
11916: 	                                          : %hostname;
11917: 	my %result;
11918: 	if (ref($domain) eq 'ARRAY') {
11919: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
11920: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
11921: 		    $result{$host} = $hostname;
11922: 		}
11923: 	    }
11924: 	} else {
11925: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
11926: 		if ($hostdom{$host} eq $domain) {
11927: 		    $result{$host} = $hostname;
11928: 		}
11929: 	    }
11930: 	}
11931: 	return %result;
11932:     }
11933: 
11934:     sub get_unique_servers {
11935:         my %unique = reverse &get_servers(@_);
11936: 	return reverse %unique;
11937:     }
11938: 
11939:     sub host_domain {
11940: 	&load_hosts_tab() if (!$loaded);
11941: 
11942: 	my ($lonid) = @_;
11943: 	return $hostdom{$lonid};
11944:     }
11945: 
11946:     sub all_domains {
11947: 	&load_hosts_tab() if (!$loaded);
11948: 
11949: 	my %seen;
11950: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
11951: 	return @uniq;
11952:     }
11953: 
11954:     sub internet_dom {
11955:         &load_hosts_tab() if (!$loaded);
11956: 
11957:         my ($lonid) = @_;
11958:         return $internetdom{$lonid};
11959:     }
11960: 
11961:     sub is_LC_dns {
11962:         &load_hosts_tab() if (!$loaded);
11963: 
11964:         my ($hostname) = @_;
11965:         return exists($LC_dns_serv{$hostname});
11966:     }
11967: 
11968: }
11969: 
11970: { 
11971:     my %iphost;
11972:     my %name_to_ip;
11973:     my %lonid_to_ip;
11974: 
11975:     sub get_hosts_from_ip {
11976: 	my ($ip) = @_;
11977: 	my %iphosts = &get_iphost();
11978: 	if (ref($iphosts{$ip})) {
11979: 	    return @{$iphosts{$ip}};
11980: 	}
11981: 	return;
11982:     }
11983:     
11984:     sub reset_hosts_ip_info {
11985: 	undef(%iphost);
11986: 	undef(%name_to_ip);
11987: 	undef(%lonid_to_ip);
11988:     }
11989: 
11990:     sub get_host_ip {
11991: 	my ($lonid) = @_;
11992: 	if (exists($lonid_to_ip{$lonid})) {
11993: 	    return $lonid_to_ip{$lonid};
11994: 	}
11995: 	my $name=&hostname($lonid);
11996:    	my $ip = gethostbyname($name);
11997: 	return if (!$ip || length($ip) ne 4);
11998: 	$ip=inet_ntoa($ip);
11999: 	$name_to_ip{$name}   = $ip;
12000: 	$lonid_to_ip{$lonid} = $ip;
12001: 	return $ip;
12002:     }
12003:     
12004:     sub get_iphost {
12005: 	my ($ignore_cache) = @_;
12006: 
12007: 	if (!$ignore_cache) {
12008: 	    if (%iphost) {
12009: 		return %iphost;
12010: 	    }
12011: 	    my ($ip_info,$cached)=
12012: 		&Apache::lonnet::is_cached_new('iphost','iphost');
12013: 	    if ($cached) {
12014: 		%iphost      = %{$ip_info->[0]};
12015: 		%name_to_ip  = %{$ip_info->[1]};
12016: 		%lonid_to_ip = %{$ip_info->[2]};
12017: 		return %iphost;
12018: 	    }
12019: 	}
12020: 
12021: 	# get yesterday's info for fallback
12022: 	my %old_name_to_ip;
12023: 	my ($ip_info,$cached)=
12024: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
12025: 	if ($cached) {
12026: 	    %old_name_to_ip = %{$ip_info->[1]};
12027: 	}
12028: 
12029: 	my %name_to_host = &all_names();
12030: 	foreach my $name (keys(%name_to_host)) {
12031: 	    my $ip;
12032: 	    if (!exists($name_to_ip{$name})) {
12033: 		$ip = gethostbyname($name);
12034: 		if (!$ip || length($ip) ne 4) {
12035: 		    if (defined($old_name_to_ip{$name})) {
12036: 			$ip = $old_name_to_ip{$name};
12037: 			&logthis("Can't find $name defaulting to old $ip");
12038: 		    } else {
12039: 			&logthis("Name $name no IP found");
12040: 			next;
12041: 		    }
12042: 		} else {
12043: 		    $ip=inet_ntoa($ip);
12044: 		}
12045: 		$name_to_ip{$name} = $ip;
12046: 	    } else {
12047: 		$ip = $name_to_ip{$name};
12048: 	    }
12049: 	    foreach my $id (@{ $name_to_host{$name} }) {
12050: 		$lonid_to_ip{$id} = $ip;
12051: 	    }
12052: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
12053: 	}
12054: 	&do_cache_new('iphost','iphost',
12055: 		      [\%iphost,\%name_to_ip,\%lonid_to_ip],
12056: 		      48*60*60);
12057: 
12058: 	return %iphost;
12059:     }
12060: 
12061:     #
12062:     #  Given a DNS returns the loncapa host name for that DNS 
12063:     # 
12064:     sub host_from_dns {
12065:         my ($dns) = @_;
12066:         my @hosts;
12067:         my $ip;
12068: 
12069:         if (exists($name_to_ip{$dns})) {
12070:             $ip = $name_to_ip{$dns};
12071:         }
12072:         if (!$ip) {
12073:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
12074:             if (length($ip) == 4) { 
12075: 	        $ip   = &IO::Socket::inet_ntoa($ip);
12076:             }
12077:         }
12078:         if ($ip) {
12079: 	    @hosts = get_hosts_from_ip($ip);
12080: 	    return $hosts[0];
12081:         }
12082:         return undef;
12083:     }
12084: 
12085:     sub get_internet_names {
12086:         my ($lonid) = @_;
12087:         return if ($lonid eq '');
12088:         my ($idnref,$cached)=
12089:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
12090:         if ($cached) {
12091:             return $idnref;
12092:         }
12093:         my $ip = &get_host_ip($lonid);
12094:         my @hosts = &get_hosts_from_ip($ip);
12095:         my %iphost = &get_iphost();
12096:         my (@idns,%seen);
12097:         foreach my $id (@hosts) {
12098:             my $dom = &host_domain($id);
12099:             my $prim_id = &domain($dom,'primary');
12100:             my $prim_ip = &get_host_ip($prim_id);
12101:             next if ($seen{$prim_ip});
12102:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
12103:                 foreach my $id (@{$iphost{$prim_ip}}) {
12104:                     my $intdom = &internet_dom($id);
12105:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
12106:                         push(@idns,$intdom);
12107:                     }
12108:                 }
12109:             }
12110:             $seen{$prim_ip} = 1;
12111:         }
12112:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
12113:     }
12114: 
12115: }
12116: 
12117: sub all_loncaparevs {
12118:     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);
12119: }
12120: 
12121: # ---------------------------------------------------------- Read loncaparev table
12122: {
12123:     sub load_loncaparevs { 
12124:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
12125:             if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
12126:                 while (my $configline=<$config>) {
12127:                     chomp($configline);
12128:                     my ($hostid,$loncaparev)=split(/:/,$configline);
12129:                     $loncaparevs{$hostid}=$loncaparev;
12130:                 }
12131:                 close($config);
12132:             }
12133:         }
12134:     }
12135: }
12136: 
12137: # ---------------------------------------------------------- Read serverhostID table
12138: {
12139:     sub load_serverhomeIDs {
12140:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
12141:             if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
12142:                 while (my $configline=<$config>) {
12143:                     chomp($configline);
12144:                     my ($name,$id)=split(/:/,$configline);
12145:                     $serverhomeIDs{$name}=$id;
12146:                 }
12147:                 close($config);
12148:             }
12149:         }
12150:     }
12151: }
12152: 
12153: 
12154: BEGIN {
12155: 
12156: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
12157:     unless ($readit) {
12158: {
12159:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
12160:     %perlvar = (%perlvar,%{$configvars});
12161: }
12162: 
12163: 
12164: # ------------------------------------------------------ Read spare server file
12165: {
12166:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
12167: 
12168:     while (my $configline=<$config>) {
12169:        chomp($configline);
12170:        if ($configline) {
12171: 	   my ($host,$type) = split(':',$configline,2);
12172: 	   if (!defined($type) || $type eq '') { $type = 'default' };
12173: 	   push(@{ $spareid{$type} }, $host);
12174:        }
12175:     }
12176:     close($config);
12177: }
12178: # ------------------------------------------------------------ Read permissions
12179: {
12180:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
12181: 
12182:     while (my $configline=<$config>) {
12183: 	chomp($configline);
12184: 	if ($configline) {
12185: 	    my ($role,$perm)=split(/ /,$configline);
12186: 	    if ($perm ne '') { $pr{$role}=$perm; }
12187: 	}
12188:     }
12189:     close($config);
12190: }
12191: 
12192: # -------------------------------------------- Read plain texts for permissions
12193: {
12194:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
12195: 
12196:     while (my $configline=<$config>) {
12197: 	chomp($configline);
12198: 	if ($configline) {
12199: 	    my ($short,@plain)=split(/:/,$configline);
12200:             %{$prp{$short}} = ();
12201: 	    if (@plain > 0) {
12202:                 $prp{$short}{'std'} = $plain[0];
12203:                 for (my $i=1; $i<@plain; $i++) {
12204:                     $prp{$short}{'alt'.$i} = $plain[$i];  
12205:                 }
12206:             }
12207: 	}
12208:     }
12209:     close($config);
12210: }
12211: 
12212: # ---------------------------------------------------------- Read package table
12213: {
12214:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
12215: 
12216:     while (my $configline=<$config>) {
12217: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
12218: 	chomp($configline);
12219: 	my ($short,$plain)=split(/:/,$configline);
12220: 	my ($pack,$name)=split(/\&/,$short);
12221: 	if ($plain ne '') {
12222: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
12223: 	    $packagetab{$short}=$plain; 
12224: 	}
12225:     }
12226:     close($config);
12227: }
12228: 
12229: # ---------------------------------------------------------- Read loncaparev table
12230: 
12231: &load_loncaparevs();
12232: 
12233: # ---------------------------------------------------------- Read serverhostID table
12234: 
12235: &load_serverhomeIDs();
12236: 
12237: # ---------------------------------------------------------- Read releaseslist XML
12238: {
12239:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
12240:     if (-e $file) {
12241:         my $parser = HTML::LCParser->new($file);
12242:         while (my $token = $parser->get_token()) {
12243:             if ($token->[0] eq 'S') {
12244:                 my $item = $token->[1];
12245:                 my $name = $token->[2]{'name'};
12246:                 my $value = $token->[2]{'value'};
12247:                 if ($item ne '' && $name ne '' && $value ne '') {
12248:                     my $release = $parser->get_text();
12249:                     $release =~ s/(^\s*|\s*$ )//gx;
12250:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
12251:                 }
12252:             }
12253:         }
12254:     }
12255: }
12256: 
12257: # ---------------------------------------------------------- Read managers table
12258: {
12259:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
12260:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
12261:             while (my $configline=<$config>) {
12262:                 chomp($configline);
12263:                 next if ($configline =~ /^\#/);
12264:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
12265:                     $managerstab{$configline} = 1;
12266:                 }
12267:             }
12268:             close($config);
12269:         }
12270:     }
12271: }
12272: 
12273: # ------------- set up temporary directory
12274: {
12275:     $tmpdir = LONCAPA::tempdir();
12276: 
12277: }
12278: 
12279: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
12280: 				'compress_threshold'=> 20_000,
12281:  			        });
12282: 
12283: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
12284: $dumpcount=0;
12285: $locknum=0;
12286: 
12287: &logtouch();
12288: &logthis('<font color="yellow">INFO: Read configuration</font>');
12289: $readit=1;
12290:     {
12291: 	use integer;
12292: 	my $test=(2**32)+1;
12293: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
12294: 	&logthis(" Detected 64bit platform ($_64bit)");
12295:     }
12296: 
12297:     {
12298:         eval {
12299:             ($apache) =
12300:                 (Apache2::ServerUtil::get_server_version() =~ m{Apache/(\d+\.\d+)});
12301:         };
12302:         if ($@) {
12303:            $apache = 1.3;
12304:         }
12305:     }
12306: 
12307: }
12308: }
12309: 
12310: 1;
12311: __END__
12312: 
12313: =pod
12314: 
12315: =head1 NAME
12316: 
12317: Apache::lonnet - Subroutines to ask questions about things in the network.
12318: 
12319: =head1 SYNOPSIS
12320: 
12321: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
12322: 
12323:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
12324: 
12325: Common parameters:
12326: 
12327: =over 4
12328: 
12329: =item *
12330: 
12331: $uname : an internal username (if $cname expecting a course Id specifically)
12332: 
12333: =item *
12334: 
12335: $udom : a domain (if $cdom expecting a course's domain specifically)
12336: 
12337: =item *
12338: 
12339: $symb : a resource instance identifier
12340: 
12341: =item *
12342: 
12343: $namespace : the name of a .db file that contains the data needed or
12344: being set.
12345: 
12346: =back
12347: 
12348: =head1 OVERVIEW
12349: 
12350: lonnet provides subroutines which interact with the
12351: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
12352: about classes, users, and resources.
12353: 
12354: For many of these objects you can also use this to store data about
12355: them or modify them in various ways.
12356: 
12357: =head2 Symbs
12358: 
12359: To identify a specific instance of a resource, LON-CAPA uses symbols
12360: or "symbs"X<symb>. These identifiers are built from the URL of the
12361: map, the resource number of the resource in the map, and the URL of
12362: the resource itself. The latter is somewhat redundant, but might help
12363: if maps change.
12364: 
12365: An example is
12366: 
12367:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
12368: 
12369: The respective map entry is
12370: 
12371:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
12372:   title="Problem 2">
12373:  </resource>
12374: 
12375: Symbs are used by the random number generator, as well as to store and
12376: restore data specific to a certain instance of for example a problem.
12377: 
12378: =head2 Storing And Retrieving Data
12379: 
12380: X<store()>X<cstore()>X<restore()>Three of the most important functions
12381: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
12382: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
12383: is is the non-critical message twin of cstore. These functions are for
12384: handlers to store a perl hash to a user's permanent data space in an
12385: easy manner, and to retrieve it again on another call. It is expected
12386: that a handler would use this once at the beginning to retrieve data,
12387: and then again once at the end to send only the new data back.
12388: 
12389: The data is stored in the user's data directory on the user's
12390: homeserver under the ID of the course.
12391: 
12392: The hash that is returned by restore will have all of the previous
12393: value for all of the elements of the hash.
12394: 
12395: Example:
12396: 
12397:  #creating a hash
12398:  my %hash;
12399:  $hash{'foo'}='bar';
12400: 
12401:  #storing it
12402:  &Apache::lonnet::cstore(\%hash);
12403: 
12404:  #changing a value
12405:  $hash{'foo'}='notbar';
12406: 
12407:  #adding a new value
12408:  $hash{'bar'}='foo';
12409:  &Apache::lonnet::cstore(\%hash);
12410: 
12411:  #retrieving the hash
12412:  my %history=&Apache::lonnet::restore();
12413: 
12414:  #print the hash
12415:  foreach my $key (sort(keys(%history))) {
12416:    print("\%history{$key} = $history{$key}");
12417:  }
12418: 
12419: Will print out:
12420: 
12421:  %history{1:foo} = bar
12422:  %history{1:keys} = foo:timestamp
12423:  %history{1:timestamp} = 990455579
12424:  %history{2:bar} = foo
12425:  %history{2:foo} = notbar
12426:  %history{2:keys} = foo:bar:timestamp
12427:  %history{2:timestamp} = 990455580
12428:  %history{bar} = foo
12429:  %history{foo} = notbar
12430:  %history{timestamp} = 990455580
12431:  %history{version} = 2
12432: 
12433: Note that the special hash entries C<keys>, C<version> and
12434: C<timestamp> were added to the hash. C<version> will be equal to the
12435: total number of versions of the data that have been stored. The
12436: C<timestamp> attribute will be the UNIX time the hash was
12437: stored. C<keys> is available in every historical section to list which
12438: keys were added or changed at a specific historical revision of a
12439: hash.
12440: 
12441: B<Warning>: do not store the hash that restore returns directly. This
12442: will cause a mess since it will restore the historical keys as if the
12443: were new keys. I.E. 1:foo will become 1:1:foo etc.
12444: 
12445: Calling convention:
12446: 
12447:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
12448:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname);
12449: 
12450: For more detailed information, see lonnet specific documentation.
12451: 
12452: =head1 RETURN MESSAGES
12453: 
12454: =over 4
12455: 
12456: =item * B<con_lost>: unable to contact remote host
12457: 
12458: =item * B<con_delayed>: unable to contact remote host, message will be delivered
12459: when the connection is brought back up
12460: 
12461: =item * B<con_failed>: unable to contact remote host and unable to save message
12462: for later delivery
12463: 
12464: =item * B<error:>: an error a occurred, a description of the error follows the :
12465: 
12466: =item * B<no_such_host>: unable to fund a host associated with the user/domain
12467: that was requested
12468: 
12469: =back
12470: 
12471: =head1 PUBLIC SUBROUTINES
12472: 
12473: =head2 Session Environment Functions
12474: 
12475: =over 4
12476: 
12477: =item * 
12478: X<appenv()>
12479: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
12480: the user envirnoment file, and will be restored for each access this
12481: user makes during this session, also modifies the %env for the current
12482: process. Optional rolesarrayref - if defined contains a reference to an array
12483: of roles which are exempt from the restriction on modifying user.role entries 
12484: in the user's environment.db and in %env.    
12485: 
12486: =item *
12487: X<delenv()>
12488: B<delenv($delthis,$regexp)>: removes all items from the session
12489: environment file that begin with $delthis. If the 
12490: optional second arg - $regexp - is true, $delthis is treated as a 
12491: regular expression, otherwise \Q$delthis\E is used. 
12492: The values are also deleted from the current processes %env.
12493: 
12494: =item * get_env_multiple($name) 
12495: 
12496: gets $name from the %env hash, it seemlessly handles the cases where multiple
12497: values may be defined and end up as an array ref.
12498: 
12499: returns an array of values
12500: 
12501: =back
12502: 
12503: =head2 User Information
12504: 
12505: =over 4
12506: 
12507: =item *
12508: X<queryauthenticate()>
12509: B<queryauthenticate($uname,$udom)>: try to determine user's current 
12510: authentication scheme
12511: 
12512: =item *
12513: X<authenticate()>
12514: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
12515: authenticate user from domain's lib servers (first use the current
12516: one). C<$upass> should be the users password.
12517: $checkdefauth is optional (value is 1 if a check should be made to
12518:    authenticate user using default authentication method, and allow
12519:    account creation if username does not have account in the domain).
12520: $clientcancheckhost is optional (value is 1 if checking whether the
12521:    server can host will occur on the client side in lonauth.pm).   
12522: 
12523: =item *
12524: X<homeserver()>
12525: B<homeserver($uname,$udom)>: find the server which has
12526: the user's directory and files (there must be only one), this caches
12527: the answer, and also caches if there is a borken connection.
12528: 
12529: =item *
12530: X<idget()>
12531: B<idget($udom,@ids)>: find the usernames behind a list of IDs
12532: (IDs are a unique resource in a domain, there must be only 1 ID per
12533: username, and only 1 username per ID in a specific domain) (returns
12534: hash: id=>name,id=>name)
12535: 
12536: =item *
12537: X<idrget()>
12538: B<idrget($udom,@unames)>: find the IDs behind a list of
12539: usernames (returns hash: name=>id,name=>id)
12540: 
12541: =item *
12542: X<idput()>
12543: B<idput($udom,%ids)>: store away a list of names and associated IDs
12544: 
12545: =item *
12546: X<rolesinit()>
12547: B<rolesinit($udom,$username)>: get user privileges.
12548: returns user role, first access and timer interval hashes
12549: 
12550: =item *
12551: X<privileged()>
12552: B<privileged($username,$domain)>: returns a true if user has a
12553: privileged and active role (i.e. su or dc), false otherwise.
12554: 
12555: =item *
12556: X<getsection()>
12557: B<getsection($udom,$uname,$cname)>: finds the section of student in the
12558: course $cname, return section name/number or '' for "not in course"
12559: and '-1' for "no section"
12560: 
12561: =item *
12562: X<userenvironment()>
12563: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
12564: passed in @what from the requested user's environment, returns a hash
12565: 
12566: =item * 
12567: X<userlog_query()>
12568: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
12569: activity.log file. %filters defines filters applied when parsing the
12570: log file. These can be start or end timestamps, or the type of action
12571: - log to look for Login or Logout events, check for Checkin or
12572: Checkout, role for role selection. The response is in the form
12573: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
12574: escaped strings of the action recorded in the activity.log file.
12575: 
12576: =back
12577: 
12578: =head2 User Roles
12579: 
12580: =over 4
12581: 
12582: =item *
12583: 
12584: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
12585:  F: full access
12586:  U,I,K: authentication modes (cxx only)
12587:  '': forbidden
12588:  1: user needs to choose course
12589:  2: browse allowed
12590:  A: passphrase authentication needed
12591: 
12592: =item *
12593: 
12594: constructaccess($url,$setpriv) : check for access to construction space URL
12595: 
12596: See if the owner domain and name in the URL match those in the
12597: expected environment.  If so, return three element list
12598: ($ownername,$ownerdomain,$ownerhome).
12599: 
12600: Otherwise return the null string.
12601: 
12602: If second argument 'setpriv' is true, it assigns the privileges,
12603: and returns the same three element list, unless the owner has
12604: blocked "ad hoc" Domain Coordinator access to the Author Space,
12605: in which case the null string is returned.
12606: 
12607: =item *
12608: 
12609: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
12610: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
12611: and course level
12612: 
12613: =item *
12614: 
12615: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
12616: (rolesplain.tab); plain text explanation of a user role term.
12617: $type is Course (default) or Community.
12618: If $forcedefault evaluates to true, text returned will be default 
12619: text for $type. Otherwise, if this is a course, the text returned 
12620: will be a custom name for the role (if defined in the course's 
12621: environment).  If no custom name is defined the default is returned.
12622:    
12623: =item *
12624: 
12625: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
12626: All arguments are optional. Returns a hash of a roles, either for
12627: co-author/assistant author roles for a user's Construction Space
12628: (default), or if $context is 'userroles', roles for the user himself,
12629: In the hash, keys are set to colon-separated $uname,$udom,$role, and
12630: (optionally) if $withsec is true, a fourth colon-separated item - $section.
12631: For each key, value is set to colon-separated start and end times for
12632: the role.  If no username and domain are specified, will default to
12633: current user/domain. Types, roles, and roledoms are references to arrays
12634: of role statuses (active, future or previous), roles 
12635: (e.g., cc,in, st etc.) and domains of the roles which can be used
12636: to restrict the list of roles reported. If no array ref is 
12637: provided for types, will default to return only active roles.
12638: 
12639: =item *
12640: 
12641: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
12642: user: $uname:$udom has a role in the course: $cdom_$cnum. 
12643: 
12644: Additional optional arguments are: $type (if role checking is to be restricted 
12645: to certain user status types -- previous (expired roles), active (currently
12646: available roles) or future (roles available in the future), and
12647: $hideprivileged -- if true will not report course roles for users who
12648: have active Domain Coordinator role in course's domain or in additional
12649: domains (specified in 'Domains to check for privileged users' in course
12650: environment -- set via:  Course Settings -> Classlists and staff listing).
12651: 
12652: =item *
12653: 
12654: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
12655: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
12656: $possdomains and $possroles are optional array refs -- to domains to check and
12657: roles to check.  If $possdomains is not specified, a dump will be done of the
12658: users' roles.db to check for a dc or su role in any domain. This can be
12659: time consuming if &privileged is called repeatedly (e.g., when displaying a
12660: classlist), so in such cases, supplying a $possdomains array is preferred, as
12661: this then allows &privileged_by_domain() to be used, which caches the identity
12662: of privileged users, eliminating the need for repeated calls to &dump().
12663: 
12664: =item *
12665: 
12666: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
12667: where the outer hash keys are domains specified in the $possdomains array ref,
12668: next inner hash keys are privileged roles specified in the $roles array ref,
12669: and the innermost hash contains key = value pairs for username:domain = end:start
12670: for active or future "privileged" users with that role in that domain. To avoid
12671: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
12672: innerhash are cached using priv_$role and $dom as the identifiers.
12673: 
12674: =back
12675: 
12676: =head2 User Modification
12677: 
12678: =over 4
12679: 
12680: =item *
12681: 
12682: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
12683: user for the level given by URL.  Optional start and end dates (leave empty
12684: string or zero for "no date")
12685: 
12686: =item *
12687: 
12688: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
12689: change a users, password, possible return values are: ok,
12690: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
12691: refused
12692: 
12693: =item *
12694: 
12695: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
12696: 
12697: =item *
12698: 
12699: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
12700:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
12701: 
12702: will update user information (firstname,middlename,lastname,generation,
12703: permanentemail), and if forceid is true, student/employee ID also.
12704: A user's institutional affiliation(s) can also be updated.
12705: User information fields will not be overwritten with empty entries 
12706: unless the field is included in the $candelete array reference.
12707: This array is included when a single user is modified via "Manage Users",
12708: or when Autoupdate.pl is run by cron in a domain.
12709: 
12710: =item *
12711: 
12712: modifystudent
12713: 
12714: modify a student's enrollment and identification information.
12715: The course id is resolved based on the current user's environment.  
12716: This means the invoking user must be a course coordinator or otherwise
12717: associated with a course.
12718: 
12719: This call is essentially a wrapper for lonnet::modifyuser and
12720: lonnet::modify_student_enrollment
12721: 
12722: Inputs: 
12723: 
12724: =over 4
12725: 
12726: =item B<$udom> Student's loncapa domain
12727: 
12728: =item B<$uname> Student's loncapa login name
12729: 
12730: =item B<$uid> Student/Employee ID
12731: 
12732: =item B<$umode> Student's authentication mode
12733: 
12734: =item B<$upass> Student's password
12735: 
12736: =item B<$first> Student's first name
12737: 
12738: =item B<$middle> Student's middle name
12739: 
12740: =item B<$last> Student's last name
12741: 
12742: =item B<$gene> Student's generation
12743: 
12744: =item B<$usec> Student's section in course
12745: 
12746: =item B<$end> Unix time of the roles expiration
12747: 
12748: =item B<$start> Unix time of the roles start date
12749: 
12750: =item B<$forceid> If defined, allow $uid to be changed
12751: 
12752: =item B<$desiredhome> server to use as home server for student
12753: 
12754: =item B<$email> Student's permanent e-mail address
12755: 
12756: =item B<$type> Type of enrollment (auto or manual)
12757: 
12758: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
12759: 
12760: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
12761: 
12762: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
12763: 
12764: =item B<$context> role change context (shown in User Management Logs display in a course)
12765: 
12766: =item B<$inststatus> institutional status of user - : separated string of escaped status types
12767: 
12768: =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.
12769: 
12770: =back
12771: 
12772: =item *
12773: 
12774: modify_student_enrollment
12775: 
12776: Change a student's enrollment status in a class.  The environment variable
12777: 'role.request.course' must be defined for this function to proceed.
12778: 
12779: Inputs:
12780: 
12781: =over 4
12782: 
12783: =item $udom, student's domain
12784: 
12785: =item $uname, student's name
12786: 
12787: =item $uid, student's user id
12788: 
12789: =item $first, student's first name
12790: 
12791: =item $middle
12792: 
12793: =item $last
12794: 
12795: =item $gene
12796: 
12797: =item $usec
12798: 
12799: =item $end
12800: 
12801: =item $start
12802: 
12803: =item $type
12804: 
12805: =item $locktype
12806: 
12807: =item $cid
12808: 
12809: =item $selfenroll
12810: 
12811: =item $context
12812: 
12813: =item $credits, number of credits student will earn from this class
12814: 
12815: =back
12816: 
12817: 
12818: =item *
12819: 
12820: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
12821: custom role; give a custom role to a user for the level given by URL.  Specify
12822: name and domain of role author, and role name
12823: 
12824: =item *
12825: 
12826: revokerole($udom,$uname,$url,$role) : revoke a role for url
12827: 
12828: =item *
12829: 
12830: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
12831: 
12832: =back
12833: 
12834: =head2 Course Infomation
12835: 
12836: =over 4
12837: 
12838: =item *
12839: 
12840: coursedescription($courseid,$options) : returns a hash of information about the
12841: specified course id, including all environment settings for the
12842: course, the description of the course will be in the hash under the
12843: key 'description'
12844: 
12845: $options is an optional parameter that if supplied is a hash reference that controls
12846: what how this function works.  It has the following key/values:
12847: 
12848: =over 4
12849: 
12850: =item freshen_cache
12851: 
12852: If defined, and the environment cache for the course is valid, it is 
12853: returned in the returned hash.
12854: 
12855: =item one_time
12856: 
12857: If defined, the last cache time is set to _now_
12858: 
12859: =item user
12860: 
12861: If defined, the supplied username is used instead of the current user.
12862: 
12863: 
12864: =back
12865: 
12866: =item *
12867: 
12868: resdata($name,$domain,$type,@which) : request for current parameter
12869: setting for a specific $type, where $type is either 'course' or 'user',
12870: @what should be a list of parameters to ask about. This routine caches
12871: answers for 10 minutes.
12872: 
12873: =item *
12874: 
12875: get_courseresdata($courseid, $domain) : dump the entire course resource
12876: data base, returning a hash that is keyed by the resource name and has
12877: values that are the resource value.  I believe that the timestamps and
12878: versions are also returned.
12879: 
12880: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
12881: supplemental content area. This routine caches the number of files for 
12882: 10 minutes.
12883: 
12884: =back
12885: 
12886: =head2 Course Modification
12887: 
12888: =over 4
12889: 
12890: =item *
12891: 
12892: writecoursepref($courseid,%prefs) : write preferences (environment
12893: database) for a course
12894: 
12895: =item *
12896: 
12897: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
12898: 
12899: =item *
12900: 
12901: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
12902: 
12903: =item *
12904: 
12905: is_course($courseid), is_course($cdom, $cnum)
12906: 
12907: Accepts either a combined $courseid (in the form of domain_courseid) or the
12908: two component version $cdom, $cnum. It checks if the specified course exists.
12909: 
12910: Returns:
12911:     undef if the course doesn't exist, otherwise
12912:     in scalar context the combined courseid.
12913:     in list context the two components of the course identifier, domain and 
12914:     courseid.    
12915: 
12916: =back
12917: 
12918: =head2 Resource Subroutines
12919: 
12920: =over 4
12921: 
12922: =item *
12923: 
12924: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
12925: 
12926: =item *
12927: 
12928: repcopy($filename) : subscribes to the requested file, and attempts to
12929: replicate from the owning library server, Might return
12930: 'unavailable', 'not_found', 'forbidden', 'ok', or
12931: 'bad_request', also attempts to grab the metadata for the
12932: resource. Expects the local filesystem pathname
12933: (/home/httpd/html/res/....)
12934: 
12935: =back
12936: 
12937: =head2 Resource Information
12938: 
12939: =over 4
12940: 
12941: =item *
12942: 
12943: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
12944: and returns the value of a variety of different possible values,
12945: $varname should be a request string, and the other parameters can be
12946: used to specify who and what one is asking about. Ordinarily, $cid 
12947: does not need to be specified, as it is retrived from 
12948: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
12949: within lonuserstate::loadmap() when initializing a course, before
12950: $env{'request.course.id'} has been set, so it needs to be provided
12951: in that one case.
12952: 
12953: Possible values for $varname are environment.lastname (or other item
12954: from the envirnment hash), user.name (or someother aspect about the
12955: user), resource.0.maxtries (or some other part and parameter of a
12956: resource)
12957: 
12958: =item *
12959: 
12960: directcondval($number) : get current value of a condition; reads from a state
12961: string
12962: 
12963: =item *
12964: 
12965: condval($condidx) : value of condition index based on state
12966: 
12967: =item *
12968: 
12969: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
12970: resource's metadata, $what should be either a specific key, or either
12971: 'keys' (to get a list of possible keys) or 'packages' to get a list of
12972: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
12973: 
12974: this function automatically caches all requests
12975: 
12976: =item *
12977: 
12978: metadata_query($query,$custom,$customshow) : make a metadata query against the
12979: network of library servers; returns file handle of where SQL and regex results
12980: will be stored for query
12981: 
12982: =item *
12983: 
12984: symbread($filename) : return symbolic list entry (filename argument optional);
12985: returns the data handle
12986: 
12987: =item *
12988: 
12989: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
12990: and is a possible symb for the URL in $thisfn, and if is an encrypted
12991: resource that the user accessed using /enc/ returns a 1 on success, 0
12992: on failure, user must be in a course, as it assumes the existence of
12993: the course initial hash, and uses $env('request.course.id'}.  The third
12994: arg is an optional reference to a scalar.  If this arg is passed in the 
12995: call to symbverify, it will be set to 1 if the symb has been set to be 
12996: encrypted; otherwise it will be null.  
12997: 
12998: =item *
12999: 
13000: symbclean($symb) : removes versions numbers from a symb, returns the
13001: cleaned symb
13002: 
13003: =item *
13004: 
13005: is_on_map($uri) : checks if the $uri is somewhere on the current
13006: course map, user must be in a course for it to work.
13007: 
13008: =item *
13009: 
13010: numval($salt) : return random seed value (addend for rndseed)
13011: 
13012: =item *
13013: 
13014: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
13015: a random seed, all arguments are optional, if they aren't sent it uses the
13016: environment to derive them. Note: if symb isn't sent and it can't get one
13017: from &symbread it will use the current time as its return value
13018: 
13019: =item *
13020: 
13021: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
13022: unfakeable, receipt
13023: 
13024: =item *
13025: 
13026: receipt() : API to ireceipt working off of env values; given out to users
13027: 
13028: =item *
13029: 
13030: countacc($url) : count the number of accesses to a given URL
13031: 
13032: =item *
13033: 
13034: 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
13035: 
13036: =item *
13037: 
13038: 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)
13039: 
13040: =item *
13041: 
13042: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
13043: 
13044: =item *
13045: 
13046: devalidate($symb) : devalidate temporary spreadsheet calculations,
13047: forcing spreadsheet to reevaluate the resource scores next time.
13048: 
13049: =item * 
13050: 
13051: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
13052: when viewing in course context.
13053: 
13054:  input: six args -- filename (decluttered), course number, course domain,
13055:                     url, symb (if registered) and group (if this is a 
13056:                     group item -- e.g., bulletin board, group page etc.).
13057: 
13058:  output: array of five scalars --
13059:          $cfile -- url for file editing if editable on current server
13060:          $home -- homeserver of resource (i.e., for author if published,
13061:                                           or course if uploaded.).
13062:          $switchserver --  1 if server switch will be needed.
13063:          $forceedit -- 1 if icon/link should be to go to edit mode 
13064:          $forceview -- 1 if icon/link should be to go to view mode
13065: 
13066: =item *
13067: 
13068: is_course_upload($file,$cnum,$cdom)
13069: 
13070: Used in course context to determine if current file was uploaded to 
13071: the course (i.e., would be found in /userfiles/docs on the course's 
13072: homeserver.
13073: 
13074:   input: 3 args -- filename (decluttered), course number and course domain.
13075:   output: boolean -- 1 if file was uploaded.
13076: 
13077: =back
13078: 
13079: =head2 Storing/Retreiving Data
13080: 
13081: =over 4
13082: 
13083: =item *
13084: 
13085: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
13086: for this url; hashref needs to be given and should be a \%hashname; the
13087: remaining args aren't required and if they aren't passed or are '' they will
13088: be derived from the env
13089: 
13090: =item *
13091: 
13092: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
13093: uses critical subroutine
13094: 
13095: =item *
13096: 
13097: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
13098: all args are optional
13099: 
13100: =item *
13101: 
13102: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
13103: dumps the complete (or key matching regexp) namespace into a hash
13104: ($udom, $uname, $regexp, $range are optional) for a namespace that is
13105: normally &store()ed into
13106: 
13107: $range should be either an integer '100' (give me the first 100
13108:                                            matching records)
13109:               or be  two integers sperated by a - with no spaces
13110:                  '30-50' (give me the 30th through the 50th matching
13111:                           records)
13112: 
13113: 
13114: =item *
13115: 
13116: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
13117: replaces a &store() version of data with a replacement set of data
13118: for a particular resource in a namespace passed in the $storehash hash 
13119: reference
13120: 
13121: =item *
13122: 
13123: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
13124: works very similar to store/cstore, but all data is stored in a
13125: temporary location and can be reset using tmpreset, $storehash should
13126: be a hash reference, returns nothing on success
13127: 
13128: =item *
13129: 
13130: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
13131: similar to restore, but all data is stored in a temporary location and
13132: can be reset using tmpreset. Returns a hash of values on success,
13133: error string otherwise.
13134: 
13135: =item *
13136: 
13137: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
13138: deltes all keys for $symb form the temporary storage hash.
13139: 
13140: =item *
13141: 
13142: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13143: reference filled in from namesp ($udom and $uname are optional)
13144: 
13145: =item *
13146: 
13147: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
13148: namesp ($udom and $uname are optional)
13149: 
13150: =item *
13151: 
13152: dump($namespace,$udom,$uname,$regexp,$range) : 
13153: dumps the complete (or key matching regexp) namespace into a hash
13154: ($udom, $uname, $regexp, $range are optional)
13155: 
13156: $range should be either an integer '100' (give me the first 100
13157:                                            matching records)
13158:               or be  two integers sperated by a - with no spaces
13159:                  '30-50' (give me the 30th through the 50th matching
13160:                           records)
13161: =item *
13162: 
13163: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
13164: $store can be a scalar, an array reference, or if the amount to be 
13165: incremented is > 1, a hash reference.
13166: 
13167: ($udom and $uname are optional)
13168: 
13169: =item *
13170: 
13171: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
13172: ($udom and $uname are optional)
13173: 
13174: =item *
13175: 
13176: cput($namespace,$storehash,$udom,$uname) : critical put
13177: ($udom and $uname are optional)
13178: 
13179: =item *
13180: 
13181: newput($namespace,$storehash,$udom,$uname) :
13182: 
13183: Attempts to store the items in the $storehash, but only if they don't
13184: currently exist, if this succeeds you can be certain that you have 
13185: successfully created a new key value pair in the $namespace db.
13186: 
13187: 
13188: Args:
13189:  $namespace: name of database to store values to
13190:  $storehash: hashref to store to the db
13191:  $udom: (optional) domain of user containing the db
13192:  $uname: (optional) name of user caontaining the db
13193: 
13194: Returns:
13195:  'ok' -> succeeded in storing all keys of $storehash
13196:  'key_exists: <key>' -> failed to anything out of $storehash, as at
13197:                         least <key> already existed in the db (other
13198:                         requested keys may also already exist)
13199:  'error: <msg>' -> unable to tie the DB or other error occurred
13200:  'con_lost' -> unable to contact request server
13201:  'refused' -> action was not allowed by remote machine
13202: 
13203: 
13204: =item *
13205: 
13206: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13207: reference filled in from namesp (encrypts the return communication)
13208: ($udom and $uname are optional)
13209: 
13210: =item *
13211: 
13212: log($udom,$name,$home,$message) : write to permanent log for user; use
13213: critical subroutine
13214: 
13215: =item *
13216: 
13217: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
13218: array reference filled in from namespace found in domain level on either
13219: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
13220: 
13221: =item *
13222: 
13223: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
13224: domain level either on specified domain server ($uhome) or primary domain 
13225: server ($udom and $uhome are optional)
13226: 
13227: =item * 
13228: 
13229: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
13230: for: authentication, language, quotas, timezone, date locale, and portal URL in
13231: the target domain.
13232: 
13233: May also include additional key => value pairs for the following groups:
13234: 
13235: =over
13236: 
13237: =item
13238: disk quotas (MB allocated by default to portfolios and authoring spaces).
13239: 
13240: =over
13241: 
13242: =item defaultquota, authorquota
13243: 
13244: =back
13245: 
13246: =item
13247: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
13248: portfolio for users).
13249: 
13250: =over
13251: 
13252: =item
13253: aboutme, blog, webdav, portfolio
13254: 
13255: =back
13256: 
13257: =item
13258: requestcourses: ability to request courses, and how requests are processed.
13259: 
13260: =over
13261: 
13262: =item
13263: official, unofficial, community
13264: 
13265: =back
13266: 
13267: =item
13268: inststatus: types of institutional affiliation, and order in which they are displayed.
13269: 
13270: =over
13271: 
13272: =item
13273: inststatustypes, inststatusorder
13274: 
13275: =back
13276: 
13277: =item
13278: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
13279: for course's uploaded content.
13280: 
13281: =over
13282: 
13283: =item
13284: canuse_pdfforms, officialcredits, unofficialcredits, officialquota, unofficialquota, communityquota
13285: 
13286: =back
13287: 
13288: =item
13289: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
13290: on your servers.
13291: 
13292: =over
13293: 
13294: =item 
13295: remotesessions, hostedsessions
13296: 
13297: =back
13298: 
13299: =back
13300: 
13301: In cases where a domain coordinator has never used the "Set Domain Configuration"
13302: utility to create a configuration.db file on a domain's primary library server 
13303: only the following domain defaults: auth_def, auth_arg_def, lang_def
13304: -- corresponding values are authentication type (internal, krb4, krb5,
13305: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
13306: will be available. Values are retrieved from cache (if current), unless the
13307: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
13308: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
13309: 
13310: Typical usage:
13311: 
13312: %domdefaults = &get_domain_defaults($target_domain);
13313: 
13314: =back
13315: 
13316: =head2 Network Status Functions
13317: 
13318: =over 4
13319: 
13320: =item *
13321: 
13322: dirlist() : return directory list based on URI (first arg).
13323: 
13324: Inputs: 1 required, 5 optional.
13325: 
13326: =over
13327: 
13328: =item 
13329: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
13330: 
13331: =item
13332: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
13333: 
13334: =item
13335: $username -  username of user/course to be listed. Extracted from $uri if absent. 
13336: 
13337: =item
13338: $getpropath - boolean: 1 if prepend path using &propath(). 
13339: 
13340: =item
13341: $getuserdir - boolean: 1 if prepend path for "userfiles".
13342: 
13343: =item 
13344: $alternateRoot - path to prepend in place of path from $uri.
13345: 
13346: =back
13347: 
13348: Returns: Array of up to two items.
13349: 
13350: =over
13351: 
13352: a reference to an array of files/subdirectories
13353: 
13354: =over
13355: 
13356: Each element in the array of files/subdirectories is a & separated list of
13357: item name and the result of running stat on the item.  If dirlist was requested
13358: for a file instead of a directory, the item name will be ''. For a directory 
13359: listing, if the item is a metadata file, the element will end &N&M 
13360: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
13361: default copyright set (1).  
13362: 
13363: =back
13364: 
13365: a scalar containing error condition (if encountered).
13366: 
13367: =over
13368: 
13369: =item 
13370: no_host (no homeserver identified for $username:$domain).
13371: 
13372: =item 
13373: no_such_host (server contacted for listing not identified as valid host).
13374: 
13375: =item 
13376: con_lost (connection to remote server failed).
13377: 
13378: =item 
13379: refused (invalid $username:$domain received on lond side).
13380: 
13381: =item 
13382: no_such_dir (directory at specified path on lond side does not exist). 
13383: 
13384: =item 
13385: empty (directory at specified path on lond side is empty).
13386: 
13387: =over
13388: 
13389: This is currently not encountered because the &ls3, &ls2, 
13390: &ls (_handler) routines on the lond side do not filter out
13391: . and .. from a directory listing. 
13392: 
13393: =back
13394: 
13395: =back
13396: 
13397: =back
13398: 
13399: =item *
13400: 
13401: spareserver() : find server with least workload from spare.tab
13402: 
13403: 
13404: =item *
13405: 
13406: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
13407: if there is no corresponding loncapa host.
13408: 
13409: =back
13410: 
13411: 
13412: =head2 Apache Request
13413: 
13414: =over 4
13415: 
13416: =item *
13417: 
13418: ssi($url,%hash) : server side include, does a complete request cycle on url to
13419: localhost, posts hash
13420: 
13421: =back
13422: 
13423: =head2 Data to String to Data
13424: 
13425: =over 4
13426: 
13427: =item *
13428: 
13429: hash2str(%hash) : convert a hash into a string complete with escaping and '='
13430: and '&' separators, supports elements that are arrayrefs and hashrefs
13431: 
13432: =item *
13433: 
13434: hashref2str($hashref) : convert a hashref into a string complete with
13435: escaping and '=' and '&' separators, supports elements that are
13436: arrayrefs and hashrefs
13437: 
13438: =item *
13439: 
13440: arrayref2str($arrayref) : convert an arrayref into a string complete
13441: with escaping and '&' separators, supports elements that are arrayrefs
13442: and hashrefs
13443: 
13444: =item *
13445: 
13446: str2hash($string) : convert string to hash using unescaping and
13447: splitting on '=' and '&', supports elements that are arrayrefs and
13448: hashrefs
13449: 
13450: =item *
13451: 
13452: str2array($string) : convert string to hash using unescaping and
13453: splitting on '&', supports elements that are arrayrefs and hashrefs
13454: 
13455: =back
13456: 
13457: =head2 Logging Routines
13458: 
13459: 
13460: These routines allow one to make log messages in the lonnet.log and
13461: lonnet.perm logfiles.
13462: 
13463: =over 4
13464: 
13465: =item *
13466: 
13467: logtouch() : make sure the logfile, lonnet.log, exists
13468: 
13469: =item *
13470: 
13471: logthis() : append message to the normal lonnet.log file, it gets
13472: preiodically rolled over and deleted.
13473: 
13474: =item *
13475: 
13476: logperm() : append a permanent message to lonnet.perm.log, this log
13477: file never gets deleted by any automated portion of the system, only
13478: messages of critical importance should go in here.
13479: 
13480: 
13481: =back
13482: 
13483: =head2 General File Helper Routines
13484: 
13485: =over 4
13486: 
13487: =item *
13488: 
13489: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
13490: (a) files in /uploaded
13491:   (i) If a local copy of the file exists - 
13492:       compares modification date of local copy with last-modified date for 
13493:       definitive version stored on home server for course. If local copy is 
13494:       stale, requests a new version from the home server and stores it. 
13495:       If the original has been removed from the home server, then local copy 
13496:       is unlinked.
13497:   (ii) If local copy does not exist -
13498:       requests the file from the home server and stores it. 
13499:   
13500:   If $caller is 'uploadrep':  
13501:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
13502:     for request for files originally uploaded via DOCS. 
13503:      - returns 'ok' if fresh local copy now available, -1 otherwise.
13504:   
13505:   Otherwise:
13506:      This indicates a call from the content generation phase of the request.
13507:      -  returns the entire contents of the file or -1.
13508:      
13509: (b) files in /res
13510:    - returns the entire contents of a file or -1; 
13511:    it properly subscribes to and replicates the file if neccessary.
13512: 
13513: 
13514: =item *
13515: 
13516: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
13517:                   reference
13518: 
13519: returns either a stat() list of data about the file or an empty list
13520: if the file doesn't exist or couldn't find out about it (connection
13521: problems or user unknown)
13522: 
13523: =item *
13524: 
13525: filelocation($dir,$file) : returns file system location of a file
13526: based on URI; meant to be "fairly clean" absolute reference, $dir is a
13527: directory that relative $file lookups are to looked in ($dir of /a/dir
13528: and a file of ../bob will become /a/bob)
13529: 
13530: =item *
13531: 
13532: hreflocation($dir,$file) : returns file system location or a URL; same as
13533: filelocation except for hrefs
13534: 
13535: =item *
13536: 
13537: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
13538: 
13539: =back
13540: 
13541: =head2 Usererfile file routines (/uploaded*)
13542: 
13543: =over 4
13544: 
13545: =item *
13546: 
13547: userfileupload(): main rotine for putting a file in a user or course's
13548:                   filespace, arguments are,
13549: 
13550:  formname - required - this is the name of the element in $env where the
13551:            filename, and the contents of the file to create/modifed exist
13552:            the filename is in $env{'form.'.$formname.'.filename'} and the
13553:            contents of the file is located in $env{'form.'.$formname}
13554:  context - if coursedoc, store the file in the course of the active role
13555:              of the current user; 
13556:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
13557:            if 'canceloverwrite': delete file in tmp/overwrites directory
13558:  subdir - required - subdirectory to put the file in under ../userfiles/
13559:          if undefined, it will be placed in "unknown"
13560: 
13561:  (This routine calls clean_filename() to remove any dangerous
13562:  characters from the filename, and then calls finuserfileupload() to
13563:  complete the transaction)
13564: 
13565:  returns either the url of the uploaded file (/uploaded/....) if successful
13566:  and /adm/notfound.html if unsuccessful
13567: 
13568: =item *
13569: 
13570: clean_filename(): routine for cleaing a filename up for storage in
13571:                  userfile space, argument is:
13572: 
13573:  filename - proposed filename
13574: 
13575: returns: the new clean filename
13576: 
13577: =item *
13578: 
13579: finishuserfileupload(): routine that creates and sends the file to
13580: userspace, probably shouldn't be called directly
13581: 
13582:   docuname: username or courseid of destination for the file
13583:   docudom: domain of user/course of destination for the file
13584:   formname: same as for userfileupload()
13585:   fname: filename (including subdirectories) for the file
13586:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
13587:   allfiles: reference to hash used to store objects found by parser
13588:   codebase: reference to hash used for codebases of java objects found by parser
13589:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
13590:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
13591:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
13592:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
13593:   context: if 'overwrite', will move the uploaded file from its temporary location to
13594:             userfiles to facilitate overwriting a previously uploaded file with same name.
13595:   mimetype: reference to scalar to accommodate mime type determined
13596:             from File::MMagic if $parser = parse.
13597: 
13598:  returns either the url of the uploaded file (/uploaded/....) if successful
13599:  and /adm/notfound.html if unsuccessful (or an error message if context 
13600:  was 'overwrite').
13601:  
13602: 
13603: =item *
13604: 
13605: renameuserfile(): renames an existing userfile to a new name
13606: 
13607:   Args:
13608:    docuname: username or courseid of destination for the file
13609:    docudom: domain of user/course of destination for the file
13610:    old: current file name (including any subdirs under userfiles)
13611:    new: desired file name (including any subdirs under userfiles)
13612: 
13613: =item *
13614: 
13615: mkdiruserfile(): creates a directory is a userfiles dir
13616: 
13617:   Args:
13618:    docuname: username or courseid of destination for the file
13619:    docudom: domain of user/course of destination for the file
13620:    dir: dir to create (including any subdirs under userfiles)
13621: 
13622: =item *
13623: 
13624: removeuserfile(): removes a file that exists in userfiles
13625: 
13626:   Args:
13627:    docuname: username or courseid of destination for the file
13628:    docudom: domain of user/course of destination for the file
13629:    fname: filname to delete (including any subdirs under userfiles)
13630: 
13631: =item *
13632: 
13633: removeuploadedurl(): convience function for removeuserfile()
13634: 
13635:   Args:
13636:    url:  a full /uploaded/... url to delete
13637: 
13638: =item * 
13639: 
13640: get_portfile_permissions():
13641:   Args:
13642:     domain: domain of user or course contain the portfolio files
13643:     user: name of user or num of course contain the portfolio files
13644:   Returns:
13645:     hashref of a dump of the proper file_permissions.db
13646:    
13647: 
13648: =item * 
13649: 
13650: get_access_controls():
13651: 
13652: Args:
13653:   current_permissions: the hash ref returned from get_portfile_permissions()
13654:   group: (optional) the group you want the files associated with
13655:   file: (optional) the file you want access info on
13656: 
13657: Returns:
13658:     a hash (keys are file names) of hashes containing
13659:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
13660:         values are XML containing access control settings (see below) 
13661: 
13662: Internal notes:
13663: 
13664:  access controls are stored in file_permissions.db as key=value pairs.
13665:     key -> path to file/file_name\0uniqueID:scope_end_start
13666:         where scope -> public,guest,course,group,domains or users.
13667:               end -> UNIX time for end of access (0 -> no end date)
13668:               start -> UNIX time for start of access
13669: 
13670:     value -> XML description of access control
13671:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
13672:             <start></start>
13673:             <end></end>
13674: 
13675:             <password></password>  for scope type = guest
13676: 
13677:             <domain></domain>     for scope type = course or group
13678:             <number></number>
13679:             <roles id="">
13680:              <role></role>
13681:              <access></access>
13682:              <section></section>
13683:              <group></group>
13684:             </roles>
13685: 
13686:             <dom></dom>         for scope type = domains
13687: 
13688:             <users>             for scope type = users
13689:              <user>
13690:               <uname></uname>
13691:               <udom></udom>
13692:              </user>
13693:             </users>
13694:            </scope> 
13695:               
13696:  Access data is also aggregated for each file in an additional key=value pair:
13697:  key -> path to file/file_name\0accesscontrol 
13698:  value -> reference to hash
13699:           hash contains key = value pairs
13700:           where key = uniqueID:scope_end_start
13701:                 value = UNIX time record was last updated
13702: 
13703:           Used to improve speed of look-ups of access controls for each file.  
13704:  
13705:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
13706: 
13707: =item *
13708: 
13709: modify_access_controls():
13710: 
13711: Modifies access controls for a portfolio file
13712: Args
13713: 1. file name
13714: 2. reference to hash of required changes,
13715: 3. domain
13716: 4. username
13717:   where domain,username are the domain of the portfolio owner 
13718:   (either a user or a course) 
13719: 
13720: Returns:
13721: 1. result of additions or updates ('ok' or 'error', with error message). 
13722: 2. result of deletions ('ok' or 'error', with error message).
13723: 3. reference to hash of any new or updated access controls.
13724: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
13725:    key = integer (inbound ID)
13726:    value = uniqueID
13727: 
13728: =item *
13729: 
13730: get_timebased_id():
13731: 
13732: Attempts to get a unique timestamp-based suffix for use with items added to a 
13733: course via the Course Editor (e.g., folders, composite pages, 
13734: group bulletin boards).
13735: 
13736: Args: (first three required; six others optional)
13737: 
13738: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
13739:    docssequence, or name of group
13740: 
13741: 2. keyid (alphanumeric): name of temporary locking key in hash,
13742:    e.g., num, boardids
13743: 
13744: 3. namespace: name of gdbm file used to store suffixes already assigned;  
13745:    file will be named nohist_namespace.db
13746: 
13747: 4. cdom: domain of course; default is current course domain from %env
13748: 
13749: 5. cnum: course number; default is current course number from %env
13750: 
13751: 6. idtype: set to concat if an additional digit is to be appended to the 
13752:    unix timestamp to form the suffix, if the plain timestamp is already
13753:    in use.  Default is to not do this, but simply increment the unix 
13754:    timestamp by 1 until a unique key is obtained.
13755: 
13756: 7. who: holder of locking key; defaults to user:domain for user.
13757: 
13758: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
13759:    retrying); default is 3.
13760: 
13761: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
13762: 
13763: Returns:
13764: 
13765: 1. suffix obtained (numeric)
13766: 
13767: 2. result of deleting locking key (ok if deleted, or lock never obtained)
13768: 
13769: 3. error: contains (localized) error message if an error occurred.
13770: 
13771: 
13772: =back
13773: 
13774: =head2 HTTP Helper Routines
13775: 
13776: =over 4
13777: 
13778: =item *
13779: 
13780: escape() : unpack non-word characters into CGI-compatible hex codes
13781: 
13782: =item *
13783: 
13784: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
13785: 
13786: =back
13787: 
13788: =head1 PRIVATE SUBROUTINES
13789: 
13790: =head2 Underlying communication routines (Shouldn't call)
13791: 
13792: =over 4
13793: 
13794: =item *
13795: 
13796: subreply() : tries to pass a message to lonc, returns con_lost if incapable
13797: 
13798: =item *
13799: 
13800: reply() : uses subreply to send a message to remote machine, logs all failures
13801: 
13802: =item *
13803: 
13804: critical() : passes a critical message to another server; if cannot
13805: get through then place message in connection buffer directory and
13806: returns con_delayed, if incapable of saving message, returns
13807: con_failed
13808: 
13809: =item *
13810: 
13811: reconlonc() : tries to reconnect lonc client processes.
13812: 
13813: =back
13814: 
13815: =head2 Resource Access Logging
13816: 
13817: =over 4
13818: 
13819: =item *
13820: 
13821: flushcourselogs() : flush (save) buffer logs and access logs
13822: 
13823: =item *
13824: 
13825: courselog($what) : save message for course in hash
13826: 
13827: =item *
13828: 
13829: courseacclog($what) : save message for course using &courselog().  Perform
13830: special processing for specific resource types (problems, exams, quizzes, etc).
13831: 
13832: =item *
13833: 
13834: goodbye() : flush course logs and log shutting down; it is called in srm.conf
13835: as a PerlChildExitHandler
13836: 
13837: =back
13838: 
13839: =head2 Other
13840: 
13841: =over 4
13842: 
13843: =item *
13844: 
13845: symblist($mapname,%newhash) : update symbolic storage links
13846: 
13847: =back
13848: 
13849: =cut
13850: 

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