File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1172.2.136: download - view: text, annotated - select for diffs
Thu Jan 28 22:41:44 2021 UTC (3 years, 4 months ago) by raeburn
Branches: version_2_11_X
- For 2.11
  Backport 1.1439

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1172.2.136 2021/01/28 22:41:44 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: use CGI::Cookie;
   78: 
   79: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir $deftex
   80:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
   81:             %managerstab $passwdmin);
   82: 
   83: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
   84:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
   85:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
   86:     %courseownerbuf, %coursetypebuf,$locknum);
   87: 
   88: use IO::Socket;
   89: use GDBM_File;
   90: use HTML::LCParser;
   91: use Fcntl qw(:flock);
   92: use Storable qw(thaw nfreeze);
   93: use Time::HiRes qw( sleep gettimeofday tv_interval );
   94: use Cache::Memcached;
   95: use Digest::MD5;
   96: use Math::Random;
   97: use File::MMagic;
   98: use LONCAPA qw(:DEFAULT :match);
   99: use LONCAPA::Configuration;
  100: use LONCAPA::lonmetadata;
  101: use LONCAPA::Lond;
  102: use LONCAPA::transliterate;
  103: 
  104: use File::Copy;
  105: 
  106: my $readit;
  107: my $max_connection_retries = 20;     # Or some such value.
  108: 
  109: require Exporter;
  110: 
  111: our @ISA = qw (Exporter);
  112: our @EXPORT = qw(%env);
  113: 
  114: # ------------------------------------ Logging (parameters, docs, slots, roles)
  115: {
  116:     my $logid;
  117:     sub write_log {
  118: 	my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
  119:         if ($context eq 'course') {
  120:             if (($cnum eq '') || ($cdom eq '')) {
  121:                 $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
  122:                 $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
  123:             }
  124:         }
  125: 	$logid ++;
  126:         my $now = time();
  127: 	my $id=$now.'00000'.$$.'00000'.$logid;
  128:         my $ip = &get_requestor_ip();  
  129:         my $logentry = {
  130:                          $id => {
  131:                                   'exe_uname' => $env{'user.name'},
  132:                                   'exe_udom'  => $env{'user.domain'},
  133:                                   'exe_time'  => $now,
  134:                                   'exe_ip'    => $ip,
  135:                                   'delflag'   => $delflag,
  136:                                   'logentry'  => $storehash,
  137:                                   'uname'     => $uname,
  138:                                   'udom'      => $udom,
  139:                                 }
  140:                        };
  141:         return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
  142:     }
  143: }
  144: 
  145: sub logtouch {
  146:     my $execdir=$perlvar{'lonDaemons'};
  147:     unless (-e "$execdir/logs/lonnet.log") {	
  148: 	open(my $fh,">>","$execdir/logs/lonnet.log");
  149: 	close $fh;
  150:     }
  151:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
  152:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
  153: }
  154: 
  155: sub logthis {
  156:     my $message=shift;
  157:     my $execdir=$perlvar{'lonDaemons'};
  158:     my $now=time;
  159:     my $local=localtime($now);
  160:     if (open(my $fh,">>","$execdir/logs/lonnet.log")) {
  161: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
  162: 	print $fh $logstring;
  163: 	close($fh);
  164:     }
  165:     return 1;
  166: }
  167: 
  168: sub logperm {
  169:     my $message=shift;
  170:     my $execdir=$perlvar{'lonDaemons'};
  171:     my $now=time;
  172:     my $local=localtime($now);
  173:     if (open(my $fh,">>","$execdir/logs/lonnet.perm.log")) {
  174: 	print $fh "$now:$message:$local\n";
  175: 	close($fh);
  176:     }
  177:     return 1;
  178: }
  179: 
  180: sub create_connection {
  181:     my ($hostname,$lonid) = @_;
  182:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
  183: 				     Type    => SOCK_STREAM,
  184: 				     Timeout => 10);
  185:     return 0 if (!$client);
  186:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
  187:     my $result = <$client>;
  188:     chomp($result);
  189:     return 1 if ($result eq 'done');
  190:     return 0;
  191: }
  192: 
  193: sub get_server_timezone {
  194:     my ($cnum,$cdom) = @_;
  195:     my $home=&homeserver($cnum,$cdom);
  196:     if ($home ne 'no_host') {
  197:         my $cachetime = 24*3600;
  198:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
  199:         if (defined($cached)) {
  200:             return $timezone;
  201:         } else {
  202:             my $timezone = &reply('servertimezone',$home);
  203:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
  204:         }
  205:     }
  206: }
  207: 
  208: sub get_server_distarch {
  209:     my ($lonhost,$ignore_cache) = @_;
  210:     if (defined($lonhost)) {
  211:         if (!defined(&hostname($lonhost))) {
  212:             return;
  213:         }
  214:         my $cachetime = 12*3600;
  215:         if (!$ignore_cache) {
  216:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
  217:             if (defined($cached)) {
  218:                 return $distarch;
  219:             }
  220:         }
  221:         my $rep = &reply('serverdistarch',$lonhost);
  222:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
  223:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
  224:                 $rep eq '') {
  225:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
  226:         }
  227:     }
  228:     return;
  229: }
  230: 
  231: sub get_server_loncaparev {
  232:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
  233:     if (defined($lonhost)) {
  234:         if (!defined(&hostname($lonhost))) {
  235:             undef($lonhost);
  236:         }
  237:     }
  238:     if (!defined($lonhost)) {
  239:         if (defined(&domain($dom,'primary'))) {
  240:             $lonhost=&domain($dom,'primary');
  241:             if ($lonhost eq 'no_host') {
  242:                 undef($lonhost);
  243:             }
  244:         }
  245:     }
  246:     if (defined($lonhost)) {
  247:         my $cachetime = 12*3600;
  248:         if (!$ignore_cache) {
  249:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
  250:             if (defined($cached)) {
  251:                 return $loncaparev;
  252:             }
  253:         }
  254:         my ($answer,$loncaparev);
  255:         my @ids=&current_machine_ids();
  256:         if (grep(/^\Q$lonhost\E$/,@ids)) {
  257:             $answer = $perlvar{'lonVersion'};
  258:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  259:                 $loncaparev = $1;
  260:             }
  261:         } else {
  262:             $answer = &reply('serverloncaparev',$lonhost);
  263:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
  264:                 if ($caller eq 'loncron') {
  265:                     my $ua=new LWP::UserAgent;
  266:                     $ua->timeout(4);
  267:                     my $hostname = &hostname($lonhost);
  268:                     my $protocol = $protocol{$lonhost};
  269:                     $protocol = 'http' if ($protocol ne 'https');
  270:                     my $url = $protocol.'://'.$hostname.'/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:     return &reply('devalidatecache:'.&escape($cachestr),$lonhost);
  364: }
  365: 
  366: # -------------------------------------------------- Non-critical communication
  367: sub subreply {
  368:     my ($cmd,$server)=@_;
  369:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
  370:     #
  371:     #  With loncnew process trimming, there's a timing hole between lonc server
  372:     #  process exit and the master server picking up the listen on the AF_UNIX
  373:     #  socket.  In that time interval, a lock file will exist:
  374: 
  375:     my $lockfile=$peerfile.".lock";
  376:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
  377: 	sleep(0.1);
  378:     }
  379:     # At this point, either a loncnew parent is listening or an old lonc
  380:     # or loncnew child is listening so we can connect or everything's dead.
  381:     #
  382:     #   We'll give the connection a few tries before abandoning it.  If
  383:     #   connection is not possible, we'll con_lost back to the client.
  384:     #   
  385:     my $client;
  386:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
  387: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  388: 				      Type    => SOCK_STREAM,
  389: 				      Timeout => 10);
  390: 	if ($client) {
  391: 	    last;		# Connected!
  392: 	} else {
  393: 	    &create_connection(&hostname($server),$server);
  394: 	}
  395:         sleep(0.1);		# Try again later if failed connection.
  396:     }
  397:     my $answer;
  398:     if ($client) {
  399: 	print $client "sethost:$server:$cmd\n";
  400: 	$answer=<$client>;
  401: 	if (!$answer) { $answer="con_lost"; }
  402: 	chomp($answer);
  403:     } else {
  404: 	$answer = 'con_lost';	# Failed connection.
  405:     }
  406:     return $answer;
  407: }
  408: 
  409: sub reply {
  410:     my ($cmd,$server)=@_;
  411:     unless (defined(&hostname($server))) { return 'no_such_host'; }
  412:     my $answer=subreply($cmd,$server);
  413:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
  414:         my $logged = $cmd;
  415:         if ($cmd =~ /^encrypt:([^:]+):/) {
  416:             my $subcmd = $1;
  417:             if (($subcmd eq 'auth') || ($subcmd eq 'passwd') ||
  418:                 ($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
  419:                 ($subcmd eq 'putdom') || ($subcmd eq 'autoexportgrades')) {
  420:                 (undef,undef,my @rest) = split(/:/,$cmd);
  421:                 if (($subcmd eq 'auth') || ($subcmd eq 'putdom')) {
  422:                     splice(@rest,2,1,'Hidden');
  423:                 } elsif ($subcmd eq 'passwd') {
  424:                     splice(@rest,2,2,('Hidden','Hidden'));
  425:                 } elsif (($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
  426:                          ($subcmd eq 'autoexportgrades')) {
  427:                     splice(@rest,3,1,'Hidden');
  428:                 }
  429:                 $logged = join(':',('encrypt:'.$subcmd,@rest));
  430:             }
  431:         }
  432:         &logthis("<font color=\"blue\">WARNING:".
  433:                  " $logged to $server returned $answer</font>");
  434:     }
  435:     return $answer;
  436: }
  437: 
  438: # ----------------------------------------------------------- Send USR1 to lonc
  439: 
  440: sub reconlonc {
  441:     my ($lonid) = @_;
  442:     if ($lonid) {
  443:         my $hostname = &hostname($lonid);
  444: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
  445: 	if ($hostname && -e $peerfile) {
  446: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
  447: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
  448: 					     Type    => SOCK_STREAM,
  449: 					     Timeout => 10);
  450: 	    if ($client) {
  451: 		print $client ("reset_retries\n");
  452: 		my $answer=<$client>;
  453: 		#reset just this one.
  454: 	    }
  455: 	}
  456: 	return;
  457:     }
  458: 
  459:     &logthis("Trying to reconnect lonc");
  460:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  461:     if (open(my $fh,"<",$loncfile)) {
  462: 	my $loncpid=<$fh>;
  463:         chomp($loncpid);
  464:         if (kill 0 => $loncpid) {
  465: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  466:             kill USR1 => $loncpid;
  467:             sleep 1;
  468:          } else {
  469: 	    &logthis(
  470:                "<font color=\"blue\">WARNING:".
  471:                " lonc at pid $loncpid not responding, giving up</font>");
  472:         }
  473:     } else {
  474: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
  475:     }
  476: }
  477: 
  478: # ------------------------------------------------------ Critical communication
  479: 
  480: sub critical {
  481:     my ($cmd,$server)=@_;
  482:     unless (&hostname($server)) {
  483:         &logthis("<font color=\"blue\">WARNING:".
  484:                " Critical message to unknown server ($server)</font>");
  485:         return 'no_such_host';
  486:     }
  487:     my $answer=reply($cmd,$server);
  488:     if ($answer eq 'con_lost') {
  489: 	&reconlonc($server);
  490: 	my $answer=reply($cmd,$server);
  491:         if ($answer eq 'con_lost') {
  492:             my $now=time;
  493:             my $middlename=$cmd;
  494:             $middlename=substr($middlename,0,16);
  495:             $middlename=~s/\W//g;
  496:             my $dfilename=
  497:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
  498:             $dumpcount++;
  499:             {
  500: 		my $dfh;
  501: 		if (open($dfh,">",$dfilename)) {
  502: 		    print $dfh "$cmd\n"; 
  503: 		    close($dfh);
  504: 		}
  505:             }
  506:             sleep 1;
  507:             my $wcmd='';
  508:             {
  509: 		my $dfh;
  510: 		if (open($dfh,"<",$dfilename)) {
  511: 		    $wcmd=<$dfh>; 
  512: 		    close($dfh);
  513: 		}
  514:             }
  515:             chomp($wcmd);
  516:             if ($wcmd eq $cmd) {
  517: 		&logthis("<font color=\"blue\">WARNING: ".
  518:                          "Connection buffer $dfilename: $cmd</font>");
  519:                 &logperm("D:$server:$cmd");
  520: 	        return 'con_delayed';
  521:             } else {
  522:                 &logthis("<font color=\"red\">CRITICAL:"
  523:                         ." Critical connection failed: $server $cmd</font>");
  524:                 &logperm("F:$server:$cmd");
  525:                 return 'con_failed';
  526:             }
  527:         }
  528:     }
  529:     return $answer;
  530: }
  531: 
  532: # ------------------------------------------- check if return value is an error
  533: 
  534: sub error {
  535:     my ($result) = @_;
  536:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
  537: 	if ($2 == 2) { return undef; }
  538: 	return $1;
  539:     }
  540:     return undef;
  541: }
  542: 
  543: sub convert_and_load_session_env {
  544:     my ($lonidsdir,$handle)=@_;
  545:     my @profile;
  546:     {
  547: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  548: 	if (!$opened) {
  549: 	    return 0;
  550: 	}
  551: 	flock($idf,LOCK_SH);
  552: 	@profile=<$idf>;
  553: 	close($idf);
  554:     }
  555:     my %temp_env;
  556:     foreach my $line (@profile) {
  557: 	if ($line !~ m/=/) {
  558: 	    return 0;
  559: 	}
  560: 	chomp($line);
  561: 	my ($envname,$envvalue)=split(/=/,$line,2);
  562: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
  563:     }
  564:     unlink("$lonidsdir/$handle.id");
  565:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
  566: 	    0640)) {
  567: 	%disk_env = %temp_env;
  568: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
  569: 	untie(%disk_env);
  570:     }
  571:     return 1;
  572: }
  573: 
  574: # ------------------------------------------- Transfer profile into environment
  575: my $env_loaded;
  576: sub transfer_profile_to_env {
  577:     my ($lonidsdir,$handle,$force_transfer) = @_;
  578:     if (!$force_transfer && $env_loaded) { return; } 
  579: 
  580:     if (!defined($lonidsdir)) {
  581: 	$lonidsdir = $perlvar{'lonIDsDir'};
  582:     }
  583:     if (!defined($handle)) {
  584:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
  585:     }
  586: 
  587:     my $convert;
  588:     {
  589:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  590: 	if (!$opened) {
  591: 	    return;
  592: 	}
  593: 	flock($idf,LOCK_SH);
  594: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  595: 		&GDBM_READER(),0640)) {
  596: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
  597: 	    untie(%disk_env);
  598: 	} else {
  599: 	    $convert = 1;
  600: 	}
  601:     }
  602:     if ($convert) {
  603: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
  604: 	    &logthis("Failed to load session, or convert session.");
  605: 	}
  606:     }
  607: 
  608:     my %remove;
  609:     while ( my $envname = each(%env) ) {
  610:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  611:             if ($time < time-300) {
  612:                 $remove{$key}++;
  613:             }
  614:         }
  615:     }
  616: 
  617:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  618:     $env_loaded=1;
  619:     foreach my $expired_key (keys(%remove)) {
  620:         &delenv($expired_key);
  621:     }
  622: }
  623: 
  624: # ---------------------------------------------------- Check for valid session 
  625: sub check_for_valid_session {
  626:     my ($r,$name,$userhashref,$domref) = @_;
  627:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
  628:     my ($lonidsdir,$linkname,$pubname,$secure,$lonid);
  629:     if ($name eq 'lonDAV') {
  630:         $lonidsdir=$r->dir_config('lonDAVsessDir');
  631:     } else {
  632:         $lonidsdir=$r->dir_config('lonIDsDir');
  633:         if ($name eq '') {
  634:             $name = 'lonID';
  635:         }
  636:     }
  637:     if ($name eq 'lonID') {
  638:         $secure = 'lonSID';
  639:         $linkname = 'lonLinkID';
  640:         $pubname = 'lonPubID';
  641:         if (exists($cookies{$secure})) {
  642:             $lonid=$cookies{$secure};
  643:         } elsif (exists($cookies{$name})) {
  644:             $lonid=$cookies{$name};
  645:         } elsif ((exists($cookies{$linkname})) && ($ENV{'SERVER_PORT'} != 443)) {
  646:             $lonid=$cookies{$linkname};
  647:         } elsif (exists($cookies{$pubname})) {
  648:             $lonid=$cookies{$pubname};
  649:         }
  650:     } else {
  651:         $lonid=$cookies{$name};
  652:     }
  653:     return undef if (!$lonid);
  654: 
  655:     my $handle=&LONCAPA::clean_handle($lonid->value);
  656:     if (-l "$lonidsdir/$handle.id") {
  657:         my $link = readlink("$lonidsdir/$handle.id");
  658:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
  659:             $handle = $1;
  660:         }
  661:     }
  662:     if (!-e "$lonidsdir/$handle.id") {
  663:         if ((ref($domref)) && ($name eq 'lonID') &&
  664:             ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
  665:             my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
  666:             if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
  667:                 $$domref = $possudom;
  668:             }
  669:         }
  670:         return undef;
  671:     }
  672: 
  673:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  674:     return undef if (!$opened);
  675: 
  676:     flock($idf,LOCK_SH);
  677:     my %disk_env;
  678:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  679: 	    &GDBM_READER(),0640)) {
  680: 	return undef;	
  681:     }
  682: 
  683:     if (!defined($disk_env{'user.name'})
  684: 	|| !defined($disk_env{'user.domain'})) {
  685:         untie(%disk_env);
  686: 	return undef;
  687:     }
  688: 
  689:     if (ref($userhashref) eq 'HASH') {
  690:         $userhashref->{'name'} = $disk_env{'user.name'};
  691:         $userhashref->{'domain'} = $disk_env{'user.domain'};
  692:     }
  693:     untie(%disk_env);
  694: 
  695:     return $handle;
  696: }
  697: 
  698: sub timed_flock {
  699:     my ($file,$lock_type) = @_;
  700:     my $failed=0;
  701:     eval {
  702: 	local $SIG{__DIE__}='DEFAULT';
  703: 	local $SIG{ALRM}=sub {
  704: 	    $failed=1;
  705: 	    die("failed lock");
  706: 	};
  707: 	alarm(13);
  708: 	flock($file,$lock_type);
  709: 	alarm(0);
  710:     };
  711:     if ($failed) {
  712: 	return undef;
  713:     } else {
  714: 	return 1;
  715:     }
  716: }
  717: 
  718: sub get_sessionfile_vars {
  719:     my ($handle,$lonidsdir,$storearr) = @_;
  720:     my %returnhash;
  721:     unless (ref($storearr) eq 'ARRAY') {
  722:         return %returnhash;
  723:     }
  724:     if (-l "$lonidsdir/$handle.id") {
  725:         my $link = readlink("$lonidsdir/$handle.id");
  726:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
  727:             $handle = $1;
  728:         }
  729:     }
  730:     if ((-e "$lonidsdir/$handle.id") &&
  731:         ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
  732:         my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
  733:         if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
  734:             if (open(my $idf,'+<',"$lonidsdir/$handle.id")) {
  735:                 flock($idf,LOCK_SH);
  736:                 if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  737:                         &GDBM_READER(),0640)) {
  738:                     foreach my $item (@{$storearr}) {
  739:                         $returnhash{$item} = $disk_env{$item};
  740:                     }
  741:                     untie(%disk_env);
  742:                 }
  743:             }
  744:         }
  745:     }
  746:     return %returnhash;
  747: }
  748: 
  749: # ---------------------------------------------------------- Append Environment
  750: 
  751: sub appenv {
  752:     my ($newenv,$roles) = @_;
  753:     if (ref($newenv) eq 'HASH') {
  754:         foreach my $key (keys(%{$newenv})) {
  755:             my $refused = 0;
  756: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
  757:                 $refused = 1;
  758:                 if (ref($roles) eq 'ARRAY') {
  759:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
  760:                     if (grep(/^\Q$role\E$/,@{$roles})) {
  761:                         $refused = 0;
  762:                     }
  763:                 }
  764:             }
  765:             if ($refused) {
  766:                 &logthis("<font color=\"blue\">WARNING: ".
  767:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
  768:                          .'</font>');
  769: 	        delete($newenv->{$key});
  770:             } else {
  771:                 $env{$key}=$newenv->{$key};
  772:             }
  773:         }
  774:         my $lonids = $perlvar{'lonIDsDir'};
  775:         if ($env{'user.environment'} =~ m{^\Q$lonids/\E$match_username\_\d+\_$match_domain\_[\w\-.]+\.id$}) {
  776:             my $opened = open(my $env_file,'+<',$env{'user.environment'});
  777:             if ($opened
  778: 	        && &timed_flock($env_file,LOCK_EX)
  779: 	        &&
  780: 	        tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  781: 	            (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  782: 	        while (my ($key,$value) = each(%{$newenv})) {
  783: 	            $disk_env{$key} = $value;
  784: 	        }
  785: 	        untie(%disk_env);
  786:             }
  787:         }
  788:     }
  789:     return 'ok';
  790: }
  791: # ----------------------------------------------------- Delete from Environment
  792: 
  793: sub delenv {
  794:     my ($delthis,$regexp,$roles) = @_;
  795:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
  796:         my $refused = 1;
  797:         if (ref($roles) eq 'ARRAY') {
  798:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
  799:             if (grep(/^\Q$role\E$/,@{$roles})) {
  800:                 $refused = 0;
  801:             }
  802:         }
  803:         if ($refused) {
  804:             &logthis("<font color=\"blue\">WARNING: ".
  805:                      "Attempt to delete from environment ".$delthis);
  806:             return 'error';
  807:         }
  808:     }
  809:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
  810:     if ($opened
  811: 	&& &timed_flock($env_file,LOCK_EX)
  812: 	&&
  813: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  814: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  815: 	foreach my $key (keys(%disk_env)) {
  816: 	    if ($regexp) {
  817:                 if ($key=~/^$delthis/) {
  818:                     delete($env{$key});
  819:                     delete($disk_env{$key});
  820:                 } 
  821:             } else {
  822:                 if ($key=~/^\Q$delthis\E/) {
  823: 		    delete($env{$key});
  824: 		    delete($disk_env{$key});
  825: 	        }
  826:             }
  827: 	}
  828: 	untie(%disk_env);
  829:     }
  830:     return 'ok';
  831: }
  832: 
  833: sub get_env_multiple {
  834:     my ($name) = @_;
  835:     my @values;
  836:     if (defined($env{$name})) {
  837:         # exists is it an array
  838:         if (ref($env{$name})) {
  839:             @values=@{ $env{$name} };
  840:         } else {
  841:             $values[0]=$env{$name};
  842:         }
  843:     }
  844:     return(@values);
  845: }
  846: 
  847: # ------------------------------------------------------------------- Locking
  848: 
  849: sub set_lock {
  850:     my ($text)=@_;
  851:     $locknum++;
  852:     my $id=$$.'-'.$locknum;
  853:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
  854:              'session.lock.'.$id => $text});
  855:     return $id;
  856: }
  857: 
  858: sub get_locks {
  859:     my $num=0;
  860:     my %texts=();
  861:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  862:        if ($lock=~/\w/) {
  863:           $num++;
  864:           $texts{$lock}=$env{'session.lock.'.$lock};
  865:        }
  866:    }
  867:    return ($num,%texts);
  868: }
  869: 
  870: sub remove_lock {
  871:     my ($id)=@_;
  872:     my $newlocks='';
  873:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  874:        if (($lock=~/\w/) && ($lock ne $id)) {
  875:           $newlocks.=','.$lock;
  876:        }
  877:     }
  878:     &appenv({'session.locks' => $newlocks});
  879:     &delenv('session.lock.'.$id);
  880: }
  881: 
  882: sub remove_all_locks {
  883:     my $activelocks=$env{'session.locks'};
  884:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  885:        if ($lock=~/\w/) {
  886:           &remove_lock($lock);
  887:        }
  888:     }
  889: }
  890: 
  891: 
  892: # ------------------------------------------ Find out current server userload
  893: sub userload {
  894:     my $numusers=0;
  895:     {
  896: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  897: 	my $filename;
  898: 	my $curtime=time;
  899: 	while ($filename=readdir(LONIDS)) {
  900: 	    next if ($filename eq '.' || $filename eq '..');
  901: 	    next if ($filename =~ /publicuser_\d+\.id/);
  902:             next if ($filename =~ /^[a-f0-9]+_linked\.id$/);
  903: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  904: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  905: 	}
  906: 	closedir(LONIDS);
  907:     }
  908:     my $userloadpercent=0;
  909:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  910:     if ($maxuserload) {
  911: 	$userloadpercent=100*$numusers/$maxuserload;
  912:     }
  913:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  914:     return $userloadpercent;
  915: }
  916: 
  917: # ------------------------------ Find server with least workload from spare.tab
  918: 
  919: sub spareserver {
  920:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
  921:     my $spare_server;
  922:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  923:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
  924:                                                      :  $userloadpercent;
  925:     my ($uint_dom,$remotesessions);
  926:     if (($udom ne '') && (&domain($udom) ne '')) {
  927:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
  928:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
  929:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
  930:         $remotesessions = $udomdefaults{'remotesessions'};
  931:     }
  932:     my $spareshash = &this_host_spares($udom);
  933:     if (ref($spareshash) eq 'HASH') {
  934:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
  935:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
  936:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
  937:                                              $try_server));
  938: 	        ($spare_server, $lowest_load) =
  939: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
  940:             }
  941:         }
  942: 
  943:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
  944: 
  945:         if (!$found_server) {
  946:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
  947: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
  948:                     next unless (&spare_can_host($udom,$uint_dom,
  949:                                                  $remotesessions,$try_server));
  950: 	            ($spare_server, $lowest_load) =
  951: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
  952:                 }
  953: 	    }
  954:         }
  955:     }
  956: 
  957:     if (!$want_server_name) {
  958:         if (defined($spare_server)) {
  959:             my $hostname = &hostname($spare_server);
  960:             if (defined($hostname)) {
  961:                 my $protocol = 'http';
  962:                 if ($protocol{$spare_server} eq 'https') {
  963:                     $protocol = $protocol{$spare_server};
  964:                 }
  965: 	        $spare_server = $protocol.'://'.$hostname;
  966:             }
  967:         }
  968:     }
  969:     return $spare_server;
  970: }
  971: 
  972: sub compare_server_load {
  973:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
  974: 
  975:     if ($required) {
  976:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
  977:         my $remoterev = &get_server_loncaparev(undef,$try_server);
  978:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
  979:         if (($major eq '' && $minor eq '') ||
  980:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
  981:             return ($spare_server,$lowest_load);
  982:         }
  983:     }
  984: 
  985:     my $loadans     = &reply('load',    $try_server);
  986:     my $userloadans = &reply('userload',$try_server);
  987: 
  988:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
  989: 	return ($spare_server, $lowest_load); #didn't get a number from the server
  990:     }
  991: 
  992:     my $load;
  993:     if ($loadans =~ /\d/) {
  994: 	if ($userloadans =~ /\d/) {
  995: 	    #both are numbers, pick the bigger one
  996: 	    $load = ($loadans > $userloadans) ? $loadans 
  997: 		                              : $userloadans;
  998: 	} else {
  999: 	    $load = $loadans;
 1000: 	}
 1001:     } else {
 1002: 	$load = $userloadans;
 1003:     }
 1004: 
 1005:     if (($load =~ /\d/) && ($load < $lowest_load)) {
 1006: 	$spare_server = $try_server;
 1007: 	$lowest_load  = $load;
 1008:     }
 1009:     return ($spare_server,$lowest_load);
 1010: }
 1011: 
 1012: # --------------------------- ask offload servers if user already has a session
 1013: sub find_existing_session {
 1014:     my ($udom,$uname) = @_;
 1015:     my $spareshash = &this_host_spares($udom);
 1016:     if (ref($spareshash) eq 'HASH') {
 1017:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
 1018:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
 1019:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
 1020:             }
 1021:         }
 1022:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
 1023:             foreach my $try_server (@{ $spareshash->{'default'} }) {
 1024:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
 1025:             }
 1026:         }
 1027:     }
 1028:     return;
 1029: }
 1030: 
 1031: # check if user's browser sent load balancer cookie and server still has session
 1032: # and is not overloaded.
 1033: sub check_for_balancer_cookie {
 1034:     my ($r,$update_mtime) = @_;
 1035:     my ($otherserver,$cookie);
 1036:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
 1037:     if (exists($cookies{'balanceID'})) {
 1038:         my $balid = $cookies{'balanceID'};
 1039:         $cookie=&LONCAPA::clean_handle($balid->value);
 1040:         my $balancedir=$r->dir_config('lonBalanceDir');
 1041:         if ((-d $balancedir) && (-e "$balancedir/$cookie.id")) {
 1042:             if ($cookie =~ /^($match_domain)_($match_username)_[a-f0-9]+$/) {
 1043:                 my ($possudom,$possuname) = ($1,$2);
 1044:                 my $has_session = 0;
 1045:                 if ((&domain($possudom) ne '') &&
 1046:                     (&homeserver($possuname,$possudom) ne 'no_host')) {
 1047:                     my $try_server;
 1048:                     my $opened = open(my $idf,'+<',"$balancedir/$cookie.id");
 1049:                     if ($opened) {
 1050:                         flock($idf,LOCK_SH);
 1051:                         while (my $line = <$idf>) {
 1052:                             chomp($line);
 1053:                             if (&hostname($line) ne '') {
 1054:                                 $try_server = $line;
 1055:                                 last;
 1056:                             }
 1057:                         }
 1058:                         close($idf);
 1059:                         if (($try_server) &&
 1060:                             (&has_user_session($try_server,$possudom,$possuname))) {
 1061:                             my $lowest_load = 30000;
 1062:                             ($otherserver,$lowest_load) =
 1063:                                 &compare_server_load($try_server,undef,$lowest_load);
 1064:                             if ($otherserver ne '' && $lowest_load < 100) {
 1065:                                 $has_session = 1;
 1066:                             } else {
 1067:                                 undef($otherserver);
 1068:                             }
 1069:                         }
 1070:                     }
 1071:                 }
 1072:                 if ($has_session) {
 1073:                     if ($update_mtime) {
 1074:                         my $atime = my $mtime = time;
 1075:                         utime($atime,$mtime,"$balancedir/$cookie.id");
 1076:                     }
 1077:                 } else {
 1078:                     unlink("$balancedir/$cookie.id");
 1079:                 }
 1080:             }
 1081:         }
 1082:     }
 1083:     return ($otherserver,$cookie);
 1084: }
 1085: 
 1086: sub updatebalcookie {
 1087:     my ($cookie,$balancer,$lastentry)=@_;
 1088:     if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
 1089:         my ($udom,$uname) = ($1,$2);
 1090:         my $uprimary_id = &domain($udom,'primary');
 1091:         my $uintdom = &internet_dom($uprimary_id);
 1092:         my $intdom = &internet_dom($balancer);
 1093:         my $serverhomedom = &host_domain($balancer);
 1094:         if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1095:             return &reply('updatebalcookie:'.&escape($cookie).':'.&escape($lastentry),$balancer);
 1096:         }
 1097:     }
 1098:     return;
 1099: }
 1100: 
 1101: sub delbalcookie {
 1102:     my ($cookie,$balancer) =@_;
 1103:     if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
 1104:         my ($udom,$uname) = ($1,$2);
 1105:         my $uprimary_id = &domain($udom,'primary');
 1106:         my $uintdom = &internet_dom($uprimary_id);
 1107:         my $intdom = &internet_dom($balancer);
 1108:         my $serverhomedom = &host_domain($balancer);
 1109:         if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1110:             return &reply('delbalcookie:'.&escape($cookie),$balancer);
 1111:         }
 1112:     }
 1113: }
 1114: 
 1115: # -------------------------------- ask if server already has a session for user
 1116: sub has_user_session {
 1117:     my ($lonid,$udom,$uname) = @_;
 1118:     my $result = &reply(join(':','userhassession',
 1119: 			     map {&escape($_)} ($udom,$uname)),$lonid);
 1120:     return 1 if ($result eq 'ok');
 1121: 
 1122:     return 0;
 1123: }
 1124: 
 1125: # --------- determine least loaded server in a user's domain which allows login
 1126: 
 1127: sub choose_server {
 1128:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
 1129:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
 1130:     my %servers = &get_servers($udom);
 1131:     my $lowest_load = 30000;
 1132:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
 1133:     if ($skiploadbal) {
 1134:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
 1135:         unless (defined($cached)) {
 1136:             my $cachetime = 60*60*24;
 1137:             my %domconfig =
 1138:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
 1139:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1140:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
 1141:                                            $cachetime);
 1142:             }
 1143:         }
 1144:     }
 1145:     foreach my $lonhost (keys(%servers)) {
 1146:         my $loginvia;
 1147:         if ($skiploadbal) {
 1148:             if (ref($balancers) eq 'HASH') {
 1149:                 next if (exists($balancers->{$lonhost}));
 1150:             }
 1151:         }
 1152:         if ($checkloginvia) {
 1153:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
 1154:             if ($loginvia) {
 1155:                 my ($server,$path) = split(/:/,$loginvia);
 1156:                 ($login_host, $lowest_load) =
 1157:                     &compare_server_load($server, $login_host, $lowest_load, $required);
 1158:                 if ($login_host eq $server) {
 1159:                     $portal_path = $path;
 1160:                     $isredirect = 1;
 1161:                 }
 1162:             } else {
 1163:                 ($login_host, $lowest_load) =
 1164:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
 1165:                 if ($login_host eq $lonhost) {
 1166:                     $portal_path = '';
 1167:                     $isredirect = ''; 
 1168:                 }
 1169:             }
 1170:         } else {
 1171:             ($login_host, $lowest_load) =
 1172:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
 1173:         }
 1174:     }
 1175:     if ($login_host ne '') {
 1176:         $hostname = &hostname($login_host);
 1177:     }
 1178:     return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
 1179: }
 1180: 
 1181: sub get_course_sessions {
 1182:     my ($cnum,$cdom,$lastactivity) = @_;
 1183:     my %servers = &internet_dom_servers($cdom);
 1184:     my %returnhash;
 1185:     foreach my $server (sort(keys(%servers))) {
 1186:         my $rep = &reply("coursesessions:$cdom:$cnum:$lastactivity",$server);
 1187:         my @pairs=split(/\&/,$rep);
 1188:         unless (($rep eq 'unknown_cmd') || ($rep =~ /^error/)) {
 1189:             foreach my $item (@pairs) {
 1190:                 my ($key,$value)=split(/=/,$item,2);
 1191:                 $key = &unescape($key);
 1192:                 next if ($key =~ /^error: 2 /);
 1193:                 if (exists($returnhash{$key})) {
 1194:                     next if ($value < $returnhash{$key});
 1195:                 }
 1196:                 $returnhash{$key}=$value;
 1197:             }
 1198:         }
 1199:     }
 1200:     return %returnhash;
 1201: }
 1202: 
 1203: # --------------------------------------------- Try to change a user's password
 1204: 
 1205: sub changepass {
 1206:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
 1207:     $currentpass = &escape($currentpass);
 1208:     $newpass     = &escape($newpass);
 1209:     my $lonhost = $perlvar{'lonHostID'};
 1210:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
 1211: 		       $server);
 1212:     if (! $answer) {
 1213: 	&logthis("No reply on password change request to $server ".
 1214: 		 "by $uname in domain $udom.");
 1215:     } elsif ($answer =~ "^ok") {
 1216:         &logthis("$uname in $udom successfully changed their password ".
 1217: 		 "on $server.");
 1218:     } elsif ($answer =~ "^pwchange_failure") {
 1219: 	&logthis("$uname in $udom was unable to change their password ".
 1220: 		 "on $server.  The action was blocked by either lcpasswd ".
 1221: 		 "or pwchange");
 1222:     } elsif ($answer =~ "^non_authorized") {
 1223:         &logthis("$uname in $udom did not get their password correct when ".
 1224: 		 "attempting to change it on $server.");
 1225:     } elsif ($answer =~ "^auth_mode_error") {
 1226:         &logthis("$uname in $udom attempted to change their password despite ".
 1227: 		 "not being locally or internally authenticated on $server.");
 1228:     } elsif ($answer =~ "^unknown_user") {
 1229:         &logthis("$uname in $udom attempted to change their password ".
 1230: 		 "on $server but were unable to because $server is not ".
 1231: 		 "their home server.");
 1232:     } elsif ($answer =~ "^refused") {
 1233: 	&logthis("$server refused to change $uname in $udom password because ".
 1234: 		 "it was sent an unencrypted request to change the password.");
 1235:     } elsif ($answer =~ "invalid_client") {
 1236:         &logthis("$server refused to change $uname in $udom password because ".
 1237:                  "it was a reset by e-mail originating from an invalid server.");
 1238:     } elsif ($answer =~ "^prioruse") {
 1239:        &logthis("$server refused to change $uname in $udom password because ".
 1240:                 "the password had been used before");
 1241:     }
 1242:     return $answer;
 1243: }
 1244: 
 1245: # ----------------------- Try to determine user's current authentication scheme
 1246: 
 1247: sub queryauthenticate {
 1248:     my ($uname,$udom)=@_;
 1249:     my $uhome=&homeserver($uname,$udom);
 1250:     if (!$uhome) {
 1251: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
 1252: 	return 'no_host';
 1253:     }
 1254:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
 1255:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
 1256: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1257:     }
 1258:     return $answer;
 1259: }
 1260: 
 1261: # --------- Try to authenticate user from domain's lib servers (first this one)
 1262: 
 1263: sub authenticate {
 1264:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
 1265:     $upass=&escape($upass);
 1266:     $uname= &LONCAPA::clean_username($uname);
 1267:     my $uhome=&homeserver($uname,$udom,1);
 1268:     my $newhome;
 1269:     if ((!$uhome) || ($uhome eq 'no_host')) {
 1270: # Maybe the machine was offline and only re-appeared again recently?
 1271:         &reconlonc();
 1272: # One more
 1273: 	$uhome=&homeserver($uname,$udom,1);
 1274:         if (($uhome eq 'no_host') && $checkdefauth) {
 1275:             if (defined(&domain($udom,'primary'))) {
 1276:                 $newhome=&domain($udom,'primary');
 1277:             }
 1278:             if ($newhome ne '') {
 1279:                 $uhome = $newhome;
 1280:             }
 1281:         }
 1282: 	if ((!$uhome) || ($uhome eq 'no_host')) {
 1283: 	    &logthis("User $uname at $udom is unknown in authenticate");
 1284: 	    return 'no_host';
 1285:         }
 1286:     }
 1287:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
 1288:     if ($answer eq 'authorized') {
 1289:         if ($newhome) {
 1290:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
 1291:             return 'no_account_on_host'; 
 1292:         } else {
 1293:             &logthis("User $uname at $udom authorized by $uhome");
 1294:             return $uhome;
 1295:         }
 1296:     }
 1297:     if ($answer eq 'non_authorized') {
 1298: 	&logthis("User $uname at $udom rejected by $uhome");
 1299: 	return 'no_host'; 
 1300:     }
 1301:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1302:     return 'no_host';
 1303: }
 1304: 
 1305: sub can_host_session {
 1306:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
 1307:     my $canhost = 1;
 1308:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
 1309:     if (ref($remotesessions) eq 'HASH') {
 1310:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
 1311:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
 1312:                 $canhost = 0;
 1313:             } else {
 1314:                 $canhost = 1;
 1315:             }
 1316:         }
 1317:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
 1318:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
 1319:                 $canhost = 1;
 1320:             } else {
 1321:                 $canhost = 0;
 1322:             }
 1323:         }
 1324:         if ($canhost) {
 1325:             if ($remotesessions->{'version'} ne '') {
 1326:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
 1327:                 if ($reqmajor ne '' && $reqminor ne '') {
 1328:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
 1329:                         my $major = $1;
 1330:                         my $minor = $2;
 1331:                         if (($major < $reqmajor ) ||
 1332:                             (($major == $reqmajor) && ($minor < $reqminor))) {
 1333:                             $canhost = 0;
 1334:                         }
 1335:                     } else {
 1336:                         $canhost = 0;
 1337:                     }
 1338:                 }
 1339:             }
 1340:         }
 1341:     }
 1342:     if ($canhost) {
 1343:         if (ref($hostedsessions) eq 'HASH') {
 1344:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1345:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
 1346:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
 1347:                 if (($uint_dom ne '') && 
 1348:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
 1349:                     $canhost = 0;
 1350:                 } else {
 1351:                     $canhost = 1;
 1352:                 }
 1353:             }
 1354:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
 1355:                 if (($uint_dom ne '') && 
 1356:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
 1357:                     $canhost = 1;
 1358:                 } else {
 1359:                     $canhost = 0;
 1360:                 }
 1361:             }
 1362:         }
 1363:     }
 1364:     return $canhost;
 1365: }
 1366: 
 1367: sub spare_can_host {
 1368:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
 1369:     my $canhost=1;
 1370:     my $try_server_hostname = &hostname($try_server);
 1371:     my $serverhomeID = &get_server_homeID($try_server_hostname);
 1372:     my $serverhomedom = &host_domain($serverhomeID);
 1373:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
 1374:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
 1375:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
 1376:             $canhost = 0;
 1377:         }
 1378:     }
 1379:     if ($canhost) {
 1380:         if (ref($defdomdefaults{'offloadoth'}) eq 'HASH') {
 1381:             if ($defdomdefaults{'offloadoth'}{$try_server}) {
 1382:                 unless (&shared_institution($udom,$try_server)) {
 1383:                     $canhost = 0;
 1384:                 }
 1385:             }
 1386:         }
 1387:     }
 1388:     if (($canhost) && ($uint_dom)) {
 1389:         my @intdoms;
 1390:         my $internet_names = &get_internet_names($try_server);
 1391:         if (ref($internet_names) eq 'ARRAY') {
 1392:             @intdoms = @{$internet_names};
 1393:         }
 1394:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
 1395:             my $remoterev = &get_server_loncaparev(undef,$try_server);
 1396:             $canhost = &can_host_session($udom,$try_server,$remoterev,
 1397:                                          $remotesessions,
 1398:                                          $defdomdefaults{'hostedsessions'});
 1399:         }
 1400:     }
 1401:     return $canhost;
 1402: }
 1403: 
 1404: sub this_host_spares {
 1405:     my ($dom) = @_;
 1406:     my ($dom_in_use,$lonhost_in_use,$result);
 1407:     my @hosts = &current_machine_ids();
 1408:     foreach my $lonhost (@hosts) {
 1409:         if (&host_domain($lonhost) eq $dom) {
 1410:             $dom_in_use = $dom;
 1411:             $lonhost_in_use = $lonhost;
 1412:             last;
 1413:         }
 1414:     }
 1415:     if ($dom_in_use ne '') {
 1416:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1417:     }
 1418:     if (ref($result) ne 'HASH') {
 1419:         $lonhost_in_use = $perlvar{'lonHostID'};
 1420:         $dom_in_use = &host_domain($lonhost_in_use);
 1421:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1422:         if (ref($result) ne 'HASH') {
 1423:             $result = \%spareid;
 1424:         }
 1425:     }
 1426:     return $result;
 1427: }
 1428: 
 1429: sub spares_for_offload  {
 1430:     my ($dom_in_use,$lonhost_in_use) = @_;
 1431:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
 1432:     if (defined($cached)) {
 1433:         return $result;
 1434:     } else {
 1435:         my $cachetime = 60*60*24;
 1436:         my %domconfig =
 1437:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
 1438:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
 1439:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
 1440:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
 1441:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
 1442:                 }
 1443:             }
 1444:         }
 1445:     }
 1446:     return;
 1447: }
 1448: 
 1449: sub get_lonbalancer_config {
 1450:     my ($servers) = @_;
 1451:     my ($currbalancer,$currtargets);
 1452:     if (ref($servers) eq 'HASH') {
 1453:         foreach my $server (keys(%{$servers})) {
 1454:             my %what = (
 1455:                          spareid => 1,
 1456:                          perlvar => 1,
 1457:                        );
 1458:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
 1459:             if ($result eq 'ok') {
 1460:                 if (ref($returnhash) eq 'HASH') {
 1461:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
 1462:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
 1463:                             $currbalancer = $server;
 1464:                             $currtargets = {};
 1465:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
 1466:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
 1467:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
 1468:                                 }
 1469:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
 1470:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
 1471:                                 }
 1472:                             }
 1473:                             last;
 1474:                         }
 1475:                     }
 1476:                 }
 1477:             }
 1478:         }
 1479:     }
 1480:     return ($currbalancer,$currtargets);
 1481: }
 1482: 
 1483: sub check_loadbalancing {
 1484:     my ($uname,$udom,$caller) = @_;
 1485:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
 1486:         $rule_in_effect,$offloadto,$otherserver,$setcookie);
 1487:     my $lonhost = $perlvar{'lonHostID'};
 1488:     my @hosts = &current_machine_ids();
 1489:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1490:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
 1491:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
 1492:     my $serverhomedom = &host_domain($lonhost);
 1493:     my $domneedscache; 
 1494:     my $cachetime = 60*60*24;
 1495: 
 1496:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1497:         $dom_in_use = $udom;
 1498:         $homeintdom = 1;
 1499:     } else {
 1500:         $dom_in_use = $serverhomedom;
 1501:     }
 1502:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
 1503:     unless (defined($cached)) {
 1504:         my %domconfig =
 1505:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
 1506:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1507:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1508:         } else {
 1509:             $domneedscache = $dom_in_use;
 1510:         }
 1511:     }
 1512:     if (ref($result) eq 'HASH') {
 1513:         ($is_balancer,$currtargets,$currrules,$setcookie) =
 1514:             &check_balancer_result($result,@hosts);
 1515:         if ($is_balancer) {
 1516:             if (ref($currrules) eq 'HASH') {
 1517:                 if ($homeintdom) {
 1518:                     if ($uname ne '') {
 1519:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
 1520:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
 1521:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
 1522:                                 $rule_in_effect = $currrules->{'_LC_author'};
 1523:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
 1524:                                 $rule_in_effect = $currrules->{'_LC_adv'}
 1525:                             }
 1526:                         }
 1527:                         if ($rule_in_effect eq '') {
 1528:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
 1529:                             if ($userenv{'inststatus'} ne '') {
 1530:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
 1531:                                 my ($othertitle,$usertypes,$types) =
 1532:                                     &Apache::loncommon::sorted_inst_types($udom);
 1533:                                 if (ref($types) eq 'ARRAY') {
 1534:                                     foreach my $type (@{$types}) {
 1535:                                         if (grep(/^\Q$type\E$/,@statuses)) {
 1536:                                             if (exists($currrules->{$type})) {
 1537:                                                 $rule_in_effect = $currrules->{$type};
 1538:                                             }
 1539:                                         }
 1540:                                     }
 1541:                                 }
 1542:                             } else {
 1543:                                 if (exists($currrules->{'default'})) {
 1544:                                     $rule_in_effect = $currrules->{'default'};
 1545:                                 }
 1546:                             }
 1547:                         }
 1548:                     } else {
 1549:                         if (exists($currrules->{'default'})) {
 1550:                             $rule_in_effect = $currrules->{'default'};
 1551:                         }
 1552:                     }
 1553:                 } else {
 1554:                     if ($currrules->{'_LC_external'} ne '') {
 1555:                         $rule_in_effect = $currrules->{'_LC_external'};
 1556:                     }
 1557:                 }
 1558:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1559:                                                        $uname,$udom);
 1560:             }
 1561:         }
 1562:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
 1563:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
 1564:         unless (defined($cached)) {
 1565:             my %domconfig =
 1566:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
 1567:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1568:                 $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
 1569:             } else {
 1570:                 $domneedscache = $serverhomedom;
 1571:             }
 1572:         }
 1573:         if (ref($result) eq 'HASH') {
 1574:             ($is_balancer,$currtargets,$currrules,$setcookie) =
 1575:                 &check_balancer_result($result,@hosts);
 1576:             if ($is_balancer) {
 1577:                 if (ref($currrules) eq 'HASH') {
 1578:                     if ($currrules->{'_LC_internetdom'} ne '') {
 1579:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
 1580:                     }
 1581:                 }
 1582:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1583:                                                        $uname,$udom);
 1584:             }
 1585:         } else {
 1586:             if ($perlvar{'lonBalancer'} eq 'yes') {
 1587:                 $is_balancer = 1;
 1588:                 $offloadto = &this_host_spares($dom_in_use);
 1589:             }
 1590:             unless (defined($cached)) {
 1591:                 $domneedscache = $serverhomedom;
 1592:             }
 1593:         }
 1594:     } else {
 1595:         if ($perlvar{'lonBalancer'} eq 'yes') {
 1596:             $is_balancer = 1;
 1597:             $offloadto = &this_host_spares($dom_in_use);
 1598:         }
 1599:         unless (defined($cached)) {
 1600:             $domneedscache = $serverhomedom;
 1601:         }
 1602:     }
 1603:     if ($domneedscache) {
 1604:         &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
 1605:     }
 1606:     if (($is_balancer) && ($caller ne 'switchserver')) {
 1607:         my $lowest_load = 30000;
 1608:         if (ref($offloadto) eq 'HASH') {
 1609:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
 1610:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
 1611:                     ($otherserver,$lowest_load) =
 1612:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1613:                 }
 1614:             }
 1615:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
 1616: 
 1617:             if (!$found_server) {
 1618:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
 1619:                     foreach my $try_server (@{$offloadto->{'default'}}) {
 1620:                         ($otherserver,$lowest_load) =
 1621:                             &compare_server_load($try_server,$otherserver,$lowest_load);
 1622:                     }
 1623:                 }
 1624:             }
 1625:         } elsif (ref($offloadto) eq 'ARRAY') {
 1626:             if (@{$offloadto} == 1) {
 1627:                 $otherserver = $offloadto->[0];
 1628:             } elsif (@{$offloadto} > 1) {
 1629:                 foreach my $try_server (@{$offloadto}) {
 1630:                     ($otherserver,$lowest_load) =
 1631:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1632:                 }
 1633:             }
 1634:         }
 1635:         unless ($caller eq 'login') {
 1636:             if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
 1637:                 $is_balancer = 0;
 1638:                 if ($uname ne '' && $udom ne '') {
 1639:                     if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
 1640:                         &appenv({'user.loadbalexempt'     => $lonhost,
 1641:                                  'user.loadbalcheck.time' => time});
 1642:                     }
 1643:                 }
 1644:             }
 1645:         }
 1646:     }
 1647:     if (($is_balancer) && (!$homeintdom)) {
 1648:         undef($setcookie);
 1649:     }
 1650:     return ($is_balancer,$otherserver,$setcookie);
 1651: }
 1652: 
 1653: sub check_balancer_result {
 1654:     my ($result,@hosts) = @_;
 1655:     my ($is_balancer,$currtargets,$currrules,$setcookie);
 1656:     if (ref($result) eq 'HASH') {
 1657:         if ($result->{'lonhost'} ne '') {
 1658:             my $currbalancer = $result->{'lonhost'};
 1659:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
 1660:                 $is_balancer = 1;
 1661:                 $currtargets = $result->{'targets'};
 1662:                 $currrules = $result->{'rules'};
 1663:             }
 1664:         } else {
 1665:             foreach my $key (keys(%{$result})) {
 1666:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
 1667:                     (ref($result->{$key}) eq 'HASH')) {
 1668:                     $is_balancer = 1;
 1669:                     $currrules = $result->{$key}{'rules'};
 1670:                     $currtargets = $result->{$key}{'targets'};
 1671:                     $setcookie = $result->{$key}{'cookie'};
 1672:                     last;
 1673:                 }
 1674:             }
 1675:         }
 1676:     }
 1677:     return ($is_balancer,$currtargets,$currrules,$setcookie);
 1678: }
 1679: 
 1680: sub get_loadbalancer_targets {
 1681:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
 1682:     my $offloadto;
 1683:     if ($rule_in_effect eq 'none') {
 1684:         return [$perlvar{'lonHostID'}];
 1685:     } elsif ($rule_in_effect eq '') {
 1686:         $offloadto = $currtargets;
 1687:     } else {
 1688:         if ($rule_in_effect eq 'homeserver') {
 1689:             my $homeserver = &homeserver($uname,$udom);
 1690:             if ($homeserver ne 'no_host') {
 1691:                 $offloadto = [$homeserver];
 1692:             }
 1693:         } elsif ($rule_in_effect eq 'externalbalancer') {
 1694:             my %domconfig =
 1695:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
 1696:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1697:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
 1698:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
 1699:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
 1700:                     }
 1701:                 }
 1702:             } else {
 1703:                 my %servers = &internet_dom_servers($udom);
 1704:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
 1705:                 if (&hostname($remotebalancer) ne '') {
 1706:                     $offloadto = [$remotebalancer];
 1707:                 }
 1708:             }
 1709:         } elsif (&hostname($rule_in_effect) ne '') {
 1710:             $offloadto = [$rule_in_effect];
 1711:         }
 1712:     }
 1713:     return $offloadto;
 1714: }
 1715: 
 1716: sub internet_dom_servers {
 1717:     my ($dom) = @_;
 1718:     my (%uniqservers,%servers);
 1719:     my $primaryserver = &hostname(&domain($dom,'primary'));
 1720:     my @machinedoms = &machine_domains($primaryserver);
 1721:     foreach my $mdom (@machinedoms) {
 1722:         my %currservers = %servers;
 1723:         my %server = &get_servers($mdom);
 1724:         %servers = (%currservers,%server);
 1725:     }
 1726:     my %by_hostname;
 1727:     foreach my $id (keys(%servers)) {
 1728:         push(@{$by_hostname{$servers{$id}}},$id);
 1729:     }
 1730:     foreach my $hostname (sort(keys(%by_hostname))) {
 1731:         if (@{$by_hostname{$hostname}} > 1) {
 1732:             my $match = 0;
 1733:             foreach my $id (@{$by_hostname{$hostname}}) {
 1734:                 if (&host_domain($id) eq $dom) {
 1735:                     $uniqservers{$id} = $hostname;
 1736:                     $match = 1;
 1737:                 }
 1738:             }
 1739:             unless ($match) {
 1740:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1741:             }
 1742:         } else {
 1743:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1744:         }
 1745:     }
 1746:     return %uniqservers;
 1747: }
 1748: 
 1749: # ---------------------- Find the homebase for a user from domain's lib servers
 1750: 
 1751: my %homecache;
 1752: sub homeserver {
 1753:     my ($uname,$udom,$ignoreBadCache)=@_;
 1754:     my $index="$uname:$udom";
 1755: 
 1756:     if (exists($homecache{$index})) { return $homecache{$index}; }
 1757: 
 1758:     my %servers = &get_servers($udom,'library');
 1759:     foreach my $tryserver (keys(%servers)) {
 1760:         next if ($ignoreBadCache ne 'true' && 
 1761: 		 exists($badServerCache{$tryserver}));
 1762: 
 1763: 	my $answer=reply("home:$udom:$uname",$tryserver);
 1764: 	if ($answer eq 'found') {
 1765: 	    delete($badServerCache{$tryserver}); 
 1766: 	    return $homecache{$index}=$tryserver;
 1767: 	} elsif ($answer eq 'no_host') {
 1768: 	    $badServerCache{$tryserver}=1;
 1769: 	}
 1770:     }    
 1771:     return 'no_host';
 1772: }
 1773: 
 1774: # ------------------------------------- Find the usernames behind a list of IDs
 1775: 
 1776: sub idget {
 1777:     my ($udom,@ids)=@_;
 1778:     my %returnhash=();
 1779:     
 1780:     my %servers = &get_servers($udom,'library');
 1781:     foreach my $tryserver (keys(%servers)) {
 1782: 	my $idlist=join('&', map { &escape($_); } @ids);
 1783: 	$idlist=~tr/A-Z/a-z/; 
 1784: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
 1785: 	my @answer=();
 1786: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
 1787: 	    @answer=split(/\&/,$reply);
 1788: 	}                    ;
 1789: 	my $i;
 1790: 	for ($i=0;$i<=$#ids;$i++) {
 1791: 	    if ($answer[$i]) {
 1792: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
 1793: 	    } 
 1794: 	}
 1795:     } 
 1796:     return %returnhash;
 1797: }
 1798: 
 1799: # ------------------------------------- Find the IDs behind a list of usernames
 1800: 
 1801: sub idrget {
 1802:     my ($udom,@unames)=@_;
 1803:     my %returnhash=();
 1804:     foreach my $uname (@unames) {
 1805:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
 1806:     }
 1807:     return %returnhash;
 1808: }
 1809: 
 1810: # ------------------------------- Store away a list of names and associated IDs
 1811: 
 1812: sub idput {
 1813:     my ($udom,%ids)=@_;
 1814:     my %servers=();
 1815:     foreach my $uname (keys(%ids)) {
 1816: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
 1817:         my $uhom=&homeserver($uname,$udom);
 1818:         if ($uhom ne 'no_host') {
 1819:             my $id=&escape($ids{$uname});
 1820:             $id=~tr/A-Z/a-z/;
 1821:             my $esc_unam=&escape($uname);
 1822: 	    if ($servers{$uhom}) {
 1823: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
 1824:             } else {
 1825:                 $servers{$uhom}=$id.'='.$esc_unam;
 1826:             }
 1827:         }
 1828:     }
 1829:     foreach my $server (keys(%servers)) {
 1830:         &critical('idput:'.$udom.':'.$servers{$server},$server);
 1831:     }
 1832: }
 1833: 
 1834: # ---------------------------------------- Delete unwanted IDs from ids.db file
 1835: 
 1836: sub iddel {
 1837:     my ($udom,$idshashref,$uhome)=@_;
 1838:     my %result=();
 1839:     unless (ref($idshashref) eq 'HASH') {
 1840:         return %result;
 1841:     }
 1842:     my %servers=();
 1843:     while (my ($id,$uname) = each(%{$idshashref})) {
 1844:         my $uhom;
 1845:         if ($uhome) {
 1846:             $uhom = $uhome;
 1847:         } else {
 1848:             $uhom=&homeserver($uname,$udom);
 1849:         }
 1850:         if ($uhom ne 'no_host') {
 1851:             if ($servers{$uhom}) {
 1852:                 $servers{$uhom}.='&'.&escape($id);
 1853:             } else {
 1854:                 $servers{$uhom}=&escape($id);
 1855:             }
 1856:         }
 1857:     }
 1858:     foreach my $server (keys(%servers)) {
 1859:         $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
 1860:     }
 1861:     return %result;
 1862: }
 1863: 
 1864: # ------------------------------dump from db file owned by domainconfig user
 1865: sub dump_dom {
 1866:     my ($namespace, $udom, $regexp) = @_;
 1867: 
 1868:     $udom ||= $env{'user.domain'};
 1869: 
 1870:     return () unless $udom;
 1871: 
 1872:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
 1873: }
 1874: 
 1875: # ------------------------------------------ get items from domain db files   
 1876: 
 1877: sub get_dom {
 1878:     my ($namespace,$storearr,$udom,$uhome)=@_;
 1879:     return if ($udom eq 'public');
 1880:     my $items='';
 1881:     foreach my $item (@$storearr) {
 1882:         $items.=&escape($item).'&';
 1883:     }
 1884:     $items=~s/\&$//;
 1885:     if (!$udom) {
 1886:         $udom=$env{'user.domain'};
 1887:         return if ($udom eq 'public');
 1888:         if (defined(&domain($udom,'primary'))) {
 1889:             $uhome=&domain($udom,'primary');
 1890:         } else {
 1891:             undef($uhome);
 1892:         }
 1893:     } else {
 1894:         if (!$uhome) {
 1895:             if (defined(&domain($udom,'primary'))) {
 1896:                 $uhome=&domain($udom,'primary');
 1897:             }
 1898:         }
 1899:     }
 1900:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1901:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
 1902:         my %returnhash;
 1903:         if ($rep eq '' || $rep =~ /^error: 2 /) {
 1904:             return %returnhash;
 1905:         }
 1906:         my @pairs=split(/\&/,$rep);
 1907:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 1908:             return @pairs;
 1909:         }
 1910:         my $i=0;
 1911:         foreach my $item (@$storearr) {
 1912:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
 1913:             $i++;
 1914:         }
 1915:         return %returnhash;
 1916:     } else {
 1917:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
 1918:     }
 1919: }
 1920: 
 1921: # -------------------------------------------- put items in domain db files 
 1922: 
 1923: sub put_dom {
 1924:     my ($namespace,$storehash,$udom,$uhome)=@_;
 1925:     if (!$udom) {
 1926:         $udom=$env{'user.domain'};
 1927:         if (defined(&domain($udom,'primary'))) {
 1928:             $uhome=&domain($udom,'primary');
 1929:         } else {
 1930:             undef($uhome);
 1931:         }
 1932:     } else {
 1933:         if (!$uhome) {
 1934:             if (defined(&domain($udom,'primary'))) {
 1935:                 $uhome=&domain($udom,'primary');
 1936:             }
 1937:         }
 1938:     } 
 1939:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1940:         my $items='';
 1941:         foreach my $item (keys(%$storehash)) {
 1942:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 1943:         }
 1944:         $items=~s/\&$//;
 1945:         return &reply("putdom:$udom:$namespace:$items",$uhome);
 1946:     } else {
 1947:         &logthis("put_dom failed - no homeserver and/or domain");
 1948:     }
 1949: }
 1950: 
 1951: # --------------------- newput for items in db file owned by domainconfig user
 1952: sub newput_dom {
 1953:     my ($namespace,$storehash,$udom) = @_;
 1954:     my $result;
 1955:     if (!$udom) {
 1956:         $udom=$env{'user.domain'};
 1957:     }
 1958:     if ($udom) {
 1959:         my $uname = &get_domainconfiguser($udom);
 1960:         $result = &newput($namespace,$storehash,$udom,$uname);
 1961:     }
 1962:     return $result;
 1963: }
 1964: 
 1965: # --------------------- delete for items in db file owned by domainconfig user
 1966: sub del_dom {
 1967:     my ($namespace,$storearr,$udom)=@_;
 1968:     if (ref($storearr) eq 'ARRAY') {
 1969:         if (!$udom) {
 1970:             $udom=$env{'user.domain'};
 1971:         }
 1972:         if ($udom) {
 1973:             my $uname = &get_domainconfiguser($udom); 
 1974:             return &del($namespace,$storearr,$udom,$uname);
 1975:         }
 1976:     }
 1977: }
 1978: 
 1979: # ----------------------------------construct domainconfig user for a domain 
 1980: sub get_domainconfiguser {
 1981:     my ($udom) = @_;
 1982:     return $udom.'-domainconfig';
 1983: }
 1984: 
 1985: sub retrieve_inst_usertypes {
 1986:     my ($udom) = @_;
 1987:     my (%returnhash,@order);
 1988:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 1989:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
 1990:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
 1991:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
 1992:     } else {
 1993:         if (defined(&domain($udom,'primary'))) {
 1994:             my $uhome=&domain($udom,'primary');
 1995:             my $rep=&reply("inst_usertypes:$udom",$uhome);
 1996:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
 1997:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
 1998:                 return (\%returnhash,\@order);
 1999:             }
 2000:             my ($hashitems,$orderitems) = split(/:/,$rep); 
 2001:             my @pairs=split(/\&/,$hashitems);
 2002:             foreach my $item (@pairs) {
 2003:                 my ($key,$value)=split(/=/,$item,2);
 2004:                 $key = &unescape($key);
 2005:                 next if ($key =~ /^error: 2 /);
 2006:                 $returnhash{$key}=&thaw_unescape($value);
 2007:             }
 2008:             my @esc_order = split(/\&/,$orderitems);
 2009:             foreach my $item (@esc_order) {
 2010:                 push(@order,&unescape($item));
 2011:             }
 2012:         } else {
 2013:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
 2014:         }
 2015:         return (\%returnhash,\@order);
 2016:     }
 2017: }
 2018: 
 2019: sub is_domainimage {
 2020:     my ($url) = @_;
 2021:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
 2022:         if (&domain($1) ne '') {
 2023:             return '1';
 2024:         }
 2025:     }
 2026:     return;
 2027: }
 2028: 
 2029: sub inst_directory_query {
 2030:     my ($srch) = @_;
 2031:     my $udom = $srch->{'srchdomain'};
 2032:     my %results;
 2033:     my $homeserver = &domain($udom,'primary');
 2034:     my $outcome;
 2035:     if ($homeserver ne '') {
 2036:         unless ($homeserver eq $perlvar{'lonHostID'}) {
 2037:             if ($srch->{'srchby'} eq 'email') {
 2038:                 my $lcrev = &get_server_loncaparev($udom,$homeserver);
 2039:                 my ($major,$minor,$subver) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.(\d+)[\w.\-]+\'?$/);
 2040:                 if (($major eq '' && $minor eq '') || ($major < 2) ||
 2041:                     (($major == 2) && ($minor < 11)) ||
 2042:                     (($major == 2) && ($minor == 11) && ($subver < 3))) {
 2043:                     return;
 2044:                 }
 2045:             }
 2046:         }
 2047: 	my $queryid=&reply("querysend:instdirsearch:".
 2048: 			   &escape($srch->{'srchby'}).':'.
 2049: 			   &escape($srch->{'srchterm'}).':'.
 2050: 			   &escape($srch->{'srchtype'}),$homeserver);
 2051: 	my $host=&hostname($homeserver);
 2052: 	if ($queryid !~/^\Q$host\E\_/) {
 2053: 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
 2054: 	    return;
 2055: 	}
 2056: 	my $response = &get_query_reply($queryid);
 2057: 	my $maxtries = 5;
 2058: 	my $tries = 1;
 2059: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 2060: 	    $response = &get_query_reply($queryid);
 2061: 	    $tries ++;
 2062: 	}
 2063: 
 2064:         if (!&error($response) && $response ne 'refused') {
 2065:             if ($response eq 'unavailable') {
 2066:                 $outcome = $response;
 2067:             } else {
 2068:                 $outcome = 'ok';
 2069:                 my @matches = split(/\n/,$response);
 2070:                 foreach my $match (@matches) {
 2071:                     my ($key,$value) = split(/=/,$match);
 2072:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 2073:                 }
 2074:             }
 2075:         }
 2076:     }
 2077:     return ($outcome,%results);
 2078: }
 2079: 
 2080: sub usersearch {
 2081:     my ($srch) = @_;
 2082:     my $dom = $srch->{'srchdomain'};
 2083:     my %results;
 2084:     my %libserv = &all_library();
 2085:     my $query = 'usersearch';
 2086:     foreach my $tryserver (keys(%libserv)) {
 2087:         if (&host_domain($tryserver) eq $dom) {
 2088:             unless ($tryserver eq $perlvar{'lonHostID'}) {
 2089:                 if ($srch->{'srchby'} eq 'email') {
 2090:                     my $lcrev = &get_server_loncaparev($dom,$tryserver);
 2091:                     my ($major,$minor,$subver) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.(\d+)[\w.\-]+\'?$/);
 2092:                     next if (($major eq '' && $minor eq '') || ($major < 2) ||
 2093:                              (($major == 2) && ($minor < 11)) ||
 2094:                              (($major == 2) && ($minor == 11) && ($subver < 3)));
 2095:                 }
 2096:             }
 2097:             my $host=&hostname($tryserver);
 2098:             my $queryid=
 2099:                 &reply("querysend:".&escape($query).':'.
 2100:                        &escape($srch->{'srchby'}).':'.
 2101:                        &escape($srch->{'srchtype'}).':'.
 2102:                        &escape($srch->{'srchterm'}),$tryserver);
 2103:             if ($queryid !~/^\Q$host\E\_/) {
 2104:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 2105:                 next;
 2106:             }
 2107:             my $reply = &get_query_reply($queryid);
 2108:             my $maxtries = 1;
 2109:             my $tries = 1;
 2110:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 2111:                 $reply = &get_query_reply($queryid);
 2112:                 $tries ++;
 2113:             }
 2114:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 2115:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 2116:             } else {
 2117:                 my @matches;
 2118:                 if ($reply =~ /\n/) {
 2119:                     @matches = split(/\n/,$reply);
 2120:                 } else {
 2121:                     @matches = split(/\&/,$reply);
 2122:                 }
 2123:                 foreach my $match (@matches) {
 2124:                     my ($uname,$udom,%userhash);
 2125:                     foreach my $entry (split(/:/,$match)) {
 2126:                         my ($key,$value) =
 2127:                             map {&unescape($_);} split(/=/,$entry);
 2128:                         $userhash{$key} = $value;
 2129:                         if ($key eq 'username') {
 2130:                             $uname = $value;
 2131:                         } elsif ($key eq 'domain') {
 2132:                             $udom = $value;
 2133:                         }
 2134:                     }
 2135:                     $results{$uname.':'.$udom} = \%userhash;
 2136:                 }
 2137:             }
 2138:         }
 2139:     }
 2140:     return %results;
 2141: }
 2142: 
 2143: sub get_instuser {
 2144:     my ($udom,$uname,$id) = @_;
 2145:     my $homeserver = &domain($udom,'primary');
 2146:     my ($outcome,%results);
 2147:     if ($homeserver ne '') {
 2148:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 2149:                            &escape($id).':'.&escape($udom),$homeserver);
 2150:         my $host=&hostname($homeserver);
 2151:         if ($queryid !~/^\Q$host\E\_/) {
 2152:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 2153:             return;
 2154:         }
 2155:         my $response = &get_query_reply($queryid);
 2156:         my $maxtries = 5;
 2157:         my $tries = 1;
 2158:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 2159:             $response = &get_query_reply($queryid);
 2160:             $tries ++;
 2161:         }
 2162:         if (!&error($response) && $response ne 'refused') {
 2163:             if ($response eq 'unavailable') {
 2164:                 $outcome = $response;
 2165:             } else {
 2166:                 $outcome = 'ok';
 2167:                 my @matches = split(/\n/,$response);
 2168:                 foreach my $match (@matches) {
 2169:                     my ($key,$value) = split(/=/,$match);
 2170:                     $results{&unescape($key)} = &thaw_unescape($value);
 2171:                 }
 2172:             }
 2173:         }
 2174:     }
 2175:     my %userinfo;
 2176:     if (ref($results{$uname}) eq 'HASH') {
 2177:         %userinfo = %{$results{$uname}};
 2178:     } 
 2179:     return ($outcome,%userinfo);
 2180: }
 2181: 
 2182: sub get_multiple_instusers {
 2183:     my ($udom,$users,$caller) = @_;
 2184:     my ($outcome,$results);
 2185:     if (ref($users) eq 'HASH') {
 2186:         my $count = keys(%{$users});
 2187:         my $requested = &freeze_escape($users);
 2188:         my $homeserver = &domain($udom,'primary');
 2189:         if ($homeserver ne '') {
 2190:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
 2191:             my $host=&hostname($homeserver);
 2192:             if ($queryid !~/^\Q$host\E\_/) {
 2193:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
 2194:                          ' for host: '.$homeserver.'in domain '.$udom);
 2195:                 return ($outcome,$results);
 2196:             }
 2197:             my $response = &get_query_reply($queryid);
 2198:             my $maxtries = 5;
 2199:             if ($count > 100) {
 2200:                 $maxtries = 1+int($count/20);
 2201:             }
 2202:             my $tries = 1;
 2203:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
 2204:                 $response = &get_query_reply($queryid);
 2205:                 $tries ++;
 2206:             }
 2207:             if ($response eq '') {
 2208:                 $results = {};
 2209:                 foreach my $key (keys(%{$users})) {
 2210:                     my ($uname,$id);
 2211:                     if ($caller eq 'id') {
 2212:                         $id = $key;
 2213:                     } else {
 2214:                         $uname = $key;
 2215:                     }
 2216:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
 2217:                     $outcome = $resp;
 2218:                     if ($resp eq 'ok') {
 2219:                         %{$results} = (%{$results}, %info);
 2220:                     } else {
 2221:                         last;
 2222:                     }
 2223:                 }
 2224:             } elsif(!&error($response) && ($response ne 'refused')) {
 2225:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
 2226:                     $outcome = $response;
 2227:                 } else {
 2228:                     ($outcome,my $userdata) = split(/=/,$response,2);
 2229:                     if ($outcome eq 'ok') {
 2230:                         $results = &thaw_unescape($userdata);
 2231:                     }
 2232:                 }
 2233:             }
 2234:         }
 2235:     }
 2236:     return ($outcome,$results);
 2237: }
 2238: 
 2239: sub inst_rulecheck {
 2240:     my ($udom,$uname,$id,$item,$rules) = @_;
 2241:     my %returnhash;
 2242:     if ($udom ne '') {
 2243:         if (ref($rules) eq 'ARRAY') {
 2244:             @{$rules} = map {&escape($_);} (@{$rules});
 2245:             my $rulestr = join(':',@{$rules});
 2246:             my $homeserver=&domain($udom,'primary');
 2247:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 2248:                 my $response;
 2249:                 if ($item eq 'username') {                
 2250:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 2251:                                               ':'.&escape($uname).':'.$rulestr,
 2252:                                               $homeserver));
 2253:                 } elsif ($item eq 'id') {
 2254:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 2255:                                               ':'.&escape($id).':'.$rulestr,
 2256:                                               $homeserver));
 2257:                 } elsif ($item eq 'selfcreate') {
 2258:                     $response=&unescape(&reply('instselfcreatecheck:'.
 2259:                                                &escape($udom).':'.&escape($uname).
 2260:                                               ':'.$rulestr,$homeserver));
 2261:                 }
 2262:                 if ($response ne 'refused') {
 2263:                     my @pairs=split(/\&/,$response);
 2264:                     foreach my $item (@pairs) {
 2265:                         my ($key,$value)=split(/=/,$item,2);
 2266:                         $key = &unescape($key);
 2267:                         next if ($key =~ /^error: 2 /);
 2268:                         $returnhash{$key}=&thaw_unescape($value);
 2269:                     }
 2270:                 }
 2271:             }
 2272:         }
 2273:     }
 2274:     return %returnhash;
 2275: }
 2276: 
 2277: sub inst_userrules {
 2278:     my ($udom,$check) = @_;
 2279:     my (%ruleshash,@ruleorder);
 2280:     if ($udom ne '') {
 2281:         my $homeserver=&domain($udom,'primary');
 2282:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 2283:             my $response;
 2284:             if ($check eq 'id') {
 2285:                 $response=&reply('instidrules:'.&escape($udom),
 2286:                                  $homeserver);
 2287:             } elsif ($check eq 'email') {
 2288:                 $response=&reply('instemailrules:'.&escape($udom),
 2289:                                  $homeserver);
 2290:             } else {
 2291:                 $response=&reply('instuserrules:'.&escape($udom),
 2292:                                  $homeserver);
 2293:             }
 2294:             if (($response ne 'refused') && ($response ne 'error') && 
 2295:                 ($response ne 'unknown_cmd') && 
 2296:                 ($response ne 'no_such_host')) {
 2297:                 my ($hashitems,$orderitems) = split(/:/,$response);
 2298:                 my @pairs=split(/\&/,$hashitems);
 2299:                 foreach my $item (@pairs) {
 2300:                     my ($key,$value)=split(/=/,$item,2);
 2301:                     $key = &unescape($key);
 2302:                     next if ($key =~ /^error: 2 /);
 2303:                     $ruleshash{$key}=&thaw_unescape($value);
 2304:                 }
 2305:                 my @esc_order = split(/\&/,$orderitems);
 2306:                 foreach my $item (@esc_order) {
 2307:                     push(@ruleorder,&unescape($item));
 2308:                 }
 2309:             }
 2310:         }
 2311:     }
 2312:     return (\%ruleshash,\@ruleorder);
 2313: }
 2314: 
 2315: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 2316: 
 2317: sub get_domain_defaults {
 2318:     my ($domain,$ignore_cache) = @_;
 2319:     return if (($domain eq '') || ($domain eq 'public'));
 2320:     my $cachetime = 60*60*24;
 2321:     unless ($ignore_cache) {
 2322:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 2323:         if (defined($cached)) {
 2324:             if (ref($result) eq 'HASH') {
 2325:                 return %{$result};
 2326:             }
 2327:         }
 2328:     }
 2329:     my %domdefaults;
 2330:     my %domconfig =
 2331:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
 2332:                                   'requestcourses','inststatus',
 2333:                                   'coursedefaults','usersessions',
 2334:                                   'requestauthor','selfenrollment',
 2335:                                   'coursecategories','autoenroll',
 2336:                                   'helpsettings'],$domain);
 2337:     my @coursetypes = ('official','unofficial','community','textbook');
 2338:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 2339:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 2340:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 2341:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 2342:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 2343:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
 2344:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
 2345:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
 2346:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
 2347:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
 2348:     } else {
 2349:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 2350:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 2351:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 2352:     }
 2353:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 2354:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 2355:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 2356:         } else {
 2357:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 2358:         }
 2359:         my @usertools = ('aboutme','blog','webdav','portfolio');
 2360:         foreach my $item (@usertools) {
 2361:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 2362:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 2363:             }
 2364:         }
 2365:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
 2366:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
 2367:         }
 2368:     }
 2369:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 2370:         foreach my $item ('official','unofficial','community','textbook') {
 2371:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
 2372:         }
 2373:     }
 2374:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
 2375:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
 2376:     }
 2377:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
 2378:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
 2379:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
 2380:         }
 2381:     }
 2382:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
 2383:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
 2384:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
 2385:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
 2386:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
 2387:         }
 2388:         foreach my $type (@coursetypes) {
 2389:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
 2390:                 unless ($type eq 'community') {
 2391:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
 2392:                 }
 2393:             }
 2394:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
 2395:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
 2396:             }
 2397:             if ($domdefaults{'postsubmit'} eq 'on') {
 2398:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
 2399:                     $domdefaults{$type.'postsubtimeout'} =
 2400:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
 2401:                 }
 2402:             }
 2403:         }
 2404:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
 2405:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
 2406:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
 2407:                 if (@clonecodes) {
 2408:                     $domdefaults{'canclone'} = join('+',@clonecodes);
 2409:                 }
 2410:             }
 2411:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
 2412:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
 2413:         }
 2414:         if ($domconfig{'coursedefaults'}{'texengine'}) {
 2415:             $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
 2416:         }
 2417:     }
 2418:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
 2419:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
 2420:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
 2421:         }
 2422:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
 2423:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
 2424:         }
 2425:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
 2426:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
 2427:         }
 2428:         if (ref($domconfig{'usersessions'}{offloadoth'} eq 'HASH') {
 2429:             $domdefaults{'offloadoth'} = $domconfig{'usersessions'}{'offloadoth'};
 2430:         }
 2431:     }
 2432:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
 2433:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
 2434:             my @settings = ('types','registered','enroll_dates','access_dates','section',
 2435:                             'approval','limit');
 2436:             foreach my $type (@coursetypes) {
 2437:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
 2438:                     my @mgrdc = ();
 2439:                     foreach my $item (@settings) {
 2440:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
 2441:                             push(@mgrdc,$item);
 2442:                         }
 2443:                     }
 2444:                     if (@mgrdc) {
 2445:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
 2446:                     }
 2447:                 }
 2448:             }
 2449:         }
 2450:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
 2451:             foreach my $type (@coursetypes) {
 2452:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
 2453:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
 2454:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
 2455:                     }
 2456:                 }
 2457:             }
 2458:         }
 2459:     }
 2460:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 2461:         $domdefaults{'catauth'} = 'std';
 2462:         $domdefaults{'catunauth'} = 'std';
 2463:         if ($domconfig{'coursecategories'}{'auth'}) {
 2464:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
 2465:         }
 2466:         if ($domconfig{'coursecategories'}{'unauth'}) {
 2467:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
 2468:         }
 2469:     }
 2470:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 2471:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
 2472:     }
 2473:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
 2474:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
 2475:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
 2476:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
 2477:         }
 2478:     }
 2479:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
 2480:     return %domdefaults;
 2481: }
 2482: 
 2483: sub get_dom_cats {
 2484:     my ($dom) = @_;
 2485:     return unless (&domain($dom));
 2486:     my ($cats,$cached)=&is_cached_new('cats',$dom);
 2487:     unless (defined($cached)) {
 2488:         my %domconfig = &get_dom('configuration',['coursecategories'],$dom);
 2489:         if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 2490:             if (ref($domconfig{'coursecategories'}{'cats'}) eq 'HASH') {
 2491:                 %{$cats} = %{$domconfig{'coursecategories'}{'cats'}};
 2492:             } else {
 2493:                 $cats = {};
 2494:             }
 2495:         } else {
 2496:             $cats = {};
 2497:         }
 2498:         &Apache::lonnet::do_cache_new('cats',$dom,$cats,3600);
 2499:     }
 2500:     return $cats;
 2501: }
 2502: 
 2503: sub get_dom_instcats {
 2504:     my ($dom) = @_;
 2505:     return unless (&domain($dom));
 2506:     my ($instcats,$cached)=&is_cached_new('instcats',$dom);
 2507:     unless (defined($cached)) {
 2508:         my (%coursecodes,%codes,@codetitles,%cat_titles,%cat_order);
 2509:         my $totcodes = &retrieve_instcodes(\%coursecodes,$dom);
 2510:         if ($totcodes > 0) {
 2511:             my $caller = 'global';
 2512:             if (&auto_instcode_format($caller,$dom,\%coursecodes,\%codes,
 2513:                                       \@codetitles,\%cat_titles,\%cat_order) eq 'ok') {
 2514:                 $instcats = {
 2515:                                 codes => \%codes,
 2516:                                 codetitles => \@codetitles,
 2517:                                 cat_titles => \%cat_titles,
 2518:                                 cat_order => \%cat_order,
 2519:                             };
 2520:                 &do_cache_new('instcats',$dom,$instcats,3600);
 2521:             }
 2522:         }
 2523:     }
 2524:     return $instcats;
 2525: }
 2526: 
 2527: sub retrieve_instcodes {
 2528:     my ($coursecodes,$dom) = @_;
 2529:     my $totcodes;
 2530:     my %courses = &courseiddump($dom,'.',1,'.','.','.',undef,undef,'Course');
 2531:     foreach my $course (keys(%courses)) {
 2532:         if (ref($courses{$course}) eq 'HASH') {
 2533:             if ($courses{$course}{'inst_code'} ne '') {
 2534:                 $$coursecodes{$course} = $courses{$course}{'inst_code'};
 2535:                 $totcodes ++;
 2536:             }
 2537:         }
 2538:     }
 2539:     return $totcodes;
 2540: }
 2541: 
 2542: # --------------------------------------------- Get domain config for passwords
 2543: 
 2544: sub get_passwdconf {
 2545:     my ($dom) = @_;
 2546:     my (%passwdconf,$gotconf,$lookup);
 2547:     my ($result,$cached)=&is_cached_new('passwdconf',$dom);
 2548:     if (defined($cached)) {
 2549:         if (ref($result) eq 'HASH') {
 2550:             %passwdconf = %{$result};
 2551:             $gotconf = 1;
 2552:         }
 2553:     }
 2554:     unless ($gotconf) {
 2555:         my %domconfig = &get_dom('configuration',['passwords'],$dom);
 2556:         if (ref($domconfig{'passwords'}) eq 'HASH') {
 2557:             %passwdconf = %{$domconfig{'passwords'}};
 2558:         }
 2559:         my $cachetime = 24*60*60;
 2560:         &do_cache_new('passwdconf',$dom,\%passwdconf,$cachetime);
 2561:     }
 2562:     return %passwdconf;
 2563: }
 2564: 
 2565: # --------------------------------------------------- Assign a key to a student
 2566: 
 2567: sub assign_access_key {
 2568: #
 2569: # a valid key looks like uname:udom#comments
 2570: # comments are being appended
 2571: #
 2572:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 2573:     $kdom=
 2574:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 2575:     $knum=
 2576:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 2577:     $cdom=
 2578:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2579:     $cnum=
 2580:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2581:     $udom=$env{'user.name'} unless (defined($udom));
 2582:     $uname=$env{'user.domain'} unless (defined($uname));
 2583:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 2584:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 2585:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 2586:                                                   # assigned to this person
 2587:                                                   # - this should not happen,
 2588:                                                   # unless something went wrong
 2589:                                                   # the first time around
 2590: # ready to assign
 2591:         $logentry=$1.'; '.$logentry;
 2592:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 2593:                                                  $kdom,$knum) eq 'ok') {
 2594: # key now belongs to user
 2595: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 2596:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 2597:                 &appenv({'environment.'.$envkey => $ckey});
 2598:                 return 'ok';
 2599:             } else {
 2600:                 return 
 2601:   'error: Count not permanently assign key, will need to be re-entered later.';
 2602: 	    }
 2603:         } else {
 2604:             return 'error: Could not assign key, try again later.';
 2605:         }
 2606:     } elsif (!$existing{$ckey}) {
 2607: # the key does not exist
 2608: 	return 'error: The key does not exist';
 2609:     } else {
 2610: # the key is somebody else's
 2611: 	return 'error: The key is already in use';
 2612:     }
 2613: }
 2614: 
 2615: # ------------------------------------------ put an additional comment on a key
 2616: 
 2617: sub comment_access_key {
 2618: #
 2619: # a valid key looks like uname:udom#comments
 2620: # comments are being appended
 2621: #
 2622:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 2623:     $cdom=
 2624:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2625:     $cnum=
 2626:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2627:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2628:     if ($existing{$ckey}) {
 2629:         $existing{$ckey}.='; '.$logentry;
 2630: # ready to assign
 2631:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 2632:                                                  $cdom,$cnum) eq 'ok') {
 2633: 	    return 'ok';
 2634:         } else {
 2635: 	    return 'error: Count not store comment.';
 2636:         }
 2637:     } else {
 2638: # the key does not exist
 2639: 	return 'error: The key does not exist';
 2640:     }
 2641: }
 2642: 
 2643: # ------------------------------------------------------ Generate a set of keys
 2644: 
 2645: sub generate_access_keys {
 2646:     my ($number,$cdom,$cnum,$logentry)=@_;
 2647:     $cdom=
 2648:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2649:     $cnum=
 2650:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2651:     unless (&allowed('mky',$cdom)) { return 0; }
 2652:     unless (($cdom) && ($cnum)) { return 0; }
 2653:     if ($number>10000) { return 0; }
 2654:     sleep(2); # make sure don't get same seed twice
 2655:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 2656:     my $total=0;
 2657:     for (my $i=1;$i<=$number;$i++) {
 2658:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 2659:                   sprintf("%lx",int(100000*rand)).'-'.
 2660:                   sprintf("%lx",int(100000*rand));
 2661:        $newkey=~s/1/g/g; # folks mix up 1 and l
 2662:        $newkey=~s/0/h/g; # and also 0 and O
 2663:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 2664:        if ($existing{$newkey}) {
 2665:            $i--;
 2666:        } else {
 2667: 	  if (&put('accesskeys',
 2668:               { $newkey => '# generated '.localtime().
 2669:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 2670:                            '; '.$logentry },
 2671: 		   $cdom,$cnum) eq 'ok') {
 2672:               $total++;
 2673: 	  }
 2674:        }
 2675:     }
 2676:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 2677:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 2678:     return $total;
 2679: }
 2680: 
 2681: # ------------------------------------------------------- Validate an accesskey
 2682: 
 2683: sub validate_access_key {
 2684:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 2685:     $cdom=
 2686:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2687:     $cnum=
 2688:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2689:     $udom=$env{'user.domain'} unless (defined($udom));
 2690:     $uname=$env{'user.name'} unless (defined($uname));
 2691:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2692:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 2693: }
 2694: 
 2695: # ------------------------------------- Find the section of student in a course
 2696: sub devalidate_getsection_cache {
 2697:     my ($udom,$unam,$courseid)=@_;
 2698:     my $hashid="$udom:$unam:$courseid";
 2699:     &devalidate_cache_new('getsection',$hashid);
 2700: }
 2701: 
 2702: sub courseid_to_courseurl {
 2703:     my ($courseid) = @_;
 2704:     #already url style courseid
 2705:     return $courseid if ($courseid =~ m{^/});
 2706: 
 2707:     if (exists($env{'course.'.$courseid.'.num'})) {
 2708: 	my $cnum = $env{'course.'.$courseid.'.num'};
 2709: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 2710: 	return "/$cdom/$cnum";
 2711:     }
 2712: 
 2713:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 2714:     if (exists($courseinfo{'num'})) {
 2715: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 2716:     }
 2717: 
 2718:     return undef;
 2719: }
 2720: 
 2721: sub getsection {
 2722:     my ($udom,$unam,$courseid)=@_;
 2723:     my $cachetime=1800;
 2724: 
 2725:     my $hashid="$udom:$unam:$courseid";
 2726:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 2727:     if (defined($cached)) { return $result; }
 2728: 
 2729:     my %Pending; 
 2730:     my %Expired;
 2731:     #
 2732:     # Each role can either have not started yet (pending), be active, 
 2733:     #    or have expired.
 2734:     #
 2735:     # If there is an active role, we are done.
 2736:     #
 2737:     # If there is more than one role which has not started yet, 
 2738:     #     choose the one which will start sooner
 2739:     # If there is one role which has not started yet, return it.
 2740:     #
 2741:     # If there is more than one expired role, choose the one which ended last.
 2742:     # If there is a role which has expired, return it.
 2743:     #
 2744:     $courseid = &courseid_to_courseurl($courseid);
 2745:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 2746:     foreach my $key (keys(%roleshash)) {
 2747:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 2748:         my $section=$1;
 2749:         if ($key eq $courseid.'_st') { $section=''; }
 2750:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 2751:         my $now=time;
 2752:         if (defined($end) && $end && ($now > $end)) {
 2753:             $Expired{$end}=$section;
 2754:             next;
 2755:         }
 2756:         if (defined($start) && $start && ($now < $start)) {
 2757:             $Pending{$start}=$section;
 2758:             next;
 2759:         }
 2760:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 2761:     }
 2762:     #
 2763:     # Presumedly there will be few matching roles from the above
 2764:     # loop and the sorting time will be negligible.
 2765:     if (scalar(keys(%Pending))) {
 2766:         my ($time) = sort {$a <=> $b} keys(%Pending);
 2767:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 2768:     } 
 2769:     if (scalar(keys(%Expired))) {
 2770:         my @sorted = sort {$a <=> $b} keys(%Expired);
 2771:         my $time = pop(@sorted);
 2772:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 2773:     }
 2774:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 2775: }
 2776: 
 2777: sub save_cache {
 2778:     &purge_remembered();
 2779:     #&Apache::loncommon::validate_page();
 2780:     undef(%env);
 2781:     undef($env_loaded);
 2782: }
 2783: 
 2784: my $to_remember=-1;
 2785: my %remembered;
 2786: my %accessed;
 2787: my $kicks=0;
 2788: my $hits=0;
 2789: sub make_key {
 2790:     my ($name,$id) = @_;
 2791:     if (length($id) > 65 
 2792: 	&& length(&escape($id)) > 200) {
 2793: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 2794:     }
 2795:     return &escape($name.':'.$id);
 2796: }
 2797: 
 2798: sub devalidate_cache_new {
 2799:     my ($name,$id,$debug) = @_;
 2800:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 2801:     my $remembered_id=$name.':'.$id;
 2802:     $id=&make_key($name,$id);
 2803:     $memcache->delete($id);
 2804:     delete($remembered{$remembered_id});
 2805:     delete($accessed{$remembered_id});
 2806: }
 2807: 
 2808: sub is_cached_new {
 2809:     my ($name,$id,$debug) = @_;
 2810:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) for 
 2811:                                      # keys in %remembered hash, which persists for
 2812:                                      # duration of request (no restriction on key length).
 2813:     if (exists($remembered{$remembered_id})) {
 2814: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
 2815: 	$accessed{$remembered_id}=[&gettimeofday()];
 2816: 	$hits++;
 2817: 	return ($remembered{$remembered_id},1);
 2818:     }
 2819:     $id=&make_key($name,$id);
 2820:     my $value = $memcache->get($id);
 2821:     if (!(defined($value))) {
 2822: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 2823: 	return (undef,undef);
 2824:     }
 2825:     if ($value eq '__undef__') {
 2826: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 2827: 	$value=undef;
 2828:     }
 2829:     &make_room($remembered_id,$value,$debug);
 2830:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 2831:     return ($value,1);
 2832: }
 2833: 
 2834: sub do_cache_new {
 2835:     my ($name,$id,$value,$time,$debug) = @_;
 2836:     my $remembered_id=$name.':'.$id;
 2837:     $id=&make_key($name,$id);
 2838:     my $setvalue=$value;
 2839:     if (!defined($setvalue)) {
 2840: 	$setvalue='__undef__';
 2841:     }
 2842:     if (!defined($time) ) {
 2843: 	$time=600;
 2844:     }
 2845:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 2846:     my $result = $memcache->set($id,$setvalue,$time);
 2847:     if (! $result) {
 2848: 	&logthis("caching of id -> $id  failed");
 2849: 	$memcache->disconnect_all();
 2850:     }
 2851:     # need to make a copy of $value
 2852:     &make_room($remembered_id,$value,$debug);
 2853:     return $value;
 2854: }
 2855: 
 2856: sub make_room {
 2857:     my ($remembered_id,$value,$debug)=@_;
 2858: 
 2859:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
 2860:                                     : $value;
 2861:     if ($to_remember<0) { return; }
 2862:     $accessed{$remembered_id}=[&gettimeofday()];
 2863:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 2864:     my $to_kick;
 2865:     my $max_time=0;
 2866:     foreach my $other (keys(%accessed)) {
 2867: 	if (&tv_interval($accessed{$other}) > $max_time) {
 2868: 	    $to_kick=$other;
 2869: 	    $max_time=&tv_interval($accessed{$other});
 2870: 	}
 2871:     }
 2872:     delete($remembered{$to_kick});
 2873:     delete($accessed{$to_kick});
 2874:     $kicks++;
 2875:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 2876:     return;
 2877: }
 2878: 
 2879: sub purge_remembered {
 2880:     #&logthis("Tossing ".scalar(keys(%remembered)));
 2881:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 2882:     undef(%remembered);
 2883:     undef(%accessed);
 2884: }
 2885: # ------------------------------------- Read an entry from a user's environment
 2886: 
 2887: sub userenvironment {
 2888:     my ($udom,$unam,@what)=@_;
 2889:     my $items;
 2890:     foreach my $item (@what) {
 2891:         $items.=&escape($item).'&';
 2892:     }
 2893:     $items=~s/\&$//;
 2894:     my %returnhash=();
 2895:     my $uhome = &homeserver($unam,$udom);
 2896:     unless ($uhome eq 'no_host') {
 2897:         my @answer=split(/\&/, 
 2898:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
 2899:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
 2900:             return %returnhash;
 2901:         }
 2902:         my $i;
 2903:         for ($i=0;$i<=$#what;$i++) {
 2904: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
 2905:         }
 2906:     }
 2907:     return %returnhash;
 2908: }
 2909: 
 2910: # ---------------------------------------------------------- Get a studentphoto
 2911: sub studentphoto {
 2912:     my ($udom,$unam,$ext) = @_;
 2913:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 2914:     if (defined($env{'request.course.id'})) {
 2915:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 2916:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 2917:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 2918:             } else {
 2919:                 my ($result,$perm_reqd)=
 2920: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 2921:                 if ($result eq 'ok') {
 2922:                     if (!($perm_reqd eq 'yes')) {
 2923:                         return(&retrievestudentphoto($udom,$unam,$ext));
 2924:                     }
 2925:                 }
 2926:             }
 2927:         }
 2928:     } else {
 2929:         my ($result,$perm_reqd) = 
 2930: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 2931:         if ($result eq 'ok') {
 2932:             if (!($perm_reqd eq 'yes')) {
 2933:                 return(&retrievestudentphoto($udom,$unam,$ext));
 2934:             }
 2935:         }
 2936:     }
 2937:     return '/adm/lonKaputt/lonlogo_broken.gif';
 2938: }
 2939: 
 2940: sub retrievestudentphoto {
 2941:     my ($udom,$unam,$ext,$type) = @_;
 2942:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 2943:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 2944:     if ($ret eq 'ok') {
 2945:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 2946:         if ($type eq 'thumbnail') {
 2947:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 2948:         }
 2949:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 2950:         return $tokenurl;
 2951:     } else {
 2952:         if ($type eq 'thumbnail') {
 2953:             return '/adm/lonKaputt/genericstudent_tn.gif';
 2954:         } else { 
 2955:             return '/adm/lonKaputt/lonlogo_broken.gif';
 2956:         }
 2957:     }
 2958: }
 2959: 
 2960: # -------------------------------------------------------------------- New chat
 2961: 
 2962: sub chatsend {
 2963:     my ($newentry,$anon,$group)=@_;
 2964:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 2965:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2966:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 2967:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 2968: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 2969: 		   &escape($newentry)).':'.$group,$chome);
 2970: }
 2971: 
 2972: # ------------------------------------------ Find current version of a resource
 2973: 
 2974: sub getversion {
 2975:     my $fname=&clutter(shift);
 2976:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
 2977:     return &currentversion(&filelocation('',$fname));
 2978: }
 2979: 
 2980: sub currentversion {
 2981:     my $fname=shift;
 2982:     my $author=$fname;
 2983:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2984:     my ($udom,$uname)=split(/\//,$author);
 2985:     my $home=&homeserver($uname,$udom);
 2986:     if ($home eq 'no_host') { 
 2987:         return -1; 
 2988:     }
 2989:     my $answer=&reply("currentversion:$fname",$home);
 2990:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 2991: 	return -1;
 2992:     }
 2993:     return $answer;
 2994: }
 2995: 
 2996: #
 2997: # Return special version number of resource if set by override, empty otherwise
 2998: #
 2999: sub usedversion {
 3000:     my $fname=shift;
 3001:     unless ($fname) { $fname=$env{'request.uri'}; }
 3002:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
 3003:     if ($urlversion) { return $urlversion; }
 3004:     return '';
 3005: }
 3006: 
 3007: # ----------------------------- Subscribe to a resource, return URL if possible
 3008: 
 3009: sub subscribe {
 3010:     my $fname=shift;
 3011:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 3012:     $fname=~s/[\n\r]//g;
 3013:     my $author=$fname;
 3014:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3015:     my ($udom,$uname)=split(/\//,$author);
 3016:     my $home=homeserver($uname,$udom);
 3017:     if ($home eq 'no_host') {
 3018:         return 'not_found';
 3019:     }
 3020:     my $answer=reply("sub:$fname",$home);
 3021:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 3022: 	$answer.=' by '.$home;
 3023:     }
 3024:     return $answer;
 3025: }
 3026:     
 3027: # -------------------------------------------------------------- Replicate file
 3028: 
 3029: sub repcopy {
 3030:     my $filename=shift;
 3031:     $filename=~s/\/+/\//g;
 3032:     my $londocroot = $perlvar{'lonDocRoot'};
 3033:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
 3034:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
 3035:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
 3036: 	$filename=~m{^/*(uploaded|editupload)/}) {
 3037: 	return &repcopy_userfile($filename);
 3038:     }
 3039:     $filename=~s/[\n\r]//g;
 3040:     my $transname="$filename.in.transfer";
 3041: # FIXME: this should flock
 3042:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 3043:     my $remoteurl=subscribe($filename);
 3044:     if ($remoteurl =~ /^con_lost by/) {
 3045: 	   &logthis("Subscribe returned $remoteurl: $filename");
 3046:            return 'unavailable';
 3047:     } elsif ($remoteurl eq 'not_found') {
 3048: 	   #&logthis("Subscribe returned not_found: $filename");
 3049: 	   return 'not_found';
 3050:     } elsif ($remoteurl =~ /^rejected by/) {
 3051: 	   &logthis("Subscribe returned $remoteurl: $filename");
 3052:            return 'forbidden';
 3053:     } elsif ($remoteurl eq 'directory') {
 3054:            return 'ok';
 3055:     } else {
 3056:         my $author=$filename;
 3057:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3058:         my ($udom,$uname)=split(/\//,$author);
 3059:         my $home=homeserver($uname,$udom);
 3060:         unless ($home eq $perlvar{'lonHostID'}) {
 3061:            my @parts=split(/\//,$filename);
 3062:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 3063:            if ($path ne "$londocroot/res") {
 3064:                &logthis("Malconfiguration for replication: $filename");
 3065: 	       return 'bad_request';
 3066:            }
 3067:            my $count;
 3068:            for ($count=5;$count<$#parts;$count++) {
 3069:                $path.="/$parts[$count]";
 3070:                if ((-e $path)!=1) {
 3071: 		   mkdir($path,0777);
 3072:                }
 3073:            }
 3074:            my $ua=new LWP::UserAgent;
 3075:            my $request=new HTTP::Request('GET',"$remoteurl");
 3076:            my $response=$ua->request($request,$transname);
 3077:            if ($response->is_error()) {
 3078: 	       unlink($transname);
 3079:                my $message=$response->status_line;
 3080:                &logthis("<font color=\"blue\">WARNING:"
 3081:                        ." LWP get: $message: $filename</font>");
 3082:                return 'unavailable';
 3083:            } else {
 3084: 	       if ($remoteurl!~/\.meta$/) {
 3085:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 3086:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
 3087:                   if ($mresponse->is_error()) {
 3088: 		      unlink($filename.'.meta');
 3089:                       &logthis(
 3090:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 3091:                   }
 3092: 	       }
 3093:                rename($transname,$filename);
 3094:                return 'ok';
 3095:            }
 3096:        }
 3097:     }
 3098: }
 3099: 
 3100: # ------------------------------------------------- Unsubscribe from a resource
 3101: 
 3102: sub unsubscribe {
 3103:     my ($fname) = @_;
 3104:     my $answer;
 3105:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return $answer; }
 3106:     $fname=~s/[\n\r]//g;
 3107:     my $author=$fname;
 3108:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3109:     my ($udom,$uname)=split(/\//,$author);
 3110:     my $home=homeserver($uname,$udom);
 3111:     if ($home eq 'no_host') {
 3112:         $answer = 'no_host';
 3113:     } elsif (grep { $_ eq $home } &current_machine_ids()) {
 3114:         $answer = 'home';
 3115:     } else {
 3116:         $answer = reply("unsub:$fname",$home);
 3117:     }
 3118:     return $answer;
 3119: }
 3120: 
 3121: # ------------------------------------------------ Get server side include body
 3122: sub ssi_body {
 3123:     my ($filelink,%form)=@_;
 3124:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 3125:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 3126:     }
 3127:     my $output='';
 3128:     my $response;
 3129:     if ($filelink=~/^https?\:/) {
 3130:        ($output,$response)=&externalssi($filelink);
 3131:     } else {
 3132:        $filelink .= $filelink=~/\?/ ? '&' : '?';
 3133:        $filelink .= 'inhibitmenu=yes';
 3134:        ($output,$response)=&ssi($filelink,%form);
 3135:     }
 3136:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 3137:     $output=~s/^.*?\<body[^\>]*\>//si;
 3138:     $output=~s/\<\/body\s*\>.*?$//si;
 3139:     if (wantarray) {
 3140:         return ($output, $response);
 3141:     } else {
 3142:         return $output;
 3143:     }
 3144: }
 3145: 
 3146: # --------------------------------------------------------- Server Side Include
 3147: 
 3148: sub absolute_url {
 3149:     my ($host_name) = @_;
 3150:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 3151:     if ($host_name eq '') {
 3152: 	$host_name = $ENV{'SERVER_NAME'};
 3153:     }
 3154:     return $protocol.$host_name;
 3155: }
 3156: 
 3157: #
 3158: #   Server side include.
 3159: # Parameters:
 3160: #  fn     Possibly encrypted resource name/id.
 3161: #  form   Hash that describes how the rendering should be done
 3162: #         and other things.
 3163: # Returns:
 3164: #   Scalar context: The content of the response.
 3165: #   Array context:  2 element list of the content and the full response object.
 3166: #     
 3167: sub ssi {
 3168: 
 3169:     my ($fn,%form)=@_;
 3170:     my ($request,$response);
 3171: 
 3172:     $form{'no_update_last_known'}=1;
 3173:     &Apache::lonenc::check_encrypt(\$fn);
 3174:     if (%form) {
 3175:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 3176:       $request->content(join('&',map {
 3177:             my $name = escape($_);
 3178:             "$name=" . ( ref($form{$_}) eq 'ARRAY'
 3179:             ? join("&$name=", map {escape($_) } @{$form{$_}})
 3180:             : &escape($form{$_}) );
 3181:         } keys(%form)));
 3182:     } else {
 3183:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 3184:     }
 3185: 
 3186:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 3187: 
 3188:     if (($env{'request.course.id'}) &&
 3189:         ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
 3190:         ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
 3191:         ($form{'grade_symb'} ne '') &&
 3192:         (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
 3193:                                  ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
 3194:         if (LWP::UserAgent->VERSION >= 5.834) {
 3195:             my $ua=new LWP::UserAgent;
 3196:             $ua->local_address('127.0.0.1');
 3197:             $response = $ua->request($request);
 3198:         } else {
 3199:             {
 3200:                 require LWP::Protocol::http;
 3201:                 local @LWP::Protocol::http::EXTRA_SOCK_OPTS = (LocalAddr => '127.0.0.1');
 3202:                 my $ua=new LWP::UserAgent;
 3203:                 $response = $ua->request($request);
 3204:                 @LWP::Protocol::http::EXTRA_SOCK_OPTS = ();
 3205:             }
 3206:         }
 3207:     } else {
 3208:         my $ua=new LWP::UserAgent;
 3209:         $response = $ua->request($request);
 3210:     }
 3211:     if (wantarray) {
 3212: 	return ($response->content, $response);
 3213:     } else {
 3214: 	return $response->content;
 3215:     }
 3216: }
 3217: 
 3218: sub externalssi {
 3219:     my ($url)=@_;
 3220:     my $ua=new LWP::UserAgent;
 3221:     my $request=new HTTP::Request('GET',$url);
 3222:     my $response=$ua->request($request);
 3223:     if (wantarray) {
 3224:         return ($response->content, $response);
 3225:     } else {
 3226:         return $response->content;
 3227:     }
 3228: }
 3229: 
 3230: # If the local copy of a replicated resource is outdated, trigger a
 3231: # connection from the homeserver to flush the delayed queue. If no update
 3232: # happens, remove local copies of outdated resource (and corresponding
 3233: # metadata file).
 3234: 
 3235: sub remove_stale_resfile {
 3236:     my ($url) = @_;
 3237:     my $removed;
 3238:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
 3239:         my $audom = $1;
 3240:         my $auname = $2;
 3241:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
 3242:             my $homeserver = &homeserver($auname,$audom);
 3243:             unless (($homeserver eq 'no_host') ||
 3244:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
 3245:                 my $fname = &filelocation('',$url);
 3246:                 if (-e $fname) {
 3247:                     my $hostname = &hostname($homeserver);
 3248:                     if ($hostname) {
 3249:                         my $protocol = $protocol{$homeserver};
 3250:                         $protocol = 'http' if ($protocol ne 'https');
 3251:                         my $uri = $protocol.'://'.$hostname.'/raw/'.&declutter($url);
 3252:                         my $ua=new LWP::UserAgent;
 3253:                         $ua->timeout(5);
 3254:                         my $request=new HTTP::Request('HEAD',$uri);
 3255:                         my $response=$ua->request($request);
 3256:                         if ($response->is_success()) {
 3257:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
 3258:                             my $locmodtime = (stat($fname))[9];
 3259:                             if ($locmodtime < $remmodtime) {
 3260:                                 my $stale;
 3261:                                 my $answer = &reply('pong',$homeserver);
 3262:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
 3263:                                     sleep(0.2);
 3264:                                     $locmodtime = (stat($fname))[9];
 3265:                                     if ($locmodtime < $remmodtime) {
 3266:                                         my $posstransfer = $fname.'.in.transfer';
 3267:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
 3268:                                             $removed = 1;
 3269:                                         } else {
 3270:                                             $stale = 1;
 3271:                                         }
 3272:                                     } else {
 3273:                                         $removed = 1;
 3274:                                     }
 3275:                                 } else {
 3276:                                     $stale = 1;
 3277:                                 }
 3278:                                 if ($stale) {
 3279:                                     if (unlink($fname)) {
 3280:                                         if ($uri!~/\.meta$/) {
 3281:                                             if (-e $fname.'.meta') {
 3282:                                                 unlink($fname.'.meta');
 3283:                                             }
 3284:                                         }
 3285:                                         my $unsubresult = &unsubscribe($fname);
 3286:                                         unless ($unsubresult eq 'ok') {
 3287:                                             &logthis("no unsub of $fname from $homeserver, reason: $unsubresult");
 3288:                                         }
 3289:                                         $removed = 1;
 3290:                                     }
 3291:                                 }
 3292:                             }
 3293:                         }
 3294:                     }
 3295:                 }
 3296:             }
 3297:         }
 3298:     }
 3299:     return $removed;
 3300: }
 3301: 
 3302: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 3303: 
 3304: sub allowuploaded {
 3305:     my ($srcurl,$url)=@_;
 3306:     $url=&clutter(&declutter($url));
 3307:     my $dir=$url;
 3308:     $dir=~s/\/[^\/]+$//;
 3309:     my %httpref=();
 3310:     my $httpurl=&hreflocation('',$url);
 3311:     $httpref{'httpref.'.$httpurl}=$srcurl;
 3312:     &Apache::lonnet::appenv(\%httpref);
 3313: }
 3314: 
 3315: #
 3316: # Determine if the current user should be able to edit a particular resource,
 3317: # when viewing in course context.
 3318: # (a) When viewing resource used to determine if "Edit" item is included in
 3319: #     Functions.
 3320: # (b) When displaying folder contents in course editor, used to determine if
 3321: #     "Edit" link will be displayed alongside resource.
 3322: #
 3323: #  input: six args -- filename (decluttered), course number, course domain,
 3324: #                   url, symb (if registered) and group (if this is a group
 3325: #                   item -- e.g., bulletin board, group page etc.).
 3326: #  output: array of five scalars --
 3327: #          $cfile -- url for file editing if editable on current server
 3328: #          $home -- homeserver of resource (i.e., for author if published,
 3329: #                                           or course if uploaded.).
 3330: #          $switchserver --  1 if server switch will be needed.
 3331: #          $forceedit -- 1 if icon/link should be to go to edit mode
 3332: #          $forceview -- 1 if icon/link should be to go to view mode
 3333: #
 3334: 
 3335: sub can_edit_resource {
 3336:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
 3337:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
 3338: #
 3339: # For aboutme pages user can only edit his/her own.
 3340: #
 3341:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
 3342:         my ($sdom,$sname) = ($1,$2);
 3343:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
 3344:             $home = $env{'user.home'};
 3345:             $cfile = $resurl;
 3346:             if ($env{'form.forceedit'}) {
 3347:                 $forceview = 1;
 3348:             } else {
 3349:                 $forceedit = 1;
 3350:             }
 3351:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
 3352:         } else {
 3353:             return;
 3354:         }
 3355:     }
 3356: 
 3357:     if ($env{'request.course.id'}) {
 3358:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
 3359:         if ($group ne '') {
 3360: # if this is a group homepage or group bulletin board, check group privs
 3361:             my $allowed = 0;
 3362:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
 3363:                 if ((&allowed('mdg',$env{'request.course.id'}.
 3364:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 3365:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 3366:                     $allowed = 1;
 3367:                 }
 3368:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
 3369:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 3370:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 3371:                     $allowed = 1;
 3372:                 }
 3373:             }
 3374:             if ($allowed) {
 3375:                 $home=&homeserver($cnum,$cdom);
 3376:                 if ($env{'form.forceedit'}) {
 3377:                     $forceview = 1;
 3378:                 } else {
 3379:                     $forceedit = 1;
 3380:                 }
 3381:                 $cfile = $resurl;
 3382:             } else {
 3383:                 return;
 3384:             }
 3385:         } else {
 3386:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
 3387:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
 3388:                     return;
 3389:                 }
 3390:             } elsif (!$crsedit) {
 3391: #
 3392: # No edit allowed where CC has switched to student role.
 3393: #
 3394:                 return;
 3395:             }
 3396:         }
 3397:     }
 3398: 
 3399:     if ($file ne '') {
 3400:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
 3401:             if (&is_course_upload($file,$cnum,$cdom)) {
 3402:                 $uploaded = 1;
 3403:                 $incourse = 1;
 3404:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
 3405:                     $cfile = &hreflocation('',$file);
 3406:                     if ($env{'form.forceedit'}) {
 3407:                         $forceview = 1;
 3408:                     } else {
 3409:                         $forceedit = 1;
 3410:                     }
 3411:                 }
 3412:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
 3413:                 $incourse = 1;
 3414:                 if ($env{'form.forceedit'}) {
 3415:                     $forceview = 1;
 3416:                 } else {
 3417:                     $forceedit = 1;
 3418:                 }
 3419:                 $cfile = $resurl;
 3420:             } elsif (($resurl ne '') && (&is_on_map($resurl))) {
 3421:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
 3422:                     $incourse = 1;
 3423:                     if ($env{'form.forceedit'}) {
 3424:                         $forceview = 1;
 3425:                     } else {
 3426:                         $forceedit = 1;
 3427:                     }
 3428:                     $cfile = $resurl;
 3429:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
 3430:                     $incourse = 1;
 3431:                     $cfile = $resurl.'/smpedit';
 3432:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
 3433:                     $incourse = 1;
 3434:                     if ($env{'form.forceedit'}) {
 3435:                         $forceview = 1;
 3436:                     } else {
 3437:                         $forceedit = 1;
 3438:                     }
 3439:                     $cfile = $resurl;
 3440:                 } elsif (($resurl =~ m{^/ext/}) && ($symb ne '')) {
 3441:                     my ($map,$id,$res) = &decode_symb($symb);
 3442:                     if ($map =~ /\.page$/) {
 3443:                         $incourse = 1;
 3444:                         if ($env{'form.forceedit'}) {
 3445:                             $forceview = 1;
 3446:                             $cfile = $map;
 3447:                         } else {
 3448:                             $forceedit = 1;
 3449:                             $cfile =  '/adm/wrapper'.$resurl;
 3450:                         }
 3451:                     }
 3452:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 3453:                     $incourse = 1;
 3454:                     if ($env{'form.forceedit'}) {
 3455:                         $forceview = 1;
 3456:                     } else {
 3457:                         $forceedit = 1;
 3458:                     }
 3459:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 3460:                 }
 3461:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
 3462:                 my $template = '/res/lib/templates/simpleproblem.problem';
 3463:                 if (&is_on_map($template)) {
 3464:                     $incourse = 1;
 3465:                     $forceview = 1;
 3466:                     $cfile = $template;
 3467:                 }
 3468:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 3469:                 $incourse = 1;
 3470:                 if ($env{'form.forceedit'}) {
 3471:                     $forceview = 1;
 3472:                 } else {
 3473:                     $forceedit = 1;
 3474:                 }
 3475:                 $cfile = $resurl;
 3476:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
 3477:                 $incourse = 1;
 3478:                 $forceview = 1;
 3479:                 if ($symb) {
 3480:                     my ($map,$id,$res)=&decode_symb($symb);
 3481:                     $env{'request.symb'} = $symb;
 3482:                     $cfile = &clutter($res);
 3483:                 } else {
 3484:                     $cfile = $env{'form.suppurl'};
 3485:                     $cfile =~ s{^http://}{};
 3486:                     $cfile = '/adm/wrapper/ext/'.$cfile;
 3487:                 }
 3488:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 3489:                 if ($env{'form.forceedit'}) {
 3490:                     $forceview = 1;
 3491:                 } else {
 3492:                     $forceedit = 1;
 3493:                 }
 3494:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 3495:             }
 3496:         }
 3497:         if ($uploaded || $incourse) {
 3498:             $home=&homeserver($cnum,$cdom);
 3499:         } elsif ($file !~ m{/$}) {
 3500:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
 3501:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
 3502:             # Check that the user has permission to edit this resource
 3503:             my $setpriv = 1;
 3504:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
 3505:             if (defined($cfudom)) {
 3506:                 $home=&homeserver($cfuname,$cfudom);
 3507:                 $cfile=$file;
 3508:             }
 3509:         }
 3510:         if (($cfile ne '') && (!$incourse || $uploaded) &&
 3511:             (($home ne '') && ($home ne 'no_host'))) {
 3512:             my @ids=&current_machine_ids();
 3513:             unless (grep(/^\Q$home\E$/,@ids)) {
 3514:                 $switchserver=1;
 3515:             }
 3516:         }
 3517:     }
 3518:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
 3519: }
 3520: 
 3521: sub is_course_upload {
 3522:     my ($file,$cnum,$cdom) = @_;
 3523:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
 3524:     $uploadpath =~ s{^\/}{};
 3525:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
 3526:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
 3527:         return 1;
 3528:     }
 3529:     return;
 3530: }
 3531: 
 3532: sub in_course {
 3533:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
 3534:     if ($hideprivileged) {
 3535:         my $skipuser;
 3536:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
 3537:         my @possdoms = ($cdom);
 3538:         if ($coursehash{'checkforpriv'}) {
 3539:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
 3540:         }
 3541:         if (&privileged($uname,$udom,\@possdoms)) {
 3542:             $skipuser = 1;
 3543:             if ($coursehash{'nothideprivileged'}) {
 3544:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3545:                     my $user;
 3546:                     if ($item =~ /:/) {
 3547:                         $user = $item;
 3548:                     } else {
 3549:                         $user = join(':',split(/[\@]/,$item));
 3550:                     }
 3551:                     if ($user eq $uname.':'.$udom) {
 3552:                         undef($skipuser);
 3553:                         last;
 3554:                     }
 3555:                 }
 3556:             }
 3557:             if ($skipuser) {
 3558:                 return 0;
 3559:             }
 3560:         }
 3561:     }
 3562:     $type ||= 'any';
 3563:     if (!defined($cdom) || !defined($cnum)) {
 3564:         my $cid  = $env{'request.course.id'};
 3565:         $cdom = $env{'course.'.$cid.'.domain'};
 3566:         $cnum = $env{'course.'.$cid.'.num'};
 3567:     }
 3568:     my $typesref;
 3569:     if (($type eq 'any') || ($type eq 'all')) {
 3570:         $typesref = ['active','previous','future'];
 3571:     } elsif ($type eq 'previous' || $type eq 'future') {
 3572:         $typesref = [$type];
 3573:     }
 3574:     my %roles = &get_my_roles($uname,$udom,'userroles',
 3575:                               $typesref,undef,[$cdom]);
 3576:     my ($tmp) = keys(%roles);
 3577:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
 3578:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
 3579:     if (@course_roles > 0) {
 3580:         return 1;
 3581:     }
 3582:     return 0;
 3583: }
 3584: 
 3585: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 3586: # input: action, courseID, current domain, intended
 3587: #        path to file, source of file, instruction to parse file for objects,
 3588: #        ref to hash for embedded objects,
 3589: #        ref to hash for codebase of java objects.
 3590: #        reference to scalar to accommodate mime type determined
 3591: #          from File::MMagic if $parser = parse.
 3592: #
 3593: # output: url to file (if action was uploaddoc), 
 3594: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 3595: #
 3596: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 3597: # course.
 3598: #
 3599: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3600: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 3601: #          course's home server.
 3602: #
 3603: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 3604: #          be copied from $source (current location) to 
 3605: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3606: #         and will then be copied to
 3607: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 3608: #         course's home server.
 3609: #
 3610: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3611: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 3612: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3613: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 3614: #         in course's home server.
 3615: #
 3616: 
 3617: sub process_coursefile {
 3618:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
 3619:         $mimetype)=@_;
 3620:     my $fetchresult;
 3621:     my $home=&homeserver($docuname,$docudom);
 3622:     if ($action eq 'propagate') {
 3623:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3624: 			     $home);
 3625:     } else {
 3626:         my $fpath = '';
 3627:         my $fname = $file;
 3628:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3629:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3630:         my $filepath = &build_filepath($fpath);
 3631:         if ($action eq 'copy') {
 3632:             if ($source eq '') {
 3633:                 $fetchresult = 'no source file';
 3634:                 return $fetchresult;
 3635:             } else {
 3636:                 my $destination = $filepath.'/'.$fname;
 3637:                 rename($source,$destination);
 3638:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3639:                                  $home);
 3640:             }
 3641:         } elsif ($action eq 'uploaddoc') {
 3642:             open(my $fh,'>',$filepath.'/'.$fname);
 3643:             print $fh $env{'form.'.$source};
 3644:             close($fh);
 3645:             if ($parser eq 'parse') {
 3646:                 my $mm = new File::MMagic;
 3647:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
 3648:                 if ($type eq 'text/html') {
 3649:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 3650:                     unless ($parse_result eq 'ok') {
 3651:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 3652:                     }
 3653:                 }
 3654:                 if (ref($mimetype)) {
 3655:                     $$mimetype = $type;
 3656:                 } 
 3657:             }
 3658:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3659:                                  $home);
 3660:             if ($fetchresult eq 'ok') {
 3661:                 return '/uploaded/'.$fpath.'/'.$fname;
 3662:             } else {
 3663:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3664:                         ' to host '.$home.': '.$fetchresult);
 3665:                 return '/adm/notfound.html';
 3666:             }
 3667:         }
 3668:     }
 3669:     unless ( $fetchresult eq 'ok') {
 3670:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3671:              ' to host '.$home.': '.$fetchresult);
 3672:     }
 3673:     return $fetchresult;
 3674: }
 3675: 
 3676: sub build_filepath {
 3677:     my ($fpath) = @_;
 3678:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 3679:     unless ($fpath eq '') {
 3680:         my @parts=split('/',$fpath);
 3681:         foreach my $part (@parts) {
 3682:             $filepath.= '/'.$part;
 3683:             if ((-e $filepath)!=1) {
 3684:                 mkdir($filepath,0777);
 3685:             }
 3686:         }
 3687:     }
 3688:     return $filepath;
 3689: }
 3690: 
 3691: sub store_edited_file {
 3692:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 3693:     my $file = $primary_url;
 3694:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 3695:     my $fpath = '';
 3696:     my $fname = $file;
 3697:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3698:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3699:     my $filepath = &build_filepath($fpath);
 3700:     open(my $fh,'>',$filepath.'/'.$fname);
 3701:     print $fh $content;
 3702:     close($fh);
 3703:     my $home=&homeserver($docuname,$docudom);
 3704:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3705: 			  $home);
 3706:     if ($$fetchresult eq 'ok') {
 3707:         return '/uploaded/'.$fpath.'/'.$fname;
 3708:     } else {
 3709:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3710: 		 ' to host '.$home.': '.$$fetchresult);
 3711:         return '/adm/notfound.html';
 3712:     }
 3713: }
 3714: 
 3715: sub clean_filename {
 3716:     my ($fname,$args)=@_;
 3717: # Replace Windows backslashes by forward slashes
 3718:     $fname=~s/\\/\//g;
 3719:     if (!$args->{'keep_path'}) {
 3720:         # Get rid of everything but the actual filename
 3721: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 3722:     }
 3723: # Replace spaces by underscores
 3724:     $fname=~s/\s+/\_/g;
 3725: # Transliterate non-ascii text to ascii
 3726:     my $lang = &Apache::lonlocal::current_language();
 3727:     $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
 3728: # Replace all other weird characters by nothing
 3729:     $fname=~s{[^/\w\.\-]}{}g;
 3730: # Replace all .\d. sequences with _\d. so they no longer look like version
 3731: # numbers
 3732:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 3733:     return $fname;
 3734: }
 3735: 
 3736: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
 3737: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
 3738: # image with the same aspect ratio as the original, but with dimensions which do 
 3739: # not exceed $resizewidth and $resizeheight.
 3740:  
 3741: sub resizeImage {
 3742:     my ($img_path,$resizewidth,$resizeheight) = @_;
 3743:     my $ima = Image::Magick->new;
 3744:     my $resized;
 3745:     if (-e $img_path) {
 3746:         $ima->Read($img_path);
 3747:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
 3748:             my $width = $ima->Get('width');
 3749:             my $height = $ima->Get('height');
 3750:             if ($width > $resizewidth) {
 3751: 	        my $factor = $width/$resizewidth;
 3752:                 my $newheight = $height/$factor;
 3753:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
 3754:                 $resized = 1;
 3755:             }
 3756:         }
 3757:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
 3758:             my $width = $ima->Get('width');
 3759:             my $height = $ima->Get('height');
 3760:             if ($height > $resizeheight) {
 3761:                 my $factor = $height/$resizeheight;
 3762:                 my $newwidth = $width/$factor;
 3763:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
 3764:                 $resized = 1;
 3765:             }
 3766:         }
 3767:         if ($resized) {
 3768:             $ima->Write($img_path);
 3769:         }
 3770:     }
 3771:     return;
 3772: }
 3773: 
 3774: # --------------- Take an uploaded file and put it into the userfiles directory
 3775: # input: $formname - the contents of the file are in $env{"form.$formname"}
 3776: #                    the desired filename is in $env{"form.$formname.filename"}
 3777: #        $context - possible values: coursedoc, existingfile, overwrite, 
 3778: #                                    canceloverwrite, scantron or ''. 
 3779: #                   if 'coursedoc': upload to the current course
 3780: #                   if 'existingfile': write file to tmp/overwrites directory 
 3781: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
 3782: #                   $context is passed as argument to &finishuserfileupload
 3783: #        $subdir - directory in userfile to store the file into
 3784: #        $parser - instruction to parse file for objects ($parser = parse) or
 3785: #                  if context is 'scantron', $parser is hashref of csv column mapping
 3786: #                  (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3,
 3787: #                          Section => 4, CODE => 5, FirstQuestion => 9 }).
 3788: #        $allfiles - reference to hash for embedded objects
 3789: #        $codebase - reference to hash for codebase of java objects
 3790: #        $desuname - username for permanent storage of uploaded file
 3791: #        $dsetudom - domain for permanaent storage of uploaded file
 3792: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 3793: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 3794: #        $resizewidth - width (pixels) to which to resize uploaded image
 3795: #        $resizeheight - height (pixels) to which to resize uploaded image
 3796: #        $mimetype - reference to scalar to accommodate mime type determined
 3797: #                    from File::MMagic.
 3798: # 
 3799: # output: url of file in userspace, or error: <message> 
 3800: #             or /adm/notfound.html if failure to upload occurse
 3801: 
 3802: sub userfileupload {
 3803:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
 3804:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
 3805:     if (!defined($subdir)) { $subdir='unknown'; }
 3806:     my $fname=$env{'form.'.$formname.'.filename'};
 3807:     $fname=&clean_filename($fname);
 3808:     # See if there is anything left
 3809:     unless ($fname) { return 'error: no uploaded file'; }
 3810:     # If filename now begins with a . prepend unix timestamp _ milliseconds
 3811:     if ($fname =~ /^\./) {
 3812:         my ($s,$usec) = &gettimeofday();
 3813:         while (length($usec) < 6) {
 3814:             $usec = '0'.$usec;
 3815:         }
 3816:         $fname = $s.'_'.substr($usec,0,3).$fname;
 3817:     }
 3818:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
 3819:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
 3820:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
 3821:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3822:         my $now = time;
 3823:         my $filepath;
 3824:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
 3825:              $filepath = 'tmp/helprequests/'.$now;
 3826:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
 3827:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 3828:                          '_'.$env{'user.domain'}.'/pending';
 3829:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3830:             my ($docuname,$docudom);
 3831:             if ($destudom =~ /^$match_domain$/) {
 3832:                 $docudom = $destudom;
 3833:             } else {
 3834:                 $docudom = $env{'user.domain'};
 3835:             }
 3836:             if ($destuname =~ /^$match_username$/) { 
 3837:                 $docuname = $destuname;
 3838:             } else {
 3839:                 $docuname = $env{'user.name'};
 3840:             }
 3841:             if (exists($env{'form.group'})) {
 3842:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3843:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3844:             }
 3845:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
 3846:             if ($context eq 'canceloverwrite') {
 3847:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
 3848:                 if (-e  $tempfile) {
 3849:                     my @info = stat($tempfile);
 3850:                     if ($info[9] eq $env{'form.timestamp'}) {
 3851:                         unlink($tempfile);
 3852:                     }
 3853:                 }
 3854:                 return;
 3855:             }
 3856:         }
 3857:         # Create the directory if not present
 3858:         my @parts=split(/\//,$filepath);
 3859:         my $fullpath = $perlvar{'lonDaemons'};
 3860:         for (my $i=0;$i<@parts;$i++) {
 3861:             $fullpath .= '/'.$parts[$i];
 3862:             if ((-e $fullpath)!=1) {
 3863:                 mkdir($fullpath,0777);
 3864:             }
 3865:         }
 3866:         open(my $fh,'>',$fullpath.'/'.$fname);
 3867:         print $fh $env{'form.'.$formname};
 3868:         close($fh);
 3869:         if ($context eq 'existingfile') {
 3870:             my @info = stat($fullpath.'/'.$fname);
 3871:             return ($fullpath.'/'.$fname,$info[9]);
 3872:         } else {
 3873:             return $fullpath.'/'.$fname;
 3874:         }
 3875:     }
 3876:     if ($subdir eq 'scantron') {
 3877:         $fname = 'scantron_orig_'.$fname;
 3878:     } else {
 3879:         $fname="$subdir/$fname";
 3880:     }
 3881:     if ($context eq 'coursedoc') {
 3882: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3883: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3884:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 3885:             return &finishuserfileupload($docuname,$docudom,
 3886: 					 $formname,$fname,$parser,$allfiles,
 3887: 					 $codebase,$thumbwidth,$thumbheight,
 3888:                                          $resizewidth,$resizeheight,$context,$mimetype);
 3889:         } else {
 3890:             if ($env{'form.folder'}) {
 3891:                 $fname=$env{'form.folder'}.'/'.$fname;
 3892:             }
 3893:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 3894: 				       $fname,$formname,$parser,
 3895: 				       $allfiles,$codebase,$mimetype);
 3896:         }
 3897:     } elsif (defined($destuname)) {
 3898:         my $docuname=$destuname;
 3899:         my $docudom=$destudom;
 3900: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 3901: 				     $parser,$allfiles,$codebase,
 3902:                                      $thumbwidth,$thumbheight,
 3903:                                      $resizewidth,$resizeheight,$context,$mimetype);
 3904:     } else {
 3905:         my $docuname=$env{'user.name'};
 3906:         my $docudom=$env{'user.domain'};
 3907:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
 3908:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3909:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3910:         }
 3911: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 3912: 				     $parser,$allfiles,$codebase,
 3913:                                      $thumbwidth,$thumbheight,
 3914:                                      $resizewidth,$resizeheight,$context,$mimetype);
 3915:     }
 3916: }
 3917: 
 3918: sub finishuserfileupload {
 3919:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 3920:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
 3921:     my $path=$docudom.'/'.$docuname.'/';
 3922:     my $filepath=$perlvar{'lonDocRoot'};
 3923:   
 3924:     my ($fnamepath,$file,$fetchthumb);
 3925:     $file=$fname;
 3926:     if ($fname=~m|/|) {
 3927:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 3928: 	$path.=$fnamepath.'/';
 3929:     }
 3930:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 3931:     my $count;
 3932:     for ($count=4;$count<=$#parts;$count++) {
 3933:         $filepath.="/$parts[$count]";
 3934:         if ((-e $filepath)!=1) {
 3935: 	    mkdir($filepath,0777);
 3936:         }
 3937:     }
 3938: 
 3939: # Save the file
 3940:     {
 3941: 	if (!open(FH,'>',$filepath.'/'.$file)) {
 3942: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 3943: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 3944: 	    return '/adm/notfound.html';
 3945: 	}
 3946:         if ($context eq 'overwrite') {
 3947:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
 3948:             my $target = $filepath.'/'.$file;
 3949:             if (-e $source) {
 3950:                 my @info = stat($source);
 3951:                 if ($info[9] eq $env{'form.timestamp'}) {   
 3952:                     unless (&File::Copy::move($source,$target)) {
 3953:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
 3954:                         return "Moving from $source failed";
 3955:                     }
 3956:                 } else {
 3957:                     return "Temporary file: $source had unexpected date/time for last modification";
 3958:                 }
 3959:             } else {
 3960:                 return "Temporary file: $source missing";
 3961:             }
 3962:         } elsif (!print FH ($env{'form.'.$formname})) {
 3963: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 3964: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 3965: 	    return '/adm/notfound.html';
 3966: 	}
 3967: 	close(FH);
 3968:         if ($resizewidth && $resizeheight) {
 3969:             my $mm = new File::MMagic;
 3970:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
 3971:             if ($mime_type =~ m{^image/}) {
 3972: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
 3973:             }  
 3974: 	}
 3975:     }
 3976:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
 3977:         if (ref($mimetype)) {
 3978:             if ($$mimetype eq '') {
 3979:                 my $mm = new File::MMagic;
 3980:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
 3981:                 $$mimetype = $type;
 3982:             }
 3983:         }
 3984:     }
 3985:     if (($context ne 'scantron') && ($parser eq 'parse')) {
 3986:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
 3987:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
 3988:                                                        $allfiles,$codebase);
 3989:             unless ($parse_result eq 'ok') {
 3990:                 &logthis('Failed to parse '.$filepath.$file.
 3991: 	   	         ' for embedded media: '.$parse_result); 
 3992:             }
 3993:         }
 3994:     } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
 3995:         my $format = $env{'form.scantron_format'};
 3996:         &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
 3997:     }
 3998:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 3999:         my $input = $filepath.'/'.$file;
 4000:         my $output = $filepath.'/'.'tn-'.$file;
 4001:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 4002:         my @args = ('convert','-sample',$thumbsize,$input,$output);
 4003:         system({$args[0]} @args);
 4004:         if (-e $filepath.'/'.'tn-'.$file) {
 4005:             $fetchthumb  = 1; 
 4006:         }
 4007:     }
 4008:  
 4009: # Notify homeserver to grep it
 4010: #
 4011:     my $docuhome=&homeserver($docuname,$docudom);	
 4012:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 4013:     if ($fetchresult eq 'ok') {
 4014:         if ($fetchthumb) {
 4015:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 4016:             if ($thumbresult ne 'ok') {
 4017:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 4018:                          $docuhome.': '.$thumbresult);
 4019:             }
 4020:         }
 4021: #
 4022: # Return the URL to it
 4023:         return '/uploaded/'.$path.$file;
 4024:     } else {
 4025:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 4026: 		 ': '.$fetchresult);
 4027:         return '/adm/notfound.html';
 4028:     }
 4029: }
 4030: 
 4031: sub extract_embedded_items {
 4032:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 4033:     my @state = ();
 4034:     my (%lastids,%related,%shockwave,%flashvars);
 4035:     my %javafiles = (
 4036:                       codebase => '',
 4037:                       code => '',
 4038:                       archive => ''
 4039:                     );
 4040:     my %mediafiles = (
 4041:                       src => '',
 4042:                       movie => '',
 4043:                      );
 4044:     my $p;
 4045:     if ($content) {
 4046:         $p = HTML::LCParser->new($content);
 4047:     } else {
 4048:         $p = HTML::LCParser->new($fullpath);
 4049:     }
 4050:     while (my $t=$p->get_token()) {
 4051: 	if ($t->[0] eq 'S') {
 4052: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 4053: 	    push(@state, $tagname);
 4054:             if (lc($tagname) eq 'allow') {
 4055:                 &add_filetype($allfiles,$attr->{'src'},'src');
 4056:             }
 4057: 	    if (lc($tagname) eq 'img') {
 4058: 		&add_filetype($allfiles,$attr->{'src'},'src');
 4059: 	    }
 4060: 	    if (lc($tagname) eq 'a') {
 4061:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
 4062: 		    &add_filetype($allfiles,$attr->{'href'},'href');
 4063:                 }
 4064: 	    }
 4065:             if (lc($tagname) eq 'script') {
 4066:                 my $src;
 4067:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 4068:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 4069:                 } else {
 4070:                     if ($attr->{'src'} ne '') {
 4071:                         $src = $attr->{'src'};
 4072:                         &add_filetype($allfiles,$src,'src');
 4073:                     }
 4074:                 }
 4075:                 my $text = $p->get_trimmed_text();
 4076:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
 4077:                     my @swfargs = split(/,/,$1);
 4078:                     foreach my $item (@swfargs) {
 4079:                         $item =~ s/["']//g;
 4080:                         $item =~ s/^\s+//;
 4081:                         $item =~ s/\s+$//;
 4082:                     }
 4083:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
 4084:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
 4085:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
 4086:                         } else {
 4087:                             $related{$swfargs[0]} = [$swfargs[2]];
 4088:                         }
 4089:                     }
 4090:                 }
 4091:             }
 4092:             if (lc($tagname) eq 'link') {
 4093:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 4094:                     &add_filetype($allfiles,$attr->{'href'},'href');
 4095:                 }
 4096:             }
 4097: 	    if (lc($tagname) eq 'object' ||
 4098: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 4099: 		foreach my $item (keys(%javafiles)) {
 4100: 		    $javafiles{$item} = '';
 4101: 		}
 4102:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
 4103:                     $lastids{lc($tagname)} = $attr->{'id'};
 4104:                 }
 4105: 	    }
 4106: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 4107: 		my $name = lc($attr->{'name'});
 4108: 		foreach my $item (keys(%javafiles)) {
 4109: 		    if ($name eq $item) {
 4110: 			$javafiles{$item} = $attr->{'value'};
 4111: 			last;
 4112: 		    }
 4113: 		}
 4114:                 my $pathfrom;
 4115: 		foreach my $item (keys(%mediafiles)) {
 4116: 		    if ($name eq $item) {
 4117:                         $pathfrom = $attr->{'value'};
 4118:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
 4119: 			&add_filetype($allfiles,$pathfrom,$name);
 4120: 			last;
 4121: 		    }
 4122: 		}
 4123:                 if ($name eq 'flashvars') {
 4124:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
 4125:                 }
 4126:                 if ($pathfrom ne '') {
 4127:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
 4128:                                          $pathfrom);
 4129:                 }
 4130: 	    }
 4131: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 4132: 		foreach my $item (keys(%javafiles)) {
 4133: 		    if ($attr->{$item}) {
 4134: 			$javafiles{$item} = $attr->{$item};
 4135: 			last;
 4136: 		    }
 4137: 		}
 4138: 		foreach my $item (keys(%mediafiles)) {
 4139: 		    if ($attr->{$item}) {
 4140: 			&add_filetype($allfiles,$attr->{$item},$item);
 4141: 			last;
 4142: 		    }
 4143: 		}
 4144:                 if (lc($tagname) eq 'embed') {
 4145:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
 4146:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
 4147:                                              $attr->{'src'});
 4148:                     }
 4149:                 }
 4150: 	    }
 4151:             if (lc($tagname) eq 'iframe') {
 4152:                 my $src = $attr->{'src'} ;
 4153:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
 4154:                     &add_filetype($allfiles,$src,'src');
 4155:                 } elsif ($src =~ m{^/}) {
 4156:                     if ($env{'request.course.id'}) {
 4157:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4158:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4159:                         my $url = &hreflocation('',$fullpath);
 4160:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
 4161:                             my $relpath = $1;
 4162:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
 4163:                                 &add_filetype($allfiles,$1,'src');
 4164:                             }
 4165:                         }
 4166:                     }
 4167:                 }
 4168:             }
 4169:             if ($t->[4] =~ m{/>$}) {
 4170:                 pop(@state);
 4171:             }
 4172: 	} elsif ($t->[0] eq 'E') {
 4173: 	    my ($tagname) = ($t->[1]);
 4174: 	    if ($javafiles{'codebase'} ne '') {
 4175: 		$javafiles{'codebase'} .= '/';
 4176: 	    }  
 4177: 	    if (lc($tagname) eq 'applet' ||
 4178: 		lc($tagname) eq 'object' ||
 4179: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 4180: 		) {
 4181: 		foreach my $item (keys(%javafiles)) {
 4182: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 4183: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 4184: 			&add_filetype($allfiles,$file,$item);
 4185: 		    }
 4186: 		}
 4187: 	    } 
 4188: 	    pop @state;
 4189: 	}
 4190:     }
 4191:     foreach my $id (sort(keys(%flashvars))) {
 4192:         if ($shockwave{$id} ne '') {
 4193:             my @pairs = split(/\&/,$flashvars{$id});
 4194:             foreach my $pair (@pairs) {
 4195:                 my ($key,$value) = split(/\=/,$pair);
 4196:                 if ($key eq 'thumb') {
 4197:                     &add_filetype($allfiles,$value,$key);
 4198:                 } elsif ($key eq 'content') {
 4199:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
 4200:                     my ($ext) = ($value =~ /\.([^.]+)$/);
 4201:                     if ($ext ne '') {
 4202:                         &add_filetype($allfiles,$path.$value,$ext);
 4203:                     }
 4204:                 }
 4205:             }
 4206:         }
 4207:     }
 4208:     return 'ok';
 4209: }
 4210: 
 4211: sub add_filetype {
 4212:     my ($allfiles,$file,$type)=@_;
 4213:     if (exists($allfiles->{$file})) {
 4214: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 4215: 	    push(@{$allfiles->{$file}}, &escape($type));
 4216: 	}
 4217:     } else {
 4218: 	@{$allfiles->{$file}} = (&escape($type));
 4219:     }
 4220: }
 4221: 
 4222: sub embedded_dependency {
 4223:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
 4224:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
 4225:         if (($identifier ne '') &&
 4226:             (ref($related->{$identifier}) eq 'ARRAY') &&
 4227:             ($pathfrom ne '')) {
 4228:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
 4229:             foreach my $dep (@{$related->{$identifier}}) {
 4230:                 &add_filetype($allfiles,$path.$dep,'object');
 4231:             }
 4232:         }
 4233:     }
 4234:     return;
 4235: }
 4236: 
 4237: sub bubblesheet_converter {
 4238:     my ($cdom,$fullpath,$config,$format) = @_;
 4239:     if ((&domain($cdom) ne '') &&
 4240:         ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
 4241:         (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
 4242:         my (%csvcols,%csvoptions);
 4243:         if (ref($config->{'fields'}) eq 'HASH') {
 4244:             %csvcols = %{$config->{'fields'}};
 4245:         }
 4246:         if (ref($config->{'options'}) eq 'HASH') {
 4247:             %csvoptions = %{$config->{'options'}};
 4248:         }
 4249:         my %csvbynum = reverse(%csvcols);
 4250:         my %scantronconf = &get_scantron_config($format,$cdom);
 4251:         if (keys(%scantronconf)) {
 4252:             my %bynum = (
 4253:                           $scantronconf{CODEstart} => 'CODEstart',
 4254:                           $scantronconf{IDstart}   => 'IDstart',
 4255:                           $scantronconf{PaperID}   => 'PaperID',
 4256:                           $scantronconf{FirstName} => 'FirstName',
 4257:                           $scantronconf{LastName}  => 'LastName',
 4258:                           $scantronconf{Qstart}    => 'Qstart',
 4259:                         );
 4260:             my @ordered;
 4261:             foreach my $item (sort { $a <=> $b } keys(%bynum)) {
 4262:                 push(@ordered,$bynum{$item});
 4263:             }
 4264:             my %mapstart = (
 4265:                               CODEstart => 'CODE',
 4266:                               IDstart   => 'ID',
 4267:                               PaperID   => 'PaperID',
 4268:                               FirstName => 'FirstName',
 4269:                               LastName  => 'LastName',
 4270:                               Qstart    => 'FirstQuestion',
 4271:                            );
 4272:             my %maplength = (
 4273:                               CODEstart => 'CODElength',
 4274:                               IDstart   => 'IDlength',
 4275:                               PaperID   => 'PaperIDlength',
 4276:                               FirstName => 'FirstNamelength',
 4277:                               LastName  => 'LastNamelength',
 4278:             );
 4279:             if (open(my $fh,'<',$fullpath)) {
 4280:                 my $output;
 4281:                 my %lettdig = &letter_to_digits();
 4282:                 my %diglett = reverse(%lettdig);
 4283:                 my $numletts = scalar(keys(%lettdig));
 4284:                 my $num = 0;
 4285:                 while (my $line=<$fh>) {
 4286:                     $num ++;
 4287:                     next if (($num == 1) && ($csvoptions{'hdr'} == 1));
 4288:                     $line =~ s{[\r\n]+$}{};
 4289:                     my %found;
 4290:                     my @values = split(/,/,$line);
 4291:                     my ($qstart,$record);
 4292:                     for (my $i=0; $i<@values; $i++) {
 4293:                         if ((($qstart ne '') && ($i > $qstart)) ||
 4294:                             ($csvbynum{$i} eq 'FirstQuestion')) {
 4295:                             if ($values[$i] eq '') {
 4296:                                 $values[$i] = $scantronconf{'Qoff'};
 4297:                             } elsif ($scantronconf{'Qon'} eq 'number') {
 4298:                                 if ($values[$i] =~ /^[A-Ja-j]$/) {
 4299:                                     $values[$i] = $lettdig{uc($values[$i])};
 4300:                                 }
 4301:                             } elsif ($scantronconf{'Qon'} eq 'letter') {
 4302:                                 if ($values[$i] =~ /^[0-9]$/) {
 4303:                                     $values[$i] = $diglett{$values[$i]};
 4304:                                 }
 4305:                             } else {
 4306:                                 if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
 4307:                                     my $digit;
 4308:                                     if ($values[$i] =~ /^[A-Ja-j]$/) {
 4309:                                         $digit = $lettdig{uc($values[$i])}-1;
 4310:                                         if ($values[$i] eq 'J') {
 4311:                                             $digit += $numletts;
 4312:                                         }
 4313:                                     } elsif ($values[$i] =~ /^[0-9]$/) {
 4314:                                         $digit = $values[$i]-1;
 4315:                                         if ($values[$i] eq '0') {
 4316:                                             $digit += $numletts;
 4317:                                         }
 4318:                                     }
 4319:                                     my $qval='';
 4320:                                     for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
 4321:                                         if ($j == $digit) {
 4322:                                             $qval .= $scantronconf{'Qon'};
 4323:                                         } else {
 4324:                                             $qval .= $scantronconf{'Qoff'};
 4325:                                         }
 4326:                                     }
 4327:                                     $values[$i] = $qval;
 4328:                                 }
 4329:                             }
 4330:                             if (length($values[$i]) > $scantronconf{'Qlength'}) {
 4331:                                 $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
 4332:                             }
 4333:                             my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
 4334:                             if ($numblank > 0) {
 4335:                                  $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
 4336:                             }
 4337:                             if ($csvbynum{$i} eq 'FirstQuestion') {
 4338:                                 $qstart = $i;
 4339:                                 $found{$csvbynum{$i}} = $values[$i];
 4340:                             } else {
 4341:                                 $found{'FirstQuestion'} .= $values[$i];
 4342:                             }
 4343:                         } elsif (exists($csvbynum{$i})) {
 4344:                             if ($csvoptions{'rem'}) {
 4345:                                 $values[$i] =~ s/^\s+//;
 4346:                             }
 4347:                             if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
 4348:                                 while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
 4349:                                     $values[$i] = '0'.$values[$i];
 4350:                                 }
 4351:                             }
 4352:                             $found{$csvbynum{$i}} = $values[$i];
 4353:                         }
 4354:                     }
 4355:                     foreach my $item (@ordered) {
 4356:                         my $currlength = 1+length($record);
 4357:                         my $numspaces = $scantronconf{$item} - $currlength;
 4358:                         if ($numspaces > 0) {
 4359:                             $record .= (' ' x $numspaces);
 4360:                         }
 4361:                         if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
 4362:                             unless ($item eq 'Qstart') {
 4363:                                 if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
 4364:                                     $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
 4365:                                 }
 4366:                             }
 4367:                             $record .= $found{$mapstart{$item}};
 4368:                         }
 4369:                     }
 4370:                     $output .= "$record\n";
 4371:                 }
 4372:                 close($fh);
 4373:                 if ($output) {
 4374:                     if (open(my $fh,'>',$fullpath)) {
 4375:                         print $fh $output;
 4376:                         close($fh);
 4377:                     }
 4378:                 }
 4379:             }
 4380:         }
 4381:         return;
 4382:     }
 4383: }
 4384: 
 4385: sub letter_to_digits {
 4386:     my %lettdig = (
 4387:                     A => 1,
 4388:                     B => 2,
 4389:                     C => 3,
 4390:                     D => 4,
 4391:                     E => 5,
 4392:                     F => 6,
 4393:                     G => 7,
 4394:                     H => 8,
 4395:                     I => 9,
 4396:                     J => 0,
 4397:                   );
 4398:     return %lettdig;
 4399: }
 4400: 
 4401: sub get_scantron_config {
 4402:     my ($which,$cdom) = @_;
 4403:     my @lines = &get_scantronformat_file($cdom);
 4404:     my %config;
 4405:     #FIXME probably should move to XML it has already gotten a bit much now
 4406:     foreach my $line (@lines) {
 4407:         my ($name,$descrip)=split(/:/,$line);
 4408:         if ($name ne $which ) { next; }
 4409:         chomp($line);
 4410:         my @config=split(/:/,$line);
 4411:         $config{'name'}=$config[0];
 4412:         $config{'description'}=$config[1];
 4413:         $config{'CODElocation'}=$config[2];
 4414:         $config{'CODEstart'}=$config[3];
 4415:         $config{'CODElength'}=$config[4];
 4416:         $config{'IDstart'}=$config[5];
 4417:         $config{'IDlength'}=$config[6];
 4418:         $config{'Qstart'}=$config[7];
 4419:         $config{'Qlength'}=$config[8];
 4420:         $config{'Qoff'}=$config[9];
 4421:         $config{'Qon'}=$config[10];
 4422:         $config{'PaperID'}=$config[11];
 4423:         $config{'PaperIDlength'}=$config[12];
 4424:         $config{'FirstName'}=$config[13];
 4425:         $config{'FirstNamelength'}=$config[14];
 4426:         $config{'LastName'}=$config[15];
 4427:         $config{'LastNamelength'}=$config[16];
 4428:         $config{'BubblesPerRow'}=$config[17];
 4429:         last;
 4430:     }
 4431:     return %config;
 4432: }
 4433: 
 4434: sub get_scantronformat_file {
 4435:     my ($cdom) = @_;
 4436:     if ($cdom eq '') {
 4437:         $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 4438:     }
 4439:     my %domconfig = &get_dom('configuration',['scantron'],$cdom);
 4440:     my $gottab = 0;
 4441:     my @lines;
 4442:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 4443:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
 4444:             my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
 4445:             if ($formatfile ne '-1') {
 4446:                 @lines = split("\n",$formatfile,-1);
 4447:                 $gottab = 1;
 4448:             }
 4449:         }
 4450:     }
 4451:     if (!$gottab) {
 4452:         my $confname = $cdom.'-domainconfig';
 4453:         my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
 4454:         my $formatfile = &getfile($default);
 4455:         if ($formatfile ne '-1') {
 4456:             @lines = split("\n",$formatfile,-1);
 4457:             $gottab = 1;
 4458:         }
 4459:     }
 4460:     if (!$gottab) {
 4461:         my @domains = &current_machine_domains();
 4462:         if (grep(/^\Q$cdom\E$/,@domains)) {
 4463:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
 4464:                 @lines = <$fh>;
 4465:                 close($fh);
 4466:             }
 4467:         } else {
 4468:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
 4469:                 @lines = <$fh>;
 4470:                 close($fh);
 4471:             }
 4472:         }
 4473:     }
 4474:     return @lines;
 4475: }
 4476: 
 4477: sub removeuploadedurl {
 4478:     my ($url)=@_;	
 4479:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 4480:     return &removeuserfile($uname,$udom,$fname);
 4481: }
 4482: 
 4483: sub removeuserfile {
 4484:     my ($docuname,$docudom,$fname)=@_;
 4485:     my $home=&homeserver($docuname,$docudom);    
 4486:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 4487:     if ($result eq 'ok') {	
 4488:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 4489:             my $metafile = $fname.'.meta';
 4490:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 4491: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 4492:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 4493:             my $sqlresult = 
 4494:                 &update_portfolio_table($docuname,$docudom,$file,
 4495:                                         'portfolio_metadata',$group,
 4496:                                         'delete');
 4497:         }
 4498:     }
 4499:     return $result;
 4500: }
 4501: 
 4502: sub mkdiruserfile {
 4503:     my ($docuname,$docudom,$dir)=@_;
 4504:     my $home=&homeserver($docuname,$docudom);
 4505:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 4506: }
 4507: 
 4508: sub renameuserfile {
 4509:     my ($docuname,$docudom,$old,$new)=@_;
 4510:     my $home=&homeserver($docuname,$docudom);
 4511:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 4512:                         &escape("$old").':'.&escape("$new"),$home);
 4513:     if ($result eq 'ok') {
 4514:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 4515:             my $oldmeta = $old.'.meta';
 4516:             my $newmeta = $new.'.meta';
 4517:             my $metaresult = 
 4518:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 4519: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 4520:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 4521:             my $sqlresult = 
 4522:                 &update_portfolio_table($docuname,$docudom,$file,
 4523:                                         'portfolio_metadata',$group,
 4524:                                         'delete');
 4525:         }
 4526:     }
 4527:     return $result;
 4528: }
 4529: 
 4530: # ------------------------------------------------------------------------- Log
 4531: 
 4532: sub log {
 4533:     my ($dom,$nam,$hom,$what)=@_;
 4534:     return critical("log:$dom:$nam:$what",$hom);
 4535: }
 4536: 
 4537: # ------------------------------------------------------------------ Course Log
 4538: #
 4539: # This routine flushes several buffers of non-mission-critical nature
 4540: #
 4541: 
 4542: sub flushcourselogs {
 4543:     &logthis('Flushing log buffers');
 4544: #
 4545: # course logs
 4546: # This is a log of all transactions in a course, which can be used
 4547: # for data mining purposes
 4548: #
 4549: # It also collects the courseid database, which lists last transaction
 4550: # times and course titles for all courseids
 4551: #
 4552:     my %courseidbuffer=();
 4553:     foreach my $crsid (keys(%courselogs)) {
 4554:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 4555: 		          &escape($courselogs{$crsid}),
 4556: 		          $coursehombuf{$crsid}) eq 'ok') {
 4557: 	    delete $courselogs{$crsid};
 4558:         } else {
 4559:             &logthis('Failed to flush log buffer for '.$crsid);
 4560:             if (length($courselogs{$crsid})>40000) {
 4561:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 4562:                         " exceeded maximum size, deleting.</font>");
 4563:                delete $courselogs{$crsid};
 4564:             }
 4565:         }
 4566:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 4567:             'description' => $coursedescrbuf{$crsid},
 4568:             'inst_code'    => $courseinstcodebuf{$crsid},
 4569:             'type'        => $coursetypebuf{$crsid},
 4570:             'owner'       => $courseownerbuf{$crsid},
 4571:         };
 4572:     }
 4573: #
 4574: # Write course id database (reverse lookup) to homeserver of courses 
 4575: # Is used in pickcourse
 4576: #
 4577:     foreach my $crs_home (keys(%courseidbuffer)) {
 4578:         my $response = &courseidput(&host_domain($crs_home),
 4579:                                     $courseidbuffer{$crs_home},
 4580:                                     $crs_home,'timeonly');
 4581:     }
 4582: #
 4583: # File accesses
 4584: # Writes to the dynamic metadata of resources to get hit counts, etc.
 4585: #
 4586:     foreach my $entry (keys(%accesshash)) {
 4587:         if ($entry =~ /___count$/) {
 4588:             my ($dom,$name);
 4589:             ($dom,$name,undef)=
 4590: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 4591:             if (! defined($dom) || $dom eq '' || 
 4592:                 ! defined($name) || $name eq '') {
 4593:                 my $cid = $env{'request.course.id'};
 4594:                 $dom  = $env{'request.'.$cid.'.domain'};
 4595:                 $name = $env{'request.'.$cid.'.num'};
 4596:             }
 4597:             my $value = $accesshash{$entry};
 4598:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 4599:             my %temphash=($url => $value);
 4600:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 4601:             if ($result eq 'ok') {
 4602:                 delete $accesshash{$entry};
 4603:             }
 4604:         } else {
 4605:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 4606:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
 4607:             my %temphash=($entry => $accesshash{$entry});
 4608:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 4609:                 delete $accesshash{$entry};
 4610:             }
 4611:         }
 4612:     }
 4613: #
 4614: # Roles
 4615: # Reverse lookup of user roles for course faculty/staff and co-authorship
 4616: #
 4617:     foreach my $entry (keys(%userrolehash)) {
 4618:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 4619: 	    split(/\:/,$entry);
 4620:         if (&Apache::lonnet::put('nohist_userroles',
 4621:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 4622:                 $rudom,$runame) eq 'ok') {
 4623: 	    delete $userrolehash{$entry};
 4624:         }
 4625:     }
 4626: #
 4627: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
 4628: #
 4629:     my %domrolebuffer = ();
 4630:     foreach my $entry (keys(%domainrolehash)) {
 4631:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 4632:         if ($domrolebuffer{$rudom}) {
 4633:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 4634:                       '='.&escape($domainrolehash{$entry});
 4635:         } else {
 4636:             $domrolebuffer{$rudom}.=&escape($entry).
 4637:                       '='.&escape($domainrolehash{$entry});
 4638:         }
 4639:         delete $domainrolehash{$entry};
 4640:     }
 4641:     foreach my $dom (keys(%domrolebuffer)) {
 4642:         my %servers;
 4643:         if (defined(&domain($dom,'primary'))) {
 4644:             my $primary=&domain($dom,'primary');
 4645:             my $hostname=&hostname($primary);
 4646:             $servers{$primary} = $hostname;
 4647:         } else {
 4648:             %servers = &get_servers($dom,'library');
 4649:         }
 4650: 	foreach my $tryserver (keys(%servers)) {
 4651: 	    if (&reply('domroleput:'.$dom.':'.
 4652: 	               $domrolebuffer{$dom},$tryserver) eq 'ok') {
 4653: 	        last;
 4654: 	    } else {
 4655: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 4656: 	    }
 4657:         }
 4658:     }
 4659:     $dumpcount++;
 4660: }
 4661: 
 4662: sub courselog {
 4663:     my $what=shift;
 4664:     $what=time.':'.$what;
 4665:     unless ($env{'request.course.id'}) { return ''; }
 4666:     $coursedombuf{$env{'request.course.id'}}=
 4667:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 4668:     $coursenumbuf{$env{'request.course.id'}}=
 4669:        $env{'course.'.$env{'request.course.id'}.'.num'};
 4670:     $coursehombuf{$env{'request.course.id'}}=
 4671:        $env{'course.'.$env{'request.course.id'}.'.home'};
 4672:     $coursedescrbuf{$env{'request.course.id'}}=
 4673:        $env{'course.'.$env{'request.course.id'}.'.description'};
 4674:     $courseinstcodebuf{$env{'request.course.id'}}=
 4675:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 4676:     $courseownerbuf{$env{'request.course.id'}}=
 4677:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 4678:     $coursetypebuf{$env{'request.course.id'}}=
 4679:        $env{'course.'.$env{'request.course.id'}.'.type'};
 4680:     if (defined $courselogs{$env{'request.course.id'}}) {
 4681: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 4682:     } else {
 4683: 	$courselogs{$env{'request.course.id'}}.=$what;
 4684:     }
 4685:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 4686: 	&flushcourselogs();
 4687:     }
 4688: }
 4689: 
 4690: sub courseacclog {
 4691:     my $fnsymb=shift;
 4692:     unless ($env{'request.course.id'}) { return ''; }
 4693:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 4694:     if ($fnsymb=~/$LONCAPA::assess_re/) {
 4695:         $what.=':POST';
 4696:         # FIXME: Probably ought to escape things....
 4697: 	foreach my $key (keys(%env)) {
 4698:             if ($key=~/^form\.(.*)/) {
 4699:                 my $formitem = $1;
 4700:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 4701:                     $what.=':'.$formitem.'='.$env{$key};
 4702:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 4703:                     if ($formitem eq 'proctorpassword') {
 4704:                         $what.=':'.$formitem.'=' . '*' x length($env{$key});
 4705:                     } else {
 4706:                         $what.=':'.$formitem.'='.$env{$key};
 4707:                     }
 4708:                 }
 4709:             }
 4710:         }
 4711:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 4712:         # FIXME: We should not be depending on a form parameter that someone
 4713:         # editing lonsearchcat.pm might change in the future.
 4714:         if ($env{'form.phase'} eq 'course_search') {
 4715:             $what.= ':POST';
 4716:             # FIXME: Probably ought to escape things....
 4717:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 4718:                                  'crsdiscuss') {
 4719:                 $what.=':'.$element.'='.$env{'form.'.$element};
 4720:             }
 4721:         }
 4722:     }
 4723:     &courselog($what);
 4724: }
 4725: 
 4726: sub countacc {
 4727:     my $url=&declutter(shift);
 4728:     return if (! defined($url) || $url eq '');
 4729:     unless ($env{'request.course.id'}) { return ''; }
 4730: #
 4731: # Mark that this url was used in this course
 4732: #
 4733:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 4734: #
 4735: # Increase the access count for this resource in this child process
 4736: #
 4737:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 4738:     $accesshash{$key}++;
 4739: }
 4740: 
 4741: sub linklog {
 4742:     my ($from,$to)=@_;
 4743:     $from=&declutter($from);
 4744:     $to=&declutter($to);
 4745:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 4746:     $accesshash{$to.'___'.$from.'___goto'}=1;
 4747: }
 4748: 
 4749: sub statslog {
 4750:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
 4751:     if ($users<2) { return; }
 4752:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
 4753:             'course'       => $env{'request.course.id'},
 4754:             'sections'     => '"all"',
 4755:             'num_students' => $users,
 4756:             'part'         => $part,
 4757:             'symb'         => $symb,
 4758:             'mean_tries'   => $av_attempts,
 4759:             'deg_of_diff'  => $degdiff});
 4760:     foreach my $key (keys(%dynstore)) {
 4761:         $accesshash{$key}=$dynstore{$key};
 4762:     }
 4763: }
 4764:   
 4765: sub userrolelog {
 4766:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 4767:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
 4768:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 4769:        $userrolehash
 4770:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 4771:                     =$tend.':'.$tstart;
 4772:     }
 4773:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
 4774:        $userrolehash
 4775:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 4776:                     =$tend.':'.$tstart;
 4777:     }
 4778:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
 4779:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 4780:        $domainrolehash
 4781:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 4782:                     = $tend.':'.$tstart;
 4783:     }
 4784: }
 4785: 
 4786: sub courserolelog {
 4787:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 4788:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 4789:         my $cdom = $1;
 4790:         my $cnum = $2;
 4791:         my $sec = $3;
 4792:         my $namespace = 'rolelog';
 4793:         my %storehash = (
 4794:                            role    => $trole,
 4795:                            start   => $tstart,
 4796:                            end     => $tend,
 4797:                            selfenroll => $selfenroll,
 4798:                            context    => $context,
 4799:                         );
 4800:         if ($trole eq 'gr') {
 4801:             $namespace = 'groupslog';
 4802:             $storehash{'group'} = $sec;
 4803:         } else {
 4804:             $storehash{'section'} = $sec;
 4805:         }
 4806:         &write_log('course',$namespace,\%storehash,$delflag,$username,
 4807:                    $domain,$cnum,$cdom);
 4808:         if (($trole ne 'st') || ($sec ne '')) {
 4809:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 4810:         }
 4811:     }
 4812:     return;
 4813: }
 4814: 
 4815: sub domainrolelog {
 4816:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 4817:     if ($area =~ m{^/($match_domain)/$}) {
 4818:         my $cdom = $1;
 4819:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
 4820:         my $namespace = 'rolelog';
 4821:         my %storehash = (
 4822:                            role    => $trole,
 4823:                            start   => $tstart,
 4824:                            end     => $tend,
 4825:                            context => $context,
 4826:                         );
 4827:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
 4828:                    $domain,$domconfiguser,$cdom);
 4829:     }
 4830:     return;
 4831: 
 4832: }
 4833: 
 4834: sub coauthorrolelog {
 4835:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 4836:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
 4837:         my $audom = $1;
 4838:         my $auname = $2;
 4839:         my $namespace = 'rolelog';
 4840:         my %storehash = (
 4841:                            role    => $trole,
 4842:                            start   => $tstart,
 4843:                            end     => $tend,
 4844:                            context => $context,
 4845:                         );
 4846:         &write_log('author',$namespace,\%storehash,$delflag,$username,
 4847:                    $domain,$auname,$audom);
 4848:     }
 4849:     return;
 4850: }
 4851: 
 4852: sub get_course_adv_roles {
 4853:     my ($cid,$codes) = @_;
 4854:     $cid=$env{'request.course.id'} unless (defined($cid));
 4855:     my %coursehash=&coursedescription($cid);
 4856:     my $crstype = &Apache::loncommon::course_type($cid);
 4857:     my %nothide=();
 4858:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 4859:         if ($user !~ /:/) {
 4860: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 4861:         } else {
 4862:             $nothide{$user}=1;
 4863:         }
 4864:     }
 4865:     my @possdoms = ($coursehash{'domain'});
 4866:     if ($coursehash{'checkforpriv'}) {
 4867:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
 4868:     }
 4869:     my %returnhash=();
 4870:     my %dumphash=
 4871:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 4872:     my $now=time;
 4873:     my %privileged;
 4874:     foreach my $entry (keys(%dumphash)) {
 4875: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 4876:         if (($tstart) && ($tstart<0)) { next; }
 4877:         if (($tend) && ($tend<$now)) { next; }
 4878:         if (($tstart) && ($now<$tstart)) { next; }
 4879:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 4880: 	if ($username eq '' || $domain eq '') { next; }
 4881:         if ((&privileged($username,$domain,\@possdoms)) &&
 4882:             (!$nothide{$username.':'.$domain})) { next; }
 4883: 	if ($role eq 'cr') { next; }
 4884:         if ($codes) {
 4885:             if ($section) { $role .= ':'.$section; }
 4886:             if ($returnhash{$role}) {
 4887:                 $returnhash{$role}.=','.$username.':'.$domain;
 4888:             } else {
 4889:                 $returnhash{$role}=$username.':'.$domain;
 4890:             }
 4891:         } else {
 4892:             my $key=&plaintext($role,$crstype);
 4893:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 4894:             if ($returnhash{$key}) {
 4895: 	        $returnhash{$key}.=','.$username.':'.$domain;
 4896:             } else {
 4897:                 $returnhash{$key}=$username.':'.$domain;
 4898:             }
 4899:         }
 4900:     }
 4901:     return %returnhash;
 4902: }
 4903: 
 4904: sub get_my_roles {
 4905:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 4906:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 4907:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 4908:     my (%dumphash,%nothide);
 4909:     if ($context eq 'userroles') {
 4910:         %dumphash = &dump('roles',$udom,$uname);
 4911:     } else {
 4912:         %dumphash = &dump('nohist_userroles',$udom,$uname);
 4913:         if ($hidepriv) {
 4914:             my %coursehash=&coursedescription($udom.'_'.$uname);
 4915:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 4916:                 if ($user !~ /:/) {
 4917:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 4918:                 } else {
 4919:                     $nothide{$user} = 1;
 4920:                 }
 4921:             }
 4922:         }
 4923:     }
 4924:     my %returnhash=();
 4925:     my $now=time;
 4926:     my %privileged;
 4927:     foreach my $entry (keys(%dumphash)) {
 4928:         my ($role,$tend,$tstart);
 4929:         if ($context eq 'userroles') {
 4930:             next if ($entry =~ /^rolesdef/);
 4931: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 4932:         } else {
 4933:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 4934:         }
 4935:         if (($tstart) && ($tstart<0)) { next; }
 4936:         my $status = 'active';
 4937:         if (($tend) && ($tend<=$now)) {
 4938:             $status = 'previous';
 4939:         } 
 4940:         if (($tstart) && ($now<$tstart)) {
 4941:             $status = 'future';
 4942:         }
 4943:         if (ref($types) eq 'ARRAY') {
 4944:             if (!grep(/^\Q$status\E$/,@{$types})) {
 4945:                 next;
 4946:             } 
 4947:         } else {
 4948:             if ($status ne 'active') {
 4949:                 next;
 4950:             }
 4951:         }
 4952:         my ($rolecode,$username,$domain,$section,$area);
 4953:         if ($context eq 'userroles') {
 4954:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
 4955:             (undef,$domain,$username,$section) = split(/\//,$area);
 4956:         } else {
 4957:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 4958:         }
 4959:         if (ref($roledoms) eq 'ARRAY') {
 4960:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 4961:                 next;
 4962:             }
 4963:         }
 4964:         if (ref($roles) eq 'ARRAY') {
 4965:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 4966:                 if ($role =~ /^cr\//) {
 4967:                     if (!grep(/^cr$/,@{$roles})) {
 4968:                         next;
 4969:                     }
 4970:                 } elsif ($role =~ /^gr\//) {
 4971:                     if (!grep(/^gr$/,@{$roles})) {
 4972:                         next;
 4973:                     }
 4974:                 } else {
 4975:                     next;
 4976:                 }
 4977:             }
 4978:         }
 4979:         if ($hidepriv) {
 4980:             my @privroles = ('dc','su');
 4981:             if ($context eq 'userroles') {
 4982:                 next if (grep(/^\Q$role\E$/,@privroles));
 4983:             } else {
 4984:                 my $possdoms = [$domain];
 4985:                 if (ref($roledoms) eq 'ARRAY') {
 4986:                    push(@{$possdoms},@{$roledoms});
 4987:                 }
 4988:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
 4989:                     if (!$nothide{$username.':'.$domain}) {
 4990:                         next;
 4991:                     }
 4992:                 }
 4993:             }
 4994:         }
 4995:         if ($withsec) {
 4996:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 4997:                 $tstart.':'.$tend;
 4998:         } else {
 4999:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 5000:         }
 5001:     }
 5002:     return %returnhash;
 5003: }
 5004: 
 5005: sub get_all_adhocroles {
 5006:     my ($dom) = @_;
 5007:     my @roles_by_num = ();
 5008:     my %domdefaults = &get_domain_defaults($dom);
 5009:     my (%description,%access_in_dom,%access_info);
 5010:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
 5011:         my $count = 0;
 5012:         my %domcurrent = %{$domdefaults{'adhocroles'}};
 5013:         my %ordered;
 5014:         foreach my $role (sort(keys(%domcurrent))) {
 5015:             my ($order,$desc,$access_in_dom);
 5016:             if (ref($domcurrent{$role}) eq 'HASH') {
 5017:                 $order = $domcurrent{$role}{'order'};
 5018:                 $desc = $domcurrent{$role}{'desc'};
 5019:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
 5020:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
 5021:             }
 5022:             if ($order eq '') {
 5023:                 $order = $count;
 5024:             }
 5025:             $ordered{$order} = $role;
 5026:             if ($desc ne '') {
 5027:                 $description{$role} = $desc;
 5028:             } else {
 5029:                 $description{$role}= $role;
 5030:             }
 5031:             $count++;
 5032:         }
 5033:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 5034:             push(@roles_by_num,$ordered{$item});
 5035:         }
 5036:     }
 5037:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
 5038: }
 5039: 
 5040: sub get_my_adhocroles {
 5041:     my ($cid,$checkreg) = @_;
 5042:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
 5043:     if ($env{'request.course.id'} eq $cid) {
 5044:         $cdom = $env{'course.'.$cid.'.domain'};
 5045:         $cnum = $env{'course.'.$cid.'.num'};
 5046:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
 5047:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
 5048:         $cdom = $1;
 5049:         $cnum = $2;
 5050:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
 5051:                                      $cdom,$cnum);
 5052:     }
 5053:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
 5054:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
 5055:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
 5056:         if ($rosterhash{$user} ne '') {
 5057:             my $type = (split(/:/,$rosterhash{$user}))[5];
 5058:             return ([],{}) if ($type eq 'auto');
 5059:         }
 5060:     }
 5061:     if (($cdom ne '') && ($cnum ne ''))  {
 5062:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
 5063:             my $then=$env{'user.login.time'};
 5064:             my $update=$env{'user.update.time'};
 5065:             if (!$update) {
 5066:                 $update = $then;
 5067:             }
 5068:             my @liveroles;
 5069:             foreach my $role ('dh','da') {
 5070:                 if ($env{"user.role.$role./$cdom/"}) {
 5071:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
 5072:                     my $limit = $update;
 5073:                     if ($env{'request.role'} eq "$role./$cdom/") {
 5074:                         $limit = $then;
 5075:                     }
 5076:                     my $activerole = 1;
 5077:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
 5078:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
 5079:                     if ($activerole) {
 5080:                         push(@liveroles,$role);
 5081:                     }
 5082:                 }
 5083:             }
 5084:             if (@liveroles) {
 5085:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
 5086:                     my ($accessref,$accessinfo,%access_in_dom);
 5087:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
 5088:                     if (ref($roles_by_num) eq 'ARRAY') {
 5089:                         if (@{$roles_by_num}) {
 5090:                             my %settings;
 5091:                             if ($env{'request.course.id'} eq $cid) {
 5092:                                 foreach my $envkey (keys(%env)) {
 5093:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
 5094:                                         $settings{$1} = $env{$envkey};
 5095:                                     }
 5096:                                 }
 5097:                             } else {
 5098:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
 5099:                             }
 5100:                             my %setincrs;
 5101:                             if ($settings{'internal.adhocaccess'}) {
 5102:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
 5103:                             }
 5104:                             my @statuses;
 5105:                             if ($env{'environment.inststatus'}) {
 5106:                                 @statuses = split(/,/,$env{'environment.inststatus'});
 5107:                             }
 5108:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
 5109:                             if (ref($accessref) eq 'HASH') {
 5110:                                 %access_in_dom = %{$accessref};
 5111:                             }
 5112:                             foreach my $role (@{$roles_by_num}) {
 5113:                                 my ($curraccess,@okstatus,@personnel);
 5114:                                 if ($setincrs{$role}) {
 5115:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
 5116:                                     if ($curraccess eq 'status') {
 5117:                                         @okstatus = split(/\&/,$rest);
 5118:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5119:                                         @personnel = split(/\&/,$rest);
 5120:                                     }
 5121:                                 } else {
 5122:                                     $curraccess = $access_in_dom{$role};
 5123:                                     if (ref($accessinfo) eq 'HASH') {
 5124:                                         if ($curraccess eq 'status') {
 5125:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
 5126:                                                 @okstatus = @{$accessinfo->{$role}};
 5127:                                             }
 5128:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5129:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
 5130:                                                 @personnel = @{$accessinfo->{$role}};
 5131:                                             }
 5132:                                         }
 5133:                                     }
 5134:                                 }
 5135:                                 if ($curraccess eq 'none') {
 5136:                                     next;
 5137:                                 } elsif ($curraccess eq 'all') {
 5138:                                     push(@possroles,$role);
 5139:                                 } elsif ($curraccess eq 'dh') {
 5140:                                     if (grep(/^dh$/,@liveroles)) {
 5141:                                         push(@possroles,$role);
 5142:                                     } else {
 5143:                                         next;
 5144:                                     }
 5145:                                 } elsif ($curraccess eq 'da') {
 5146:                                     if (grep(/^da$/,@liveroles)) {
 5147:                                         push(@possroles,$role);
 5148:                                     } else {
 5149:                                         next;
 5150:                                     }
 5151:                                 } elsif ($curraccess eq 'status') {
 5152:                                     if (@okstatus) {
 5153:                                         if (!@statuses) {
 5154:                                             if (grep(/^default$/,@okstatus)) {
 5155:                                                 push(@possroles,$role);
 5156:                                             }
 5157:                                         } else {
 5158:                                             foreach my $status (@okstatus) {
 5159:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
 5160:                                                     push(@possroles,$role);
 5161:                                                     last;
 5162:                                                 }
 5163:                                             }
 5164:                                         }
 5165:                                     }
 5166:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5167:                                     if (grep(/^\Q$user\E$/,@personnel)) {
 5168:                                         if ($curraccess eq 'exc') {
 5169:                                             push(@possroles,$role);
 5170:                                         }
 5171:                                     } elsif ($curraccess eq 'inc') {
 5172:                                         push(@possroles,$role);
 5173:                                     }
 5174:                                 }
 5175:                             }
 5176:                         }
 5177:                     }
 5178:                 }
 5179:             }
 5180:         }
 5181:     }
 5182:     unless (ref($description) eq 'HASH') {
 5183:         if (ref($roles_by_num) eq 'ARRAY') {
 5184:             my %desc;
 5185:             map { $desc{$_} = $_; } (@{$roles_by_num});
 5186:             $description = \%desc;
 5187:         } else {
 5188:             $description = {};
 5189:         }
 5190:     }
 5191:     return (\@possroles,$description);
 5192: }
 5193: 
 5194: # ----------------------------------------------------- Frontpage Announcements
 5195: #
 5196: #
 5197: 
 5198: sub postannounce {
 5199:     my ($server,$text)=@_;
 5200:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 5201:     unless ($text=~/\w/) { $text=''; }
 5202:     return &reply('setannounce:'.&escape($text),$server);
 5203: }
 5204: 
 5205: sub getannounce {
 5206: 
 5207:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 5208: 	my $announcement='';
 5209: 	while (my $line = <$fh>) { $announcement .= $line; }
 5210: 	close($fh);
 5211: 	if ($announcement=~/\w/) { 
 5212: 	    return 
 5213:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 5214:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 5215: 	} else {
 5216: 	    return '';
 5217: 	}
 5218:     } else {
 5219: 	return '';
 5220:     }
 5221: }
 5222: 
 5223: # ---------------------------------------------------------- Course ID routines
 5224: # Deal with domain's nohist_courseid.db files
 5225: #
 5226: 
 5227: sub courseidput {
 5228:     my ($domain,$storehash,$coursehome,$caller) = @_;
 5229:     return unless (ref($storehash) eq 'HASH');
 5230:     my $outcome;
 5231:     if ($caller eq 'timeonly') {
 5232:         my $cids = '';
 5233:         foreach my $item (keys(%$storehash)) {
 5234:             $cids.=&escape($item).'&';
 5235:         }
 5236:         $cids=~s/\&$//;
 5237:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 5238:                           $coursehome);       
 5239:     } else {
 5240:         my $items = '';
 5241:         foreach my $item (keys(%$storehash)) {
 5242:             $items.= &escape($item).'='.
 5243:                      &freeze_escape($$storehash{$item}).'&';
 5244:         }
 5245:         $items=~s/\&$//;
 5246:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 5247:                           $coursehome);
 5248:     }
 5249:     if ($outcome eq 'unknown_cmd') {
 5250:         my $what;
 5251:         foreach my $cid (keys(%$storehash)) {
 5252:             $what .= &escape($cid).'=';
 5253:             foreach my $item ('description','inst_code','owner','type') {
 5254:                 $what .= &escape($storehash->{$cid}{$item}).':';
 5255:             }
 5256:             $what =~ s/\:$/&/;
 5257:         }
 5258:         $what =~ s/\&$//;  
 5259:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 5260:     } else {
 5261:         return $outcome;
 5262:     }
 5263: }
 5264: 
 5265: sub courseiddump {
 5266:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 5267:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 5268:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
 5269:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
 5270:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
 5271:     my $as_hash = 1;
 5272:     my %returnhash;
 5273:     if (!$domfilter) { $domfilter=''; }
 5274:     my %libserv = &all_library();
 5275:     foreach my $tryserver (keys(%libserv)) {
 5276:         if ( (  $hostidflag == 1 
 5277: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 5278: 	     || (!defined($hostidflag)) ) {
 5279: 
 5280: 	    if (($domfilter eq '') ||
 5281: 		(&host_domain($tryserver) eq $domfilter)) {
 5282:                 my $rep;
 5283:                 if (grep { $_ eq $tryserver } &current_machine_ids()) {
 5284:                     $rep = &LONCAPA::Lond::dump_course_id_handler(
 5285:                         join(":", (&host_domain($tryserver), $sincefilter,
 5286:                                 &escape($descfilter), &escape($instcodefilter),
 5287:                                 &escape($ownerfilter), &escape($coursefilter),
 5288:                                 &escape($typefilter), &escape($regexp_ok),
 5289:                                 $as_hash, &escape($selfenrollonly),
 5290:                                 &escape($catfilter), $showhidden, $caller,
 5291:                                 &escape($cloner), &escape($cc_clone), $cloneonly,
 5292:                                 &escape($createdbefore), &escape($createdafter),
 5293:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
 5294:                                 $reqcrsdom,&escape($reqinstcode))));
 5295:                 } else {
 5296:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
 5297:                              $sincefilter.':'.&escape($descfilter).':'.
 5298:                              &escape($instcodefilter).':'.&escape($ownerfilter).
 5299:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
 5300:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
 5301:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
 5302:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
 5303:                              &escape($cc_clone).':'.$cloneonly.':'.
 5304:                              &escape($createdbefore).':'.&escape($createdafter).':'.
 5305:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
 5306:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
 5307:                 }
 5308: 
 5309:                 my @pairs=split(/\&/,$rep);
 5310:                 foreach my $item (@pairs) {
 5311:                     my ($key,$value)=split(/\=/,$item,2);
 5312:                     $key = &unescape($key);
 5313:                     next if ($key =~ /^error: 2 /);
 5314:                     my $result = &thaw_unescape($value);
 5315:                     if (ref($result) eq 'HASH') {
 5316:                         $returnhash{$key}=$result;
 5317:                     } else {
 5318:                         my @responses = split(/:/,$value);
 5319:                         my @items = ('description','inst_code','owner','type');
 5320:                         for (my $i=0; $i<@responses; $i++) {
 5321:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 5322:                         }
 5323:                     }
 5324:                 }
 5325:             }
 5326:         }
 5327:     }
 5328:     return %returnhash;
 5329: }
 5330: 
 5331: sub courselastaccess {
 5332:     my ($cdom,$cnum,$hostidref) = @_;
 5333:     my %returnhash;
 5334:     if ($cdom && $cnum) {
 5335:         my $chome = &homeserver($cnum,$cdom);
 5336:         if ($chome ne 'no_host') {
 5337:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
 5338:             &extract_lastaccess(\%returnhash,$rep);
 5339:         }
 5340:     } else {
 5341:         if (!$cdom) { $cdom=''; }
 5342:         my %libserv = &all_library();
 5343:         foreach my $tryserver (keys(%libserv)) {
 5344:             if (ref($hostidref) eq 'ARRAY') {
 5345:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
 5346:             } 
 5347:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
 5348:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
 5349:                 &extract_lastaccess(\%returnhash,$rep);
 5350:             }
 5351:         }
 5352:     }
 5353:     return %returnhash;
 5354: }
 5355: 
 5356: sub extract_lastaccess {
 5357:     my ($returnhash,$rep) = @_;
 5358:     if (ref($returnhash) eq 'HASH') {
 5359:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
 5360:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
 5361:                  $rep eq '') {
 5362:             my @pairs=split(/\&/,$rep);
 5363:             foreach my $item (@pairs) {
 5364:                 my ($key,$value)=split(/\=/,$item,2);
 5365:                 $key = &unescape($key);
 5366:                 next if ($key =~ /^error: 2 /);
 5367:                 $returnhash->{$key} = &thaw_unescape($value);
 5368:             }
 5369:         }
 5370:     }
 5371:     return;
 5372: }
 5373: 
 5374: # ---------------------------------------------------------- DC e-mail
 5375: 
 5376: sub dcmailput {
 5377:     my ($domain,$msgid,$message,$server)=@_;
 5378:     my $status = &Apache::lonnet::critical(
 5379:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 5380:        &escape($message),$server);
 5381:     return $status;
 5382: }
 5383: 
 5384: sub dcmaildump {
 5385:     my ($dom,$startdate,$enddate,$senders) = @_;
 5386:     my %returnhash=();
 5387: 
 5388:     if (defined(&domain($dom,'primary'))) {
 5389:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 5390:                                                          &escape($enddate).':';
 5391: 	my @esc_senders=map { &escape($_)} @$senders;
 5392: 	$cmd.=&escape(join('&',@esc_senders));
 5393: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 5394:             my ($key,$value) = split(/\=/,$line,2);
 5395:             if (($key) && ($value)) {
 5396:                 $returnhash{&unescape($key)} = &unescape($value);
 5397:             }
 5398:         }
 5399:     }
 5400:     return %returnhash;
 5401: }
 5402: # ---------------------------------------------------------- Domain roles
 5403: 
 5404: sub get_domain_roles {
 5405:     my ($dom,$roles,$startdate,$enddate)=@_;
 5406:     if ((!defined($startdate)) || ($startdate eq '')) {
 5407:         $startdate = '.';
 5408:     }
 5409:     if ((!defined($enddate)) || ($enddate eq '')) {
 5410:         $enddate = '.';
 5411:     }
 5412:     my $rolelist;
 5413:     if (ref($roles) eq 'ARRAY') {
 5414:         $rolelist = join('&',@{$roles});
 5415:     }
 5416:     my %personnel = ();
 5417: 
 5418:     my %servers = &get_servers($dom,'library');
 5419:     foreach my $tryserver (keys(%servers)) {
 5420: 	%{$personnel{$tryserver}}=();
 5421: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 5422: 					    &escape($startdate).':'.
 5423: 					    &escape($enddate).':'.
 5424: 					    &escape($rolelist), $tryserver))) {
 5425: 	    my ($key,$value) = split(/\=/,$line,2);
 5426: 	    if (($key) && ($value)) {
 5427: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 5428: 	    }
 5429: 	}
 5430:     }
 5431:     return %personnel;
 5432: }
 5433: 
 5434: sub get_active_domroles {
 5435:     my ($dom,$roles) = @_;
 5436:     return () unless (ref($roles) eq 'ARRAY');
 5437:     my $now = time;
 5438:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
 5439:     my %domroles;
 5440:     foreach my $server (keys(%dompersonnel)) {
 5441:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
 5442:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
 5443:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
 5444:         }
 5445:     }
 5446:     return %domroles;
 5447: }
 5448: 
 5449: # ----------------------------------------------------------- Interval timing 
 5450: 
 5451: {
 5452: # Caches needed for speedup of navmaps
 5453: # We don't want to cache this for very long at all (5 seconds at most)
 5454: # 
 5455: # The user for whom we cache
 5456: my $cachedkey='';
 5457: # The cached times for this user
 5458: my %cachedtimes=();
 5459: # When this was last done
 5460: my $cachedtime='';
 5461: 
 5462: sub load_all_first_access {
 5463:     my ($uname,$udom)=@_;
 5464:     if (($cachedkey eq $uname.':'.$udom) &&
 5465:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
 5466:         return;
 5467:     }
 5468:     $cachedtime=time;
 5469:     $cachedkey=$uname.':'.$udom;
 5470:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
 5471: }
 5472: 
 5473: sub get_first_access {
 5474:     my ($type,$argsymb,$argmap)=@_;
 5475:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 5476:     if ($argsymb) { $symb=$argsymb; }
 5477:     my ($map,$id,$res)=&decode_symb($symb);
 5478:     if ($argmap) { $map = $argmap; }
 5479:     if ($type eq 'course') {
 5480: 	$res='course';
 5481:     } elsif ($type eq 'map') {
 5482: 	$res=&symbread($map);
 5483:     } else {
 5484: 	$res=$symb;
 5485:     }
 5486:     &load_all_first_access($uname,$udom);
 5487:     return $cachedtimes{"$courseid\0$res"};
 5488: }
 5489: 
 5490: sub set_first_access {
 5491:     my ($type,$interval)=@_;
 5492:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 5493:     my ($map,$id,$res)=&decode_symb($symb);
 5494:     if ($type eq 'course') {
 5495: 	$res='course';
 5496:     } elsif ($type eq 'map') {
 5497: 	$res=&symbread($map);
 5498:     } else {
 5499: 	$res=$symb;
 5500:     }
 5501:     $cachedkey='';
 5502:     my $firstaccess=&get_first_access($type,$symb,$map);
 5503:     if ($firstaccess) {
 5504:         &logthis("First access time already set ($firstaccess) when attempting ".
 5505:                  "to set new value (type: $type, extent: $res) for $uname:$udom ".
 5506:                  "in $courseid");
 5507:         return 'already_set';
 5508:     } else {
 5509:         my $start = time;
 5510: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
 5511:                           $udom,$uname);
 5512:         if ($putres eq 'ok') {
 5513:             &put('timerinterval',{"$courseid\0$res"=>$interval},
 5514:                  $udom,$uname); 
 5515:             &appenv(
 5516:                      {
 5517:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
 5518:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
 5519:                      }
 5520:                   );
 5521:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
 5522:                 $cachedtimes{"$courseid\0$res"} = $start;
 5523:             }
 5524:         } elsif ($putres ne 'refused') {
 5525:             &logthis("Result: $putres when attempting to set first access time ".
 5526:                      "(type: $type, extent: $res) for $uname:$udom in $courseid");
 5527:         }
 5528:         return $putres;
 5529:     }
 5530:     return 'already_set';
 5531: }
 5532: }
 5533: 
 5534: sub checkout {
 5535:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
 5536:     my $now=time;
 5537:     my $lonhost=$perlvar{'lonHostID'};
 5538:     my $ip = &get_requestor_ip();
 5539:     my $infostr=&escape(
 5540:                  'CHECKOUTTOKEN&'.
 5541:                  $tuname.'&'.
 5542:                  $tudom.'&'.
 5543:                  $tcrsid.'&'.
 5544:                  $symb.'&'.
 5545:                  $now.'&'.$ip);
 5546:     my $token=&reply('tmpput:'.$infostr,$lonhost);
 5547:     if ($token=~/^error\:/) {
 5548:         &logthis("<font color=\"blue\">WARNING: ".
 5549:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
 5550:                  "</font>");
 5551:         return '';
 5552:     }
 5553: 
 5554:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
 5555:     $token=~tr/a-z/A-Z/;
 5556: 
 5557:     my %infohash=('resource.0.outtoken' => $token,
 5558:                   'resource.0.checkouttime' => $now,
 5559:                   'resource.0.outremote' => $ip);
 5560: 
 5561:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 5562:        return '';
 5563:     } else {
 5564:         &logthis("<font color=\"blue\">WARNING: ".
 5565:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
 5566:                  "</font>");
 5567:     }
 5568: 
 5569:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 5570:                          &escape('Checkout '.$infostr.' - '.
 5571:                                                  $token)) ne 'ok') {
 5572:         return '';
 5573:     } else {
 5574:         &logthis("<font color=\"blue\">WARNING: ".
 5575:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
 5576:                  "</font>");
 5577:     }
 5578:     return $token;
 5579: }
 5580: 
 5581: # ------------------------------------------------------------ Check in an item
 5582: 
 5583: sub checkin {
 5584:     my $token=shift;
 5585:     my $now=time;
 5586:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
 5587:     $lonhost=~tr/A-Z/a-z/;
 5588:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
 5589:     $dtoken=~s/\W/\_/g;
 5590:     my $ip = &get_requestor_ip();
 5591:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
 5592:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
 5593: 
 5594:     unless (($tuname) && ($tudom)) {
 5595:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
 5596:         return '';
 5597:     }
 5598: 
 5599:     unless (&allowed('mgr',$tcrsid)) {
 5600:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
 5601:                  $env{'user.name'}.' - '.$env{'user.domain'});
 5602:         return '';
 5603:     }
 5604: 
 5605:     my %infohash=('resource.0.intoken' => $token,
 5606:                   'resource.0.checkintime' => $now,
 5607:                   'resource.0.inremote' => $ip);
 5608: 
 5609:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 5610:        return '';
 5611:     }
 5612: 
 5613:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 5614:                          &escape('Checkin - '.$token)) ne 'ok') {
 5615:         return '';
 5616:     }
 5617: 
 5618:     return ($symb,$tuname,$tudom,$tcrsid);
 5619: }
 5620: 
 5621: # --------------------------------------------- Set Expire Date for Spreadsheet
 5622: 
 5623: sub expirespread {
 5624:     my ($uname,$udom,$stype,$usymb)=@_;
 5625:     my $cid=$env{'request.course.id'}; 
 5626:     if ($cid) {
 5627:        my $now=time;
 5628:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 5629:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 5630:                             $env{'course.'.$cid.'.num'}.
 5631: 	        	    ':nohist_expirationdates:'.
 5632:                             &escape($key).'='.$now,
 5633:                             $env{'course.'.$cid.'.home'})
 5634:     }
 5635:     return 'ok';
 5636: }
 5637: 
 5638: # ----------------------------------------------------- Devalidate Spreadsheets
 5639: 
 5640: sub devalidate {
 5641:     my ($symb,$uname,$udom)=@_;
 5642:     my $cid=$env{'request.course.id'}; 
 5643:     if ($cid) {
 5644:         # delete the stored spreadsheets for
 5645:         # - the student level sheet of this user in course's homespace
 5646:         # - the assessment level sheet for this resource 
 5647:         #   for this user in user's homespace
 5648: 	# - current conditional state info
 5649: 	my $key=$uname.':'.$udom.':';
 5650:         my $status=
 5651: 	    &del('nohist_calculatedsheets',
 5652: 		 [$key.'studentcalc:'],
 5653: 		 $env{'course.'.$cid.'.domain'},
 5654: 		 $env{'course.'.$cid.'.num'})
 5655: 		.' '.
 5656: 	    &del('nohist_calculatedsheets_'.$cid,
 5657: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 5658:         unless ($status eq 'ok ok') {
 5659:            &logthis('Could not devalidate spreadsheet '.
 5660:                     $uname.' at '.$udom.' for '.
 5661: 		    $symb.': '.$status);
 5662:         }
 5663: 	&delenv('user.state.'.$cid);
 5664:     }
 5665: }
 5666: 
 5667: sub get_scalar {
 5668:     my ($string,$end) = @_;
 5669:     my $value;
 5670:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 5671: 	$value = $1;
 5672:     } elsif ($$string =~ s/^([^&]*?)&//) {
 5673: 	$value = $1;
 5674:     }
 5675:     return &unescape($value);
 5676: }
 5677: 
 5678: sub array2str {
 5679:   my (@array) = @_;
 5680:   my $result=&arrayref2str(\@array);
 5681:   $result=~s/^__ARRAY_REF__//;
 5682:   $result=~s/__END_ARRAY_REF__$//;
 5683:   return $result;
 5684: }
 5685: 
 5686: sub arrayref2str {
 5687:   my ($arrayref) = @_;
 5688:   my $result='__ARRAY_REF__';
 5689:   foreach my $elem (@$arrayref) {
 5690:     if(ref($elem) eq 'ARRAY') {
 5691:       $result.=&arrayref2str($elem).'&';
 5692:     } elsif(ref($elem) eq 'HASH') {
 5693:       $result.=&hashref2str($elem).'&';
 5694:     } elsif(ref($elem)) {
 5695:       #print("Got a ref of ".(ref($elem))." skipping.");
 5696:     } else {
 5697:       $result.=&escape($elem).'&';
 5698:     }
 5699:   }
 5700:   $result=~s/\&$//;
 5701:   $result .= '__END_ARRAY_REF__';
 5702:   return $result;
 5703: }
 5704: 
 5705: sub hash2str {
 5706:   my (%hash) = @_;
 5707:   my $result=&hashref2str(\%hash);
 5708:   $result=~s/^__HASH_REF__//;
 5709:   $result=~s/__END_HASH_REF__$//;
 5710:   return $result;
 5711: }
 5712: 
 5713: sub hashref2str {
 5714:   my ($hashref)=@_;
 5715:   my $result='__HASH_REF__';
 5716:   foreach my $key (sort(keys(%$hashref))) {
 5717:     if (ref($key) eq 'ARRAY') {
 5718:       $result.=&arrayref2str($key).'=';
 5719:     } elsif (ref($key) eq 'HASH') {
 5720:       $result.=&hashref2str($key).'=';
 5721:     } elsif (ref($key)) {
 5722:       $result.='=';
 5723:       #print("Got a ref of ".(ref($key))." skipping.");
 5724:     } else {
 5725: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
 5726:     }
 5727: 
 5728:     if(ref($hashref->{$key}) eq 'ARRAY') {
 5729:       $result.=&arrayref2str($hashref->{$key}).'&';
 5730:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 5731:       $result.=&hashref2str($hashref->{$key}).'&';
 5732:     } elsif(ref($hashref->{$key})) {
 5733:        $result.='&';
 5734:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 5735:     } else {
 5736:       $result.=&escape($hashref->{$key}).'&';
 5737:     }
 5738:   }
 5739:   $result=~s/\&$//;
 5740:   $result .= '__END_HASH_REF__';
 5741:   return $result;
 5742: }
 5743: 
 5744: sub str2hash {
 5745:     my ($string)=@_;
 5746:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 5747:     return %$hash;
 5748: }
 5749: 
 5750: sub str2hashref {
 5751:   my ($string) = @_;
 5752: 
 5753:   my %hash;
 5754: 
 5755:   if($string !~ /^__HASH_REF__/) {
 5756:       if (! ($string eq '' || !defined($string))) {
 5757: 	  $hash{'error'}='Not hash reference';
 5758:       }
 5759:       return (\%hash, $string);
 5760:   }
 5761: 
 5762:   $string =~ s/^__HASH_REF__//;
 5763: 
 5764:   while($string !~ /^__END_HASH_REF__/) {
 5765:       #key
 5766:       my $key='';
 5767:       if($string =~ /^__HASH_REF__/) {
 5768:           ($key, $string)=&str2hashref($string);
 5769:           if(defined($key->{'error'})) {
 5770:               $hash{'error'}='Bad data';
 5771:               return (\%hash, $string);
 5772:           }
 5773:       } elsif($string =~ /^__ARRAY_REF__/) {
 5774:           ($key, $string)=&str2arrayref($string);
 5775:           if($key->[0] eq 'Array reference error') {
 5776:               $hash{'error'}='Bad data';
 5777:               return (\%hash, $string);
 5778:           }
 5779:       } else {
 5780:           $string =~ s/^(.*?)=//;
 5781: 	  $key=&unescape($1);
 5782:       }
 5783:       $string =~ s/^=//;
 5784: 
 5785:       #value
 5786:       my $value='';
 5787:       if($string =~ /^__HASH_REF__/) {
 5788:           ($value, $string)=&str2hashref($string);
 5789:           if(defined($value->{'error'})) {
 5790:               $hash{'error'}='Bad data';
 5791:               return (\%hash, $string);
 5792:           }
 5793:       } elsif($string =~ /^__ARRAY_REF__/) {
 5794:           ($value, $string)=&str2arrayref($string);
 5795:           if($value->[0] eq 'Array reference error') {
 5796:               $hash{'error'}='Bad data';
 5797:               return (\%hash, $string);
 5798:           }
 5799:       } else {
 5800: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 5801:       }
 5802:       $string =~ s/^&//;
 5803: 
 5804:       $hash{$key}=$value;
 5805:   }
 5806: 
 5807:   $string =~ s/^__END_HASH_REF__//;
 5808: 
 5809:   return (\%hash, $string);
 5810: }
 5811: 
 5812: sub str2array {
 5813:     my ($string)=@_;
 5814:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 5815:     return @$array;
 5816: }
 5817: 
 5818: sub str2arrayref {
 5819:   my ($string) = @_;
 5820:   my @array;
 5821: 
 5822:   if($string !~ /^__ARRAY_REF__/) {
 5823:       if (! ($string eq '' || !defined($string))) {
 5824: 	  $array[0]='Array reference error';
 5825:       }
 5826:       return (\@array, $string);
 5827:   }
 5828: 
 5829:   $string =~ s/^__ARRAY_REF__//;
 5830: 
 5831:   while($string !~ /^__END_ARRAY_REF__/) {
 5832:       my $value='';
 5833:       if($string =~ /^__HASH_REF__/) {
 5834:           ($value, $string)=&str2hashref($string);
 5835:           if(defined($value->{'error'})) {
 5836:               $array[0] ='Array reference error';
 5837:               return (\@array, $string);
 5838:           }
 5839:       } elsif($string =~ /^__ARRAY_REF__/) {
 5840:           ($value, $string)=&str2arrayref($string);
 5841:           if($value->[0] eq 'Array reference error') {
 5842:               $array[0] ='Array reference error';
 5843:               return (\@array, $string);
 5844:           }
 5845:       } else {
 5846: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 5847:       }
 5848:       $string =~ s/^&//;
 5849: 
 5850:       push(@array, $value);
 5851:   }
 5852: 
 5853:   $string =~ s/^__END_ARRAY_REF__//;
 5854: 
 5855:   return (\@array, $string);
 5856: }
 5857: 
 5858: # -------------------------------------------------------------------Temp Store
 5859: 
 5860: sub tmpreset {
 5861:   my ($symb,$namespace,$domain,$stuname) = @_;
 5862:   if (!$symb) {
 5863:     $symb=&symbread();
 5864:     if (!$symb) { $symb= $env{'request.url'}; }
 5865:   }
 5866:   $symb=escape($symb);
 5867: 
 5868:   if (!$namespace) { $namespace=$env{'request.state'}; }
 5869:   $namespace=~s/\//\_/g;
 5870:   $namespace=~s/\W//g;
 5871: 
 5872:   if (!$domain) { $domain=$env{'user.domain'}; }
 5873:   if (!$stuname) { $stuname=$env{'user.name'}; }
 5874:   if ($domain eq 'public' && $stuname eq 'public') {
 5875:       $stuname=$ENV{'REMOTE_ADDR'};
 5876:   }
 5877:   my $path=LONCAPA::tempdir();
 5878:   my %hash;
 5879:   if (tie(%hash,'GDBM_File',
 5880: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 5881: 	  &GDBM_WRCREAT(),0640)) {
 5882:     foreach my $key (keys(%hash)) {
 5883:       if ($key=~ /:$symb/) {
 5884: 	delete($hash{$key});
 5885:       }
 5886:     }
 5887:   }
 5888: }
 5889: 
 5890: sub tmpstore {
 5891:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 5892: 
 5893:   if (!$symb) {
 5894:     $symb=&symbread();
 5895:     if (!$symb) { $symb= $env{'request.url'}; }
 5896:   }
 5897:   $symb=escape($symb);
 5898: 
 5899:   if (!$namespace) {
 5900:     # I don't think we would ever want to store this for a course.
 5901:     # it seems this will only be used if we don't have a course.
 5902:     #$namespace=$env{'request.course.id'};
 5903:     #if (!$namespace) {
 5904:       $namespace=$env{'request.state'};
 5905:     #}
 5906:   }
 5907:   $namespace=~s/\//\_/g;
 5908:   $namespace=~s/\W//g;
 5909:   if (!$domain) { $domain=$env{'user.domain'}; }
 5910:   if (!$stuname) { $stuname=$env{'user.name'}; }
 5911:   if ($domain eq 'public' && $stuname eq 'public') {
 5912:       $stuname=$ENV{'REMOTE_ADDR'};
 5913:   }
 5914:   my $now=time;
 5915:   my %hash;
 5916:   my $path=LONCAPA::tempdir();
 5917:   if (tie(%hash,'GDBM_File',
 5918: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 5919: 	  &GDBM_WRCREAT(),0640)) {
 5920:     $hash{"version:$symb"}++;
 5921:     my $version=$hash{"version:$symb"};
 5922:     my $allkeys=''; 
 5923:     foreach my $key (keys(%$storehash)) {
 5924:       $allkeys.=$key.':';
 5925:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 5926:     }
 5927:     $hash{"$version:$symb:timestamp"}=$now;
 5928:     $allkeys.='timestamp';
 5929:     $hash{"$version:keys:$symb"}=$allkeys;
 5930:     if (untie(%hash)) {
 5931:       return 'ok';
 5932:     } else {
 5933:       return "error:$!";
 5934:     }
 5935:   } else {
 5936:     return "error:$!";
 5937:   }
 5938: }
 5939: 
 5940: # -----------------------------------------------------------------Temp Restore
 5941: 
 5942: sub tmprestore {
 5943:   my ($symb,$namespace,$domain,$stuname) = @_;
 5944: 
 5945:   if (!$symb) {
 5946:     $symb=&symbread();
 5947:     if (!$symb) { $symb= $env{'request.url'}; }
 5948:   }
 5949:   $symb=escape($symb);
 5950: 
 5951:   if (!$namespace) { $namespace=$env{'request.state'}; }
 5952: 
 5953:   if (!$domain) { $domain=$env{'user.domain'}; }
 5954:   if (!$stuname) { $stuname=$env{'user.name'}; }
 5955:   if ($domain eq 'public' && $stuname eq 'public') {
 5956:       $stuname=$ENV{'REMOTE_ADDR'};
 5957:   }
 5958:   my %returnhash;
 5959:   $namespace=~s/\//\_/g;
 5960:   $namespace=~s/\W//g;
 5961:   my %hash;
 5962:   my $path=LONCAPA::tempdir();
 5963:   if (tie(%hash,'GDBM_File',
 5964: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 5965: 	  &GDBM_READER(),0640)) {
 5966:     my $version=$hash{"version:$symb"};
 5967:     $returnhash{'version'}=$version;
 5968:     my $scope;
 5969:     for ($scope=1;$scope<=$version;$scope++) {
 5970:       my $vkeys=$hash{"$scope:keys:$symb"};
 5971:       my @keys=split(/:/,$vkeys);
 5972:       my $key;
 5973:       $returnhash{"$scope:keys"}=$vkeys;
 5974:       foreach $key (@keys) {
 5975: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 5976: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 5977:       }
 5978:     }
 5979:     if (!(untie(%hash))) {
 5980:       return "error:$!";
 5981:     }
 5982:   } else {
 5983:     return "error:$!";
 5984:   }
 5985:   return %returnhash;
 5986: }
 5987: 
 5988: # ----------------------------------------------------------------------- Store
 5989: 
 5990: sub store {
 5991:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 5992:     my $home='';
 5993: 
 5994:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 5995: 
 5996:     $symb=&symbclean($symb);
 5997:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 5998: 
 5999:     if (!$domain) { $domain=$env{'user.domain'}; }
 6000:     if (!$stuname) { $stuname=$env{'user.name'}; }
 6001: 
 6002:     &devalidate($symb,$stuname,$domain);
 6003: 
 6004:     $symb=escape($symb);
 6005:     if (!$namespace) { 
 6006:        unless ($namespace=$env{'request.course.id'}) { 
 6007:           return ''; 
 6008:        } 
 6009:     }
 6010:     if (!$home) { $home=$env{'user.home'}; }
 6011: 
 6012:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 6013:     $$storehash{'host'}=$perlvar{'lonHostID'};
 6014: 
 6015:     my $namevalue='';
 6016:     foreach my $key (keys(%$storehash)) {
 6017:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 6018:     }
 6019:     $namevalue=~s/\&$//;
 6020:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 6021:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 6022: }
 6023: 
 6024: # -------------------------------------------------------------- Critical Store
 6025: 
 6026: sub cstore {
 6027:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 6028:     my $home='';
 6029: 
 6030:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 6031: 
 6032:     $symb=&symbclean($symb);
 6033:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 6034: 
 6035:     if (!$domain) { $domain=$env{'user.domain'}; }
 6036:     if (!$stuname) { $stuname=$env{'user.name'}; }
 6037: 
 6038:     &devalidate($symb,$stuname,$domain);
 6039: 
 6040:     $symb=escape($symb);
 6041:     if (!$namespace) { 
 6042:        unless ($namespace=$env{'request.course.id'}) { 
 6043:           return ''; 
 6044:        } 
 6045:     }
 6046:     if (!$home) { $home=$env{'user.home'}; }
 6047: 
 6048:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 6049:     $$storehash{'host'}=$perlvar{'lonHostID'};
 6050: 
 6051:     my $namevalue='';
 6052:     foreach my $key (keys(%$storehash)) {
 6053:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 6054:     }
 6055:     $namevalue=~s/\&$//;
 6056:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 6057:     return critical
 6058:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 6059: }
 6060: 
 6061: # --------------------------------------------------------------------- Restore
 6062: 
 6063: sub restore {
 6064:     my ($symb,$namespace,$domain,$stuname) = @_;
 6065:     my $home='';
 6066: 
 6067:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 6068: 
 6069:     if (!$symb) {
 6070:         return if ($namespace eq 'courserequests');
 6071:         unless ($symb=escape(&symbread())) { return ''; }
 6072:     } else {
 6073:         unless ($namespace eq 'courserequests') {
 6074:             $symb=&escape(&symbclean($symb));
 6075:         }
 6076:     }
 6077:     if (!$namespace) { 
 6078:        unless ($namespace=$env{'request.course.id'}) { 
 6079:           return ''; 
 6080:        } 
 6081:     }
 6082:     if (!$domain) { $domain=$env{'user.domain'}; }
 6083:     if (!$stuname) { $stuname=$env{'user.name'}; }
 6084:     if (!$home) { $home=$env{'user.home'}; }
 6085:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 6086: 
 6087:     my %returnhash=();
 6088:     foreach my $line (split(/\&/,$answer)) {
 6089: 	my ($name,$value)=split(/\=/,$line);
 6090:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 6091:     }
 6092:     my $version;
 6093:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 6094:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 6095:           $returnhash{$item}=$returnhash{$version.':'.$item};
 6096:        }
 6097:     }
 6098:     return %returnhash;
 6099: }
 6100: 
 6101: # ---------------------------------------------------------- Course Description
 6102: #
 6103: #  
 6104: 
 6105: sub coursedescription {
 6106:     my ($courseid,$args)=@_;
 6107:     $courseid=~s/^\///;
 6108:     $courseid=~s/\_/\//g;
 6109:     my ($cdomain,$cnum)=split(/\//,$courseid);
 6110:     my $chome=&homeserver($cnum,$cdomain);
 6111:     my $normalid=$cdomain.'_'.$cnum;
 6112:     # need to always cache even if we get errors otherwise we keep 
 6113:     # trying and trying and trying to get the course description.
 6114:     my %envhash=();
 6115:     my %returnhash=();
 6116:     
 6117:     my $expiretime=600;
 6118:     if ($env{'request.course.id'} eq $normalid) {
 6119: 	$expiretime=120;
 6120:     }
 6121: 
 6122:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 6123:     if (!$args->{'freshen_cache'}
 6124: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 6125: 	foreach my $key (keys(%env)) {
 6126: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 6127: 	    my ($setting) = $1;
 6128: 	    $returnhash{$setting} = $env{$key};
 6129: 	}
 6130: 	return %returnhash;
 6131:     }
 6132: 
 6133:     # get the data again
 6134: 
 6135:     if (!$args->{'one_time'}) {
 6136: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 6137:     }
 6138: 
 6139:     if ($chome ne 'no_host') {
 6140:        %returnhash=&dump('environment',$cdomain,$cnum);
 6141:        if (!exists($returnhash{'con_lost'})) {
 6142: 	   my $username = $env{'user.name'}; # Defult username
 6143: 	   if(defined $args->{'user'}) {
 6144: 	       $username = $args->{'user'};
 6145: 	   }
 6146:            $returnhash{'home'}= $chome;
 6147: 	   $returnhash{'domain'} = $cdomain;
 6148: 	   $returnhash{'num'} = $cnum;
 6149:            if (!defined($returnhash{'type'})) {
 6150:                $returnhash{'type'} = 'Course';
 6151:            }
 6152:            while (my ($name,$value) = each %returnhash) {
 6153:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 6154:            }
 6155:            $returnhash{'url'}=&clutter($returnhash{'url'});
 6156:            $returnhash{'fn'}=LONCAPA::tempdir() .
 6157: 	       $username.'_'.$cdomain.'_'.$cnum;
 6158:            $envhash{'course.'.$normalid.'.home'}=$chome;
 6159:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 6160:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 6161:        }
 6162:     }
 6163:     if (!$args->{'one_time'}) {
 6164: 	&appenv(\%envhash);
 6165:     }
 6166:     return %returnhash;
 6167: }
 6168: 
 6169: sub update_released_required {
 6170:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
 6171:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
 6172:         $cid = $env{'request.course.id'};
 6173:         $cdom = $env{'course.'.$cid.'.domain'};
 6174:         $cnum = $env{'course.'.$cid.'.num'};
 6175:         $chome = $env{'course.'.$cid.'.home'};
 6176:     }
 6177:     if ($needsrelease) {
 6178:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
 6179:         my $needsupdate;
 6180:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
 6181:             $needsupdate = 1;
 6182:         } else {
 6183:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
 6184:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
 6185:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
 6186:                 $needsupdate = 1;
 6187:             }
 6188:         }
 6189:         if ($needsupdate) {
 6190:             my %needshash = (
 6191:                              'internal.releaserequired' => $needsrelease,
 6192:                             );
 6193:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
 6194:             if ($putresult eq 'ok') {
 6195:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
 6196:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 6197:                 if (ref($crsinfo{$cid}) eq 'HASH') {
 6198:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
 6199:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
 6200:                 }
 6201:             }
 6202:         }
 6203:     }
 6204:     return;
 6205: }
 6206: 
 6207: # -------------------------------------------------See if a user is privileged
 6208: 
 6209: sub privileged {
 6210:     my ($username,$domain,$possdomains,$possroles)=@_;
 6211:     my $now = time;
 6212:     my $roles;
 6213:     if (ref($possroles) eq 'ARRAY') {
 6214:         $roles = $possroles;
 6215:     } else {
 6216:         $roles = ['dc','su'];
 6217:     }
 6218:     if (ref($possdomains) eq 'ARRAY') {
 6219:         my %privileged = &privileged_by_domain($possdomains,$roles);
 6220:         foreach my $dom (@{$possdomains}) {
 6221:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
 6222:                 (ref($privileged{$dom}) eq 'HASH')) {
 6223:                 foreach my $role (@{$roles}) {
 6224:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 6225:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
 6226:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
 6227:                             return 1 unless (($end && $end < $now) ||
 6228:                                              ($start && $start > $now));
 6229:                         }
 6230:                     }
 6231:                 }
 6232:             }
 6233:         }
 6234:     } else {
 6235:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
 6236:         my $now = time;
 6237: 
 6238:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
 6239:             my ($trole, $tend, $tstart) = split(/_/, $role);
 6240:             if (grep(/^\Q$trole\E$/,@{$roles})) {
 6241:                 return 1 unless ($tend && $tend < $now)
 6242:                         or ($tstart && $tstart > $now);
 6243:             }
 6244:         }
 6245:     }
 6246:     return 0;
 6247: }
 6248: 
 6249: sub privileged_by_domain {
 6250:     my ($domains,$roles) = @_;
 6251:     my %privileged = ();
 6252:     my $cachetime = 60*60*24;
 6253:     my $now = time;
 6254:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
 6255:         return %privileged;
 6256:     }
 6257:     foreach my $dom (@{$domains}) {
 6258:         next if (ref($privileged{$dom}) eq 'HASH');
 6259:         my $needroles;
 6260:         foreach my $role (@{$roles}) {
 6261:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
 6262:             if (defined($cached)) {
 6263:                 if (ref($result) eq 'HASH') {
 6264:                     $privileged{$dom}{$role} = $result;
 6265:                 }
 6266:             } else {
 6267:                 $needroles = 1;
 6268:             }
 6269:         }
 6270:         if ($needroles) {
 6271:             my %dompersonnel = &get_domain_roles($dom,$roles);
 6272:             $privileged{$dom} = {};
 6273:             foreach my $server (keys(%dompersonnel)) {
 6274:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 6275:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
 6276:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
 6277:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
 6278:                         next if ($end && $end < $now);
 6279:                         $privileged{$dom}{$trole}{$uname.':'.$udom} =
 6280:                             $dompersonnel{$server}{$item};
 6281:                     }
 6282:                 }
 6283:             }
 6284:             if (ref($privileged{$dom}) eq 'HASH') {
 6285:                 foreach my $role (@{$roles}) {
 6286:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 6287:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
 6288:                     } else {
 6289:                         my %hash = ();
 6290:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
 6291:                     }
 6292:                 }
 6293:             }
 6294:         }
 6295:     }
 6296:     return %privileged;
 6297: }
 6298: 
 6299: # -------------------------------------------------------- Get user privileges
 6300: 
 6301: sub rolesinit {
 6302:     my ($domain, $username) = @_;
 6303:     my %userroles = ('user.login.time' => time);
 6304:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
 6305: 
 6306:     # firstaccess and timerinterval are related to timed maps/resources. 
 6307:     # also, blocking can be triggered by an activating timer
 6308:     # it's saved in the user's %env.
 6309:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
 6310:     my %timerinterval = &dump('timerinterval', $domain, $username);
 6311:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
 6312:         %timerintchk, %timerintenv);
 6313: 
 6314:     foreach my $key (keys(%firstaccess)) {
 6315:         my ($cid, $rest) = split(/\0/, $key);
 6316:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
 6317:     }
 6318: 
 6319:     foreach my $key (keys(%timerinterval)) {
 6320:         my ($cid,$rest) = split(/\0/,$key);
 6321:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
 6322:     }
 6323: 
 6324:     my %allroles=();
 6325:     my %allgroups=();
 6326: 
 6327:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
 6328:         my $role = $rolesdump{$area};
 6329:         $area =~ s/\_\w\w$//;
 6330: 
 6331:         my ($trole, $tend, $tstart, $group_privs);
 6332: 
 6333:         if ($role =~ /^cr/) {
 6334:         # Custom role, defined by a user 
 6335:         # e.g., user.role.cr/msu/smith/mynewrole
 6336:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 6337:                 $trole = $1;
 6338:                 ($tend, $tstart) = split('_', $2);
 6339:             } else {
 6340:                 $trole = $role;
 6341:             }
 6342:         } elsif ($role =~ m|^gr/|) {
 6343:         # Role of member in a group, defined within a course/community
 6344:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
 6345:             ($trole, $tend, $tstart) = split(/_/, $role);
 6346:             next if $tstart eq '-1';
 6347:             ($trole, $group_privs) = split(/\//, $trole);
 6348:             $group_privs = &unescape($group_privs);
 6349:         } else {
 6350:         # Just a normal role, defined in roles.tab
 6351:             ($trole, $tend, $tstart) = split(/_/,$role);
 6352:         }
 6353: 
 6354:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 6355:                  $username);
 6356:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 6357: 
 6358:         # role expired or not available yet?
 6359:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
 6360:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
 6361: 
 6362:         next if $area eq '' or $trole eq '';
 6363: 
 6364:         my $spec = "$trole.$area";
 6365:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
 6366: 
 6367:         if ($trole =~ /^cr\//) {
 6368:         # Custom role, defined by a user
 6369:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 6370:         } elsif ($trole eq 'gr') {
 6371:         # Role of a member in a group, defined within a course/community
 6372:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 6373:             next;
 6374:         } else {
 6375:         # Normal role, defined in roles.tab
 6376:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 6377:         }
 6378: 
 6379:         my $cid = $tdomain.'_'.$trest;
 6380:         unless ($firstaccchk{$cid}) {
 6381:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
 6382:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
 6383:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
 6384:                         $coursetimerstarts{$cid}{$item}; 
 6385:                 }
 6386:             }
 6387:             $firstaccchk{$cid} = 1;
 6388:         }
 6389:         unless ($timerintchk{$cid}) {
 6390:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
 6391:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
 6392:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
 6393:                        $coursetimerintervals{$cid}{$item};
 6394:                 }
 6395:             }
 6396:             $timerintchk{$cid} = 1;
 6397:         }
 6398:     }
 6399: 
 6400:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
 6401:                                                           \%allroles, \%allgroups);
 6402:     $env{'user.adv'} = $userroles{'user.adv'};
 6403:     $env{'user.rar'} = $userroles{'user.rar'};
 6404: 
 6405:     return (\%userroles,\%firstaccenv,\%timerintenv);
 6406: }
 6407: 
 6408: sub set_arearole {
 6409:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
 6410:     unless ($nolog) {
 6411: # log the associated role with the area
 6412:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 6413:     }
 6414:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 6415: }
 6416: 
 6417: sub custom_roleprivs {
 6418:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 6419:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 6420:     my $homsvr = &homeserver($rauthor,$rdomain);
 6421:     if (&hostname($homsvr) ne '') {
 6422:         my ($rdummy,$roledef)=
 6423:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 6424:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 6425:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 6426:             if (defined($syspriv)) {
 6427:                 if ($trest =~ /^$match_community$/) {
 6428:                     $syspriv =~ s/bre\&S//; 
 6429:                 }
 6430:                 $$allroles{'cm./'}.=':'.$syspriv;
 6431:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 6432:             }
 6433:             if ($tdomain ne '') {
 6434:                 if (defined($dompriv)) {
 6435:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 6436:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 6437:                 }
 6438:                 if (($trest ne '') && (defined($coursepriv))) {
 6439:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
 6440:                         my $rolename = $1;
 6441:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
 6442:                     }
 6443:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 6444:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 6445:                 }
 6446:             }
 6447:         }
 6448:     }
 6449: }
 6450: 
 6451: sub course_adhocrole_privs {
 6452:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
 6453:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
 6454:     if ($overrides{"internal.adhocpriv.$rolename"}) {
 6455:         my (%currprivs,%storeprivs);
 6456:         foreach my $item (split(/:/,$coursepriv)) {
 6457:             my ($priv,$restrict) = split(/\&/,$item);
 6458:             $currprivs{$priv} = $restrict;
 6459:         }
 6460:         my (%possadd,%possremove,%full);
 6461:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
 6462:             my ($priv,$restrict)=split(/\&/,$item);
 6463:             $full{$priv} = $restrict;
 6464:         }
 6465:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
 6466:              next if ($item eq '');
 6467:              my ($rule,$rest) = split(/=/,$item);
 6468:              next unless (($rule eq 'off') || ($rule eq 'on'));
 6469:              foreach my $priv (split(/:/,$rest)) {
 6470:                  if ($priv ne '') {
 6471:                      if ($rule eq 'off') {
 6472:                          $possremove{$priv} = 1;
 6473:                      } else {
 6474:                          $possadd{$priv} = 1;
 6475:                      }
 6476:                  }
 6477:              }
 6478:          }
 6479:          foreach my $priv (sort(keys(%full))) {
 6480:              if (exists($currprivs{$priv})) {
 6481:                  unless (exists($possremove{$priv})) {
 6482:                      $storeprivs{$priv} = $currprivs{$priv};
 6483:                  }
 6484:              } elsif (exists($possadd{$priv})) {
 6485:                  $storeprivs{$priv} = $full{$priv};
 6486:              }
 6487:          }
 6488:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
 6489:      }
 6490:      return $coursepriv;
 6491: }
 6492: 
 6493: sub group_roleprivs {
 6494:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 6495:     my $access = 1;
 6496:     my $now = time;
 6497:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 6498:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 6499:     if ($access) {
 6500:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 6501:         $$allgroups{$course}{$group} .=':'.$group_privs;
 6502:     }
 6503: }
 6504: 
 6505: sub standard_roleprivs {
 6506:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 6507:     if (defined($pr{$trole.':s'})) {
 6508:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 6509:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 6510:     }
 6511:     if ($tdomain ne '') {
 6512:         if (defined($pr{$trole.':d'})) {
 6513:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 6514:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 6515:         }
 6516:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 6517:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 6518:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 6519:         }
 6520:     }
 6521: }
 6522: 
 6523: sub set_userprivs {
 6524:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
 6525:     my $author=0;
 6526:     my $adv=0;
 6527:     my $rar=0;
 6528:     my %grouproles = ();
 6529:     if (keys(%{$allgroups}) > 0) {
 6530:         my @groupkeys; 
 6531:         foreach my $role (keys(%{$allroles})) {
 6532:             push(@groupkeys,$role);
 6533:         }
 6534:         if (ref($groups_roles) eq 'HASH') {
 6535:             foreach my $key (keys(%{$groups_roles})) {
 6536:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
 6537:                     push(@groupkeys,$key);
 6538:                 }
 6539:             }
 6540:         }
 6541:         if (@groupkeys > 0) {
 6542:             foreach my $role (@groupkeys) {
 6543:                 my ($trole,$area,$sec,$extendedarea);
 6544:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 6545:                     $trole = $1;
 6546:                     $area = $2;
 6547:                     $sec = $3;
 6548:                     $extendedarea = $area.$sec;
 6549:                     if (exists($$allgroups{$area})) {
 6550:                         foreach my $group (keys(%{$$allgroups{$area}})) {
 6551:                             my $spec = $trole.'.'.$extendedarea;
 6552:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
 6553:                                                 $$allgroups{$area}{$group};
 6554:                         }
 6555:                     }
 6556:                 }
 6557:             }
 6558:         }
 6559:     }
 6560:     foreach my $group (keys(%grouproles)) {
 6561:         $$allroles{$group} = $grouproles{$group};
 6562:     }
 6563:     foreach my $role (keys(%{$allroles})) {
 6564:         my %thesepriv;
 6565:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 6566:         foreach my $item (split(/:/,$$allroles{$role})) {
 6567:             if ($item ne '') {
 6568:                 my ($privilege,$restrictions)=split(/&/,$item);
 6569:                 if ($restrictions eq '') {
 6570:                     $thesepriv{$privilege}='F';
 6571:                 } elsif ($thesepriv{$privilege} ne 'F') {
 6572:                     $thesepriv{$privilege}.=$restrictions;
 6573:                 }
 6574:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 6575:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
 6576:             }
 6577:         }
 6578:         my $thesestr='';
 6579:         foreach my $priv (sort(keys(%thesepriv))) {
 6580: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 6581: 	}
 6582:         $userroles->{'user.priv.'.$role} = $thesestr;
 6583:     }
 6584:     return ($author,$adv,$rar);
 6585: }
 6586: 
 6587: sub role_status {
 6588:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 6589:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 6590:         my ($one,$two) = split(m{\./},$rolekey,2);
 6591:         (undef,undef,$$role) = split(/\./,$one,3);
 6592:         unless (!defined($$role) || $$role eq '') {
 6593:             $$where = '/'.$two;
 6594:             $$trolecode=$$role.'.'.$$where;
 6595:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 6596:             $$tstatus='is';
 6597:             if ($$tstart && $$tstart>$update) {
 6598:                 $$tstatus='future';
 6599:                 if ($$tstart<$now) {
 6600:                     if ($$tstart && $$tstart>$refresh) {
 6601:                         if (($$where ne '') && ($$role ne '')) {
 6602:                             my (%allroles,%allgroups,$group_privs,
 6603:                                 %groups_roles,@rolecodes);
 6604:                             my %userroles = (
 6605:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 6606:                             );
 6607:                             @rolecodes = ('cm'); 
 6608:                             my $spec=$$role.'.'.$$where;
 6609:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 6610:                             if ($$role =~ /^cr\//) {
 6611:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 6612:                                 push(@rolecodes,'cr');
 6613:                             } elsif ($$role eq 'gr') {
 6614:                                 push(@rolecodes,$$role);
 6615:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 6616:                                                     $env{'user.name'});
 6617:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
 6618:                                 (undef,my $group_privs) = split(/\//,$trole);
 6619:                                 $group_privs = &unescape($group_privs);
 6620:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 6621:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
 6622:                                 &get_groups_roles($tdomain,$trest,
 6623:                                                   \%course_roles,\@rolecodes,
 6624:                                                   \%groups_roles);
 6625:                             } else {
 6626:                                 push(@rolecodes,$$role);
 6627:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 6628:                             }
 6629:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
 6630:                                                                    \%groups_roles);
 6631:                             &appenv(\%userroles,\@rolecodes);
 6632:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
 6633:                         }
 6634:                     }
 6635:                     $$tstatus = 'is';
 6636:                 }
 6637:             }
 6638:             if ($$tend) {
 6639:                 if ($$tend<$update) {
 6640:                     $$tstatus='expired';
 6641:                 } elsif ($$tend<$now) {
 6642:                     $$tstatus='will_not';
 6643:                 }
 6644:             }
 6645:         }
 6646:     }
 6647: }
 6648: 
 6649: sub get_groups_roles {
 6650:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
 6651:     return unless((ref($cdom_courseroles) eq 'HASH') && 
 6652:                   (ref($rolecodes) eq 'ARRAY') && 
 6653:                   (ref($groups_roles) eq 'HASH')); 
 6654:     if (keys(%{$cdom_courseroles}) > 0) {
 6655:         my ($cnum) = ($rest =~ /^($match_courseid)/);
 6656:         if ($cdom ne '' && $cnum ne '') {
 6657:             foreach my $key (keys(%{$cdom_courseroles})) {
 6658:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
 6659:                     my $crsrole = $1;
 6660:                     my $crssec = $2;
 6661:                     if ($crsrole =~ /^cr/) {
 6662:                         unless (grep(/^cr$/,@{$rolecodes})) {
 6663:                             push(@{$rolecodes},'cr');
 6664:                         }
 6665:                     } else {
 6666:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
 6667:                             push(@{$rolecodes},$crsrole);
 6668:                         }
 6669:                     }
 6670:                     my $rolekey = "$crsrole./$cdom/$cnum";
 6671:                     if ($crssec ne '') {
 6672:                         $rolekey .= "/$crssec";
 6673:                     }
 6674:                     $rolekey .= './';
 6675:                     $groups_roles->{$rolekey} = $rolecodes;
 6676:                 }
 6677:             }
 6678:         }
 6679:     }
 6680:     return;
 6681: }
 6682: 
 6683: sub delete_env_groupprivs {
 6684:     my ($where,$courseroles,$possroles) = @_;
 6685:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
 6686:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
 6687:     unless (ref($courseroles->{$udom}) eq 'HASH') {
 6688:         %{$courseroles->{$udom}} =
 6689:             &get_my_roles('','','userroles',['active'],
 6690:                           $possroles,[$udom],1);
 6691:     }
 6692:     if (ref($courseroles->{$udom}) eq 'HASH') {
 6693:         foreach my $item (keys(%{$courseroles->{$udom}})) {
 6694:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
 6695:             my $area = '/'.$cdom.'/'.$cnum;
 6696:             my $privkey = "user.priv.$crsrole.$area";
 6697:             if ($crssec ne '') {
 6698:                 $privkey .= '/'.$crssec;
 6699:             }
 6700:             $privkey .= ".$area/$group";
 6701:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
 6702:         }
 6703:     }
 6704:     return;
 6705: }
 6706: 
 6707: sub check_adhoc_privs {
 6708:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
 6709:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 6710:     if ($sec) {
 6711:         $cckey .= '/'.$sec;
 6712:     }
 6713:     my $setprivs;
 6714:     if ($env{$cckey}) {
 6715:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 6716:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 6717:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 6718:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
 6719:             $setprivs = 1;
 6720:         }
 6721:     } else {
 6722:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
 6723:         $setprivs = 1;
 6724:     }
 6725:     return $setprivs;
 6726: }
 6727: 
 6728: sub set_adhoc_privileges {
 6729: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
 6730:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
 6731:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 6732:     if ($sec ne '') {
 6733:         $area .= '/'.$sec;
 6734:     }
 6735:     my $spec = $role.'.'.$area;
 6736:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 6737:                                   $env{'user.name'},1);
 6738:     my %rolehash = ();
 6739:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
 6740:         my $rolename = $1;
 6741:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
 6742:         my %domdef = &get_domain_defaults($dcdom);
 6743:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
 6744:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
 6745:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
 6746:             }
 6747:         }
 6748:     } else {
 6749:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
 6750:     }
 6751:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
 6752:     &appenv(\%userroles,[$role,'cm']);
 6753:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
 6754:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
 6755:         &appenv( {'request.role'        => $spec,
 6756:                   'request.role.domain' => $dcdom,
 6757:                   'request.course.sec'  => $sec, 
 6758:                  }
 6759:                );
 6760:         my $tadv=0;
 6761:         if (&allowed('adv') eq 'F') { $tadv=1; }
 6762:         &appenv({'request.role.adv'    => $tadv});
 6763:     }
 6764: }
 6765: 
 6766: # --------------------------------------------------------------- get interface
 6767: 
 6768: sub get {
 6769:    my ($namespace,$storearr,$udomain,$uname)=@_;
 6770:    my $items='';
 6771:    foreach my $item (@$storearr) {
 6772:        $items.=&escape($item).'&';
 6773:    }
 6774:    $items=~s/\&$//;
 6775:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6776:    if (!$uname) { $uname=$env{'user.name'}; }
 6777:    my $uhome=&homeserver($uname,$udomain);
 6778: 
 6779:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 6780:    my @pairs=split(/\&/,$rep);
 6781:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 6782:      return @pairs;
 6783:    }
 6784:    my %returnhash=();
 6785:    my $i=0;
 6786:    foreach my $item (@$storearr) {
 6787:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 6788:       $i++;
 6789:    }
 6790:    return %returnhash;
 6791: }
 6792: 
 6793: # --------------------------------------------------------------- del interface
 6794: 
 6795: sub del {
 6796:    my ($namespace,$storearr,$udomain,$uname)=@_;
 6797:    my $items='';
 6798:    foreach my $item (@$storearr) {
 6799:        $items.=&escape($item).'&';
 6800:    }
 6801: 
 6802:    $items=~s/\&$//;
 6803:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6804:    if (!$uname) { $uname=$env{'user.name'}; }
 6805:    my $uhome=&homeserver($uname,$udomain);
 6806:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 6807: }
 6808: 
 6809: # -------------------------------------------------------------- dump interface
 6810: 
 6811: sub unserialize {
 6812:     my ($rep, $escapedkeys) = @_;
 6813: 
 6814:     return {} if $rep =~ /^error/;
 6815: 
 6816:     my %returnhash=();
 6817:     foreach my $item (split(/\&/,$rep)) {
 6818:         my ($key, $value) = split(/=/, $item, 2);
 6819:         $key = unescape($key) unless $escapedkeys;
 6820:         next if $key =~ /^error: 2 /;
 6821:         $returnhash{$key} = &thaw_unescape($value);
 6822:     }
 6823:     return \%returnhash;
 6824: }
 6825: 
 6826: # see Lond::dump_with_regexp
 6827: # if $escapedkeys hash keys won't get unescaped.
 6828: sub dump {
 6829:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
 6830:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 6831:     if (!$uname) { $uname=$env{'user.name'}; }
 6832:     my $uhome=&homeserver($uname,$udomain);
 6833: 
 6834:     if ($regexp) {
 6835:         $regexp=&escape($regexp);
 6836:     } else {
 6837:         $regexp='.';
 6838:     }
 6839:     if (grep { $_ eq $uhome } &current_machine_ids()) {
 6840:         # user is hosted on this machine
 6841:         my $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
 6842:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
 6843:         return %{&unserialize($reply, $escapedkeys)};
 6844:     }
 6845:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 6846:     my @pairs=split(/\&/,$rep);
 6847:     my %returnhash=();
 6848:     if (!($rep =~ /^error/ )) {
 6849: 	foreach my $item (@pairs) {
 6850: 	    my ($key,$value)=split(/=/,$item,2);
 6851:             $key = &unescape($key) unless ($escapedkeys);
 6852: 	    next if ($key =~ /^error: 2 /);
 6853: 	    $returnhash{$key}=&thaw_unescape($value);
 6854: 	}
 6855:     }
 6856:     return %returnhash;
 6857: }
 6858: 
 6859: 
 6860: # --------------------------------------------------------- dumpstore interface
 6861: 
 6862: sub dumpstore {
 6863:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 6864:    # same as dump but keys must be escaped. They may contain colon separated
 6865:    # lists of values that may themself contain colons (e.g. symbs).
 6866:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
 6867: }
 6868: 
 6869: # -------------------------------------------------------------- keys interface
 6870: 
 6871: sub getkeys {
 6872:    my ($namespace,$udomain,$uname)=@_;
 6873:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6874:    if (!$uname) { $uname=$env{'user.name'}; }
 6875:    my $uhome=&homeserver($uname,$udomain);
 6876:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 6877:    my @keyarray=();
 6878:    foreach my $key (split(/\&/,$rep)) {
 6879:       next if ($key =~ /^error: 2 /);
 6880:       push(@keyarray,&unescape($key));
 6881:    }
 6882:    return @keyarray;
 6883: }
 6884: 
 6885: # --------------------------------------------------------------- currentdump
 6886: sub currentdump {
 6887:    my ($courseid,$sdom,$sname)=@_;
 6888:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 6889:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 6890:    $sname    = $env{'user.name'}         if (! defined($sname));
 6891:    my $uhome = &homeserver($sname,$sdom);
 6892:    my $rep;
 6893: 
 6894:    if (grep { $_ eq $uhome } current_machine_ids()) {
 6895:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
 6896:                    $courseid)));
 6897:    } else {
 6898:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 6899:    }
 6900: 
 6901:    return if ($rep =~ /^(error:|no_such_host)/);
 6902:    #
 6903:    my %returnhash=();
 6904:    #
 6905:    if ($rep eq "unknown_cmd") { 
 6906:        # an old lond will not know currentdump
 6907:        # Do a dump and make it look like a currentdump
 6908:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 6909:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 6910:        my %hash = @tmp;
 6911:        @tmp=();
 6912:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 6913:    } else {
 6914:        my @pairs=split(/\&/,$rep);
 6915:        foreach my $pair (@pairs) {
 6916:            my ($key,$value)=split(/=/,$pair,2);
 6917:            my ($symb,$param) = split(/:/,$key);
 6918:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 6919:                                                         &thaw_unescape($value);
 6920:        }
 6921:    }
 6922:    return %returnhash;
 6923: }
 6924: 
 6925: sub convert_dump_to_currentdump{
 6926:     my %hash = %{shift()};
 6927:     my %returnhash;
 6928:     # Code ripped from lond, essentially.  The only difference
 6929:     # here is the unescaping done by lonnet::dump().  Conceivably
 6930:     # we might run in to problems with parameter names =~ /^v\./
 6931:     while (my ($key,$value) = each(%hash)) {
 6932:         my ($v,$symb,$param) = split(/:/,$key);
 6933: 	$symb  = &unescape($symb);
 6934: 	$param = &unescape($param);
 6935:         next if ($v eq 'version' || $symb eq 'keys');
 6936:         next if (exists($returnhash{$symb}) &&
 6937:                  exists($returnhash{$symb}->{$param}) &&
 6938:                  $returnhash{$symb}->{'v.'.$param} > $v);
 6939:         $returnhash{$symb}->{$param}=$value;
 6940:         $returnhash{$symb}->{'v.'.$param}=$v;
 6941:     }
 6942:     #
 6943:     # Remove all of the keys in the hashes which keep track of
 6944:     # the version of the parameter.
 6945:     while (my ($symb,$param_hash) = each(%returnhash)) {
 6946:         # use a foreach because we are going to delete from the hash.
 6947:         foreach my $key (keys(%$param_hash)) {
 6948:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 6949:         }
 6950:     }
 6951:     return \%returnhash;
 6952: }
 6953: 
 6954: # ------------------------------------------------------ critical inc interface
 6955: 
 6956: sub cinc {
 6957:     return &inc(@_,'critical');
 6958: }
 6959: 
 6960: # --------------------------------------------------------------- inc interface
 6961: 
 6962: sub inc {
 6963:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 6964:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 6965:     if (!$uname) { $uname=$env{'user.name'}; }
 6966:     my $uhome=&homeserver($uname,$udomain);
 6967:     my $items='';
 6968:     if (! ref($store)) {
 6969:         # got a single value, so use that instead
 6970:         $items = &escape($store).'=&';
 6971:     } elsif (ref($store) eq 'SCALAR') {
 6972:         $items = &escape($$store).'=&';        
 6973:     } elsif (ref($store) eq 'ARRAY') {
 6974:         $items = join('=&',map {&escape($_);} @{$store});
 6975:     } elsif (ref($store) eq 'HASH') {
 6976:         while (my($key,$value) = each(%{$store})) {
 6977:             $items.= &escape($key).'='.&escape($value).'&';
 6978:         }
 6979:     }
 6980:     $items=~s/\&$//;
 6981:     if ($critical) {
 6982: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 6983:     } else {
 6984: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 6985:     }
 6986: }
 6987: 
 6988: # --------------------------------------------------------------- put interface
 6989: 
 6990: sub put {
 6991:    my ($namespace,$storehash,$udomain,$uname)=@_;
 6992:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6993:    if (!$uname) { $uname=$env{'user.name'}; }
 6994:    my $uhome=&homeserver($uname,$udomain);
 6995:    my $items='';
 6996:    foreach my $item (keys(%$storehash)) {
 6997:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 6998:    }
 6999:    $items=~s/\&$//;
 7000:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 7001: }
 7002: 
 7003: # ------------------------------------------------------------ newput interface
 7004: 
 7005: sub newput {
 7006:    my ($namespace,$storehash,$udomain,$uname)=@_;
 7007:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7008:    if (!$uname) { $uname=$env{'user.name'}; }
 7009:    my $uhome=&homeserver($uname,$udomain);
 7010:    my $items='';
 7011:    foreach my $key (keys(%$storehash)) {
 7012:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 7013:    }
 7014:    $items=~s/\&$//;
 7015:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 7016: }
 7017: 
 7018: # ---------------------------------------------------------  putstore interface
 7019: 
 7020: sub putstore {
 7021:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
 7022:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7023:    if (!$uname) { $uname=$env{'user.name'}; }
 7024:    my $uhome=&homeserver($uname,$udomain);
 7025:    my $items='';
 7026:    foreach my $key (keys(%$storehash)) {
 7027:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 7028:    }
 7029:    $items=~s/\&$//;
 7030:    my $esc_symb=&escape($symb);
 7031:    my $esc_v=&escape($version);
 7032:    my $reply =
 7033:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 7034: 	      $uhome);
 7035:    if (($tolog) && ($reply eq 'ok')) {
 7036:        my $namevalue='';
 7037:        foreach my $key (keys(%{$storehash})) {
 7038:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 7039:        }
 7040:        my $ip = &get_requestor_ip();
 7041:        $namevalue .= 'ip='.&escape($ip).
 7042:                      '&host='.&escape($perlvar{'lonHostID'}).
 7043:                      '&version='.$esc_v.
 7044:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
 7045:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
 7046:    }
 7047:    if ($reply eq 'unknown_cmd') {
 7048:        # gfall back to way things use to be done
 7049:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 7050: 			    $uname);
 7051:    }
 7052:    return $reply;
 7053: }
 7054: 
 7055: sub old_putstore {
 7056:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 7057:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 7058:     if (!$uname) { $uname=$env{'user.name'}; }
 7059:     my $uhome=&homeserver($uname,$udomain);
 7060:     my %newstorehash;
 7061:     foreach my $item (keys(%$storehash)) {
 7062: 	my $key = $version.':'.&escape($symb).':'.$item;
 7063: 	$newstorehash{$key} = $storehash->{$item};
 7064:     }
 7065:     my $items='';
 7066:     my %allitems = ();
 7067:     foreach my $item (keys(%newstorehash)) {
 7068: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 7069: 	    my $key = $1.':keys:'.$2;
 7070: 	    $allitems{$key} .= $3.':';
 7071: 	}
 7072: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 7073:     }
 7074:     foreach my $item (keys(%allitems)) {
 7075: 	$allitems{$item} =~ s/\:$//;
 7076: 	$items.= $item.'='.$allitems{$item}.'&';
 7077:     }
 7078:     $items=~s/\&$//;
 7079:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 7080: }
 7081: 
 7082: # ------------------------------------------------------ critical put interface
 7083: 
 7084: sub cput {
 7085:    my ($namespace,$storehash,$udomain,$uname)=@_;
 7086:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7087:    if (!$uname) { $uname=$env{'user.name'}; }
 7088:    my $uhome=&homeserver($uname,$udomain);
 7089:    my $items='';
 7090:    foreach my $item (keys(%$storehash)) {
 7091:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 7092:    }
 7093:    $items=~s/\&$//;
 7094:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 7095: }
 7096: 
 7097: # -------------------------------------------------------------- eget interface
 7098: 
 7099: sub eget {
 7100:    my ($namespace,$storearr,$udomain,$uname)=@_;
 7101:    my $items='';
 7102:    foreach my $item (@$storearr) {
 7103:        $items.=&escape($item).'&';
 7104:    }
 7105:    $items=~s/\&$//;
 7106:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7107:    if (!$uname) { $uname=$env{'user.name'}; }
 7108:    my $uhome=&homeserver($uname,$udomain);
 7109:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 7110:    my @pairs=split(/\&/,$rep);
 7111:    my %returnhash=();
 7112:    my $i=0;
 7113:    foreach my $item (@$storearr) {
 7114:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 7115:       $i++;
 7116:    }
 7117:    return %returnhash;
 7118: }
 7119: 
 7120: # ------------------------------------------------------------ tmpput interface
 7121: sub tmpput {
 7122:     my ($storehash,$server,$context)=@_;
 7123:     my $items='';
 7124:     foreach my $item (keys(%$storehash)) {
 7125: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 7126:     }
 7127:     $items=~s/\&$//;
 7128:     if (defined($context)) {
 7129:         $items .= ':'.&escape($context);
 7130:     }
 7131:     return &reply("tmpput:$items",$server);
 7132: }
 7133: 
 7134: # ------------------------------------------------------------ tmpget interface
 7135: sub tmpget {
 7136:     my ($token,$server)=@_;
 7137:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 7138:     my $rep=&reply("tmpget:$token",$server);
 7139:     my %returnhash;
 7140:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
 7141:         return %returnhash;
 7142:     }
 7143:     foreach my $item (split(/\&/,$rep)) {
 7144: 	my ($key,$value)=split(/=/,$item);
 7145: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 7146:     }
 7147:     return %returnhash;
 7148: }
 7149: 
 7150: # ------------------------------------------------------------ tmpdel interface
 7151: sub tmpdel {
 7152:     my ($token,$server)=@_;
 7153:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 7154:     return &reply("tmpdel:$token",$server);
 7155: }
 7156: 
 7157: # ------------------------------------------------------------ get_timebased_id
 7158: 
 7159: sub get_timebased_id {
 7160:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
 7161:         $maxtries) = @_;
 7162:     my ($newid,$error,$dellock);
 7163:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
 7164:         return ('','ok','invalid call to get suffix');
 7165:     }
 7166: 
 7167: # set defaults for any optional args for which values were not supplied
 7168:     if ($who eq '') {
 7169:         $who = $env{'user.name'}.':'.$env{'user.domain'};
 7170:     }
 7171:     if (!$locktries) {
 7172:         $locktries = 3;
 7173:     }
 7174:     if (!$maxtries) {
 7175:         $maxtries = 10;
 7176:     }
 7177: 
 7178:     if (($cdom eq '') || ($cnum eq '')) {
 7179:         if ($env{'request.course.id'}) {
 7180:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7181:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7182:         }
 7183:         if (($cdom eq '') || ($cnum eq '')) {
 7184:             return ('','ok','call to get suffix not in course context');
 7185:         }
 7186:     }
 7187: 
 7188: # construct locking item
 7189:     my $lockhash = {
 7190:                       $prefix."\0".'locked_'.$keyid => $who,
 7191:                    };
 7192:     my $tries = 0;
 7193: 
 7194: # attempt to get lock on nohist_$namespace file
 7195:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 7196:     while (($gotlock ne 'ok') && $tries <$locktries) {
 7197:         $tries ++;
 7198:         sleep 1;
 7199:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 7200:     }
 7201: 
 7202: # attempt to get unique identifier, based on current timestamp
 7203:     if ($gotlock eq 'ok') {
 7204:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
 7205:         my $id = time;
 7206:         $newid = $id;
 7207:         if ($idtype eq 'addcode') {
 7208:             $newid .= &sixnum_code();
 7209:         }
 7210:         my $idtries = 0;
 7211:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
 7212:             if ($idtype eq 'concat') {
 7213:                 $newid = $id.$idtries;
 7214:             } elsif ($idtype eq 'addcode') {
 7215:                 $newid = $newid.&sixnum_code();
 7216:             } else {
 7217:                 $newid ++;
 7218:             }
 7219:             $idtries ++;
 7220:         }
 7221:         if (!exists($inuse{$prefix."\0".$newid})) {
 7222:             my %new_item =  (
 7223:                               $prefix."\0".$newid => $who,
 7224:                             );
 7225:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
 7226:                                                  $cdom,$cnum);
 7227:             if ($putresult ne 'ok') {
 7228:                 undef($newid);
 7229:                 $error = 'error saving new item: '.$putresult;
 7230:             }
 7231:         } else {
 7232:              undef($newid);
 7233:              $error = ('error: no unique suffix available for the new item ');
 7234:         }
 7235: #  remove lock
 7236:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
 7237:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
 7238:     } else {
 7239:         $error = "error: could not obtain lockfile\n";
 7240:         $dellock = 'ok';
 7241:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
 7242:             $dellock = 'nolock';
 7243:         }
 7244:     }
 7245:     return ($newid,$dellock,$error);
 7246: }
 7247: 
 7248: sub sixnum_code {
 7249:     my $code;
 7250:     for (0..6) {
 7251:         $code .= int( rand(9) );
 7252:     }
 7253:     return $code;
 7254: }
 7255: 
 7256: # -------------------------------------------------- portfolio access checking
 7257: 
 7258: sub portfolio_access {
 7259:     my ($requrl,$clientip) = @_;
 7260:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 7261:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
 7262:     if ($result) {
 7263:         my %setters;
 7264:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 7265:             my ($startblock,$endblock) =
 7266:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 7267:             if ($startblock && $endblock) {
 7268:                 return 'B';
 7269:             }
 7270:         } else {
 7271:             my ($startblock,$endblock) =
 7272:                 &Apache::loncommon::blockcheck(\%setters,'port');
 7273:             if ($startblock && $endblock) {
 7274:                 return 'B';
 7275:             }
 7276:         }
 7277:     }
 7278:     if ($result eq 'ok') {
 7279:        return 'F';
 7280:     } elsif ($result =~ /^[^:]+:guest_/) {
 7281:        return 'A';
 7282:     }
 7283:     return '';
 7284: }
 7285: 
 7286: sub get_portfolio_access {
 7287:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
 7288: 
 7289:     if (!ref($access_hash)) {
 7290: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 7291: 	my %access_controls = &get_access_controls($current_perms,$group,
 7292: 						   $file_name);
 7293: 	$access_hash = $access_controls{$file_name};
 7294:     }
 7295: 
 7296:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
 7297:     my $now = time;
 7298:     if (ref($access_hash) eq 'HASH') {
 7299:         foreach my $key (keys(%{$access_hash})) {
 7300:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 7301:             if ($start > $now) {
 7302:                 next;
 7303:             }
 7304:             if ($end && $end<$now) {
 7305:                 next;
 7306:             }
 7307:             if ($scope eq 'public') {
 7308:                 $public = $key;
 7309:                 last;
 7310:             } elsif ($scope eq 'guest') {
 7311:                 $guest = $key;
 7312:             } elsif ($scope eq 'domains') {
 7313:                 push(@domains,$key);
 7314:             } elsif ($scope eq 'users') {
 7315:                 push(@users,$key);
 7316:             } elsif ($scope eq 'course') {
 7317:                 push(@courses,$key);
 7318:             } elsif ($scope eq 'group') {
 7319:                 push(@groups,$key);
 7320:             } elsif ($scope eq 'ip') {
 7321:                 push(@ips,$key);
 7322:             }
 7323:         }
 7324:         if ($public) {
 7325:             return 'ok';
 7326:         } elsif (@ips > 0) {
 7327:             my $allowed;
 7328:             foreach my $ipkey (@ips) {
 7329:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
 7330:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
 7331:                         $allowed = 1;
 7332:                         last;
 7333:                     }
 7334:                 }
 7335:             }
 7336:             if ($allowed) {
 7337:                 return 'ok';
 7338:             }
 7339:         }
 7340:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 7341:             if ($guest) {
 7342:                 return $guest;
 7343:             }
 7344:         } else {
 7345:             if (@domains > 0) {
 7346:                 foreach my $domkey (@domains) {
 7347:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 7348:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 7349:                             return 'ok';
 7350:                         }
 7351:                     }
 7352:                 }
 7353:             }
 7354:             if (@users > 0) {
 7355:                 foreach my $userkey (@users) {
 7356:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 7357:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 7358:                             if (ref($item) eq 'HASH') {
 7359:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 7360:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 7361:                                     return 'ok';
 7362:                                 }
 7363:                             }
 7364:                         }
 7365:                     } 
 7366:                 }
 7367:             }
 7368:             my %roleshash;
 7369:             my @courses_and_groups = @courses;
 7370:             push(@courses_and_groups,@groups); 
 7371:             if (@courses_and_groups > 0) {
 7372:                 my (%allgroups,%allroles); 
 7373:                 my ($start,$end,$role,$sec,$group);
 7374:                 foreach my $envkey (%env) {
 7375:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 7376:                         my $cid = $2.'_'.$3; 
 7377:                         if ($1 eq 'gr') {
 7378:                             $group = $4;
 7379:                             $allgroups{$cid}{$group} = $env{$envkey};
 7380:                         } else {
 7381:                             if ($4 eq '') {
 7382:                                 $sec = 'none';
 7383:                             } else {
 7384:                                 $sec = $4;
 7385:                             }
 7386:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 7387:                         }
 7388:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 7389:                         my $cid = $2.'_'.$3;
 7390:                         if ($4 eq '') {
 7391:                             $sec = 'none';
 7392:                         } else {
 7393:                             $sec = $4;
 7394:                         }
 7395:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 7396:                     }
 7397:                 }
 7398:                 if (keys(%allroles) == 0) {
 7399:                     return;
 7400:                 }
 7401:                 foreach my $key (@courses_and_groups) {
 7402:                     my %content = %{$$access_hash{$key}};
 7403:                     my $cnum = $content{'number'};
 7404:                     my $cdom = $content{'domain'};
 7405:                     my $cid = $cdom.'_'.$cnum;
 7406:                     if (!exists($allroles{$cid})) {
 7407:                         next;
 7408:                     }    
 7409:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 7410:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 7411:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 7412:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 7413:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 7414:                         foreach my $role (keys(%{$allroles{$cid}})) {
 7415:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 7416:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 7417:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 7418:                                         if (grep/^all$/,@sections) {
 7419:                                             return 'ok';
 7420:                                         } else {
 7421:                                             if (grep/^$sec$/,@sections) {
 7422:                                                 return 'ok';
 7423:                                             }
 7424:                                         }
 7425:                                     }
 7426:                                 }
 7427:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 7428:                                     if (grep/^none$/,@groups) {
 7429:                                         return 'ok';
 7430:                                     }
 7431:                                 } else {
 7432:                                     if (grep/^all$/,@groups) {
 7433:                                         return 'ok';
 7434:                                     } 
 7435:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 7436:                                         if (grep/^$group$/,@groups) {
 7437:                                             return 'ok';
 7438:                                         }
 7439:                                     }
 7440:                                 } 
 7441:                             }
 7442:                         }
 7443:                     }
 7444:                 }
 7445:             }
 7446:             if ($guest) {
 7447:                 return $guest;
 7448:             }
 7449:         }
 7450:     }
 7451:     return;
 7452: }
 7453: 
 7454: sub course_group_datechecker {
 7455:     my ($dates,$now,$status) = @_;
 7456:     my ($start,$end) = split(/\./,$dates);
 7457:     if (!$start && !$end) {
 7458:         return 'ok';
 7459:     }
 7460:     if (grep/^active$/,@{$status}) {
 7461:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 7462:             return 'ok';
 7463:         }
 7464:     }
 7465:     if (grep/^previous$/,@{$status}) {
 7466:         if ($end > $now ) {
 7467:             return 'ok';
 7468:         }
 7469:     }
 7470:     if (grep/^future$/,@{$status}) {
 7471:         if ($start > $now) {
 7472:             return 'ok';
 7473:         }
 7474:     }
 7475:     return; 
 7476: }
 7477: 
 7478: sub parse_portfolio_url {
 7479:     my ($url) = @_;
 7480: 
 7481:     my ($type,$udom,$unum,$group,$file_name);
 7482:     
 7483:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 7484: 	$type = 1;
 7485:         $udom = $1;
 7486:         $unum = $2;
 7487:         $file_name = $3;
 7488:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 7489: 	$type = 2;
 7490:         $udom = $1;
 7491:         $unum = $2;
 7492:         $group = $3;
 7493:         $file_name = $3.'/'.$4;
 7494:     }
 7495:     if (wantarray) {
 7496: 	return ($type,$udom,$unum,$file_name,$group);
 7497:     }
 7498:     return $type;
 7499: }
 7500: 
 7501: sub is_portfolio_url {
 7502:     my ($url) = @_;
 7503:     return scalar(&parse_portfolio_url($url));
 7504: }
 7505: 
 7506: sub is_portfolio_file {
 7507:     my ($file) = @_;
 7508:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 7509:         return 1;
 7510:     }
 7511:     return;
 7512: }
 7513: 
 7514: sub usertools_access {
 7515:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
 7516:     my ($access,%tools);
 7517:     if ($context eq '') {
 7518:         $context = 'tools';
 7519:     }
 7520:     if ($context eq 'requestcourses') {
 7521:         %tools = (
 7522:                       official   => 1,
 7523:                       unofficial => 1,
 7524:                       community  => 1,
 7525:                       textbook   => 1,
 7526:                  );
 7527:     } elsif ($context eq 'requestauthor') {
 7528:         %tools = (
 7529:                       requestauthor => 1,
 7530:                  );
 7531:     } else {
 7532:         %tools = (
 7533:                       aboutme   => 1,
 7534:                       blog      => 1,
 7535:                       webdav    => 1,
 7536:                       portfolio => 1,
 7537:                  );
 7538:     }
 7539:     return if (!defined($tools{$tool}));
 7540: 
 7541:     if (($udom eq '') || ($uname eq '')) {
 7542:         $udom = $env{'user.domain'};
 7543:         $uname = $env{'user.name'};
 7544:     }
 7545: 
 7546:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 7547:         if ($action ne 'reload') {
 7548:             if ($context eq 'requestcourses') {
 7549:                 return $env{'environment.canrequest.'.$tool};
 7550:             } elsif ($context eq 'requestauthor') {
 7551:                 return $env{'environment.canrequest.author'};
 7552:             } else {
 7553:                 return $env{'environment.availabletools.'.$tool};
 7554:             }
 7555:         }
 7556:     }
 7557: 
 7558:     my ($toolstatus,$inststatus,$envkey);
 7559:     if ($context eq 'requestauthor') {
 7560:         $envkey = $context;
 7561:     } else {
 7562:         $envkey = $context.'.'.$tool;
 7563:     }
 7564: 
 7565:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 7566:          ($action ne 'reload')) {
 7567:         $toolstatus = $env{'environment.'.$envkey};
 7568:         $inststatus = $env{'environment.inststatus'};
 7569:     } else {
 7570:         if (ref($userenvref) eq 'HASH') {
 7571:             $toolstatus = $userenvref->{$envkey};
 7572:             $inststatus = $userenvref->{'inststatus'};
 7573:         } else {
 7574:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
 7575:             $toolstatus = $userenv{$envkey};
 7576:             $inststatus = $userenv{'inststatus'};
 7577:         }
 7578:     }
 7579: 
 7580:     if ($toolstatus ne '') {
 7581:         if ($toolstatus) {
 7582:             $access = 1;
 7583:         } else {
 7584:             $access = 0;
 7585:         }
 7586:         return $access;
 7587:     }
 7588: 
 7589:     my ($is_adv,%domdef);
 7590:     if (ref($is_advref) eq 'HASH') {
 7591:         $is_adv = $is_advref->{'is_adv'};
 7592:     } else {
 7593:         $is_adv = &is_advanced_user($udom,$uname);
 7594:     }
 7595:     if (ref($domdefref) eq 'HASH') {
 7596:         %domdef = %{$domdefref};
 7597:     } else {
 7598:         %domdef = &get_domain_defaults($udom);
 7599:     }
 7600:     if (ref($domdef{$tool}) eq 'HASH') {
 7601:         if ($is_adv) {
 7602:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 7603:                 if ($domdef{$tool}{'_LC_adv'}) { 
 7604:                     $access = 1;
 7605:                 } else {
 7606:                     $access = 0;
 7607:                 }
 7608:                 return $access;
 7609:             }
 7610:         }
 7611:         if ($inststatus ne '') {
 7612:             my ($hasaccess,$hasnoaccess);
 7613:             foreach my $affiliation (split(/:/,$inststatus)) {
 7614:                 if ($domdef{$tool}{$affiliation} ne '') { 
 7615:                     if ($domdef{$tool}{$affiliation}) {
 7616:                         $hasaccess = 1;
 7617:                     } else {
 7618:                         $hasnoaccess = 1;
 7619:                     }
 7620:                 }
 7621:             }
 7622:             if ($hasaccess || $hasnoaccess) {
 7623:                 if ($hasaccess) {
 7624:                     $access = 1;
 7625:                 } elsif ($hasnoaccess) {
 7626:                     $access = 0; 
 7627:                 }
 7628:                 return $access;
 7629:             }
 7630:         } else {
 7631:             if ($domdef{$tool}{'default'} ne '') {
 7632:                 if ($domdef{$tool}{'default'}) {
 7633:                     $access = 1;
 7634:                 } elsif ($domdef{$tool}{'default'} == 0) {
 7635:                     $access = 0;
 7636:                 }
 7637:                 return $access;
 7638:             }
 7639:         }
 7640:     } else {
 7641:         if (($context eq 'tools') && ($tool ne 'webdav')) {
 7642:             $access = 1;
 7643:         } else {
 7644:             $access = 0;
 7645:         }
 7646:         return $access;
 7647:     }
 7648: }
 7649: 
 7650: sub is_course_owner {
 7651:     my ($cdom,$cnum,$udom,$uname) = @_;
 7652:     if (($udom eq '') || ($uname eq '')) {
 7653:         $udom = $env{'user.domain'};
 7654:         $uname = $env{'user.name'};
 7655:     }
 7656:     unless (($udom eq '') || ($uname eq '')) {
 7657:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
 7658:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
 7659:                 return 1;
 7660:             } else {
 7661:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
 7662:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
 7663:                     return 1;
 7664:                 }
 7665:             }
 7666:         }
 7667:     }
 7668:     return;
 7669: }
 7670: 
 7671: sub is_advanced_user {
 7672:     my ($udom,$uname) = @_;
 7673:     if ($udom ne '' && $uname ne '') {
 7674:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 7675:             if (wantarray) {
 7676:                 return ($env{'user.adv'},$env{'user.author'});
 7677:             } else {
 7678:                 return $env{'user.adv'};
 7679:             }
 7680:         }
 7681:     }
 7682:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 7683:     my %allroles;
 7684:     my ($is_adv,$is_author);
 7685:     foreach my $role (keys(%roleshash)) {
 7686:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 7687:         my $area = '/'.$tdomain.'/'.$trest;
 7688:         if ($sec ne '') {
 7689:             $area .= '/'.$sec;
 7690:         }
 7691:         if (($area ne '') && ($trole ne '')) {
 7692:             my $spec=$trole.'.'.$area;
 7693:             if ($trole =~ /^cr\//) {
 7694:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 7695:             } elsif ($trole ne 'gr') {
 7696:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 7697:             }
 7698:             if ($trole eq 'au') {
 7699:                 $is_author = 1;
 7700:             }
 7701:         }
 7702:     }
 7703:     foreach my $role (keys(%allroles)) {
 7704:         last if ($is_adv);
 7705:         foreach my $item (split(/:/,$allroles{$role})) {
 7706:             if ($item ne '') {
 7707:                 my ($privilege,$restrictions)=split(/&/,$item);
 7708:                 if ($privilege eq 'adv') {
 7709:                     $is_adv = 1;
 7710:                     last;
 7711:                 }
 7712:             }
 7713:         }
 7714:     }
 7715:     if (wantarray) {
 7716:         return ($is_adv,$is_author);
 7717:     }
 7718:     return $is_adv;
 7719: }
 7720: 
 7721: sub check_can_request {
 7722:     my ($dom,$can_request,$request_domains) = @_;
 7723:     my $canreq = 0;
 7724:     my ($types,$typename) = &Apache::loncommon::course_types();
 7725:     my @options = ('approval','validate','autolimit');
 7726:     my $optregex = join('|',@options);
 7727:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
 7728:         foreach my $type (@{$types}) {
 7729:             if (&usertools_access($env{'user.name'},
 7730:                                   $env{'user.domain'},
 7731:                                   $type,undef,'requestcourses')) {
 7732:                 $canreq ++;
 7733:                 if (ref($request_domains) eq 'HASH') {
 7734:                     push(@{$request_domains->{$type}},$env{'user.domain'});
 7735:                 }
 7736:                 if ($dom eq $env{'user.domain'}) {
 7737:                     $can_request->{$type} = 1;
 7738:                 }
 7739:             }
 7740:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
 7741:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
 7742:                 if (@curr > 0) {
 7743:                     foreach my $item (@curr) {
 7744:                         if (ref($request_domains) eq 'HASH') {
 7745:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
 7746:                             if ($otherdom ne '') {
 7747:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
 7748:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
 7749:                                         push(@{$request_domains->{$type}},$otherdom);
 7750:                                     }
 7751:                                 } else {
 7752:                                     push(@{$request_domains->{$type}},$otherdom);
 7753:                                 }
 7754:                             }
 7755:                         }
 7756:                     }
 7757:                     unless($dom eq $env{'user.domain'}) {
 7758:                         $canreq ++;
 7759:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
 7760:                             $can_request->{$type} = 1;
 7761:                         }
 7762:                     }
 7763:                 }
 7764:             }
 7765:         }
 7766:     }
 7767:     return $canreq;
 7768: }
 7769: 
 7770: # ---------------------------------------------- Custom access rule evaluation
 7771: 
 7772: sub customaccess {
 7773:     my ($priv,$uri)=@_;
 7774:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 7775:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 7776:     $udom = &LONCAPA::clean_domain($udom);
 7777:     $ucrs = &LONCAPA::clean_username($ucrs);
 7778:     my $access=0;
 7779:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 7780: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 7781: 	if ($type eq 'user') {
 7782: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 7783: 		my ($tdom,$tuname)=split(m{/},$scope);
 7784: 		if ($tdom) {
 7785: 		    if ($tdom ne $env{'user.domain'}) { next; }
 7786: 		}
 7787: 		if ($tuname) {
 7788: 		    if ($tuname ne $env{'user.name'}) { next; }
 7789: 		}
 7790: 		$access=($effect eq 'allow');
 7791: 		last;
 7792: 	    }
 7793: 	} else {
 7794: 	    if ($role) {
 7795: 		if ($role ne $urole) { next; }
 7796: 	    }
 7797: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 7798: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 7799: 		if ($tdom) {
 7800: 		    if ($tdom ne $udom) { next; }
 7801: 		}
 7802: 		if ($tcrs) {
 7803: 		    if ($tcrs ne $ucrs) { next; }
 7804: 		}
 7805: 		if ($tsec) {
 7806: 		    if ($tsec ne $usec) { next; }
 7807: 		}
 7808: 		$access=($effect eq 'allow');
 7809: 		last;
 7810: 	    }
 7811: 	    if ($realm eq '' && $role eq '') {
 7812: 		$access=($effect eq 'allow');
 7813: 	    }
 7814: 	}
 7815:     }
 7816:     return $access;
 7817: }
 7818: 
 7819: # ------------------------------------------------- Check for a user privilege
 7820: 
 7821: sub allowed {
 7822:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck,$ignorecache)=@_;
 7823:     my $ver_orguri=$uri;
 7824:     $uri=&deversion($uri);
 7825:     my $orguri=$uri;
 7826:     $uri=&declutter($uri);
 7827: 
 7828:     if ($priv eq 'evb') {
 7829: # Evade communication block restrictions for specified role in a course
 7830:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 7831:             return $1;
 7832:         } else {
 7833:             return;
 7834:         }
 7835:     }
 7836: 
 7837:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 7838: # Free bre access to adm and meta resources
 7839:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|viewclasslist|aboutme)$})) 
 7840: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 7841: 	&& ($priv eq 'bre')) {
 7842: 	return 'F';
 7843:     }
 7844: 
 7845: # Free bre access to user's own portfolio contents
 7846:     my ($space,$domain,$name,@dir)=split('/',$uri);
 7847:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 7848: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 7849:         my %setters;
 7850:         my ($startblock,$endblock) = 
 7851:             &Apache::loncommon::blockcheck(\%setters,'port');
 7852:         if ($startblock && $endblock) {
 7853:             return 'B';
 7854:         } else {
 7855:             return 'F';
 7856:         }
 7857:     }
 7858: 
 7859: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 7860:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 7861:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 7862:         if (exists($env{'request.course.id'})) {
 7863:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7864:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7865:             if (($domain eq $cdom) && ($name eq $cnum)) {
 7866:                 my $courseprivid=$env{'request.course.id'};
 7867:                 $courseprivid=~s/\_/\//;
 7868:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 7869:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 7870:                     return $1; 
 7871:                 } else {
 7872:                     if ($env{'request.course.sec'}) {
 7873:                         $courseprivid.='/'.$env{'request.course.sec'};
 7874:                     }
 7875:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 7876:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 7877:                         return $2;
 7878:                     }
 7879:                 }
 7880:             }
 7881:         }
 7882:     }
 7883: 
 7884: # Free bre to public access
 7885: 
 7886:     if ($priv eq 'bre') {
 7887:         my $copyright=&metadata($uri,'copyright');
 7888: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 7889:            return 'F'; 
 7890:         }
 7891:         if ($copyright eq 'priv') {
 7892:             $uri=~/([^\/]+)\/([^\/]+)\//;
 7893: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 7894: 		return '';
 7895:             }
 7896:         }
 7897:         if ($copyright eq 'domain') {
 7898:             $uri=~/([^\/]+)\/([^\/]+)\//;
 7899: 	    unless (($env{'user.domain'} eq $1) ||
 7900:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 7901: 		return '';
 7902:             }
 7903:         }
 7904:         if ($env{'request.role'}=~ /li\.\//) {
 7905:             # Library role, so allow browsing of resources in this domain.
 7906:             return 'F';
 7907:         }
 7908:         if ($copyright eq 'custom') {
 7909: 	    unless (&customaccess($priv,$uri)) { return ''; }
 7910:         }
 7911:     }
 7912:     # Domain coordinator is trying to create a course
 7913:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 7914:         # uri is the requested domain in this case.
 7915:         # comparison to 'request.role.domain' shows if the user has selected
 7916:         # a role of dc for the domain in question.
 7917:         return 'F' if ($uri eq $env{'request.role.domain'});
 7918:     }
 7919: 
 7920:     my $thisallowed='';
 7921:     my $statecond=0;
 7922:     my $courseprivid='';
 7923: 
 7924:     my $ownaccess;
 7925:     # Community Coordinator or Assistant Co-author browsing resource space.
 7926:     if (($priv eq 'bro') && ($env{'user.author'})) {
 7927:         if ($uri eq '') {
 7928:             $ownaccess = 1;
 7929:         } else {
 7930:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
 7931:                 my $udom = $env{'user.domain'};
 7932:                 my $uname = $env{'user.name'};
 7933:                 if ($uri =~ m{^\Q$udom\E/?$}) {
 7934:                     $ownaccess = 1;
 7935:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
 7936:                     unless ($uri =~ m{\.\./}) {
 7937:                         $ownaccess = 1;
 7938:                     }
 7939:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
 7940:                     my $now = time;
 7941:                     if ($uri =~ m{^([^/]+)/?$}) {
 7942:                         my $adom = $1;
 7943:                         foreach my $key (keys(%env)) {
 7944:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
 7945:                                 my ($start,$end) = split('.',$env{$key});
 7946:                                 if (($now >= $start) && (!$end || $end < $now)) {
 7947:                                     $ownaccess = 1;
 7948:                                     last;
 7949:                                 }
 7950:                             }
 7951:                         }
 7952:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
 7953:                         my $adom = $1;
 7954:                         my $aname = $2;
 7955:                         foreach my $role ('ca','aa') { 
 7956:                             if ($env{"user.role.$role./$adom/$aname"}) {
 7957:                                 my ($start,$end) =
 7958:                                     split('.',$env{"user.role.$role./$adom/$aname"});
 7959:                                 if (($now >= $start) && (!$end || $end < $now)) {
 7960:                                     $ownaccess = 1;
 7961:                                     last;
 7962:                                 }
 7963:                             }
 7964:                         }
 7965:                     }
 7966:                 }
 7967:             }
 7968:         }
 7969:     }
 7970: 
 7971: # Course
 7972: 
 7973:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 7974:         unless (($priv eq 'bro') && (!$ownaccess)) {
 7975:             $thisallowed.=$1;
 7976:         }
 7977:     }
 7978: 
 7979: # Domain
 7980: 
 7981:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 7982:        =~/\Q$priv\E\&([^\:]*)/) {
 7983:         unless (($priv eq 'bro') && (!$ownaccess)) {
 7984:             $thisallowed.=$1;
 7985:         }
 7986:     }
 7987: 
 7988: # User who is not author or co-author might still be able to edit
 7989: # resource of an author in the domain (e.g., if Domain Coordinator).
 7990:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
 7991:         (&allowed('mdc',$env{'request.course.id'}))) {
 7992:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
 7993:             $thisallowed.=$1;
 7994:         }
 7995:     }
 7996: 
 7997: # Course: uri itself is a course
 7998:     my $courseuri=$uri;
 7999:     $courseuri=~s/\_(\d)/\/$1/;
 8000:     $courseuri=~s/^([^\/])/\/$1/;
 8001: 
 8002:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 8003:        =~/\Q$priv\E\&([^\:]*)/) {
 8004:         if ($priv eq 'mip') {
 8005:             my $rem = $1;
 8006:             if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
 8007:                 ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
 8008:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8009:                 if ($cdom ne '') {
 8010:                     my %passwdconf = &get_passwdconf($cdom);
 8011:                     if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
 8012:                         if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
 8013:                             if (@{$passwdconf{'crsownerchg'}{'by'}}) {
 8014:                                 my @inststatuses = split(':',$env{'environment.inststatus'});
 8015:                                 unless (@inststatuses) {
 8016:                                     @inststatuses = ('default');
 8017:                                 }
 8018:                                 foreach my $status (@inststatuses) {
 8019:                                     if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
 8020:                                         $thisallowed.=$rem;
 8021:                                     }
 8022:                                 }
 8023:                             }
 8024:                         }
 8025:                     }
 8026:                 }
 8027:             }
 8028:         } else {
 8029:             unless (($priv eq 'bro') && (!$ownaccess)) {
 8030:                 $thisallowed.=$1;
 8031:             }
 8032:         }
 8033:     }
 8034: 
 8035: # URI is an uploaded document for this course, default permissions don't matter
 8036: # not allowing 'edit' access (editupload) to uploaded course docs
 8037:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 8038: 	$thisallowed='';
 8039:         my ($match)=&is_on_map($uri);
 8040:         if ($match) {
 8041:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 8042:                   =~/\Q$priv\E\&([^\:]*)/) {
 8043:                 my $value = $1;
 8044:                 if ($noblockcheck) {
 8045:                     $thisallowed.=$value;
 8046:                 } else {
 8047:                     my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
 8048:                     if (@blockers > 0) {
 8049:                         $thisallowed = 'B';
 8050:                     } else {
 8051:                         $thisallowed.=$value;
 8052:                     }
 8053:                 }
 8054:             }
 8055:         } else {
 8056:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 8057:             if ($refuri) {
 8058:                 if ($refuri =~ m|^/adm/|) {
 8059:                     $thisallowed='F';
 8060:                 } else {
 8061:                     $refuri=&declutter($refuri);
 8062:                     my ($match) = &is_on_map($refuri);
 8063:                     if ($match) {
 8064:                         if ($noblockcheck) {
 8065:                             $thisallowed='F';
 8066:                         } else {
 8067:                             my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
 8068:                             if (@blockers > 0) {
 8069:                                 $thisallowed = 'B';
 8070:                             } else {
 8071:                                 $thisallowed='F';
 8072:                             }
 8073:                         }
 8074:                     }
 8075:                 }
 8076:             }
 8077:         }
 8078:     }
 8079: 
 8080:     if ($priv eq 'bre'
 8081: 	&& $thisallowed ne 'F' 
 8082: 	&& $thisallowed ne '2'
 8083: 	&& &is_portfolio_url($uri)) {
 8084: 	$thisallowed = &portfolio_access($uri,$clientip);
 8085:     }
 8086:     
 8087: # Full access at system, domain or course-wide level? Exit.
 8088:     if ($thisallowed=~/F/) {
 8089: 	return 'F';
 8090:     }
 8091: 
 8092: # If this is generating or modifying users, exit with special codes
 8093: 
 8094:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 8095: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 8096: 	    my ($audom,$auname)=split('/',$uri);
 8097: # no author name given, so this just checks on the general right to make a co-author in this domain
 8098: 	    unless ($auname) { return $thisallowed; }
 8099: # an author name is given, so we are about to actually make a co-author for a certain account
 8100: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 8101: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 8102: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 8103: 	}
 8104: 	return $thisallowed;
 8105:     }
 8106: #
 8107: # Gathered so far: system, domain and course wide privileges
 8108: #
 8109: # Course: See if uri or referer is an individual resource that is part of 
 8110: # the course
 8111: 
 8112:     if ($env{'request.course.id'}) {
 8113: 
 8114: # If this is modifying password (internal auth) domains must match for user and user's role.
 8115: 
 8116:         if ($priv eq 'mip') {
 8117:             if ($env{'user.domain'} eq $env{'request.role.domain'}) {
 8118:                 return $thisallowed;
 8119:             } else {
 8120:                 return '';
 8121:             }
 8122:         }
 8123: 
 8124:        $courseprivid=$env{'request.course.id'};
 8125:        if ($env{'request.course.sec'}) {
 8126:           $courseprivid.='/'.$env{'request.course.sec'};
 8127:        }
 8128:        $courseprivid=~s/\_/\//;
 8129:        my $checkreferer=1;
 8130:        my ($match,$cond)=&is_on_map($uri);
 8131:        if ($match) {
 8132:            $statecond=$cond;
 8133:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 8134:                =~/\Q$priv\E\&([^\:]*)/) {
 8135:                my $value = $1;
 8136:                if ($priv eq 'bre') {
 8137:                    if ($noblockcheck) {
 8138:                        $thisallowed.=$value;
 8139:                    } else {
 8140:                        my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
 8141:                        if (@blockers > 0) {
 8142:                            $thisallowed = 'B';
 8143:                        } else {
 8144:                            $thisallowed.=$value;
 8145:                        }
 8146:                    }
 8147:                } else {
 8148:                    $thisallowed.=$value;
 8149:                }
 8150:                $checkreferer=0;
 8151:            }
 8152:        }
 8153: 
 8154:        if ($checkreferer) {
 8155: 	  my $refuri=$env{'httpref.'.$orguri};
 8156:             unless ($refuri) {
 8157:                 foreach my $key (keys(%env)) {
 8158: 		    if ($key=~/^httpref\..*\*/) {
 8159: 			my $pattern=$key;
 8160:                         $pattern=~s/^httpref\.\/res\///;
 8161:                         $pattern=~s/\*/\[\^\/\]\+/g;
 8162:                         $pattern=~s/\//\\\//g;
 8163:                         if ($orguri=~/$pattern/) {
 8164: 			    $refuri=$env{$key};
 8165:                         }
 8166:                     }
 8167:                 }
 8168:             }
 8169: 
 8170:          if ($refuri) { 
 8171: 	  $refuri=&declutter($refuri);
 8172:           my ($match,$cond)=&is_on_map($refuri);
 8173:             if ($match) {
 8174:               my $refstatecond=$cond;
 8175:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 8176:                   =~/\Q$priv\E\&([^\:]*)/) {
 8177:                   my $value = $1;
 8178:                   if ($priv eq 'bre') {
 8179:                       if ($noblockcheck) {
 8180:                           $thisallowed.=$value;
 8181:                       } else {
 8182:                           my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
 8183:                           if (@blockers > 0) {
 8184:                               $thisallowed = 'B';
 8185:                           } else {
 8186:                               $thisallowed.=$value;
 8187:                           }
 8188:                       }
 8189:                   } else {
 8190:                       $thisallowed.=$value;
 8191:                   }
 8192:                   $uri=$refuri;
 8193:                   $statecond=$refstatecond;
 8194:               }
 8195:           }
 8196:         }
 8197:        }
 8198:    }
 8199: 
 8200: #
 8201: # Gathered now: all privileges that could apply, and condition number
 8202: # 
 8203: #
 8204: # Full or no access?
 8205: #
 8206: 
 8207:     if ($thisallowed=~/F/) {
 8208: 	return 'F';
 8209:     }
 8210: 
 8211:     unless ($thisallowed) {
 8212:         return '';
 8213:     }
 8214: 
 8215: # Restrictions exist, deal with them
 8216: #
 8217: #   C:according to course preferences
 8218: #   R:according to resource settings
 8219: #   L:unless locked
 8220: #   X:according to user session state
 8221: #
 8222: 
 8223: # Possibly locked functionality, check all courses
 8224: # Locks might take effect only after 10 minutes cache expiration for other
 8225: # courses, and 2 minutes for current course
 8226: 
 8227:     my $envkey;
 8228:     if ($thisallowed=~/L/) {
 8229:         foreach $envkey (keys(%env)) {
 8230:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 8231:                my $courseid=$2;
 8232:                my $roleid=$1.'.'.$2;
 8233:                $courseid=~s/^\///;
 8234:                my $expiretime=600;
 8235:                if ($env{'request.role'} eq $roleid) {
 8236: 		  $expiretime=120;
 8237:                }
 8238: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 8239:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 8240:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 8241: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 8242:                }
 8243:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 8244:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 8245: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 8246:                        &log($env{'user.domain'},$env{'user.name'},
 8247:                             $env{'user.home'},
 8248:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 8249:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 8250:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 8251: 		       return '';
 8252:                    }
 8253:                }
 8254:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 8255:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 8256: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 8257:                        &log($env{'user.domain'},$env{'user.name'},
 8258:                             $env{'user.home'},
 8259:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 8260:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 8261:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 8262: 		       return '';
 8263:                    }
 8264:                }
 8265: 	   }
 8266:        }
 8267:     }
 8268: 
 8269: #
 8270: # Rest of the restrictions depend on selected course
 8271: #
 8272: 
 8273:     unless ($env{'request.course.id'}) {
 8274: 	if ($thisallowed eq 'A') {
 8275: 	    return 'A';
 8276:         } elsif ($thisallowed eq 'B') {
 8277:             return 'B';
 8278: 	} else {
 8279: 	    return '1';
 8280: 	}
 8281:     }
 8282: 
 8283: #
 8284: # Now user is definitely in a course
 8285: #
 8286: 
 8287: 
 8288: # Course preferences
 8289: 
 8290:    if ($thisallowed=~/C/) {
 8291:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 8292:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 8293:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 8294: 	   =~/\Q$rolecode\E/) {
 8295: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 8296: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 8297: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 8298: 			$env{'request.course.id'});
 8299: 	   }
 8300:            return '';
 8301:        }
 8302: 
 8303:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 8304: 	   =~/\Q$unamedom\E/) {
 8305: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 8306: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 8307: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 8308: 			$env{'request.course.id'});
 8309: 	   }
 8310:            return '';
 8311:        }
 8312:    }
 8313: 
 8314: # Resource preferences
 8315: 
 8316:    if ($thisallowed=~/R/) {
 8317:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 8318:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 8319: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 8320: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 8321: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 8322: 	   }
 8323: 	   return '';
 8324:        }
 8325:    }
 8326: 
 8327: # Restricted by state or randomout?
 8328: 
 8329:    if ($thisallowed=~/X/) {
 8330:       if ($env{'acc.randomout'}) {
 8331: 	 if (!$symb) { $symb=&symbread($uri,1); }
 8332:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 8333:             return ''; 
 8334:          }
 8335:       }
 8336:       if (&condval($statecond)) {
 8337: 	 return '2';
 8338:       } else {
 8339:          return '';
 8340:       }
 8341:    }
 8342: 
 8343:     if ($thisallowed eq 'A') {
 8344: 	return 'A';
 8345:     } elsif ($thisallowed eq 'B') {
 8346:         return 'B';
 8347:     }
 8348:    return 'F';
 8349: }
 8350: 
 8351: # ------------------------------------------- Check construction space access
 8352: 
 8353: sub constructaccess {
 8354:     my ($url,$setpriv)=@_;
 8355: 
 8356: # We do not allow editing of previous versions of files
 8357:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
 8358: 
 8359: # Get username and domain from URL
 8360:     my ($ownername,$ownerdomain,$ownerhome);
 8361: 
 8362:     ($ownerdomain,$ownername) =
 8363:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)(?:/|$)});
 8364: 
 8365: # The URL does not really point to any authorspace, forget it
 8366:     unless (($ownername) && ($ownerdomain)) { return ''; }
 8367: 
 8368: # Now we need to see if the user has access to the authorspace of
 8369: # $ownername at $ownerdomain
 8370: 
 8371:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
 8372: # Real author for this?
 8373:        $ownerhome = $env{'user.home'};
 8374:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
 8375:           return ($ownername,$ownerdomain,$ownerhome);
 8376:        }
 8377:     } else {
 8378: # Co-author for this?
 8379:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
 8380:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
 8381:             $ownerhome = &homeserver($ownername,$ownerdomain);
 8382:             return ($ownername,$ownerdomain,$ownerhome);
 8383:         }
 8384:     }
 8385: 
 8386: # We don't have any access right now. If we are not possibly going to do anything about this,
 8387: # we might as well leave
 8388:    unless ($setpriv) { return ''; }
 8389: 
 8390: # Backdoor access?
 8391:     my $allowed=&allowed('eco',$ownerdomain);
 8392: # Nope
 8393:     unless ($allowed) { return ''; }
 8394: # Looks like we may have access, but could be locked by the owner of the construction space
 8395:     if ($allowed eq 'U') {
 8396:         my %blocked=&get('environment',['domcoord.author'],
 8397:                          $ownerdomain,$ownername);
 8398: # Is blocked by owner
 8399:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
 8400:     }
 8401:     if (($allowed eq 'F') || ($allowed eq 'U')) {
 8402: # Grant temporary access
 8403:         my $then=$env{'user.login.time'};
 8404:         my $update=$env{'user.update.time'};
 8405:         if (!$update) { $update = $then; }
 8406:         my $refresh=$env{'user.refresh.time'};
 8407:         if (!$refresh) { $refresh = $update; }
 8408:         my $now = time;
 8409:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
 8410:                            $now,'ca','constructaccess');
 8411:         $ownerhome = &homeserver($ownername,$ownerdomain);
 8412:         return($ownername,$ownerdomain,$ownerhome);
 8413:     }
 8414: # No business here
 8415:     return '';
 8416: }
 8417: 
 8418: # ----------------------------------------------------------- Content Blocking
 8419: 
 8420: {
 8421: # Caches for faster Course Contents display where content blocking
 8422: # is in operation (i.e., interval param set) for timed quiz.
 8423: #
 8424: # User for whom data are being temporarily cached.
 8425: my $cacheduser='';
 8426: # Course for which data are being temporarily cached.
 8427: my $cachedcid='';
 8428: # Cached blockers for this user (a hash of blocking items).
 8429: my %cachedblockers=();
 8430: # When the data were last cached.
 8431: my $cachedlast='';
 8432: 
 8433: sub load_all_blockers {
 8434:     my ($uname,$udom)=@_;
 8435:     if (($uname ne '') && ($udom ne '')) {
 8436:         if (($cacheduser eq $uname.':'.$udom) &&
 8437:             ($cachedcid eq $env{'request.course.id'}) &&
 8438:             (abs($cachedlast-time)<5)) {
 8439:             return;
 8440:         }
 8441:     }
 8442:     $cachedlast=time;
 8443:     $cacheduser=$uname.':'.$udom;
 8444:     $cachedcid=$env{'request.course.id'};
 8445:     %cachedblockers = &get_commblock_resources();
 8446:     return;
 8447: }
 8448: 
 8449: sub get_comm_blocks {
 8450:     my ($cdom,$cnum) = @_;
 8451:     if ($cdom eq '' || $cnum eq '') {
 8452:         return unless ($env{'request.course.id'});
 8453:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8454:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8455:     }
 8456:     my %commblocks;
 8457:     my $hashid=$cdom.'_'.$cnum;
 8458:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
 8459:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
 8460:         %commblocks = %{$blocksref};
 8461:     } else {
 8462:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
 8463:         my $cachetime = 600;
 8464:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
 8465:     }
 8466:     return %commblocks;
 8467: }
 8468: 
 8469: sub get_commblock_resources {
 8470:     my ($blocks) = @_;
 8471:     my %blockers = ();
 8472:     return %blockers unless ($env{'request.course.id'});
 8473:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 8474:     my %commblocks;
 8475:     if (ref($blocks) eq 'HASH') {
 8476:         %commblocks = %{$blocks};
 8477:     } else {
 8478:         %commblocks = &get_comm_blocks();
 8479:     }
 8480:     return %blockers unless (keys(%commblocks) > 0);
 8481:     my $navmap = Apache::lonnavmaps::navmap->new();
 8482:     return %blockers unless (ref($navmap));
 8483:     my $now = time;
 8484:     foreach my $block (keys(%commblocks)) {
 8485:         if ($block =~ /^(\d+)____(\d+)$/) {
 8486:             my ($start,$end) = ($1,$2);
 8487:             if ($start <= $now && $end >= $now) {
 8488:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 8489:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 8490:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 8491:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 8492:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
 8493:                             }
 8494:                         }
 8495:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 8496:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 8497:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 8498:                             }
 8499:                         }
 8500:                     }
 8501:                 }
 8502:             }
 8503:         } elsif ($block =~ /^firstaccess____(.+)$/) {
 8504:             my $item = $1;
 8505:             my @to_test;
 8506:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 8507:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 8508:                     my @interval;
 8509:                     my $type = 'map';
 8510:                     if ($item eq 'course') {
 8511:                         $type = 'course';
 8512:                         @interval=&EXT("resource.0.interval");
 8513:                     } else {
 8514:                         if ($item =~ /___\d+___/) {
 8515:                             $type = 'resource';
 8516:                             @interval=&EXT("resource.0.interval",$item);
 8517:                             if (ref($navmap)) {
 8518:                                 my $res = $navmap->getBySymb($item);
 8519:                                 push(@to_test,$res);
 8520:                             }
 8521:                         } else {
 8522:                             my $mapsymb = &symbread($item,1);
 8523:                             if ($mapsymb) {
 8524:                                 if (ref($navmap)) {
 8525:                                     my $mapres = $navmap->getBySymb($mapsymb);
 8526:                                     if (ref($mapres)) {
 8527:                                         my $first = $mapres->map_start();
 8528:                                         my $finish = $mapres->map_finish();
 8529:                                         my $it = $navmap->getIterator($first,$finish,undef,0,0);
 8530:                                         if (ref($it)) {
 8531:                                             my $res;
 8532:                                             while ($res = $it->next(undef,1)) {
 8533:                                                 next unless (ref($res));
 8534:                                                 my $symb = $res->symb();
 8535:                                                 next if (($symb eq $mapsymb) || ($symb eq ''));
 8536:                                                 @interval=&EXT("resource.0.interval",$symb);
 8537:                                                 if ($interval[1] eq 'map') {
 8538:                                                     if ($res->answerable()) {
 8539:                                                         push(@to_test,$res);
 8540:                                                         last;
 8541:                                                     }
 8542:                                                 }
 8543:                                             }
 8544:                                         }
 8545:                                     }
 8546:                                 }
 8547:                             }
 8548:                         }
 8549:                     }
 8550:                     if ($interval[0] =~ /^\d+$/) {
 8551:                         my $first_access;
 8552:                         if ($type eq 'resource') {
 8553:                             $first_access=&get_first_access($interval[1],$item);
 8554:                         } elsif ($type eq 'map') {
 8555:                             $first_access=&get_first_access($interval[1],undef,$item);
 8556:                         } else {
 8557:                             $first_access=&get_first_access($interval[1]);
 8558:                         }
 8559:                         if ($first_access) {
 8560:                             my $timesup = $first_access+$interval[0];
 8561:                             if ($timesup > $now) {
 8562:                                 my $activeblock;
 8563:                                 foreach my $res (@to_test) {
 8564:                                     if ($res->answerable()) {
 8565:                                         $activeblock = 1;
 8566:                                         last;
 8567:                                     }
 8568:                                 }
 8569:                                 if ($activeblock) {
 8570:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 8571:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 8572:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
 8573:                                          }
 8574:                                     }
 8575:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 8576:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 8577:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 8578:                                         }
 8579:                                     }
 8580:                                 }
 8581:                             }
 8582:                         }
 8583:                     }
 8584:                 }
 8585:             }
 8586:         }
 8587:     }
 8588:     return %blockers;
 8589: }
 8590: 
 8591: sub has_comm_blocking {
 8592:     my ($priv,$symb,$uri,$ignoresymbdb,$noenccheck,$blocked,$blocks) = @_;
 8593:     my @blockers;
 8594:     return unless ($env{'request.course.id'});
 8595:     return unless ($priv eq 'bre');
 8596:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 8597:     return if ($env{'request.state'} eq 'construct');
 8598:     my %blockinfo;
 8599:     if (ref($blocks) eq 'HASH') {
 8600:         %blockinfo = &get_commblock_resources($blocks);
 8601:     } else {
 8602:         &load_all_blockers($env{'user.name'},$env{'user.domain'});
 8603:         %blockinfo = %cachedblockers;
 8604:     }
 8605:     return unless (keys(%blockinfo) > 0);
 8606:     my (%possibles,@symbs);
 8607:     if (!$symb) {
 8608:         $symb = &symbread($uri,1,1,1,\%possibles,$ignoresymbdb,$noenccheck);
 8609:     }
 8610:     if ($symb) {
 8611:         @symbs = ($symb);
 8612:     } elsif (keys(%possibles)) {
 8613:         @symbs = keys(%possibles);
 8614:     }
 8615:     my $noblock;
 8616:     foreach my $symb (@symbs) {
 8617:         last if ($noblock);
 8618:         my ($map,$resid,$resurl)=&decode_symb($symb);
 8619:         foreach my $block (keys(%blockinfo)) {
 8620:             if ($block =~ /^firstaccess____(.+)$/) {
 8621:                 my $item = $1;
 8622:                 unless ($blocked) {
 8623:                     if (($item eq $map) || ($item eq $symb)) {
 8624:                         $noblock = 1;
 8625:                         last;
 8626:                     }
 8627:                 }
 8628:             }
 8629:             if (ref($blockinfo{$block}) eq 'HASH') {
 8630:                 if (ref($blockinfo{$block}{'resources'}) eq 'HASH') {
 8631:                     if ($blockinfo{$block}{'resources'}{$symb}) {
 8632:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 8633:                             push(@blockers,$block);
 8634:                         }
 8635:                     }
 8636:                 }
 8637:                 if (ref($blockinfo{$block}{'maps'}) eq 'HASH') {
 8638:                     if ($blockinfo{$block}{'maps'}{$map}) {
 8639:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 8640:                             push(@blockers,$block);
 8641:                         }
 8642:                     }
 8643:                 }
 8644:             }
 8645:         }
 8646:     }
 8647:     unless ($noblock) {
 8648:         return @blockers;
 8649:     }
 8650:     return;
 8651: }
 8652: }
 8653: 
 8654: # -------------------------------- Deversion and split uri into path an filename
 8655: 
 8656: #
 8657: #   Removes the version from a URI and
 8658: #   splits it in to its filename and path to the filename.
 8659: #   Seems like File::Basename could have done this more clearly.
 8660: #   Parameters:
 8661: #      $uri   - input URI
 8662: #   Returns:
 8663: #     Two element list consisting of 
 8664: #     $pathname  - the URI up to and excluding the trailing /
 8665: #     $filename  - The part of the URI following the last /
 8666: #  NOTE:
 8667: #    Another realization of this is simply:
 8668: #    use File::Basename;
 8669: #    ...
 8670: #    $uri = shift;
 8671: #    $filename = basename($uri);
 8672: #    $path     = dirname($uri);
 8673: #    return ($filename, $path);
 8674: #
 8675: #     The implementation below is probably faster however.
 8676: #
 8677: sub split_uri_for_cond {
 8678:     my $uri=&deversion(&declutter(shift));
 8679:     my @uriparts=split(/\//,$uri);
 8680:     my $filename=pop(@uriparts);
 8681:     my $pathname=join('/',@uriparts);
 8682:     return ($pathname,$filename);
 8683: }
 8684: # --------------------------------------------------- Is a resource on the map?
 8685: 
 8686: sub is_on_map {
 8687:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 8688:     #Trying to find the conditional for the file
 8689:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 8690: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 8691:     if ($match) {
 8692: 	return (1,$1);
 8693:     } else {
 8694: 	return (0,0);
 8695:     }
 8696: }
 8697: 
 8698: # --------------------------------------------------------- Get symb from alias
 8699: 
 8700: sub get_symb_from_alias {
 8701:     my $symb=shift;
 8702:     my ($map,$resid,$url)=&decode_symb($symb);
 8703: # Already is a symb
 8704:     if ($url) { return $symb; }
 8705: # Must be an alias
 8706:     my $aliassymb='';
 8707:     my %bighash;
 8708:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 8709:                             &GDBM_READER(),0640)) {
 8710:         my $rid=$bighash{'mapalias_'.$symb};
 8711: 	if ($rid) {
 8712: 	    my ($mapid,$resid)=split(/\./,$rid);
 8713: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 8714: 				    $resid,$bighash{'src_'.$rid});
 8715: 	}
 8716:         untie %bighash;
 8717:     }
 8718:     return $aliassymb;
 8719: }
 8720: 
 8721: # ----------------------------------------------------------------- Define Role
 8722: 
 8723: sub definerole {
 8724:   if (allowed('mcr','/')) {
 8725:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
 8726:     foreach my $role (split(':',$sysrole)) {
 8727: 	my ($crole,$cqual)=split(/\&/,$role);
 8728:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 8729:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 8730: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 8731:                return "refused:s:$crole&$cqual"; 
 8732:             }
 8733:         }
 8734:     }
 8735:     foreach my $role (split(':',$domrole)) {
 8736: 	my ($crole,$cqual)=split(/\&/,$role);
 8737:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 8738:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 8739: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 8740:                return "refused:d:$crole&$cqual"; 
 8741:             }
 8742:         }
 8743:     }
 8744:     foreach my $role (split(':',$courole)) {
 8745: 	my ($crole,$cqual)=split(/\&/,$role);
 8746:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 8747:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 8748: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 8749:                return "refused:c:$crole&$cqual"; 
 8750:             }
 8751:         }
 8752:     }
 8753:     my $uhome;
 8754:     if (($uname ne '') && ($udom ne '')) {
 8755:         $uhome = &homeserver($uname,$udom);
 8756:         return $uhome if ($uhome eq 'no_host');
 8757:     } else {
 8758:         $uname = $env{'user.name'};
 8759:         $udom = $env{'user.domain'};
 8760:         $uhome = $env{'user.home'};
 8761:     }
 8762:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 8763:                 "$udom:$uname:rolesdef_$rolename=".
 8764:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 8765:     return reply($command,$uhome);
 8766:   } else {
 8767:     return 'refused';
 8768:   }
 8769: }
 8770: 
 8771: # ---------------- Make a metadata query against the network of library servers
 8772: 
 8773: sub metadata_query {
 8774:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
 8775:     my %rhash;
 8776:     my %libserv = &all_library();
 8777:     my @server_list = (defined($server_array) ? @$server_array
 8778:                                               : keys(%libserv) );
 8779:     for my $server (@server_list) {
 8780:         my $domains = '';
 8781:         if (ref($domains_hash) eq 'HASH') {
 8782:             $domains = $domains_hash->{$server};    
 8783:         }
 8784: 	unless ($custom or $customshow) {
 8785: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
 8786: 	    $rhash{$server}=$reply;
 8787: 	}
 8788: 	else {
 8789: 	    my $reply=&reply("querysend:".&escape($query).':'.
 8790: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
 8791: 			     $server);
 8792: 	    $rhash{$server}=$reply;
 8793: 	}
 8794:     }
 8795:     return \%rhash;
 8796: }
 8797: 
 8798: # ----------------------------------------- Send log queries and wait for reply
 8799: 
 8800: sub log_query {
 8801:     my ($uname,$udom,$query,%filters)=@_;
 8802:     my $uhome=&homeserver($uname,$udom);
 8803:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 8804:     my $uhost=&hostname($uhome);
 8805:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 8806:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 8807:                        $uhome);
 8808:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 8809:     return get_query_reply($queryid);
 8810: }
 8811: 
 8812: # -------------------------- Update MySQL table for portfolio file
 8813: 
 8814: sub update_portfolio_table {
 8815:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 8816:     if ($group ne '') {
 8817:         $file_name =~s /^\Q$group\E//;
 8818:     }
 8819:     my $homeserver = &homeserver($uname,$udom);
 8820:     my $queryid=
 8821:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 8822:                ':'.&escape($file_name).':'.$action,$homeserver);
 8823:     my $reply = &get_query_reply($queryid);
 8824:     return $reply;
 8825: }
 8826: 
 8827: # -------------------------- Update MySQL allusers table
 8828: 
 8829: sub update_allusers_table {
 8830:     my ($uname,$udom,$names) = @_;
 8831:     my $homeserver = &homeserver($uname,$udom);
 8832:     my $queryid=
 8833:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 8834:                'lastname='.&escape($names->{'lastname'}).'%%'.
 8835:                'firstname='.&escape($names->{'firstname'}).'%%'.
 8836:                'middlename='.&escape($names->{'middlename'}).'%%'.
 8837:                'generation='.&escape($names->{'generation'}).'%%'.
 8838:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 8839:                'id='.&escape($names->{'id'}),$homeserver);
 8840:     return;
 8841: }
 8842: 
 8843: # ------- Request retrieval of institutional classlists for course(s)
 8844: 
 8845: sub fetch_enrollment_query {
 8846:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 8847:     my ($homeserver,$sleep,$loopmax);
 8848:     my $maxtries = 1;
 8849:     if ($context eq 'automated') {
 8850:         $homeserver = $perlvar{'lonHostID'};
 8851:         $sleep = 2;
 8852:         $loopmax = 100;
 8853:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 8854:     } else {
 8855:         $homeserver = &homeserver($cnum,$dom);
 8856:     }
 8857:     my $host=&hostname($homeserver);
 8858:     my $cmd = '';
 8859:     foreach my $affiliate (keys(%{$affiliatesref})) {
 8860:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 8861:     }
 8862:     $cmd =~ s/%%$//;
 8863:     $cmd = &escape($cmd);
 8864:     my $query = 'fetchenrollment';
 8865:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 8866:     unless ($queryid=~/^\Q$host\E\_/) { 
 8867:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 8868:         return 'error: '.$queryid;
 8869:     }
 8870:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
 8871:     my $tries = 1;
 8872:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 8873:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
 8874:         $tries ++;
 8875:     }
 8876:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 8877:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 8878:     } else {
 8879:         my @responses = split(/:/,$reply);
 8880:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
 8881:             foreach my $line (@responses) {
 8882:                 my ($key,$value) = split(/=/,$line,2);
 8883:                 $$replyref{$key} = $value;
 8884:             }
 8885:         } else {
 8886:             my $pathname = LONCAPA::tempdir();
 8887:             foreach my $line (@responses) {
 8888:                 my ($key,$value) = split(/=/,$line);
 8889:                 $$replyref{$key} = $value;
 8890:                 if ($value > 0) {
 8891:                     foreach my $item (@{$$affiliatesref{$key}}) {
 8892:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 8893:                         my $destname = $pathname.'/'.$filename;
 8894:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 8895:                         if ($xml_classlist =~ /^error/) {
 8896:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 8897:                         } else {
 8898:                             if ( open(FILE,">",$destname) ) {
 8899:                                 print FILE &unescape($xml_classlist);
 8900:                                 close(FILE);
 8901:                             } else {
 8902:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 8903:                             }
 8904:                         }
 8905:                     }
 8906:                 }
 8907:             }
 8908:         }
 8909:         return 'ok';
 8910:     }
 8911:     return 'error';
 8912: }
 8913: 
 8914: sub get_query_reply {
 8915:     my ($queryid,$sleep,$loopmax) = @_;
 8916:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
 8917:         $sleep = 0.2;
 8918:     }
 8919:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
 8920:         $loopmax = 100;
 8921:     }
 8922:     my $replyfile=LONCAPA::tempdir().$queryid;
 8923:     my $reply='';
 8924:     for (1..$loopmax) {
 8925: 	sleep($sleep);
 8926:         if (-e $replyfile.'.end') {
 8927: 	    if (open(my $fh,"<",$replyfile)) {
 8928: 		$reply = join('',<$fh>);
 8929: 		close($fh);
 8930: 	   } else { return 'error: reply_file_error'; }
 8931:            return &unescape($reply);
 8932: 	}
 8933:     }
 8934:     return 'timeout:'.$queryid;
 8935: }
 8936: 
 8937: sub courselog_query {
 8938: #
 8939: # possible filters:
 8940: # url: url or symb
 8941: # username
 8942: # domain
 8943: # action: view, submit, grade
 8944: # start: timestamp
 8945: # end: timestamp
 8946: #
 8947:     my (%filters)=@_;
 8948:     unless ($env{'request.course.id'}) { return 'no_course'; }
 8949:     if ($filters{'url'}) {
 8950: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 8951:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 8952:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 8953:     }
 8954:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 8955:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 8956:     return &log_query($cname,$cdom,'courselog',%filters);
 8957: }
 8958: 
 8959: sub userlog_query {
 8960: #
 8961: # possible filters:
 8962: # action: log check role
 8963: # start: timestamp
 8964: # end: timestamp
 8965: #
 8966:     my ($uname,$udom,%filters)=@_;
 8967:     return &log_query($uname,$udom,'userlog',%filters);
 8968: }
 8969: 
 8970: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 8971: 
 8972: sub auto_run {
 8973:     my ($cnum,$cdom) = @_;
 8974:     my $response = 0;
 8975:     my $settings;
 8976:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 8977:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 8978:         $settings = $domconfig{'autoenroll'};
 8979:         if ($settings->{'run'} eq '1') {
 8980:             $response = 1;
 8981:         }
 8982:     } else {
 8983:         my $homeserver;
 8984:         if (&is_course($cdom,$cnum)) {
 8985:             $homeserver = &homeserver($cnum,$cdom);
 8986:         } else {
 8987:             $homeserver = &domain($cdom,'primary');
 8988:         }
 8989:         if ($homeserver ne 'no_host') {
 8990:             $response = &reply('autorun:'.$cdom,$homeserver);
 8991:         }
 8992:     }
 8993:     return $response;
 8994: }
 8995: 
 8996: sub auto_get_sections {
 8997:     my ($cnum,$cdom,$inst_coursecode) = @_;
 8998:     my $homeserver;
 8999:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
 9000:         $homeserver = &homeserver($cnum,$cdom);
 9001:     }
 9002:     if (!defined($homeserver)) { 
 9003:         if ($cdom =~ /^$match_domain$/) {
 9004:             $homeserver = &domain($cdom,'primary');
 9005:         }
 9006:     }
 9007:     my @secs;
 9008:     if (defined($homeserver)) {
 9009:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 9010:         unless ($response eq 'refused') {
 9011:             @secs = split(/:/,$response);
 9012:         }
 9013:     }
 9014:     return @secs;
 9015: }
 9016: 
 9017: sub auto_new_course {
 9018:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
 9019:     my $homeserver = &homeserver($cnum,$cdom);
 9020:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
 9021:     return $response;
 9022: }
 9023: 
 9024: sub auto_validate_courseID {
 9025:     my ($cnum,$cdom,$inst_course_id) = @_;
 9026:     my $homeserver = &homeserver($cnum,$cdom);
 9027:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 9028:     return $response;
 9029: }
 9030: 
 9031: sub auto_validate_instcode {
 9032:     my ($cnum,$cdom,$instcode,$owner) = @_;
 9033:     my ($homeserver,$response);
 9034:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 9035:         $homeserver = &homeserver($cnum,$cdom);
 9036:     }
 9037:     if (!defined($homeserver)) {
 9038:         if ($cdom =~ /^$match_domain$/) {
 9039:             $homeserver = &domain($cdom,'primary');
 9040:         }
 9041:     }
 9042:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
 9043:                         &escape($instcode).':'.&escape($owner),$homeserver));
 9044:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
 9045:     return ($outcome,$description,$defaultcredits);
 9046: }
 9047: 
 9048: sub auto_create_password {
 9049:     my ($cnum,$cdom,$authparam,$udom) = @_;
 9050:     my ($homeserver,$response);
 9051:     my $create_passwd = 0;
 9052:     my $authchk = '';
 9053:     if ($udom =~ /^$match_domain$/) {
 9054:         $homeserver = &domain($udom,'primary');
 9055:     }
 9056:     if ($homeserver eq '') {
 9057:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 9058:             $homeserver = &homeserver($cnum,$cdom);
 9059:         }
 9060:     }
 9061:     if ($homeserver eq '') {
 9062:         $authchk = 'nodomain';
 9063:     } else {
 9064:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 9065:         if ($response eq 'refused') {
 9066:             $authchk = 'refused';
 9067:         } else {
 9068:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 9069:         }
 9070:     }
 9071:     return ($authparam,$create_passwd,$authchk);
 9072: }
 9073: 
 9074: sub auto_photo_permission {
 9075:     my ($cnum,$cdom,$students) = @_;
 9076:     my $homeserver = &homeserver($cnum,$cdom);
 9077:     my ($outcome,$perm_reqd,$conditions) = 
 9078: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 9079:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 9080: 	return (undef,undef);
 9081:     }
 9082:     return ($outcome,$perm_reqd,$conditions);
 9083: }
 9084: 
 9085: sub auto_checkphotos {
 9086:     my ($uname,$udom,$pid) = @_;
 9087:     my $homeserver = &homeserver($uname,$udom);
 9088:     my ($result,$resulttype);
 9089:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 9090: 				   &escape($uname).':'.&escape($pid),
 9091: 				   $homeserver));
 9092:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 9093: 	return (undef,undef);
 9094:     }
 9095:     if ($outcome) {
 9096:         ($result,$resulttype) = split(/:/,$outcome);
 9097:     } 
 9098:     return ($result,$resulttype);
 9099: }
 9100: 
 9101: sub auto_photochoice {
 9102:     my ($cnum,$cdom) = @_;
 9103:     my $homeserver = &homeserver($cnum,$cdom);
 9104:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 9105: 						       &escape($cdom),
 9106: 						       $homeserver)));
 9107:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 9108: 	return (undef,undef);
 9109:     }
 9110:     return ($update,$comment);
 9111: }
 9112: 
 9113: sub auto_photoupdate {
 9114:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 9115:     my $homeserver = &homeserver($cnum,$dom);
 9116:     my $host=&hostname($homeserver);
 9117:     my $cmd = '';
 9118:     my $maxtries = 1;
 9119:     foreach my $affiliate (keys(%{$affiliatesref})) {
 9120:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 9121:     }
 9122:     $cmd =~ s/%%$//;
 9123:     $cmd = &escape($cmd);
 9124:     my $query = 'institutionalphotos';
 9125:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 9126:     unless ($queryid=~/^\Q$host\E\_/) {
 9127:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 9128:         return 'error: '.$queryid;
 9129:     }
 9130:     my $reply = &get_query_reply($queryid);
 9131:     my $tries = 1;
 9132:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 9133:         $reply = &get_query_reply($queryid);
 9134:         $tries ++;
 9135:     }
 9136:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 9137:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 9138:     } else {
 9139:         my @responses = split(/:/,$reply);
 9140:         my $outcome = shift(@responses); 
 9141:         foreach my $item (@responses) {
 9142:             my ($key,$value) = split(/=/,$item);
 9143:             $$photo{$key} = $value;
 9144:         }
 9145:         return $outcome;
 9146:     }
 9147:     return 'error';
 9148: }
 9149: 
 9150: sub auto_instcode_format {
 9151:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 9152: 	$cat_order) = @_;
 9153:     my $courses = '';
 9154:     my @homeservers;
 9155:     if ($caller eq 'global') {
 9156: 	my %servers = &get_servers($codedom,'library');
 9157: 	foreach my $tryserver (keys(%servers)) {
 9158: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 9159: 		push(@homeservers,$tryserver);
 9160: 	    }
 9161:         }
 9162:     } elsif ($caller eq 'requests') {
 9163:         if ($codedom =~ /^$match_domain$/) {
 9164:             my $chome = &domain($codedom,'primary');
 9165:             unless ($chome eq 'no_host') {
 9166:                 push(@homeservers,$chome);
 9167:             }
 9168:         }
 9169:     } else {
 9170:         push(@homeservers,&homeserver($caller,$codedom));
 9171:     }
 9172:     foreach my $code (keys(%{$instcodes})) {
 9173:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 9174:     }
 9175:     chop($courses);
 9176:     my $ok_response = 0;
 9177:     my $response;
 9178:     while (@homeservers > 0 && $ok_response == 0) {
 9179:         my $server = shift(@homeservers); 
 9180:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 9181:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 9182:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 9183: 		split(/:/,$response);
 9184:             %{$codes} = (%{$codes},&str2hash($codes_str));
 9185:             push(@{$codetitles},&str2array($codetitles_str));
 9186:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 9187:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 9188:             $ok_response = 1;
 9189:         }
 9190:     }
 9191:     if ($ok_response) {
 9192:         return 'ok';
 9193:     } else {
 9194:         return $response;
 9195:     }
 9196: }
 9197: 
 9198: sub auto_instcode_defaults {
 9199:     my ($domain,$returnhash,$code_order) = @_;
 9200:     my @homeservers;
 9201: 
 9202:     my %servers = &get_servers($domain,'library');
 9203:     foreach my $tryserver (keys(%servers)) {
 9204: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 9205: 	    push(@homeservers,$tryserver);
 9206: 	}
 9207:     }
 9208: 
 9209:     my $response;
 9210:     foreach my $server (@homeservers) {
 9211:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 9212:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 9213: 	
 9214: 	foreach my $pair (split(/\&/,$response)) {
 9215: 	    my ($name,$value)=split(/\=/,$pair);
 9216: 	    if ($name eq 'code_order') {
 9217: 		@{$code_order} = split(/\&/,&unescape($value));
 9218: 	    } else {
 9219: 		$returnhash->{&unescape($name)}=&unescape($value);
 9220: 	    }
 9221: 	}
 9222: 	return 'ok';
 9223:     }
 9224: 
 9225:     return $response;
 9226: }
 9227: 
 9228: sub auto_possible_instcodes {
 9229:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
 9230:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
 9231:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 9232:         return;
 9233:     }
 9234:     my (@homeservers,$uhome);
 9235:     if (defined(&domain($domain,'primary'))) {
 9236:         $uhome=&domain($domain,'primary');
 9237:         push(@homeservers,&domain($domain,'primary'));
 9238:     } else {
 9239:         my %servers = &get_servers($domain,'library');
 9240:         foreach my $tryserver (keys(%servers)) {
 9241:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 9242:                 push(@homeservers,$tryserver);
 9243:             }
 9244:         }
 9245:     }
 9246:     my $response;
 9247:     foreach my $server (@homeservers) {
 9248:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
 9249:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 9250:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
 9251:             split(':',$response);
 9252:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
 9253:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
 9254:         foreach my $item (split('&',$cat_title)) {   
 9255:             my ($name,$value)=split('=',$item);
 9256:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
 9257:         }
 9258:         foreach my $item (split('&',$cat_order)) {
 9259:             my ($name,$value)=split('=',$item);
 9260:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
 9261:         }
 9262:         return 'ok';
 9263:     }
 9264:     return $response;
 9265: }
 9266: 
 9267: sub auto_courserequest_checks {
 9268:     my ($dom) = @_;
 9269:     my ($homeserver,%validations);
 9270:     if ($dom =~ /^$match_domain$/) {
 9271:         $homeserver = &domain($dom,'primary');
 9272:     }
 9273:     unless ($homeserver eq 'no_host') {
 9274:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
 9275:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 9276:             my @items = split(/&/,$response);
 9277:             foreach my $item (@items) {
 9278:                 my ($key,$value) = split('=',$item);
 9279:                 $validations{&unescape($key)} = &thaw_unescape($value);
 9280:             }
 9281:         }
 9282:     }
 9283:     return %validations; 
 9284: }
 9285: 
 9286: sub auto_courserequest_validation {
 9287:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
 9288:     my ($homeserver,$response);
 9289:     if ($dom =~ /^$match_domain$/) {
 9290:         $homeserver = &domain($dom,'primary');
 9291:     }
 9292:     unless ($homeserver eq 'no_host') {
 9293:         my $customdata;
 9294:         if (ref($custominfo) eq 'HASH') {
 9295:             $customdata = &freeze_escape($custominfo);
 9296:         }
 9297:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
 9298:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
 9299:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
 9300:                                     $customdata,$homeserver));
 9301:     }
 9302:     return $response;
 9303: }
 9304: 
 9305: sub auto_validate_class_sec {
 9306:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 9307:     my $homeserver = &homeserver($cnum,$cdom);
 9308:     my $ownerlist;
 9309:     if (ref($owners) eq 'ARRAY') {
 9310:         $ownerlist = join(',',@{$owners});
 9311:     } else {
 9312:         $ownerlist = $owners;
 9313:     }
 9314:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 9315:                         &escape($ownerlist).':'.$cdom,$homeserver);
 9316:     return $response;
 9317: }
 9318: 
 9319: sub auto_validate_instclasses {
 9320:     my ($cdom,$cnum,$owners,$classesref) = @_;
 9321:     my ($homeserver,%validations);
 9322:     $homeserver = &homeserver($cnum,$cdom);
 9323:     unless ($homeserver eq 'no_host') {
 9324:         my $ownerlist;
 9325:         if (ref($owners) eq 'ARRAY') {
 9326:             $ownerlist = join(',',@{$owners});
 9327:         } else {
 9328:             $ownerlist = $owners;
 9329:         }
 9330:         if (ref($classesref) eq 'HASH') {
 9331:             my $classes = &freeze_escape($classesref);
 9332:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
 9333:                                 ':'.$cdom.':'.$classes,$homeserver);
 9334:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 9335:                 my @items = split(/&/,$response);
 9336:                 foreach my $item (@items) {
 9337:                     my ($key,$value) = split('=',$item);
 9338:                     $validations{&unescape($key)} = &thaw_unescape($value);
 9339:                 }
 9340:             }
 9341:         }
 9342:     }
 9343:     return %validations;
 9344: }
 9345: 
 9346: sub auto_crsreq_update {
 9347:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
 9348:         $code,$accessstart,$accessend,$inbound) = @_;
 9349:     my ($homeserver,%crsreqresponse);
 9350:     if ($cdom =~ /^$match_domain$/) {
 9351:         $homeserver = &domain($cdom,'primary');
 9352:     }
 9353:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
 9354:         my $info;
 9355:         if (ref($inbound) eq 'HASH') {
 9356:             $info = &freeze_escape($inbound);
 9357:         }
 9358:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
 9359:                             ':'.&escape($action).':'.&escape($ownername).':'.
 9360:                             &escape($ownerdomain).':'.&escape($fullname).':'.
 9361:                             &escape($title).':'.&escape($code).':'.
 9362:                             &escape($accessstart).':'.&escape($accessend).':'.$info,$homeserver);
 9363:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 9364:             my @items = split(/&/,$response);
 9365:             foreach my $item (@items) {
 9366:                 my ($key,$value) = split('=',$item);
 9367:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
 9368:             }
 9369:         }
 9370:     }
 9371:     return \%crsreqresponse;
 9372: }
 9373: 
 9374: sub auto_export_grades {
 9375:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
 9376:     my ($homeserver,%exportresponse);
 9377:     if ($cdom =~ /^$match_domain$/) {
 9378:         $homeserver = &domain($cdom,'primary');
 9379:     }
 9380:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
 9381:         my $info;
 9382:         if (ref($inforef) eq 'HASH') {
 9383:             $info = &freeze_escape($inforef);
 9384:         }
 9385:         if (ref($gradesref) eq 'HASH') {
 9386:             my $grades = &freeze_escape($gradesref);
 9387:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
 9388:                                 $info.':'.$grades,$homeserver);
 9389:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
 9390:                 my @items = split(/&/,$response);
 9391:                 foreach my $item (@items) {
 9392:                     my ($key,$value) = split('=',$item);
 9393:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
 9394:                 }
 9395:             }
 9396:         }
 9397:     }
 9398:     return \%exportresponse;
 9399: }
 9400: 
 9401: sub check_instcode_cloning {
 9402:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
 9403:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 9404:         return;
 9405:     }
 9406:     my $canclone;
 9407:     if (@{$code_order} > 0) {
 9408:         my $instcoderegexp ='^';
 9409:         my @clonecodes = split(/\&/,$cloner);
 9410:         foreach my $item (@{$code_order}) {
 9411:             if (grep(/^\Q$item\E=/,@clonecodes)) {
 9412:                 foreach my $pair (@clonecodes) {
 9413:                     my ($key,$val) = split(/\=/,$pair,2);
 9414:                     $val = &unescape($val);
 9415:                     if ($key eq $item) {
 9416:                         $instcoderegexp .= '('.$val.')';
 9417:                         last;
 9418:                     }
 9419:                 }
 9420:             } else {
 9421:                 $instcoderegexp .= $codedefaults->{$item};
 9422:             }
 9423:         }
 9424:         $instcoderegexp .= '$';
 9425:         my (@from,@to);
 9426:         eval {
 9427:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
 9428:                (@to) = ($clonetocode =~ /$instcoderegexp/);
 9429:         };
 9430:         if ((@from > 0) && (@to > 0)) {
 9431:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
 9432:             if (!@diffs) {
 9433:                 $canclone = 1;
 9434:             }
 9435:         }
 9436:     }
 9437:     return $canclone;
 9438: }
 9439: 
 9440: sub default_instcode_cloning {
 9441:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
 9442:     my (%codedefaults,@code_order,$canclone);
 9443:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
 9444:         %codedefaults = %{$codedefaultsref};
 9445:         @code_order = @{$codeorderref};
 9446:     } elsif ($clonedom) {
 9447:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
 9448:     }
 9449:     if (($domdefclone) && (@code_order)) {
 9450:         my @clonecodes = split(/\+/,$domdefclone);
 9451:         my $instcoderegexp ='^';
 9452:         foreach my $item (@code_order) {
 9453:             if (grep(/^\Q$item\E$/,@clonecodes)) {
 9454:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
 9455:             } else {
 9456:                 $instcoderegexp .= $codedefaults{$item};
 9457:             }
 9458:         }
 9459:         $instcoderegexp .= '$';
 9460:         my (@from,@to);
 9461:         eval {
 9462:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
 9463:             (@to) = ($clonetocode =~ /$instcoderegexp/);
 9464:         };
 9465:         if ((@from > 0) && (@to > 0)) {
 9466:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
 9467:             if (!@diffs) {
 9468:                 $canclone = 1;
 9469:             }
 9470:         }
 9471:     }
 9472:     return $canclone;
 9473: }
 9474: 
 9475: # ------------------------------------------------------- Course Group routines
 9476: 
 9477: sub get_coursegroups {
 9478:     my ($cdom,$cnum,$group,$namespace) = @_;
 9479:     return(&dump($namespace,$cdom,$cnum,$group));
 9480: }
 9481: 
 9482: sub modify_coursegroup {
 9483:     my ($cdom,$cnum,$groupsettings) = @_;
 9484:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 9485: }
 9486: 
 9487: sub toggle_coursegroup_status {
 9488:     my ($cdom,$cnum,$group,$action) = @_;
 9489:     my ($from_namespace,$to_namespace);
 9490:     if ($action eq 'delete') {
 9491:         $from_namespace = 'coursegroups';
 9492:         $to_namespace = 'deleted_groups';
 9493:     } else {
 9494:         $from_namespace = 'deleted_groups';
 9495:         $to_namespace = 'coursegroups';
 9496:     }
 9497:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 9498:     if (my $tmp = &error(%curr_group)) {
 9499:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 9500:         return ('read error',$tmp);
 9501:     } else {
 9502:         my %savedsettings = %curr_group; 
 9503:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 9504:         my $deloutcome;
 9505:         if ($result eq 'ok') {
 9506:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 9507:         } else {
 9508:             return ('write error',$result);
 9509:         }
 9510:         if ($deloutcome eq 'ok') {
 9511:             return 'ok';
 9512:         } else {
 9513:             return ('delete error',$deloutcome);
 9514:         }
 9515:     }
 9516: }
 9517: 
 9518: sub modify_group_roles {
 9519:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 9520:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 9521:     my $role = 'gr/'.&escape($userprivs);
 9522:     my ($uname,$udom) = split(/:/,$user);
 9523:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 9524:     if ($result eq 'ok') {
 9525:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 9526:     }
 9527:     return $result;
 9528: }
 9529: 
 9530: sub modify_coursegroup_membership {
 9531:     my ($cdom,$cnum,$membership) = @_;
 9532:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 9533:     return $result;
 9534: }
 9535: 
 9536: sub get_active_groups {
 9537:     my ($udom,$uname,$cdom,$cnum) = @_;
 9538:     my $now = time;
 9539:     my %groups = ();
 9540:     foreach my $key (keys(%env)) {
 9541:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 9542:             my ($start,$end) = split(/\./,$env{$key});
 9543:             if (($end!=0) && ($end<$now)) { next; }
 9544:             if (($start!=0) && ($start>$now)) { next; }
 9545:             if ($1 eq $cdom && $2 eq $cnum) {
 9546:                 $groups{$3} = $env{$key} ;
 9547:             }
 9548:         }
 9549:     }
 9550:     return %groups;
 9551: }
 9552: 
 9553: sub get_group_membership {
 9554:     my ($cdom,$cnum,$group) = @_;
 9555:     return(&dump('groupmembership',$cdom,$cnum,$group));
 9556: }
 9557: 
 9558: sub get_users_groups {
 9559:     my ($udom,$uname,$courseid) = @_;
 9560:     my @usersgroups;
 9561:     my $cachetime=1800;
 9562: 
 9563:     my $hashid="$udom:$uname:$courseid";
 9564:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 9565:     if (defined($cached)) {
 9566:         @usersgroups = split(/:/,$grouplist);
 9567:     } else {  
 9568:         $grouplist = '';
 9569:         my $courseurl = &courseid_to_courseurl($courseid);
 9570:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 9571:         my $access_end = $env{'course.'.$courseid.
 9572:                               '.default_enrollment_end_date'};
 9573:         my $now = time;
 9574:         foreach my $key (keys(%roleshash)) {
 9575:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 9576:                 my $group = $1;
 9577:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 9578:                     my $start = $2;
 9579:                     my $end = $1;
 9580:                     if ($start == -1) { next; } # deleted from group
 9581:                     if (($start!=0) && ($start>$now)) { next; }
 9582:                     if (($end!=0) && ($end<$now)) {
 9583:                         if ($access_end && $access_end < $now) {
 9584:                             if ($access_end - $end < 86400) {
 9585:                                 push(@usersgroups,$group);
 9586:                             }
 9587:                         }
 9588:                         next;
 9589:                     }
 9590:                     push(@usersgroups,$group);
 9591:                 }
 9592:             }
 9593:         }
 9594:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 9595:         $grouplist = join(':',@usersgroups);
 9596:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 9597:     }
 9598:     return @usersgroups;
 9599: }
 9600: 
 9601: sub devalidate_getgroups_cache {
 9602:     my ($udom,$uname,$cdom,$cnum)=@_;
 9603:     my $courseid = $cdom.'_'.$cnum;
 9604: 
 9605:     my $hashid="$udom:$uname:$courseid";
 9606:     &devalidate_cache_new('getgroups',$hashid);
 9607: }
 9608: 
 9609: # ------------------------------------------------------------------ Plain Text
 9610: 
 9611: sub plaintext {
 9612:     my ($short,$type,$cid,$forcedefault) = @_;
 9613:     if ($short =~ m{^cr/}) {
 9614: 	return (split('/',$short))[-1];
 9615:     }
 9616:     if (!defined($cid)) {
 9617:         $cid = $env{'request.course.id'};
 9618:     }
 9619:     my %rolenames = (
 9620:                       Course    => 'std',
 9621:                       Community => 'alt1',
 9622:                     );
 9623:     if ($cid ne '') {
 9624:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
 9625:             unless ($forcedefault) {
 9626:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
 9627:                 &Apache::lonlocal::mt_escape(\$roletext);
 9628:                 return &Apache::lonlocal::mt($roletext);
 9629:             }
 9630:         }
 9631:     }
 9632:     if ((defined($type)) && (defined($rolenames{$type})) &&
 9633:         (defined($rolenames{$type})) && 
 9634:         (defined($prp{$short}{$rolenames{$type}}))) {
 9635:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 9636:     } elsif ($cid ne '') {
 9637:         my $crstype = $env{'course.'.$cid.'.type'};
 9638:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
 9639:             (defined($prp{$short}{$rolenames{$crstype}}))) {
 9640:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
 9641:         }
 9642:     }
 9643:     return &Apache::lonlocal::mt($prp{$short}{'std'});
 9644: }
 9645: 
 9646: # ----------------------------------------------------------------- Assign Role
 9647: 
 9648: sub assignrole {
 9649:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
 9650:         $context)=@_;
 9651:     my $mrole;
 9652:     if ($role =~ /^cr\//) {
 9653:         my $cwosec=$url;
 9654:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 9655: 	unless (&allowed('ccr',$cwosec)) {
 9656:            my $refused = 1;
 9657:            if ($context eq 'requestcourses') {
 9658:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 9659:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
 9660:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
 9661:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 9662:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 9663:                            if ($crsenv{'internal.courseowner'} eq
 9664:                                $env{'user.name'}.':'.$env{'user.domain'}) {
 9665:                                $refused = '';
 9666:                            }
 9667:                        }
 9668:                    }
 9669:                }
 9670:            }
 9671:            if ($refused) {
 9672:                &logthis('Refused custom assignrole: '.
 9673:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
 9674:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
 9675:                return 'refused';
 9676:            }
 9677:         }
 9678:         $mrole='cr';
 9679:     } elsif ($role =~ /^gr\//) {
 9680:         my $cwogrp=$url;
 9681:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 9682:         unless (&allowed('mdg',$cwogrp)) {
 9683:             &logthis('Refused group assignrole: '.
 9684:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 9685:                     $env{'user.name'}.' at '.$env{'user.domain'});
 9686:             return 'refused';
 9687:         }
 9688:         $mrole='gr';
 9689:     } else {
 9690:         my $cwosec=$url;
 9691:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 9692:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 9693:             my $refused;
 9694:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 9695:                 if (!(&allowed('c'.$role,$url))) {
 9696:                     $refused = 1;
 9697:                 }
 9698:             } else {
 9699:                 $refused = 1;
 9700:             }
 9701:             if ($refused) {
 9702:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 9703:                 if (!$selfenroll && $context eq 'course') {
 9704:                     my %crsenv;
 9705:                     if ($role eq 'cc' || $role eq 'co') {
 9706:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 9707:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
 9708:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
 9709:                                 if ($crsenv{'internal.courseowner'} eq 
 9710:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 9711:                                     $refused = '';
 9712:                                 }
 9713:                             }
 9714:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
 9715:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
 9716:                                 if ($crsenv{'internal.courseowner'} eq 
 9717:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 9718:                                     $refused = '';
 9719:                                 }
 9720:                             }
 9721:                         }
 9722:                     }
 9723:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 9724:                     $refused = '';
 9725:                 } elsif ($context eq 'requestcourses') {
 9726:                     my @possroles = ('st','ta','ep','in','cc','co');
 9727:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
 9728:                         my $wrongcc;
 9729:                         if ($cnum =~ /^$match_community$/) {
 9730:                             $wrongcc = 1 if ($role eq 'cc');
 9731:                         } else {
 9732:                             $wrongcc = 1 if ($role eq 'co');
 9733:                         }
 9734:                         unless ($wrongcc) {
 9735:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 9736:                             if ($crsenv{'internal.courseowner'} eq 
 9737:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
 9738:                                 $refused = '';
 9739:                             }
 9740:                         }
 9741:                     }
 9742:                 } elsif ($context eq 'requestauthor') {
 9743:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 9744:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
 9745:                         if ($env{'environment.requestauthor'} eq 'automatic') {
 9746:                             $refused = '';
 9747:                         } else {
 9748:                             my %domdefaults = &get_domain_defaults($udom);
 9749:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
 9750:                                 my $checkbystatus;
 9751:                                 if ($env{'user.adv'}) {
 9752:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
 9753:                                     if ($disposition eq 'automatic') {
 9754:                                         $refused = '';
 9755:                                     } elsif ($disposition eq '') {
 9756:                                         $checkbystatus = 1;
 9757:                                     }
 9758:                                 } else {
 9759:                                     $checkbystatus = 1;
 9760:                                 }
 9761:                                 if ($checkbystatus) {
 9762:                                     if ($env{'environment.inststatus'}) {
 9763:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
 9764:                                         foreach my $type (@inststatuses) {
 9765:                                             if (($type ne '') &&
 9766:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
 9767:                                                 $refused = '';
 9768:                                             }
 9769:                                         }
 9770:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
 9771:                                         $refused = '';
 9772:                                     }
 9773:                                 }
 9774:                             }
 9775:                         }
 9776:                     }
 9777:                 }
 9778:                 if ($refused) {
 9779:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 9780:                              ' '.$role.' '.$end.' '.$start.' by '.
 9781: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
 9782:                     return 'refused';
 9783:                 }
 9784:             }
 9785:         } elsif ($role eq 'au') {
 9786:             if ($url ne '/'.$udom.'/') {
 9787:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
 9788:                          ' to assign author role for '.$uname.':'.$udom.
 9789:                          ' in domain: '.$url.' refused (wrong domain).');
 9790:                 return 'refused';
 9791:             }
 9792:         }
 9793:         $mrole=$role;
 9794:     }
 9795:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 9796:                 "$udom:$uname:$url".'_'."$mrole=$role";
 9797:     if ($end) { $command.='_'.$end; }
 9798:     if ($start) {
 9799: 	if ($end) { 
 9800:            $command.='_'.$start; 
 9801:         } else {
 9802:            $command.='_0_'.$start;
 9803:         }
 9804:     }
 9805:     my $origstart = $start;
 9806:     my $origend = $end;
 9807:     my $delflag;
 9808: # actually delete
 9809:     if ($deleteflag) {
 9810: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 9811: # modify command to delete the role
 9812:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 9813:                 "$udom:$uname:$url".'_'."$mrole";
 9814: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 9815: # set start and finish to negative values for userrolelog
 9816:            $start=-1;
 9817:            $end=-1;
 9818:            $delflag = 1;
 9819:         }
 9820:     }
 9821: # send command
 9822:     my $answer=&reply($command,&homeserver($uname,$udom));
 9823: # log new user role if status is ok
 9824:     if ($answer eq 'ok') {
 9825: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 9826:         if (($role eq 'cc') || ($role eq 'in') ||
 9827:             ($role eq 'ep') || ($role eq 'ad') ||
 9828:             ($role eq 'ta') || ($role eq 'st') ||
 9829:             ($role=~/^cr/) || ($role eq 'gr') ||
 9830:             ($role eq 'co')) {
 9831: # for course roles, perform group memberships changes triggered by role change.
 9832:             unless ($role =~ /^gr/) {
 9833:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 9834:                                                  $origstart,$selfenroll,$context);
 9835:             }
 9836:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 9837:                            $selfenroll,$context);
 9838:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
 9839:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
 9840:                  ($role eq 'da')) {
 9841:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 9842:                            $context);
 9843:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
 9844:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 9845:                              $context);
 9846:         }
 9847:         if ($role eq 'cc') {
 9848:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
 9849:         }
 9850:     }
 9851:     return $answer;
 9852: }
 9853: 
 9854: sub autoupdate_coowners {
 9855:     my ($url,$end,$start,$uname,$udom) = @_;
 9856:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
 9857:     if (($cdom ne '') && ($cnum ne '')) {
 9858:         my $now = time;
 9859:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
 9860:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
 9861:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
 9862:             my $instcode = $coursehash{'internal.coursecode'};
 9863:             if ($instcode ne '') {
 9864:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
 9865:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
 9866:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
 9867:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
 9868:                         if ($result eq 'valid') {
 9869:                             if ($coursehash{'internal.co-owners'}) {
 9870:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 9871:                                     push(@newcoowners,$coowner);
 9872:                                 }
 9873:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
 9874:                                     push(@newcoowners,$uname.':'.$udom);
 9875:                                 }
 9876:                                 @newcoowners = sort(@newcoowners);
 9877:                             } else {
 9878:                                 push(@newcoowners,$uname.':'.$udom);
 9879:                             }
 9880:                         } else {
 9881:                             if ($coursehash{'internal.co-owners'}) {
 9882:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 9883:                                     unless ($coowner eq $uname.':'.$udom) {
 9884:                                         push(@newcoowners,$coowner);
 9885:                                     }
 9886:                                 }
 9887:                                 unless (@newcoowners > 0) {
 9888:                                     $delcoowners = 1;
 9889:                                     $coowners = '';
 9890:                                 }
 9891:                             }
 9892:                         }
 9893:                         if (@newcoowners || $delcoowners) {
 9894:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
 9895:                                             $delcoowners,@newcoowners);
 9896:                         }
 9897:                     }
 9898:                 }
 9899:             }
 9900:         }
 9901:     }
 9902: }
 9903: 
 9904: sub store_coowners {
 9905:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
 9906:     my $cid = $cdom.'_'.$cnum;
 9907:     my ($coowners,$delresult,$putresult);
 9908:     if (@newcoowners) {
 9909:         $coowners = join(',',@newcoowners);
 9910:         my %coownershash = (
 9911:                             'internal.co-owners' => $coowners,
 9912:                            );
 9913:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
 9914:         if ($putresult eq 'ok') {
 9915:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
 9916:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
 9917:             }
 9918:         }
 9919:     }
 9920:     if ($delcoowners) {
 9921:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
 9922:         if ($delresult eq 'ok') {
 9923:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
 9924:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
 9925:             }
 9926:         }
 9927:     }
 9928:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
 9929:         my %crsinfo =
 9930:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 9931:         if (ref($crsinfo{$cid}) eq 'HASH') {
 9932:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
 9933:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
 9934:         }
 9935:     }
 9936: }
 9937: 
 9938: # -------------------------------------------------- Modify user authentication
 9939: # Overrides without validation
 9940: 
 9941: sub modifyuserauth {
 9942:     my ($udom,$uname,$umode,$upass)=@_;
 9943:     my $uhome=&homeserver($uname,$udom);
 9944:     my $allowed;
 9945:     if (&allowed('mau',$udom)) {
 9946:         $allowed = 1;
 9947:     } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
 9948:              ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
 9949:              (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
 9950:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 9951:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 9952:         if (($cdom ne '') && ($cnum ne '')) {
 9953:             my $is_owner = &is_course_owner($cdom,$cnum);
 9954:             if ($is_owner) {
 9955:                 $allowed = 1;
 9956:             }
 9957:         }
 9958:     }
 9959:     unless ($allowed) { return 'refused'; }
 9960:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 9961:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 9962:              ' in domain '.$env{'request.role.domain'});  
 9963:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 9964: 		     &escape($upass),$uhome);
 9965:     my $ip = &get_requestor_ip();
 9966:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 9967:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 9968:          '(Remote '.$ip.'): '.$reply);
 9969:     &log($udom,,$uname,$uhome,
 9970:         'Authentication changed by '.$env{'user.domain'}.', '.
 9971:                                      $env{'user.name'}.', '.$umode.
 9972:          '(Remote '.$ip.'): '.$reply);
 9973:     unless ($reply eq 'ok') {
 9974:         &logthis('Authentication mode error: '.$reply);
 9975: 	return 'error: '.$reply;
 9976:     }   
 9977:     return 'ok';
 9978: }
 9979: 
 9980: # --------------------------------------------------------------- Modify a user
 9981: 
 9982: sub modifyuser {
 9983:     my ($udom,    $uname, $uid,
 9984:         $umode,   $upass, $first,
 9985:         $middle,  $last,  $gene,
 9986:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
 9987:     $udom= &LONCAPA::clean_domain($udom);
 9988:     $uname=&LONCAPA::clean_username($uname);
 9989:     my $showcandelete = 'none';
 9990:     if (ref($candelete) eq 'ARRAY') {
 9991:         if (@{$candelete} > 0) {
 9992:             $showcandelete = join(', ',@{$candelete});
 9993:         }
 9994:     }
 9995:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 9996:              $umode.', '.$first.', '.$middle.', '.
 9997: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
 9998:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 9999:                                      ' desiredhome not specified'). 
10000:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
10001:              ' in domain '.$env{'request.role.domain'});
10002:     my $uhome=&homeserver($uname,$udom,'true');
10003:     my $newuser;
10004:     if ($uhome eq 'no_host') {
10005:         $newuser = 1;
10006:     }
10007: # ----------------------------------------------------------------- Create User
10008:     if (($uhome eq 'no_host') && 
10009: 	(($umode && $upass) || ($umode eq 'localauth'))) {
10010:         my $unhome='';
10011:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
10012:             $unhome = $desiredhome;
10013: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
10014: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
10015:         } else { # load balancing routine for determining $unhome
10016:             my $loadm=10000000;
10017: 	    my %servers = &get_servers($udom,'library');
10018: 	    foreach my $tryserver (keys(%servers)) {
10019: 		my $answer=reply('load',$tryserver);
10020: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
10021: 		    $loadm=$answer;
10022: 		    $unhome=$tryserver;
10023: 		}
10024: 	    }
10025:         }
10026:         if (($unhome eq '') || ($unhome eq 'no_host')) {
10027: 	    return 'error: unable to find a home server for '.$uname.
10028:                    ' in domain '.$udom;
10029:         }
10030:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
10031:                          &escape($upass),$unhome);
10032: 	unless ($reply eq 'ok') {
10033:             return 'error: '.$reply;
10034:         }   
10035:         $uhome=&homeserver($uname,$udom,'true');
10036:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
10037: 	    return 'error: unable verify users home machine.';
10038:         }
10039:     }   # End of creation of new user
10040: # ---------------------------------------------------------------------- Add ID
10041:     if ($uid) {
10042:        $uid=~tr/A-Z/a-z/;
10043:        my %uidhash=&idrget($udom,$uname);
10044:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
10045:          && (!$forceid)) {
10046: 	  unless ($uid eq $uidhash{$uname}) {
10047: 	      return 'error: user id "'.$uid.'" does not match '.
10048:                   'current user id "'.$uidhash{$uname}.'".';
10049:           }
10050:        } else {
10051: 	  &idput($udom,($uname => $uid));
10052:        }
10053:     }
10054: # -------------------------------------------------------------- Add names, etc
10055:     my @tmp=&get('environment',
10056: 		   ['firstname','middlename','lastname','generation','id',
10057:                     'permanentemail','inststatus'],
10058: 		   $udom,$uname);
10059:     my (%names,%oldnames);
10060:     if ($tmp[0] =~ m/^error:.*/) { 
10061:         %names=(); 
10062:     } else {
10063:         %names = @tmp;
10064:         %oldnames = %names;
10065:     }
10066: #
10067: # If name, email and/or uid are blank (e.g., because an uploaded file
10068: # of users did not contain them), do not overwrite existing values
10069: # unless field is in $candelete array ref.  
10070: #
10071: 
10072:     my @fields = ('firstname','middlename','lastname','generation',
10073:                   'permanentemail','id');
10074:     my %newvalues;
10075:     if (ref($candelete) eq 'ARRAY') {
10076:         foreach my $field (@fields) {
10077:             if (grep(/^\Q$field\E$/,@{$candelete})) {
10078:                 if ($field eq 'firstname') {
10079:                     $names{$field} = $first;
10080:                 } elsif ($field eq 'middlename') {
10081:                     $names{$field} = $middle;
10082:                 } elsif ($field eq 'lastname') {
10083:                     $names{$field} = $last;
10084:                 } elsif ($field eq 'generation') { 
10085:                     $names{$field} = $gene;
10086:                 } elsif ($field eq 'permanentemail') {
10087:                     $names{$field} = $email;
10088:                 } elsif ($field eq 'id') {
10089:                     $names{$field}  = $uid;
10090:                 }
10091:             }
10092:         }
10093:     }
10094:     if ($first)  { $names{'firstname'}  = $first; }
10095:     if (defined($middle)) { $names{'middlename'} = $middle; }
10096:     if ($last)   { $names{'lastname'}   = $last; }
10097:     if (defined($gene))   { $names{'generation'} = $gene; }
10098:     if ($email) {
10099:        $email=~s/[^\w\@\.\-\,]//gs;
10100:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
10101:     }
10102:     if ($uid) { $names{'id'}  = $uid; }
10103:     if (defined($inststatus)) {
10104:         $names{'inststatus'} = '';
10105:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
10106:         if (ref($usertypes) eq 'HASH') {
10107:             my @okstatuses; 
10108:             foreach my $item (split(/:/,$inststatus)) {
10109:                 if (defined($usertypes->{$item})) {
10110:                     push(@okstatuses,$item);  
10111:                 }
10112:             }
10113:             if (@okstatuses) {
10114:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
10115:             }
10116:         }
10117:     }
10118:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
10119:                  $umode.', '.$first.', '.$middle.', '.
10120:                  $last.', '.$gene.', '.$email.', '.$inststatus;
10121:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
10122:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
10123:     } else {
10124:         $logmsg .= ' during self creation';
10125:     }
10126:     my $changed;
10127:     if ($newuser) {
10128:         $changed = 1;
10129:     } else {
10130:         foreach my $field (@fields) {
10131:             if ($names{$field} ne $oldnames{$field}) {
10132:                 $changed = 1;
10133:                 last;
10134:             }
10135:         }
10136:     }
10137:     unless ($changed) {
10138:         $logmsg = 'No changes in user information needed for: '.$logmsg;
10139:         &logthis($logmsg);
10140:         return 'ok';
10141:     }
10142:     my $reply = &put('environment', \%names, $udom,$uname);
10143:     if ($reply ne 'ok') { 
10144:         return 'error: '.$reply;
10145:     }
10146:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
10147:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
10148:     }
10149:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
10150:     &devalidate_cache_new('namescache',$uname.':'.$udom);
10151:     $logmsg = 'Success modifying user '.$logmsg;
10152:     &logthis($logmsg);
10153:     return 'ok';
10154: }
10155: 
10156: # -------------------------------------------------------------- Modify student
10157: 
10158: sub modifystudent {
10159:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
10160:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
10161:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
10162:     if (!$cid) {
10163: 	unless ($cid=$env{'request.course.id'}) {
10164: 	    return 'not_in_class';
10165: 	}
10166:     }
10167: # --------------------------------------------------------------- Make the user
10168:     my $reply=&modifyuser
10169: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
10170:          $desiredhome,$email,$inststatus);
10171:     unless ($reply eq 'ok') { return $reply; }
10172:     # This will cause &modify_student_enrollment to get the uid from the
10173:     # student's environment
10174:     $uid = undef if (!$forceid);
10175:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
10176: 					$gene,$usec,$end,$start,$type,$locktype,
10177:                                         $cid,$selfenroll,$context,$credits,$instsec);
10178:     return $reply;
10179: }
10180: 
10181: sub modify_student_enrollment {
10182:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
10183:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
10184:     my ($cdom,$cnum,$chome);
10185:     if (!$cid) {
10186: 	unless ($cid=$env{'request.course.id'}) {
10187: 	    return 'not_in_class';
10188: 	}
10189: 	$cdom=$env{'course.'.$cid.'.domain'};
10190: 	$cnum=$env{'course.'.$cid.'.num'};
10191:     } else {
10192: 	($cdom,$cnum)=split(/_/,$cid);
10193:     }
10194:     $chome=$env{'course.'.$cid.'.home'};
10195:     if (!$chome) {
10196: 	$chome=&homeserver($cnum,$cdom);
10197:     }
10198:     if (!$chome) { return 'unknown_course'; }
10199:     # Make sure the user exists
10200:     my $uhome=&homeserver($uname,$udom);
10201:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
10202: 	return 'error: no such user';
10203:     }
10204:     # Get student data if we were not given enough information
10205:     if (!defined($first)  || $first  eq '' || 
10206:         !defined($last)   || $last   eq '' || 
10207:         !defined($uid)    || $uid    eq '' || 
10208:         !defined($middle) || $middle eq '' || 
10209:         !defined($gene)   || $gene   eq '') {
10210:         # They did not supply us with enough data to enroll the student, so
10211:         # we need to pick up more information.
10212:         my %tmp = &get('environment',
10213:                        ['firstname','middlename','lastname', 'generation','id']
10214:                        ,$udom,$uname);
10215: 
10216:         #foreach my $key (keys(%tmp)) {
10217:         #    &logthis("key $key = ".$tmp{$key});
10218:         #}
10219:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
10220:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
10221:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
10222:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
10223:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
10224:     }
10225:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
10226:     my $user = "$uname:$udom";
10227:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
10228:     my $reply=cput('classlist',
10229: 		   {$user => 
10230: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
10231: 		   $cdom,$cnum);
10232:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
10233:         &devalidate_getsection_cache($udom,$uname,$cid);
10234:     } else { 
10235: 	return 'error: '.$reply;
10236:     }
10237:     # Add student role to user
10238:     my $uurl='/'.$cid;
10239:     $uurl=~s/\_/\//g;
10240:     if ($usec) {
10241: 	$uurl.='/'.$usec;
10242:     }
10243:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
10244:                              $selfenroll,$context);
10245:     if ($result ne 'ok') {
10246:         if ($old_entry{$user} ne '') {
10247:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
10248:         } else {
10249:             $reply = &del('classlist',[$user],$cdom,$cnum);
10250:         }
10251:     }
10252:     return $result; 
10253: }
10254: 
10255: sub format_name {
10256:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
10257:     my $name;
10258:     if ($first ne 'lastname') {
10259: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
10260:     } else {
10261: 	if ($lastname=~/\S/) {
10262: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
10263: 	    $name=~s/\s+,/,/;
10264: 	} else {
10265: 	    $name.= $firstname.' '.$middlename.' '.$generation;
10266: 	}
10267:     }
10268:     $name=~s/^\s+//;
10269:     $name=~s/\s+$//;
10270:     $name=~s/\s+/ /g;
10271:     return $name;
10272: }
10273: 
10274: # ------------------------------------------------- Write to course preferences
10275: 
10276: sub writecoursepref {
10277:     my ($courseid,%prefs)=@_;
10278:     $courseid=~s/^\///;
10279:     $courseid=~s/\_/\//g;
10280:     my ($cdomain,$cnum)=split(/\//,$courseid);
10281:     my $chome=homeserver($cnum,$cdomain);
10282:     if (($chome eq '') || ($chome eq 'no_host')) { 
10283: 	return 'error: no such course';
10284:     }
10285:     my $cstring='';
10286:     foreach my $pref (keys(%prefs)) {
10287: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
10288:     }
10289:     $cstring=~s/\&$//;
10290:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
10291: }
10292: 
10293: # ---------------------------------------------------------- Make/modify course
10294: 
10295: sub createcourse {
10296:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
10297:         $course_owner,$crstype,$cnum,$context,$category)=@_;
10298:     $url=&declutter($url);
10299:     my $cid='';
10300:     if ($context eq 'requestcourses') {
10301:         my $can_create = 0;
10302:         my ($ownername,$ownerdom) = split(':',$course_owner);
10303:         if ($udom eq $ownerdom) {
10304:             if (&usertools_access($ownername,$ownerdom,$category,undef,
10305:                                   $context)) {
10306:                 $can_create = 1;
10307:             }
10308:         } else {
10309:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
10310:                                            $category);
10311:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
10312:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
10313:                 if (@curr > 0) {
10314:                     my @options = qw(approval validate autolimit);
10315:                     my $optregex = join('|',@options);
10316:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
10317:                         $can_create = 1;
10318:                     }
10319:                 }
10320:             }
10321:         }
10322:         if ($can_create) {
10323:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
10324:                 unless (&allowed('ccc',$udom)) {
10325:                     return 'refused'; 
10326:                 }
10327:             }
10328:         } else {
10329:             return 'refused';
10330:         }
10331:     } elsif (!&allowed('ccc',$udom)) {
10332:         return 'refused';
10333:     }
10334: # --------------------------------------------------------------- Get Unique ID
10335:     my $uname;
10336:     if ($cnum =~ /^$match_courseid$/) {
10337:         my $chome=&homeserver($cnum,$udom,'true');
10338:         if (($chome eq '') || ($chome eq 'no_host')) {
10339:             $uname = $cnum;
10340:         } else {
10341:             $uname = &generate_coursenum($udom,$crstype);
10342:         }
10343:     } else {
10344:         $uname = &generate_coursenum($udom,$crstype);
10345:     }
10346:     return $uname if ($uname =~ /^error/);
10347: # -------------------------------------------------- Check supplied server name
10348:     if (!defined($course_server)) {
10349:         if (defined(&domain($udom,'primary'))) {
10350:             $course_server = &domain($udom,'primary');
10351:         } else {
10352:             $course_server = $env{'user.home'}; 
10353:         }
10354:     }
10355:     my %host_servers =
10356:         &Apache::lonnet::get_servers($udom,'library');
10357:     unless ($host_servers{$course_server}) {
10358:         return 'error: invalid home server for course: '.$course_server;
10359:     }
10360: # ------------------------------------------------------------- Make the course
10361:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
10362:                       $course_server);
10363:     unless ($reply eq 'ok') { return 'error: '.$reply; }
10364:     my $uhome=&homeserver($uname,$udom,'true');
10365:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
10366: 	return 'error: no such course';
10367:     }
10368: # ----------------------------------------------------------------- Course made
10369: # log existence
10370:     my $now = time;
10371:     my $newcourse = {
10372:                     $udom.'_'.$uname => {
10373:                                      description => $description,
10374:                                      inst_code   => $inst_code,
10375:                                      owner       => $course_owner,
10376:                                      type        => $crstype,
10377:                                      creator     => $env{'user.name'}.':'.
10378:                                                     $env{'user.domain'},
10379:                                      created     => $now,
10380:                                      context     => $context,
10381:                                                 },
10382:                     };
10383:     &courseidput($udom,$newcourse,$uhome,'notime');
10384: # set toplevel url
10385:     my $topurl=$url;
10386:     unless ($nonstandard) {
10387: # ------------------------------------------ For standard courses, make top url
10388:         my $mapurl=&clutter($url);
10389:         if ($mapurl eq '/res/') { $mapurl=''; }
10390:         $env{'form.initmap'}=(<<ENDINITMAP);
10391: <map>
10392: <resource id="1" type="start"></resource>
10393: <resource id="2" src="$mapurl"></resource>
10394: <resource id="3" type="finish"></resource>
10395: <link index="1" from="1" to="2"></link>
10396: <link index="2" from="2" to="3"></link>
10397: </map>
10398: ENDINITMAP
10399:         $topurl=&declutter(
10400:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
10401:                           );
10402:     }
10403: # ----------------------------------------------------------- Write preferences
10404:     &writecoursepref($udom.'_'.$uname,
10405:                      ('description'              => $description,
10406:                       'url'                      => $topurl,
10407:                       'internal.creator'         => $env{'user.name'}.':'.
10408:                                                     $env{'user.domain'},
10409:                       'internal.created'         => $now,
10410:                       'internal.creationcontext' => $context)
10411:                     );
10412:     return '/'.$udom.'/'.$uname;
10413: }
10414: 
10415: # ------------------------------------------------------------------- Create ID
10416: sub generate_coursenum {
10417:     my ($udom,$crstype) = @_;
10418:     my $domdesc = &domain($udom);
10419:     return 'error: invalid domain' if ($domdesc eq '');
10420:     my $first;
10421:     if ($crstype eq 'Community') {
10422:         $first = '0';
10423:     } else {
10424:         $first = int(1+rand(9)); 
10425:     } 
10426:     my $uname=$first.
10427:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
10428:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
10429:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
10430: # ----------------------------------------------- Make sure that does not exist
10431:     my $uhome=&homeserver($uname,$udom,'true');
10432:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
10433:         if ($crstype eq 'Community') {
10434:             $first = '0';
10435:         } else {
10436:             $first = int(1+rand(9));
10437:         }
10438:         $uname=$first.
10439:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
10440:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
10441:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
10442:         $uhome=&homeserver($uname,$udom,'true');
10443:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
10444:             return 'error: unable to generate unique course-ID';
10445:         }
10446:     }
10447:     return $uname;
10448: }
10449: 
10450: sub is_course {
10451:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
10452:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
10453:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
10454:     my $uhome=&homeserver($cnum,$cdom);
10455:     my $iscourse;
10456:     if (grep { $_ eq $uhome } current_machine_ids()) {
10457:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
10458:     } else {
10459:         my $hashid = $cdom.':'.$cnum;
10460:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
10461:         unless (defined($cached)) {
10462:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
10463:                                         $cnum,undef,undef,'.');
10464:             $iscourse = 0;
10465:             if (exists($courses{$cdom.'_'.$cnum})) {
10466:                 $iscourse = 1;
10467:             }
10468:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
10469:         }
10470:     }
10471:     return unless($iscourse);
10472:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
10473: }
10474: 
10475: sub store_userdata {
10476:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
10477:     my $result;
10478:     if ($datakey ne '') {
10479:         if (ref($storehash) eq 'HASH') {
10480:             if ($udom eq '' || $uname eq '') {
10481:                 $udom = $env{'user.domain'};
10482:                 $uname = $env{'user.name'};
10483:             }
10484:             my $uhome=&homeserver($uname,$udom);
10485:             if (($uhome eq '') || ($uhome eq 'no_host')) {
10486:                 $result = 'error: no_host';
10487:             } else {
10488:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
10489:                 $storehash->{'host'} = $perlvar{'lonHostID'};
10490: 
10491:                 my $namevalue='';
10492:                 foreach my $key (keys(%{$storehash})) {
10493:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
10494:                 }
10495:                 $namevalue=~s/\&$//;
10496:                 unless ($namespace eq 'courserequests') {
10497:                     $datakey = &escape($datakey);
10498:                 }
10499:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
10500:                                   $namevalue,$uhome);
10501:             }
10502:         } else {
10503:             $result = 'error: data to store was not a hash reference'; 
10504:         }
10505:     } else {
10506:         $result= 'error: invalid requestkey'; 
10507:     }
10508:     return $result;
10509: }
10510: 
10511: # ---------------------------------------------------------- Assign Custom Role
10512: 
10513: sub assigncustomrole {
10514:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
10515:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
10516:                        $end,$start,$deleteflag,$selfenroll,$context);
10517: }
10518: 
10519: # ----------------------------------------------------------------- Revoke Role
10520: 
10521: sub revokerole {
10522:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
10523:     my $now=time;
10524:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
10525: }
10526: 
10527: # ---------------------------------------------------------- Revoke Custom Role
10528: 
10529: sub revokecustomrole {
10530:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
10531:     my $now=time;
10532:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
10533:            $deleteflag,$selfenroll,$context);
10534: }
10535: 
10536: # ------------------------------------------------------------ Disk usage
10537: sub diskusage {
10538:     my ($udom,$uname,$directorypath,$getpropath)=@_;
10539:     $directorypath =~ s/\/$//;
10540:     my $listing=&reply('du2:'.&escape($directorypath).':'
10541:                        .&escape($getpropath).':'.&escape($uname).':'
10542:                        .&escape($udom),homeserver($uname,$udom));
10543:     if ($listing eq 'unknown_cmd') {
10544:         if ($getpropath) {
10545:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
10546:         }
10547:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
10548:     }
10549:     return $listing;
10550: }
10551: 
10552: sub is_locked {
10553:     my ($file_name, $domain, $user, $which) = @_;
10554:     my @check;
10555:     my $is_locked;
10556:     push (@check,$file_name);
10557:     my %locked = &get('file_permissions',\@check,
10558: 		      $env{'user.domain'},$env{'user.name'});
10559:     my ($tmp)=keys(%locked);
10560:     if ($tmp=~/^error:/) { undef(%locked); }
10561:     
10562:     if (ref($locked{$file_name}) eq 'ARRAY') {
10563:         $is_locked = 'false';
10564:         foreach my $entry (@{$locked{$file_name}}) {
10565:            if (ref($entry) eq 'ARRAY') {
10566:                $is_locked = 'true';
10567:                if (ref($which) eq 'ARRAY') {
10568:                    push(@{$which},$entry);
10569:                } else {
10570:                    last;
10571:                }
10572:            }
10573:        }
10574:     } else {
10575:         $is_locked = 'false';
10576:     }
10577:     return $is_locked;
10578: }
10579: 
10580: sub declutter_portfile {
10581:     my ($file) = @_;
10582:     $file =~ s{^(/portfolio/|portfolio/)}{/};
10583:     return $file;
10584: }
10585: 
10586: # ------------------------------------------------------------- Mark as Read Only
10587: 
10588: sub mark_as_readonly {
10589:     my ($domain,$user,$files,$what) = @_;
10590:     my %current_permissions = &dump('file_permissions',$domain,$user);
10591:     my ($tmp)=keys(%current_permissions);
10592:     if ($tmp=~/^error:/) { undef(%current_permissions); }
10593:     foreach my $file (@{$files}) {
10594: 	$file = &declutter_portfile($file);
10595:         push(@{$current_permissions{$file}},$what);
10596:     }
10597:     &put('file_permissions',\%current_permissions,$domain,$user);
10598:     return;
10599: }
10600: 
10601: # ------------------------------------------------------------Save Selected Files
10602: 
10603: sub save_selected_files {
10604:     my ($user, $path, @files) = @_;
10605:     my $filename = $user."savedfiles";
10606:     my @other_files = &files_not_in_path($user, $path);
10607:     open (OUT,'>',LONCAPA::tempdir().$filename);
10608:     foreach my $file (@files) {
10609:         print (OUT $env{'form.currentpath'}.$file."\n");
10610:     }
10611:     foreach my $file (@other_files) {
10612:         print (OUT $file."\n");
10613:     }
10614:     close (OUT);
10615:     return 'ok';
10616: }
10617: 
10618: sub clear_selected_files {
10619:     my ($user) = @_;
10620:     my $filename = $user."savedfiles";
10621:     open (OUT,'>',LONCAPA::tempdir().$filename);
10622:     print (OUT undef);
10623:     close (OUT);
10624:     return ("ok");    
10625: }
10626: 
10627: sub files_in_path {
10628:     my ($user, $path) = @_;
10629:     my $filename = $user."savedfiles";
10630:     my %return_files;
10631:     open (IN,'<',LONCAPA::tempdir().$filename);
10632:     while (my $line_in = <IN>) {
10633:         chomp ($line_in);
10634:         my @paths_and_file = split (m!/!, $line_in);
10635:         my $file_part = pop (@paths_and_file);
10636:         my $path_part = join ('/', @paths_and_file);
10637:         $path_part.='/';
10638:         my $path_and_file = $path_part.$file_part;
10639:         if ($path_part eq $path) {
10640:             $return_files{$file_part}= 'selected';
10641:         }
10642:     }
10643:     close (IN);
10644:     return (\%return_files);
10645: }
10646: 
10647: # called in portfolio select mode, to show files selected NOT in current directory
10648: sub files_not_in_path {
10649:     my ($user, $path) = @_;
10650:     my $filename = $user."savedfiles";
10651:     my @return_files;
10652:     my $path_part;
10653:     open(IN, '<',LONCAPA::tempdir().$filename);
10654:     while (my $line = <IN>) {
10655:         #ok, I know it's clunky, but I want it to work
10656:         my @paths_and_file = split(m|/|, $line);
10657:         my $file_part = pop(@paths_and_file);
10658:         chomp($file_part);
10659:         my $path_part = join('/', @paths_and_file);
10660:         $path_part .= '/';
10661:         my $path_and_file = $path_part.$file_part;
10662:         if ($path_part ne $path) {
10663:             push(@return_files, ($path_and_file));
10664:         }
10665:     }
10666:     close(OUT);
10667:     return (@return_files);
10668: }
10669: 
10670: #----------------------------------------------Get portfolio file permissions
10671: 
10672: sub get_portfile_permissions {
10673:     my ($domain,$user) = @_;
10674:     my %current_permissions = &dump('file_permissions',$domain,$user);
10675:     my ($tmp)=keys(%current_permissions);
10676:     if ($tmp=~/^error:/) { undef(%current_permissions); }
10677:     return \%current_permissions;
10678: }
10679: 
10680: #---------------------------------------------Get portfolio file access controls
10681: 
10682: sub get_access_controls {
10683:     my ($current_permissions,$group,$file) = @_;
10684:     my %access;
10685:     my $real_file = $file;
10686:     $file =~ s/\.meta$//;
10687:     if (defined($file)) {
10688:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
10689:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
10690:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
10691:             }
10692:         }
10693:     } else {
10694:         foreach my $key (keys(%{$current_permissions})) {
10695:             if ($key =~ /\0accesscontrol$/) {
10696:                 if (defined($group)) {
10697:                     if ($key !~ m-^\Q$group\E/-) {
10698:                         next;
10699:                     }
10700:                 }
10701:                 my ($fullpath) = split(/\0/,$key);
10702:                 if (ref($$current_permissions{$key}) eq 'HASH') {
10703:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
10704:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
10705:                     }
10706:                 }
10707:             }
10708:         }
10709:     }
10710:     return %access;
10711: }
10712: 
10713: sub modify_access_controls {
10714:     my ($file_name,$changes,$domain,$user)=@_;
10715:     my ($outcome,$deloutcome);
10716:     my %store_permissions;
10717:     my %new_values;
10718:     my %new_control;
10719:     my %translation;
10720:     my @deletions = ();
10721:     my $now = time;
10722:     if (exists($$changes{'activate'})) {
10723:         if (ref($$changes{'activate'}) eq 'HASH') {
10724:             my @newitems = sort(keys(%{$$changes{'activate'}}));
10725:             my $numnew = scalar(@newitems);
10726:             for (my $i=0; $i<$numnew; $i++) {
10727:                 my $newkey = $newitems[$i];
10728:                 my $newid = &Apache::loncommon::get_cgi_id();
10729:                 if ($newkey =~ /^\d+:/) { 
10730:                     $newkey =~ s/^(\d+)/$newid/;
10731:                     $translation{$1} = $newid;
10732:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
10733:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
10734:                     $translation{$1} = $newid;
10735:                 }
10736:                 $new_values{$file_name."\0".$newkey} = 
10737:                                           $$changes{'activate'}{$newitems[$i]};
10738:                 $new_control{$newkey} = $now;
10739:             }
10740:         }
10741:     }
10742:     my %todelete;
10743:     my %changed_items;
10744:     foreach my $action ('delete','update') {
10745:         if (exists($$changes{$action})) {
10746:             if (ref($$changes{$action}) eq 'HASH') {
10747:                 foreach my $key (keys(%{$$changes{$action}})) {
10748:                     my ($itemnum) = ($key =~ /^([^:]+):/);
10749:                     if ($action eq 'delete') { 
10750:                         $todelete{$itemnum} = 1;
10751:                     } else {
10752:                         $changed_items{$itemnum} = $key;
10753:                     }
10754:                 }
10755:             }
10756:         }
10757:     }
10758:     # get lock on access controls for file.
10759:     my $lockhash = {
10760:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
10761:                                                        ':'.$env{'user.domain'},
10762:                    }; 
10763:     my $tries = 0;
10764:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
10765:    
10766:     while (($gotlock ne 'ok') && $tries < 10) {
10767:         $tries ++;
10768:         sleep(0.1);
10769:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
10770:     }
10771:     if ($gotlock eq 'ok') {
10772:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
10773:         my ($tmp)=keys(%curr_permissions);
10774:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
10775:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
10776:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
10777:             if (ref($curr_controls) eq 'HASH') {
10778:                 foreach my $control_item (keys(%{$curr_controls})) {
10779:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
10780:                     if (defined($todelete{$itemnum})) {
10781:                         push(@deletions,$file_name."\0".$control_item);
10782:                     } else {
10783:                         if (defined($changed_items{$itemnum})) {
10784:                             $new_control{$changed_items{$itemnum}} = $now;
10785:                             push(@deletions,$file_name."\0".$control_item);
10786:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
10787:                         } else {
10788:                             $new_control{$control_item} = $$curr_controls{$control_item};
10789:                         }
10790:                     }
10791:                 }
10792:             }
10793:         }
10794:         my ($group);
10795:         if (&is_course($domain,$user)) {
10796:             ($group,my $file) = split(/\//,$file_name,2);
10797:         }
10798:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
10799:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
10800:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
10801:         #  remove lock
10802:         my @del_lock = ($file_name."\0".'locked_access_records');
10803:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
10804:         my $sqlresult =
10805:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
10806:                                     $group);
10807:     } else {
10808:         $outcome = "error: could not obtain lockfile\n";  
10809:     }
10810:     return ($outcome,$deloutcome,\%new_values,\%translation);
10811: }
10812: 
10813: sub make_public_indefinitely {
10814:     my ($requrl) = @_;
10815:     my $now = time;
10816:     my $action = 'activate';
10817:     my $aclnum = 0;
10818:     if (&is_portfolio_url($requrl)) {
10819:         my (undef,$udom,$unum,$file_name,$group) =
10820:             &parse_portfolio_url($requrl);
10821:         my $current_perms = &get_portfile_permissions($udom,$unum);
10822:         my %access_controls = &get_access_controls($current_perms,
10823:                                                    $group,$file_name);
10824:         foreach my $key (keys(%{$access_controls{$file_name}})) {
10825:             my ($num,$scope,$end,$start) = 
10826:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
10827:             if ($scope eq 'public') {
10828:                 if ($start <= $now && $end == 0) {
10829:                     $action = 'none';
10830:                 } else {
10831:                     $action = 'update';
10832:                     $aclnum = $num;
10833:                 }
10834:                 last;
10835:             }
10836:         }
10837:         if ($action eq 'none') {
10838:              return 'ok';
10839:         } else {
10840:             my %changes;
10841:             my $newend = 0;
10842:             my $newstart = $now;
10843:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
10844:             $changes{$action}{$newkey} = {
10845:                 type => 'public',
10846:                 time => {
10847:                     start => $newstart,
10848:                     end   => $newend,
10849:                 },
10850:             };
10851:             my ($outcome,$deloutcome,$new_values,$translation) =
10852:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
10853:             return $outcome;
10854:         }
10855:     } else {
10856:         return 'invalid';
10857:     }
10858: }
10859: 
10860: #------------------------------------------------------Get Marked as Read Only
10861: 
10862: sub get_marked_as_readonly {
10863:     my ($domain,$user,$what,$group) = @_;
10864:     my $current_permissions = &get_portfile_permissions($domain,$user);
10865:     my @readonly_files;
10866:     my $cmp1=$what;
10867:     if (ref($what)) { $cmp1=join('',@{$what}) };
10868:     while (my ($file_name,$value) = each(%{$current_permissions})) {
10869:         if (defined($group)) {
10870:             if ($file_name !~ m-^\Q$group\E/-) {
10871:                 next;
10872:             }
10873:         }
10874:         if (ref($value) eq "ARRAY"){
10875:             foreach my $stored_what (@{$value}) {
10876:                 my $cmp2=$stored_what;
10877:                 if (ref($stored_what) eq 'ARRAY') {
10878:                     $cmp2=join('',@{$stored_what});
10879:                 }
10880:                 if ($cmp1 eq $cmp2) {
10881:                     push(@readonly_files, $file_name);
10882:                     last;
10883:                 } elsif (!defined($what)) {
10884:                     push(@readonly_files, $file_name);
10885:                     last;
10886:                 }
10887:             }
10888:         }
10889:     }
10890:     return @readonly_files;
10891: }
10892: #-----------------------------------------------------------Get Marked as Read Only Hash
10893: 
10894: sub get_marked_as_readonly_hash {
10895:     my ($current_permissions,$group,$what) = @_;
10896:     my %readonly_files;
10897:     while (my ($file_name,$value) = each(%{$current_permissions})) {
10898:         if (defined($group)) {
10899:             if ($file_name !~ m-^\Q$group\E/-) {
10900:                 next;
10901:             }
10902:         }
10903:         if (ref($value) eq "ARRAY"){
10904:             foreach my $stored_what (@{$value}) {
10905:                 if (ref($stored_what) eq 'ARRAY') {
10906:                     foreach my $lock_descriptor(@{$stored_what}) {
10907:                         if ($lock_descriptor eq 'graded') {
10908:                             $readonly_files{$file_name} = 'graded';
10909:                         } elsif ($lock_descriptor eq 'handback') {
10910:                             $readonly_files{$file_name} = 'handback';
10911:                         } else {
10912:                             if (!exists($readonly_files{$file_name})) {
10913:                                 $readonly_files{$file_name} = 'locked';
10914:                             }
10915:                         }
10916:                     }
10917:                 } 
10918:             }
10919:         } 
10920:     }
10921:     return %readonly_files;
10922: }
10923: # ------------------------------------------------------------ Unmark as Read Only
10924: 
10925: sub unmark_as_readonly {
10926:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
10927:     # for portfolio submissions, $what contains [$symb,$crsid] 
10928:     my ($domain,$user,$what,$file_name,$group) = @_;
10929:     $file_name = &declutter_portfile($file_name);
10930:     my $symb_crs = $what;
10931:     if (ref($what)) { $symb_crs=join('',@$what); }
10932:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
10933:     my ($tmp)=keys(%current_permissions);
10934:     if ($tmp=~/^error:/) { undef(%current_permissions); }
10935:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
10936:     foreach my $file (@readonly_files) {
10937: 	my $clean_file = &declutter_portfile($file);
10938: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
10939: 	my $current_locks = $current_permissions{$file};
10940:         my @new_locks;
10941:         my @del_keys;
10942:         if (ref($current_locks) eq "ARRAY"){
10943:             foreach my $locker (@{$current_locks}) {
10944:                 my $compare=$locker;
10945:                 if (ref($locker) eq 'ARRAY') {
10946:                     $compare=join('',@{$locker});
10947:                     if ($compare ne $symb_crs) {
10948:                         push(@new_locks, $locker);
10949:                     }
10950:                 }
10951:             }
10952:             if (scalar(@new_locks) > 0) {
10953:                 $current_permissions{$file} = \@new_locks;
10954:             } else {
10955:                 push(@del_keys, $file);
10956:                 &del('file_permissions',\@del_keys, $domain, $user);
10957:                 delete($current_permissions{$file});
10958:             }
10959:         }
10960:     }
10961:     &put('file_permissions',\%current_permissions,$domain,$user);
10962:     return;
10963: }
10964: 
10965: # ------------------------------------------------------------ Directory lister
10966: 
10967: sub dirlist {
10968:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
10969:     $uri=~s/^\///;
10970:     $uri=~s/\/$//;
10971:     my ($udom, $uname);
10972:     if ($getuserdir) {
10973:         $udom = $userdomain;
10974:         $uname = $username;
10975:     } else {
10976:         (undef,$udom,$uname)=split(/\//,$uri);
10977:         if(defined($userdomain)) {
10978:             $udom = $userdomain;
10979:         }
10980:         if(defined($username)) {
10981:             $uname = $username;
10982:         }
10983:     }
10984:     my ($dirRoot,$listing,@listing_results);
10985: 
10986:     $dirRoot = $perlvar{'lonDocRoot'};
10987:     if (defined($getpropath)) {
10988:         $dirRoot = &propath($udom,$uname);
10989:         $dirRoot =~ s/\/$//;
10990:     } elsif (defined($getuserdir)) {
10991:         my $subdir=$uname.'__';
10992:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
10993:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
10994:                    ."/$udom/$subdir/$uname";
10995:     } elsif (defined($alternateRoot)) {
10996:         $dirRoot = $alternateRoot;
10997:     }
10998: 
10999:     if($udom) {
11000:         if($uname) {
11001:             my $uhome = &homeserver($uname,$udom);
11002:             if ($uhome eq 'no_host') {
11003:                 return ([],'no_host');
11004:             }
11005:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
11006:                               .$getuserdir.':'.&escape($dirRoot)
11007:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
11008:             if ($listing eq 'unknown_cmd') {
11009:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
11010:             } else {
11011:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
11012:             }
11013:             if ($listing eq 'unknown_cmd') {
11014:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
11015:                 @listing_results = split(/:/,$listing);
11016:             } else {
11017:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
11018:             }
11019:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
11020:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
11021:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11022:                 return ([],$listing);
11023:             } else {
11024:                 return (\@listing_results);
11025:             }
11026:         } elsif(!$alternateRoot) {
11027:             my (%allusers,%listerror);
11028: 	    my %servers = &get_servers($udom,'library');
11029:  	    foreach my $tryserver (keys(%servers)) {
11030:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
11031:                                   &escape($udom),$tryserver);
11032:                 if ($listing eq 'unknown_cmd') {
11033: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
11034: 				      $udom, $tryserver);
11035:                 } else {
11036:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
11037:                 }
11038: 		if ($listing eq 'unknown_cmd') {
11039: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
11040: 				      $udom, $tryserver);
11041: 		    @listing_results = split(/:/,$listing);
11042: 		} else {
11043: 		    @listing_results =
11044: 			map { &unescape($_); } split(/:/,$listing);
11045: 		}
11046:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
11047:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
11048:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11049:                     $listerror{$tryserver} = $listing;
11050:                 } else {
11051: 		    foreach my $line (@listing_results) {
11052: 			my ($entry) = split(/&/,$line,2);
11053: 			$allusers{$entry} = 1;
11054: 		    }
11055: 		}
11056:             }
11057:             my @alluserslist=();
11058:             foreach my $user (sort(keys(%allusers))) {
11059:                 push(@alluserslist,$user.'&user');
11060:             }
11061:             if (!%listerror) {
11062:                 # no errors
11063:                 return (\@alluserslist);
11064:             } elsif (scalar(keys(%servers)) == 1) {
11065:                 # one library server, one error
11066:                 my ($key) = keys(%listerror);
11067:                 return (\@alluserslist, $listerror{$key});
11068:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
11069:                 # con_lost indicates that we might miss data from at least one
11070:                 # library server
11071:                 return (\@alluserslist, 'con_lost');
11072:             } else {
11073:                 # multiple library servers and no con_lost -> data should be
11074:                 # complete.
11075:                 return (\@alluserslist);
11076:             }
11077: 
11078:         } else {
11079:             return ([],'missing username');
11080:         }
11081:     } elsif(!defined($getpropath)) {
11082:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
11083:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
11084:         return (\@all_domains);
11085:     } else {
11086:         return ([],'missing domain');
11087:     }
11088: }
11089: 
11090: # --------------------------------------------- GetFileTimestamp
11091: # This function utilizes dirlist and returns the date stamp for
11092: # when it was last modified.  It will also return an error of -1
11093: # if an error occurs
11094: 
11095: sub GetFileTimestamp {
11096:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
11097:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
11098:     $studentName   = &LONCAPA::clean_username($studentName);
11099:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
11100:                                     undef,$getuserdir);
11101:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11102:         return -1;
11103:     }
11104:     if (ref($fileref) eq 'ARRAY') {
11105:         my @stats = split('&',$fileref->[0]);
11106:         # @stats contains first the filename, then the stat output
11107:         return $stats[10]; # so this is 10 instead of 9.
11108:     } else {
11109:         return -1;
11110:     }
11111: }
11112: 
11113: sub stat_file {
11114:     my ($uri) = @_;
11115:     $uri = &clutter_with_no_wrapper($uri);
11116: 
11117:     my ($udom,$uname,$file);
11118:     if ($uri =~ m-^/(uploaded|editupload)/-) {
11119: 	($udom,$uname,$file) =
11120: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
11121: 	$file = 'userfiles/'.$file;
11122:     }
11123:     if ($uri =~ m-^/res/-) {
11124: 	($udom,$uname) = 
11125: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
11126: 	$file = $uri;
11127:     }
11128: 
11129:     if (!$udom || !$uname || !$file) {
11130: 	# unable to handle the uri
11131: 	return ();
11132:     }
11133:     my $getpropath;
11134:     if ($file =~ /^userfiles\//) {
11135:         $getpropath = 1;
11136:     }
11137:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
11138:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11139:         return ();
11140:     } else {
11141:         if (ref($listref) eq 'ARRAY') {
11142:             my @stats = split('&',$listref->[0]);
11143: 	    shift(@stats); #filename is first
11144: 	    return @stats;
11145:         }
11146:     }
11147:     return ();
11148: }
11149: 
11150: # -------------------------------------------------------- Value of a Condition
11151: 
11152: # gets the value of a specific preevaluated condition
11153: #    stored in the string  $env{user.state.<cid>}
11154: # or looks up a condition reference in the bighash and if if hasn't
11155: # already been evaluated recurses into docondval to get the value of
11156: # the condition, then memoizing it to 
11157: #   $env{user.state.<cid>.<condition>}
11158: sub directcondval {
11159:     my $number=shift;
11160:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
11161: 	&Apache::lonuserstate::evalstate();
11162:     }
11163:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
11164: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
11165:     } elsif ($number =~ /^_/) {
11166: 	my $sub_condition;
11167: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
11168: 		&GDBM_READER(),0640)) {
11169: 	    $sub_condition=$bighash{'conditions'.$number};
11170: 	    untie(%bighash);
11171: 	}
11172: 	my $value = &docondval($sub_condition);
11173: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
11174: 	return $value;
11175:     }
11176:     if ($env{'user.state.'.$env{'request.course.id'}}) {
11177:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
11178:     } else {
11179:        return 2;
11180:     }
11181: }
11182: 
11183: # get the collection of conditions for this resource
11184: sub condval {
11185:     my $condidx=shift;
11186:     my $allpathcond='';
11187:     foreach my $cond (split(/\|/,$condidx)) {
11188: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
11189: 	    $allpathcond.=
11190: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
11191: 	}
11192:     }
11193:     $allpathcond=~s/\|$//;
11194:     return &docondval($allpathcond);
11195: }
11196: 
11197: #evaluates an expression of conditions
11198: sub docondval {
11199:     my ($allpathcond) = @_;
11200:     my $result=0;
11201:     if ($env{'request.course.id'}
11202: 	&& defined($allpathcond)) {
11203: 	my $operand='|';
11204: 	my @stack;
11205: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
11206: 	    if ($chunk eq '(') {
11207: 		push @stack,($operand,$result);
11208: 	    } elsif ($chunk eq ')') {
11209: 		my $before=pop @stack;
11210: 		if (pop @stack eq '&') {
11211: 		    $result=$result>$before?$before:$result;
11212: 		} else {
11213: 		    $result=$result>$before?$result:$before;
11214: 		}
11215: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
11216: 		$operand=$chunk;
11217: 	    } else {
11218: 		my $new=directcondval($chunk);
11219: 		if ($operand eq '&') {
11220: 		    $result=$result>$new?$new:$result;
11221: 		} else {
11222: 		    $result=$result>$new?$result:$new;
11223: 		}
11224: 	    }
11225: 	}
11226:     }
11227:     return $result;
11228: }
11229: 
11230: # ---------------------------------------------------- Devalidate courseresdata
11231: 
11232: sub devalidatecourseresdata {
11233:     my ($coursenum,$coursedomain)=@_;
11234:     my $hashid=$coursenum.':'.$coursedomain;
11235:     &devalidate_cache_new('courseres',$hashid);
11236: }
11237: 
11238: 
11239: # --------------------------------------------------- Course Resourcedata Query
11240: #
11241: #  Parameters:
11242: #      $coursenum    - Number of the course.
11243: #      $coursedomain - Domain at which the course was created.
11244: #  Returns:
11245: #     A hash of the course parameters along (I think) with timestamps
11246: #     and version info.
11247: 
11248: sub get_courseresdata {
11249:     my ($coursenum,$coursedomain)=@_;
11250:     my $coursehom=&homeserver($coursenum,$coursedomain);
11251:     my $hashid=$coursenum.':'.$coursedomain;
11252:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
11253:     my %dumpreply;
11254:     unless (defined($cached)) {
11255: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
11256: 	$result=\%dumpreply;
11257: 	my ($tmp) = keys(%dumpreply);
11258: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
11259: 	    &do_cache_new('courseres',$hashid,$result,600);
11260: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
11261: 	    return $tmp;
11262: 	} elsif ($tmp =~ /^(error)/) {
11263: 	    $result=undef;
11264: 	    &do_cache_new('courseres',$hashid,$result,600);
11265: 	}
11266:     }
11267:     return $result;
11268: }
11269: 
11270: sub devalidateuserresdata {
11271:     my ($uname,$udom)=@_;
11272:     my $hashid="$udom:$uname";
11273:     &devalidate_cache_new('userres',$hashid);
11274: }
11275: 
11276: sub get_userresdata {
11277:     my ($uname,$udom)=@_;
11278:     #most student don\'t have any data set, check if there is some data
11279:     if (&EXT_cache_status($udom,$uname)) { return undef; }
11280: 
11281:     my $hashid="$udom:$uname";
11282:     my ($result,$cached)=&is_cached_new('userres',$hashid);
11283:     if (!defined($cached)) {
11284: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
11285: 	$result=\%resourcedata;
11286: 	&do_cache_new('userres',$hashid,$result,600);
11287:     }
11288:     my ($tmp)=keys(%$result);
11289:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
11290: 	return $result;
11291:     }
11292:     #error 2 occurs when the .db doesn't exist
11293:     if ($tmp!~/error: 2 /) {
11294:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
11295: 	    &logthis("<font color=\"blue\">WARNING:".
11296: 		     " Trying to get resource data for ".
11297: 		     $uname." at ".$udom.": ".
11298: 		     $tmp."</font>");
11299:         }
11300:     } elsif ($tmp=~/error: 2 /) {
11301: 	#&EXT_cache_set($udom,$uname);
11302: 	&do_cache_new('userres',$hashid,undef,600);
11303: 	undef($tmp); # not really an error so don't send it back
11304:     }
11305:     return $tmp;
11306: }
11307: #----------------------------------------------- resdata - return resource data
11308: #  Purpose:
11309: #    Return resource data for either users or for a course.
11310: #  Parameters:
11311: #     $name      - Course/user name.
11312: #     $domain    - Name of the domain the user/course is registered on.
11313: #     $type      - Type of thing $name is (must be 'course' or 'user'
11314: #     @which     - Array of names of resources desired.
11315: #  Returns:
11316: #     The value of the first reasource in @which that is found in the
11317: #     resource hash.
11318: #  Exceptional Conditions:
11319: #     If the $type passed in is not valid (not the string 'course' or 
11320: #     'user', an undefined  reference is returned.
11321: #     If none of the resources are found, an undef is returned
11322: sub resdata {
11323:     my ($name,$domain,$type,@which)=@_;
11324:     my $result;
11325:     if ($type eq 'course') {
11326: 	$result=&get_courseresdata($name,$domain);
11327:     } elsif ($type eq 'user') {
11328: 	$result=&get_userresdata($name,$domain);
11329:     }
11330:     if (!ref($result)) { return $result; }    
11331:     foreach my $item (@which) {
11332: 	if (defined($result->{$item->[0]})) {
11333: 	    return [$result->{$item->[0]},$item->[1]];
11334: 	}
11335:     }
11336:     return undef;
11337: }
11338: 
11339: sub get_numsuppfiles {
11340:     my ($cnum,$cdom,$ignorecache)=@_;
11341:     my $hashid=$cnum.':'.$cdom;
11342:     my ($suppcount,$cached);
11343:     unless ($ignorecache) {
11344:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
11345:     }
11346:     unless (defined($cached)) {
11347:         my $chome=&homeserver($cnum,$cdom);
11348:         unless ($chome eq 'no_host') {
11349:             ($suppcount,my $errors) = (0,0);
11350:             my $suppmap = 'supplemental.sequence';
11351:             ($suppcount,$errors) =
11352:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
11353:         }
11354:         &do_cache_new('suppcount',$hashid,$suppcount,600);
11355:     }
11356:     return $suppcount;
11357: }
11358: 
11359: #
11360: # EXT resource caching routines
11361: #
11362: 
11363: sub clear_EXT_cache_status {
11364:     &delenv('cache.EXT.');
11365: }
11366: 
11367: sub EXT_cache_status {
11368:     my ($target_domain,$target_user) = @_;
11369:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
11370:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
11371:         # We know already the user has no data
11372:         return 1;
11373:     } else {
11374:         return 0;
11375:     }
11376: }
11377: 
11378: sub EXT_cache_set {
11379:     my ($target_domain,$target_user) = @_;
11380:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
11381:     #&appenv({$cachename => time});
11382: }
11383: 
11384: # --------------------------------------------------------- Value of a Variable
11385: sub EXT {
11386: 
11387:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
11388:     unless ($varname) { return ''; }
11389:     #get real user name/domain, courseid and symb
11390:     my $courseid;
11391:     my $publicuser;
11392:     if ($symbparm) {
11393: 	$symbparm=&get_symb_from_alias($symbparm);
11394:     }
11395:     if (!($uname && $udom)) {
11396:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
11397:       if (!$symbparm) {	$symbparm=$cursymb; }
11398:     } else {
11399: 	$courseid=$env{'request.course.id'};
11400:     }
11401:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
11402:     my $rest;
11403:     if (defined($therest[0])) {
11404:        $rest=join('.',@therest);
11405:     } else {
11406:        $rest='';
11407:     }
11408: 
11409:     my $qualifierrest=$qualifier;
11410:     if ($rest) { $qualifierrest.='.'.$rest; }
11411:     my $spacequalifierrest=$space;
11412:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
11413:     if ($realm eq 'user') {
11414: # --------------------------------------------------------------- user.resource
11415: 	if ($space eq 'resource') {
11416: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
11417: 		  || defined($Apache::lonhomework::parsing_a_task))
11418: 		 &&
11419: 		 ($symbparm eq &symbread()) ) {	
11420: 		# if we are in the middle of processing the resource the
11421: 		# get the value we are planning on committing
11422:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
11423:                     return $Apache::lonhomework::results{$qualifierrest};
11424:                 } else {
11425:                     return $Apache::lonhomework::history{$qualifierrest};
11426:                 }
11427: 	    } else {
11428: 		my %restored;
11429: 		if ($publicuser || $env{'request.state'} eq 'construct') {
11430: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
11431: 		} else {
11432: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
11433: 		}
11434: 		return $restored{$qualifierrest};
11435: 	    }
11436: # ----------------------------------------------------------------- user.access
11437:         } elsif ($space eq 'access') {
11438: 	    # FIXME - not supporting calls for a specific user
11439:             return &allowed($qualifier,$rest);
11440: # ------------------------------------------ user.preferences, user.environment
11441:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
11442: 	    if (($uname eq $env{'user.name'}) &&
11443: 		($udom eq $env{'user.domain'})) {
11444: 		return $env{join('.',('environment',$qualifierrest))};
11445: 	    } else {
11446: 		my %returnhash;
11447: 		if (!$publicuser) {
11448: 		    %returnhash=&userenvironment($udom,$uname,
11449: 						 $qualifierrest);
11450: 		}
11451: 		return $returnhash{$qualifierrest};
11452: 	    }
11453: # ----------------------------------------------------------------- user.course
11454:         } elsif ($space eq 'course') {
11455: 	    # FIXME - not supporting calls for a specific user
11456:             return $env{join('.',('request.course',$qualifier))};
11457: # ------------------------------------------------------------------- user.role
11458:         } elsif ($space eq 'role') {
11459: 	    # FIXME - not supporting calls for a specific user
11460:             my ($role,$where)=split(/\./,$env{'request.role'});
11461:             if ($qualifier eq 'value') {
11462: 		return $role;
11463:             } elsif ($qualifier eq 'extent') {
11464:                 return $where;
11465:             }
11466: # ----------------------------------------------------------------- user.domain
11467:         } elsif ($space eq 'domain') {
11468:             return $udom;
11469: # ------------------------------------------------------------------- user.name
11470:         } elsif ($space eq 'name') {
11471:             return $uname;
11472: # ---------------------------------------------------- Any other user namespace
11473:         } else {
11474: 	    my %reply;
11475: 	    if (!$publicuser) {
11476: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
11477: 	    }
11478: 	    return $reply{$qualifierrest};
11479:         }
11480:     } elsif ($realm eq 'query') {
11481: # ---------------------------------------------- pull stuff out of query string
11482:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
11483: 						[$spacequalifierrest]);
11484: 	return $env{'form.'.$spacequalifierrest}; 
11485:    } elsif ($realm eq 'request') {
11486: # ------------------------------------------------------------- request.browser
11487:         if ($space eq 'browser') {
11488:             return $env{'browser.'.$qualifier};
11489: # ------------------------------------------------------------ request.filename
11490:         } else {
11491:             return $env{'request.'.$spacequalifierrest};
11492:         }
11493:     } elsif ($realm eq 'course') {
11494: # ---------------------------------------------------------- course.description
11495:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
11496:     } elsif ($realm eq 'resource') {
11497: 
11498: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
11499: 	    if (!$symbparm) { $symbparm=&symbread(); }
11500: 	}
11501: 
11502:         if ($qualifier eq '') {
11503: 	    if ($space eq 'title') {
11504: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
11505: 	        return &gettitle($symbparm);
11506: 	    }
11507: 	
11508: 	    if ($space eq 'map') {
11509: 	        my ($map) = &decode_symb($symbparm);
11510: 	        return &symbread($map);
11511: 	    }
11512:             if ($space eq 'maptitle') {
11513:                 my ($map) = &decode_symb($symbparm);
11514:                 return &gettitle($map);
11515:             }
11516: 	    if ($space eq 'filename') {
11517: 	        if ($symbparm) {
11518: 		    return &clutter((&decode_symb($symbparm))[2]);
11519: 	        }
11520: 	        return &hreflocation('',$env{'request.filename'});
11521: 	    }
11522: 
11523:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
11524:                 if ($space eq 'visibleparts') {
11525:                     my $navmap = Apache::lonnavmaps::navmap->new();
11526:                     my $item;
11527:                     if (ref($navmap)) {
11528:                         my $res = $navmap->getBySymb($symbparm);
11529:                         my $parts = $res->parts();
11530:                         if (ref($parts) eq 'ARRAY') {
11531:                             $item = join(',',@{$parts});
11532:                         }
11533:                         undef($navmap);
11534:                     }
11535:                     return $item;
11536:                 }
11537:             }
11538:         }
11539: 
11540: 	my ($section, $group, @groups);
11541: 	my ($courselevelm,$courselevel);
11542:         if (($courseid eq '') && ($cid)) {
11543:             $courseid = $cid;
11544:         }
11545: 	if (($symbparm && $courseid) && 
11546: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
11547: 
11548: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
11549: 
11550: # ----------------------------------------------------- Cascading lookup scheme
11551: 	    my $symbp=$symbparm;
11552: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
11553: 
11554: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
11555: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
11556: 
11557: 	    if (($env{'user.name'} eq $uname) &&
11558: 		($env{'user.domain'} eq $udom)) {
11559: 		$section=$env{'request.course.sec'};
11560:                 @groups = split(/:/,$env{'request.course.groups'});  
11561:                 @groups=&sort_course_groups($courseid,@groups); 
11562: 	    } else {
11563: 		if (! defined($usection)) {
11564: 		    $section=&getsection($udom,$uname,$courseid);
11565: 		} else {
11566: 		    $section = $usection;
11567: 		}
11568:                 @groups = &get_users_groups($udom,$uname,$courseid);
11569: 	    }
11570: 
11571: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
11572: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
11573: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
11574: 
11575: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
11576: 	    my $courselevelr=$courseid.'.'.$symbparm;
11577: 	    $courselevelm=$courseid.'.'.$mapparm;
11578: 
11579: # ----------------------------------------------------------- first, check user
11580: 
11581: 	    my $userreply=&resdata($uname,$udom,'user',
11582: 				       ([$courselevelr,'resource'],
11583: 					[$courselevelm,'map'     ],
11584: 					[$courselevel, 'course'  ]));
11585: 	    if (defined($userreply)) { return &get_reply($userreply); }
11586: 
11587: # ------------------------------------------------ second, check some of course
11588:             my $coursereply;
11589:             if (@groups > 0) {
11590:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
11591:                                        $mapparm,$spacequalifierrest);
11592:                 if (defined($coursereply)) { return &get_reply($coursereply); }
11593:             }
11594: 
11595: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
11596: 				  $env{'course.'.$courseid.'.domain'},
11597: 				  'course',
11598: 				  ([$seclevelr,   'resource'],
11599: 				   [$seclevelm,   'map'     ],
11600: 				   [$seclevel,    'course'  ],
11601: 				   [$courselevelr,'resource']));
11602: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
11603: 
11604: # ------------------------------------------------------ third, check map parms
11605: 	    my %parmhash=();
11606: 	    my $thisparm='';
11607: 	    if (tie(%parmhash,'GDBM_File',
11608: 		    $env{'request.course.fn'}.'_parms.db',
11609: 		    &GDBM_READER(),0640)) {
11610: 		$thisparm=$parmhash{$symbparm};
11611: 		untie(%parmhash);
11612: 	    }
11613: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
11614: 	}
11615: # ------------------------------------------ fourth, look in resource metadata
11616: 
11617: 	$spacequalifierrest=~s/\./\_/;
11618: 	my $filename;
11619: 	if (!$symbparm) { $symbparm=&symbread(); }
11620: 	if ($symbparm) {
11621: 	    $filename=(&decode_symb($symbparm))[2];
11622: 	} else {
11623: 	    $filename=$env{'request.filename'};
11624: 	}
11625: 	my $metadata=&metadata($filename,$spacequalifierrest);
11626: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
11627: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
11628: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
11629: 
11630: # ---------------------------------------------- fourth, look in rest of course
11631: 	if ($symbparm && defined($courseid) && 
11632: 	    $courseid eq $env{'request.course.id'}) {
11633: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
11634: 				     $env{'course.'.$courseid.'.domain'},
11635: 				     'course',
11636: 				     ([$courselevelm,'map'   ],
11637: 				      [$courselevel, 'course']));
11638: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
11639: 	}
11640: # ------------------------------------------------------------------ Cascade up
11641: 	unless ($space eq '0') {
11642: 	    my @parts=split(/_/,$space);
11643: 	    my $id=pop(@parts);
11644: 	    my $part=join('_',@parts);
11645: 	    if ($part eq '') { $part='0'; }
11646: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
11647: 				 $symbparm,$udom,$uname,$section,1);
11648: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
11649: 	}
11650: 	if ($recurse) { return undef; }
11651: 	my $pack_def=&packages_tab_default($filename,$varname);
11652: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
11653: # ---------------------------------------------------- Any other user namespace
11654:     } elsif ($realm eq 'environment') {
11655: # ----------------------------------------------------------------- environment
11656: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
11657: 	    return $env{'environment.'.$spacequalifierrest};
11658: 	} else {
11659: 	    if ($uname eq 'anonymous' && $udom eq '') {
11660: 		return '';
11661: 	    }
11662: 	    my %returnhash=&userenvironment($udom,$uname,
11663: 					    $spacequalifierrest);
11664: 	    return $returnhash{$spacequalifierrest};
11665: 	}
11666:     } elsif ($realm eq 'system') {
11667: # ----------------------------------------------------------------- system.time
11668: 	if ($space eq 'time') {
11669: 	    return time;
11670:         }
11671:     } elsif ($realm eq 'server') {
11672: # ----------------------------------------------------------------- system.time
11673: 	if ($space eq 'name') {
11674: 	    return $ENV{'SERVER_NAME'};
11675:         }
11676:     }
11677:     return '';
11678: }
11679: 
11680: sub get_reply {
11681:     my ($reply_value) = @_;
11682:     if (ref($reply_value) eq 'ARRAY') {
11683:         if (wantarray) {
11684: 	    return @$reply_value;
11685:         }
11686:         return $reply_value->[0];
11687:     } else {
11688:         return $reply_value;
11689:     }
11690: }
11691: 
11692: sub check_group_parms {
11693:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
11694:     my @groupitems = ();
11695:     my $resultitem;
11696:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
11697:     foreach my $group (@{$groups}) {
11698:         foreach my $level (@levels) {
11699:              my $item = $courseid.'.['.$group.'].'.$level->[0];
11700:              push(@groupitems,[$item,$level->[1]]);
11701:         }
11702:     }
11703:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
11704:                             $env{'course.'.$courseid.'.domain'},
11705:                                      'course',@groupitems);
11706:     return $coursereply;
11707: }
11708: 
11709: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
11710:     my ($courseid,@groups) = @_;
11711:     @groups = sort(@groups);
11712:     return @groups;
11713: }
11714: 
11715: sub packages_tab_default {
11716:     my ($uri,$varname)=@_;
11717:     my (undef,$part,$name)=split(/\./,$varname);
11718: 
11719:     my (@extension,@specifics,$do_default);
11720:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
11721: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
11722: 	if ($pack_type eq 'default') {
11723: 	    $do_default=1;
11724: 	} elsif ($pack_type eq 'extension') {
11725: 	    push(@extension,[$package,$pack_type,$pack_part]);
11726: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
11727: 	    # only look at packages defaults for packages that this id is
11728: 	    push(@specifics,[$package,$pack_type,$pack_part]);
11729: 	}
11730:     }
11731:     # first look for a package that matches the requested part id
11732:     foreach my $package (@specifics) {
11733: 	my (undef,$pack_type,$pack_part)=@{$package};
11734: 	next if ($pack_part ne $part);
11735: 	if (defined($packagetab{"$pack_type&$name&default"})) {
11736: 	    return $packagetab{"$pack_type&$name&default"};
11737: 	}
11738:     }
11739:     # look for any possible matching non extension_ package
11740:     foreach my $package (@specifics) {
11741: 	my (undef,$pack_type,$pack_part)=@{$package};
11742: 	if (defined($packagetab{"$pack_type&$name&default"})) {
11743: 	    return $packagetab{"$pack_type&$name&default"};
11744: 	}
11745: 	if ($pack_type eq 'part') { $pack_part='0'; }
11746: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
11747: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
11748: 	}
11749:     }
11750:     # look for any posible extension_ match
11751:     foreach my $package (@extension) {
11752: 	my ($package,$pack_type)=@{$package};
11753: 	if (defined($packagetab{"$pack_type&$name&default"})) {
11754: 	    return $packagetab{"$pack_type&$name&default"};
11755: 	}
11756: 	if (defined($packagetab{$package."&$name&default"})) {
11757: 	    return $packagetab{$package."&$name&default"};
11758: 	}
11759:     }
11760:     # look for a global default setting
11761:     if ($do_default && defined($packagetab{"default&$name&default"})) {
11762: 	return $packagetab{"default&$name&default"};
11763:     }
11764:     return undef;
11765: }
11766: 
11767: sub add_prefix_and_part {
11768:     my ($prefix,$part)=@_;
11769:     my $keyroot;
11770:     if (defined($prefix) && $prefix !~ /^__/) {
11771: 	# prefix that has a part already
11772: 	$keyroot=$prefix;
11773:     } elsif (defined($prefix)) {
11774: 	# prefix that is missing a part
11775: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
11776:     } else {
11777: 	# no prefix at all
11778: 	if (defined($part)) { $keyroot='_'.$part; }
11779:     }
11780:     return $keyroot;
11781: }
11782: 
11783: # ---------------------------------------------------------------- Get metadata
11784: 
11785: my %metaentry;
11786: my %importedpartids;
11787: my %importedrespids;
11788: sub metadata {
11789:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
11790:     $uri=&declutter($uri);
11791:     # if it is a non metadata possible uri return quickly
11792:     if (($uri eq '') || 
11793: 	(($uri =~ m|^/*adm/|) && 
11794: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
11795:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
11796: 	return undef;
11797:     }
11798:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
11799: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
11800: 	return undef;
11801:     }
11802:     my $filename=$uri;
11803:     $uri=~s/\.meta$//;
11804: #
11805: # Is the metadata already cached?
11806: # Look at timestamp of caching
11807: # Everything is cached by the main uri, libraries are never directly cached
11808: #
11809:     if (!defined($liburi)) {
11810: 	my ($result,$cached)=&is_cached_new('meta',$uri);
11811: 	if (defined($cached)) { return $result->{':'.$what}; }
11812:     }
11813:     {
11814: # Imported parts would go here
11815:         my @origfiletagids=();
11816:         my $importedparts=0;
11817: 
11818: # Imported responseids would go here
11819:         my $importedresponses=0;
11820: #
11821: # Is this a recursive call for a library?
11822: #
11823: #	if (! exists($metacache{$uri})) {
11824: #	    $metacache{$uri}={};
11825: #	}
11826: 	my $cachetime = 60*60;
11827:         if ($liburi) {
11828: 	    $liburi=&declutter($liburi);
11829:             $filename=$liburi;
11830:         } else {
11831: 	    &devalidate_cache_new('meta',$uri);
11832: 	    undef(%metaentry);
11833: 	}
11834:         my %metathesekeys=();
11835:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
11836: 	my $metastring;
11837: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
11838: 	    my $which = &hreflocation('','/'.($liburi || $uri));
11839: 	    $metastring = 
11840: 		&Apache::lonnet::ssi_body($which,
11841: 					  ('grade_target' => 'meta'));
11842: 	    $cachetime = 1; # only want this cached in the child not long term
11843: 	} elsif (($uri !~ m -^(editupload)/-) && 
11844:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
11845: 	    my $file=&filelocation('',&clutter($filename));
11846: 	    #push(@{$metaentry{$uri.'.file'}},$file);
11847: 	    $metastring=&getfile($file);
11848: 	}
11849:         my $parser=HTML::LCParser->new(\$metastring);
11850:         my $token;
11851:         undef %metathesekeys;
11852:         while ($token=$parser->get_token) {
11853: 	    if ($token->[0] eq 'S') {
11854: 		if (defined($token->[2]->{'package'})) {
11855: #
11856: # This is a package - get package info
11857: #
11858: 		    my $package=$token->[2]->{'package'};
11859: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11860: 		    if (defined($token->[2]->{'id'})) { 
11861: 			$keyroot.='_'.$token->[2]->{'id'}; 
11862: 		    }
11863: 		    if ($metaentry{':packages'}) {
11864: 			$metaentry{':packages'}.=','.$package.$keyroot;
11865: 		    } else {
11866: 			$metaentry{':packages'}=$package.$keyroot;
11867: 		    }
11868: 		    foreach my $pack_entry (keys(%packagetab)) {
11869: 			my $part=$keyroot;
11870: 			$part=~s/^\_//;
11871: 			if ($pack_entry=~/^\Q$package\E\&/ || 
11872: 			    $pack_entry=~/^\Q$package\E_0\&/) {
11873: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
11874: 			    # ignore package.tab specified default values
11875:                             # here &package_tab_default() will fetch those
11876: 			    if ($subp eq 'default') { next; }
11877: 			    my $value=$packagetab{$pack_entry};
11878: 			    my $unikey;
11879: 			    if ($pack =~ /_0$/) {
11880: 				$unikey='parameter_0_'.$name;
11881: 				$part=0;
11882: 			    } else {
11883: 				$unikey='parameter'.$keyroot.'_'.$name;
11884: 			    }
11885: 			    if ($subp eq 'display') {
11886: 				$value.=' [Part: '.$part.']';
11887: 			    }
11888: 			    $metaentry{':'.$unikey.'.part'}=$part;
11889: 			    $metathesekeys{$unikey}=1;
11890: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
11891: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
11892: 			    }
11893: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
11894: 				$metaentry{':'.$unikey}=
11895: 				    $metaentry{':'.$unikey.'.default'};
11896: 			    }
11897: 			}
11898: 		    }
11899: 		} else {
11900: #
11901: # This is not a package - some other kind of start tag
11902: #
11903: 		    my $entry=$token->[1];
11904: 		    my $unikey='';
11905: 
11906: 		    if ($entry eq 'import') {
11907: #
11908: # Importing a library here
11909: #
11910:                         my $location=$parser->get_text('/import');
11911:                         my $dir=$filename;
11912:                         $dir=~s|[^/]*$||;
11913:                         $location=&filelocation($dir,$location);
11914: 
11915:                         my $importid=$token->[2]->{'id'};
11916:                         my $importmode=$token->[2]->{'importmode'};
11917: #
11918: # Check metadata for imported file to
11919: # see if it contained response items
11920: #
11921:                         my %currmetaentry = %metaentry;
11922:                         my $libresponseorder = &metadata($location,'responseorder');
11923:                         my $origfile;
11924:                         if ($libresponseorder ne '') {
11925:                             if ($#origfiletagids<0) {
11926:                                 undef(%importedrespids);
11927:                                 undef(%importedpartids);
11928:                             }
11929:                             @{$importedrespids{$importid}} = split(/\s*,\s*/,$libresponseorder);
11930:                             if (@{$importedrespids{$importid}} > 0) {
11931:                                 $importedresponses = 1;
11932: # We need to get the original file and the imported file to get the response order correct
11933: # Load and inspect original file
11934:                                 if ($#origfiletagids<0) {
11935:                                     my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
11936:                                     $origfile=&getfile($origfilelocation);
11937:                                     @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
11938:                                 }
11939:                             }
11940:                         }
11941: # Do not overwrite contents of %metaentry hash for resource itself with 
11942: # hash populated for imported library file
11943:                         %metaentry = %currmetaentry;
11944:                         undef(%currmetaentry);
11945:                         if ($importmode eq 'problem') {
11946: # Import as problem/response
11947:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11948:                         } elsif ($importmode eq 'part') {
11949: # Import as part(s)
11950:                            $importedparts=1;
11951: # We need to get the original file and the imported file to get the part order correct
11952: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
11953: # Load and inspect original file if we didn't do that already
11954:                            if ($#origfiletagids<0) {
11955:                                undef(%importedrespids);
11956:                                undef(%importedpartids);
11957:                                if ($origfile eq '') {
11958:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
11959:                                    $origfile=&getfile($origfilelocation);
11960:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
11961:                                }
11962:                            }
11963: 
11964: # Load and inspect imported file
11965:                            my $impfile=&getfile($location);
11966:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
11967:                            if ($#impfilepartids>=0) {
11968: # This problem had parts
11969:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
11970:                            } else {
11971: # Importing by turning a single problem into a problem part
11972: # It gets the import-tags ID as part-ID
11973:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
11974:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
11975:                            }
11976:                         } else {
11977: # Normal import
11978:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11979:                            if (defined($token->[2]->{'id'})) {
11980:                               $unikey.='_'.$token->[2]->{'id'};
11981:                            }
11982:                         }
11983: 
11984: 			if ($depthcount<20) {
11985: 			    my $metadata = 
11986: 				&metadata($uri,'keys', $location,$unikey,
11987: 					  $depthcount+1);
11988: 			    foreach my $meta (split(',',$metadata)) {
11989: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
11990: 				$metathesekeys{$meta}=1;
11991: 			    }
11992: 			
11993:                         }
11994: 		    } else {
11995: #
11996: # Not importing, some other kind of non-package, non-library start tag
11997: # 
11998:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
11999:                         if (defined($token->[2]->{'id'})) {
12000:                             $unikey.='_'.$token->[2]->{'id'};
12001:                         }
12002: 			if (defined($token->[2]->{'name'})) { 
12003: 			    $unikey.='_'.$token->[2]->{'name'}; 
12004: 			}
12005: 			$metathesekeys{$unikey}=1;
12006: 			foreach my $param (@{$token->[3]}) {
12007: 			    $metaentry{':'.$unikey.'.'.$param} =
12008: 				$token->[2]->{$param};
12009: 			}
12010: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
12011: 			my $default=$metaentry{':'.$unikey.'.default'};
12012: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
12013: 		 # only ws inside the tag, and not in default, so use default
12014: 		 # as value
12015: 			    $metaentry{':'.$unikey}=$default;
12016: 			} elsif ( $internaltext =~ /\S/ ) {
12017: 		  # something interesting inside the tag
12018: 			    $metaentry{':'.$unikey}=$internaltext;
12019: 			} else {
12020: 		  # no interesting values, don't set a default
12021: 			}
12022: # end of not-a-package not-a-library import
12023: 		    }
12024: # end of not-a-package start tag
12025: 		}
12026: # the next is the end of "start tag"
12027: 	    }
12028: 	}
12029: 	my ($extension) = ($uri =~ /\.(\w+)$/);
12030: 	$extension = lc($extension);
12031: 	if ($extension eq 'htm') { $extension='html'; }
12032: 
12033: 	foreach my $key (keys(%packagetab)) {
12034: 	    #no specific packages #how's our extension
12035: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
12036: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
12037: 					 \%metathesekeys);
12038: 	}
12039: 
12040: 	if (!exists($metaentry{':packages'})
12041: 	    || $packagetab{"import_defaults&extension_$extension"}) {
12042: 	    foreach my $key (keys(%packagetab)) {
12043: 		#no specific packages well let's get default then
12044: 		if ($key!~/^default&/) { next; }
12045: 		&metadata_create_package_def($uri,$key,'default',
12046: 					     \%metathesekeys);
12047: 	    }
12048: 	}
12049: # are there custom rights to evaluate
12050: 	if ($metaentry{':copyright'} eq 'custom') {
12051: 
12052:     #
12053:     # Importing a rights file here
12054:     #
12055: 	    unless ($depthcount) {
12056: 		my $location=$metaentry{':customdistributionfile'};
12057: 		my $dir=$filename;
12058: 		$dir=~s|[^/]*$||;
12059: 		$location=&filelocation($dir,$location);
12060: 		my $rights_metadata =
12061: 		    &metadata($uri,'keys',$location,'_rights',
12062: 			      $depthcount+1);
12063: 		foreach my $rights (split(',',$rights_metadata)) {
12064: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
12065: 		    $metathesekeys{$rights}=1;
12066: 		}
12067: 	    }
12068: 	}
12069: 	# uniqifiy package listing
12070: 	my %seen;
12071: 	my @uniq_packages =
12072: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
12073: 	$metaentry{':packages'} = join(',',@uniq_packages);
12074: 
12075:         if (($importedresponses) || ($importedparts)) {
12076:             if ($importedparts) {
12077: # We had imported parts and need to rebuild partorder
12078:                 $metaentry{':partorder'}='';
12079:                 $metathesekeys{'partorder'}=1;
12080:             }
12081:             if ($importedresponses) {
12082: # We had imported responses and need to rebuild responseorder
12083:                 $metaentry{':responseorder'}='';
12084:                 $metathesekeys{'responseorder'}=1;
12085:             }
12086:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
12087:                 my $origid = $origfiletagids[$index+1];
12088:                 if ($origfiletagids[$index] eq 'part') {
12089: # Original part, part of the problem
12090:                     if ($importedparts) {
12091:                         $metaentry{':partorder'}.=','.$origid;
12092:                     }
12093:                 } elsif ($origfiletagids[$index] eq 'import') {
12094:                     if ($importedparts) {
12095: # We have imported parts at this position
12096:                         $metaentry{':partorder'}.=','.$importedpartids{$origid};
12097:                     }
12098:                     if ($importedresponses) {
12099: # We have imported responses at this position
12100:                         if (ref($importedrespids{$origid}) eq 'ARRAY') {
12101:                             $metaentry{':responseorder'}.=','.join(',',map { $origid.'_'.$_ } @{$importedrespids{$origid}});
12102:                         }
12103:                     }
12104:                 } else {
12105: # Original response item, part of the problem
12106:                     if ($importedresponses) {
12107:                         $metaentry{':responseorder'}.=','.$origid;
12108:                     }
12109:                 }
12110:             }
12111:             if ($importedparts) {
12112:                 $metaentry{':partorder'}=~s/^\,//;
12113:             }
12114:             if ($importedresponses) {
12115:                 $metaentry{':responseorder'}=~s/^\,//;
12116:             }
12117:         }
12118: 
12119: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
12120: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
12121: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
12122: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
12123: # this is the end of "was not already recently cached
12124:     }
12125:     return $metaentry{':'.$what};
12126: }
12127: 
12128: sub metadata_create_package_def {
12129:     my ($uri,$key,$package,$metathesekeys)=@_;
12130:     my ($pack,$name,$subp)=split(/\&/,$key);
12131:     if ($subp eq 'default') { next; }
12132:     
12133:     if (defined($metaentry{':packages'})) {
12134: 	$metaentry{':packages'}.=','.$package;
12135:     } else {
12136: 	$metaentry{':packages'}=$package;
12137:     }
12138:     my $value=$packagetab{$key};
12139:     my $unikey;
12140:     $unikey='parameter_0_'.$name;
12141:     $metaentry{':'.$unikey.'.part'}=0;
12142:     $$metathesekeys{$unikey}=1;
12143:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
12144: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
12145:     }
12146:     if (defined($metaentry{':'.$unikey.'.default'})) {
12147: 	$metaentry{':'.$unikey}=
12148: 	    $metaentry{':'.$unikey.'.default'};
12149:     }
12150: }
12151: 
12152: sub metadata_generate_part0 {
12153:     my ($metadata,$metacache,$uri) = @_;
12154:     my %allnames;
12155:     foreach my $metakey (keys(%$metadata)) {
12156: 	if ($metakey=~/^parameter\_(.*)/) {
12157: 	  my $part=$$metacache{':'.$metakey.'.part'};
12158: 	  my $name=$$metacache{':'.$metakey.'.name'};
12159: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
12160: 	    $allnames{$name}=$part;
12161: 	  }
12162: 	}
12163:     }
12164:     foreach my $name (keys(%allnames)) {
12165:       $$metadata{"parameter_0_$name"}=1;
12166:       my $key=":parameter_0_$name";
12167:       $$metacache{"$key.part"}='0';
12168:       $$metacache{"$key.name"}=$name;
12169:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
12170: 					   $allnames{$name}.'_'.$name.
12171: 					   '.type'};
12172:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
12173: 			     '.display'};
12174:       my $expr='[Part: '.$allnames{$name}.']';
12175:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
12176:       $$metacache{"$key.display"}=$olddis;
12177:     }
12178: }
12179: 
12180: # ------------------------------------------------------ Devalidate title cache
12181: 
12182: sub devalidate_title_cache {
12183:     my ($url)=@_;
12184:     if (!$env{'request.course.id'}) { return; }
12185:     my $symb=&symbread($url);
12186:     if (!$symb) { return; }
12187:     my $key=$env{'request.course.id'}."\0".$symb;
12188:     &devalidate_cache_new('title',$key);
12189: }
12190: 
12191: # ------------------------------------------------- Get the title of a course
12192: 
12193: sub current_course_title {
12194:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
12195: }
12196: # ------------------------------------------------- Get the title of a resource
12197: 
12198: sub gettitle {
12199:     my $urlsymb=shift;
12200:     my $symb=&symbread($urlsymb);
12201:     if ($symb) {
12202: 	my $key=$env{'request.course.id'}."\0".$symb;
12203: 	my ($result,$cached)=&is_cached_new('title',$key);
12204: 	if (defined($cached)) { 
12205: 	    return $result;
12206: 	}
12207: 	my ($map,$resid,$url)=&decode_symb($symb);
12208: 	my $title='';
12209: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
12210: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
12211: 	} else {
12212: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12213: 		    &GDBM_READER(),0640)) {
12214: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
12215: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
12216: 		untie(%bighash);
12217: 	    }
12218: 	}
12219: 	$title=~s/\&colon\;/\:/gs;
12220: 	if ($title) {
12221: # Remember both $symb and $title for dynamic metadata
12222:             $accesshash{$symb.'___crstitle'}=$title;
12223:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
12224: # Cache this title and then return it
12225: 	    return &do_cache_new('title',$key,$title,600);
12226: 	}
12227: 	$urlsymb=$url;
12228:     }
12229:     my $title=&metadata($urlsymb,'title');
12230:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
12231:     return $title;
12232: }
12233: 
12234: sub get_slot {
12235:     my ($which,$cnum,$cdom)=@_;
12236:     if (!$cnum || !$cdom) {
12237: 	(undef,my $courseid)=&whichuser();
12238: 	$cdom=$env{'course.'.$courseid.'.domain'};
12239: 	$cnum=$env{'course.'.$courseid.'.num'};
12240:     }
12241:     my $key=join("\0",'slots',$cdom,$cnum,$which);
12242:     my %slotinfo;
12243:     if (exists($remembered{$key})) {
12244: 	$slotinfo{$which} = $remembered{$key};
12245:     } else {
12246: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
12247: 	&Apache::lonhomework::showhash(%slotinfo);
12248: 	my ($tmp)=keys(%slotinfo);
12249: 	if ($tmp=~/^error:/) { return (); }
12250: 	$remembered{$key} = $slotinfo{$which};
12251:     }
12252:     if (ref($slotinfo{$which}) eq 'HASH') {
12253: 	return %{$slotinfo{$which}};
12254:     }
12255:     return $slotinfo{$which};
12256: }
12257: 
12258: sub get_reservable_slots {
12259:     my ($cnum,$cdom,$uname,$udom) = @_;
12260:     my $now = time;
12261:     my $reservable_info;
12262:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
12263:     if (exists($remembered{$key})) {
12264:         $reservable_info = $remembered{$key};
12265:     } else {
12266:         my %resv;
12267:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
12268:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
12269:         $reservable_info = \%resv;
12270:         $remembered{$key} = $reservable_info;
12271:     }
12272:     return $reservable_info;
12273: }
12274: 
12275: sub get_course_slots {
12276:     my ($cnum,$cdom) = @_;
12277:     my $hashid=$cnum.':'.$cdom;
12278:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
12279:     if (defined($cached)) {
12280:         if (ref($result) eq 'HASH') {
12281:             return %{$result};
12282:         }
12283:     } else {
12284:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
12285:         my ($tmp) = keys(%slots);
12286:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
12287:             &do_cache_new('allslots',$hashid,\%slots,600);
12288:             return %slots;
12289:         }
12290:     }
12291:     return;
12292: }
12293: 
12294: sub devalidate_slots_cache {
12295:     my ($cnum,$cdom)=@_;
12296:     my $hashid=$cnum.':'.$cdom;
12297:     &devalidate_cache_new('allslots',$hashid);
12298: }
12299: 
12300: sub get_coursechange {
12301:     my ($cdom,$cnum) = @_;
12302:     if ($cdom eq '' || $cnum eq '') {
12303:         return unless ($env{'request.course.id'});
12304:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
12305:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
12306:     }
12307:     my $hashid=$cdom.'_'.$cnum;
12308:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
12309:     if ((defined($cached)) && ($change ne '')) {
12310:         return $change;
12311:     } else {
12312:         my %crshash;
12313:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
12314:         if ($crshash{'internal.contentchange'} eq '') {
12315:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
12316:             if ($change eq '') {
12317:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
12318:                 $change = $crshash{'internal.created'};
12319:             }
12320:         } else {
12321:             $change = $crshash{'internal.contentchange'};
12322:         }
12323:         my $cachetime = 600;
12324:         &do_cache_new('crschange',$hashid,$change,$cachetime);
12325:     }
12326:     return $change;
12327: }
12328: 
12329: sub devalidate_coursechange_cache {
12330:     my ($cnum,$cdom)=@_;
12331:     my $hashid=$cnum.':'.$cdom;
12332:     &devalidate_cache_new('crschange',$hashid);
12333: }
12334: 
12335: # ------------------------------------------------- Update symbolic store links
12336: 
12337: sub symblist {
12338:     my ($mapname,%newhash)=@_;
12339:     $mapname=&deversion(&declutter($mapname));
12340:     my %hash;
12341:     if (($env{'request.course.fn'}) && (%newhash)) {
12342:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
12343:                       &GDBM_WRCREAT(),0640)) {
12344: 	    foreach my $url (keys(%newhash)) {
12345: 		next if ($url eq 'last_known'
12346: 			 && $env{'form.no_update_last_known'});
12347: 		$hash{declutter($url)}=&encode_symb($mapname,
12348: 						    $newhash{$url}->[1],
12349: 						    $newhash{$url}->[0]);
12350:             }
12351:             if (untie(%hash)) {
12352: 		return 'ok';
12353:             }
12354:         }
12355:     }
12356:     return 'error';
12357: }
12358: 
12359: # --------------------------------------------------------------- Verify a symb
12360: 
12361: sub symbverify {
12362:     my ($symb,$thisurl,$encstate)=@_;
12363:     my $thisfn=$thisurl;
12364:     $thisfn=&declutter($thisfn);
12365: # direct jump to resource in page or to a sequence - will construct own symbs
12366:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
12367: # check URL part
12368:     my ($map,$resid,$url)=&decode_symb($symb);
12369: 
12370:     unless ($url eq $thisfn) { return 0; }
12371: 
12372:     $symb=&symbclean($symb);
12373:     $thisurl=&deversion($thisurl);
12374:     $thisfn=&deversion($thisfn);
12375: 
12376:     my %bighash;
12377:     my $okay=0;
12378: 
12379:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12380:                             &GDBM_READER(),0640)) {
12381:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
12382:             $thisurl =~ s/\?.+$//;
12383:             if ($map =~ m{^uploaded/.+\.page$}) {
12384:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
12385:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
12386:             }
12387:         }
12388:         my $ids;
12389:         if ($map =~ m{^uploaded/.+\.page$}) {
12390:             $ids=$bighash{'ids_'.&clutter_with_no_wrapper($thisurl)};
12391:         } else {
12392:             $ids=$bighash{'ids_'.&clutter($thisurl)};
12393:         }
12394:         unless ($ids) {
12395:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
12396:             $ids=$bighash{$idkey};
12397:         }
12398:         if ($ids) {
12399: # ------------------------------------------------------------------- Has ID(s)
12400:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
12401:                 $symb =~ s/\?.+$//;
12402:             }
12403: 	    foreach my $id (split(/\,/,$ids)) {
12404: 	       my ($mapid,$resid)=split(/\./,$id);
12405:                if (
12406:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
12407:    eq $symb) {
12408:                    if (ref($encstate)) {
12409:                        $$encstate = $bighash{'encrypted_'.$id};
12410:                    }
12411:                    if (($env{'request.role.adv'}) ||
12412:                        ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
12413:                        ($thisurl eq '/adm/navmaps')) {
12414:                        $okay=1;
12415:                        last;
12416:                    }
12417:                }
12418:            }
12419:         }
12420: 	untie(%bighash);
12421:     }
12422:     return $okay;
12423: }
12424: 
12425: # --------------------------------------------------------------- Clean-up symb
12426: 
12427: sub symbclean {
12428:     my $symb=shift;
12429:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
12430: # remove version from map
12431:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
12432: 
12433: # remove version from URL
12434:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
12435: 
12436: # remove wrapper
12437: 
12438:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
12439:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
12440:     return $symb;
12441: }
12442: 
12443: # ---------------------------------------------- Split symb to find map and url
12444: 
12445: sub encode_symb {
12446:     my ($map,$resid,$url)=@_;
12447:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
12448: }
12449: 
12450: sub decode_symb {
12451:     my $symb=shift;
12452:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
12453:     my ($map,$resid,$url)=split(/___/,$symb);
12454:     return (&fixversion($map),$resid,&fixversion($url));
12455: }
12456: 
12457: sub fixversion {
12458:     my $fn=shift;
12459:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
12460:     my %bighash;
12461:     my $uri=&clutter($fn);
12462:     my $key=$env{'request.course.id'}.'_'.$uri;
12463: # is this cached?
12464:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
12465:     if (defined($cached)) { return $result; }
12466: # unfortunately not cached, or expired
12467:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12468: 	    &GDBM_READER(),0640)) {
12469:  	if ($bighash{'version_'.$uri}) {
12470:  	    my $version=$bighash{'version_'.$uri};
12471:  	    unless (($version eq 'mostrecent') || 
12472: 		    ($version==&getversion($uri))) {
12473:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
12474:  	    }
12475:  	}
12476:  	untie %bighash;
12477:     }
12478:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
12479: }
12480: 
12481: sub deversion {
12482:     my $url=shift;
12483:     $url=~s/\.\d+\.(\w+)$/\.$1/;
12484:     return $url;
12485: }
12486: 
12487: # ------------------------------------------------------ Return symb list entry
12488: 
12489: sub symbread {
12490:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles,
12491:         $ignoresymbdb,$noenccheck)=@_;
12492:     my $cache_str='request.symbread.cached.'.$thisfn;
12493:     if (defined($env{$cache_str})) {
12494:         unless (ref($possibles) eq 'HASH') {
12495:             if ($ignorecachednull) {
12496:                 return $env{$cache_str} unless ($env{$cache_str} eq '');
12497:             } else {
12498:                 return $env{$cache_str};
12499:             }
12500:         }
12501:     }
12502: # no filename provided? try from environment
12503:     unless ($thisfn) {
12504:         if ($env{'request.symb'}) {
12505:             return $env{$cache_str}=&symbclean($env{'request.symb'});
12506:         }
12507:         $thisfn=$env{'request.filename'};
12508:     }
12509:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
12510: # is that filename actually a symb? Verify, clean, and return
12511:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
12512: 	if (&symbverify($thisfn,$1)) {
12513: 	    return $env{$cache_str}=&symbclean($thisfn);
12514: 	}
12515:     }
12516:     $thisfn=declutter($thisfn);
12517:     my %hash;
12518:     my %bighash;
12519:     my $syval='';
12520:     if (($env{'request.course.fn'}) && ($thisfn)) {
12521:         my $targetfn = $thisfn;
12522:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
12523:             $targetfn = 'adm/wrapper/'.$thisfn;
12524:         }
12525: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
12526: 	    $targetfn=$1;
12527: 	}
12528:         unless ($ignoresymbdb) {
12529:             if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
12530:                           &GDBM_READER(),0640)) {
12531: 	        $syval=$hash{$targetfn};
12532:                 untie(%hash);
12533:             }
12534:             if ($syval && $checkforblock) {
12535:                 my @blockers = &has_comm_blocking('bre',$syval,$thisfn,$ignoresymbdb,$noenccheck);
12536:                 if (@blockers) {
12537:                     $syval='';
12538:                 }
12539:             }
12540:         }
12541: # ---------------------------------------------------------- There was an entry
12542:         if ($syval) {
12543: 	    #unless ($syval=~/\_\d+$/) {
12544: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
12545: 		    #&appenv({'request.ambiguous' => $thisfn});
12546: 		    #return $env{$cache_str}='';
12547: 		#}    
12548: 		#$syval.=$1;
12549: 	    #}
12550:         } else {
12551: # ------------------------------------------------------- Was not in symb table
12552:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12553:                             &GDBM_READER(),0640)) {
12554: # ---------------------------------------------- Get ID(s) for current resource
12555:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
12556:               unless ($ids) { 
12557:                  $ids=$bighash{'ids_/'.$thisfn};
12558:               }
12559:               unless ($ids) {
12560: # alias?
12561: 		  $ids=$bighash{'mapalias_'.$thisfn};
12562:               }
12563:               if ($ids) {
12564: # ------------------------------------------------------------------- Has ID(s)
12565:                  my @possibilities=split(/\,/,$ids);
12566:                  if ($#possibilities==0) {
12567: # ----------------------------------------------- There is only one possibility
12568: 		     my ($mapid,$resid)=split(/\./,$ids);
12569: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
12570: 						    $resid,$thisfn);
12571:                      if (ref($possibles) eq 'HASH') {
12572:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
12573:                              $possibles->{$syval} = 1;
12574:                          }
12575:                      }
12576:                      if ($checkforblock) {
12577:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
12578:                              my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids},'',$noenccheck);
12579:                              if (@blockers) {
12580:                                  $syval = '';
12581:                                  untie(%bighash);
12582:                                  return $env{$cache_str}='';
12583:                              }
12584:                          }
12585:                      }
12586:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
12587: # ------------------------------------------ There is more than one possibility
12588:                      my $realpossible=0;
12589:                      foreach my $id (@possibilities) {
12590: 			 my $file=$bighash{'src_'.$id};
12591:                          my $canaccess;
12592:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
12593:                              $canaccess = 1;
12594:                          } else {
12595:                              $canaccess = &allowed('bre',$file);
12596:                          }
12597:                          if ($canaccess) {
12598:          		     my ($mapid,$resid)=split(/\./,$id);
12599:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
12600:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
12601:                                                              $resid,$thisfn);
12602:                                  next if ($bighash{'randomout_'.$id} && !$env{'request.role.adv'});
12603:                                  next unless (($noenccheck) || ($bighash{'encrypted_'.$id} eq $env{'request.enc'}));
12604:                                  if ($checkforblock) {
12605:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file,'',$noenccheck);
12606:                                      if (@blockers > 0) {
12607:                                          $syval = '';
12608:                                      } else {
12609:                                          $syval = $poss_syval;
12610:                                          $realpossible++;
12611:                                      }
12612:                                  } else {
12613:                                      $syval = $poss_syval;
12614:                                      $realpossible++;
12615:                                  }
12616:                                  if ($syval) {
12617:                                      if (ref($possibles) eq 'HASH') {
12618:                                          $possibles->{$syval} = 1;
12619:                                      }
12620:                                  }
12621:                              }
12622: 			 }
12623:                      }
12624: 		     if ($realpossible!=1) { $syval=''; }
12625:                  } else {
12626:                      $syval='';
12627:                  }
12628: 	      }
12629:               untie(%bighash);
12630:            }
12631:         }
12632:         if ($syval) {
12633: 	    return $env{$cache_str}=$syval;
12634:         }
12635:     }
12636:     &appenv({'request.ambiguous' => $thisfn});
12637:     return $env{$cache_str}='';
12638: }
12639: 
12640: # ---------------------------------------------------------- Return random seed
12641: 
12642: sub numval {
12643:     my $txt=shift;
12644:     $txt=~tr/A-J/0-9/;
12645:     $txt=~tr/a-j/0-9/;
12646:     $txt=~tr/K-T/0-9/;
12647:     $txt=~tr/k-t/0-9/;
12648:     $txt=~tr/U-Z/0-5/;
12649:     $txt=~tr/u-z/0-5/;
12650:     $txt=~s/\D//g;
12651:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
12652:     return int($txt);
12653: }
12654: 
12655: sub numval2 {
12656:     my $txt=shift;
12657:     $txt=~tr/A-J/0-9/;
12658:     $txt=~tr/a-j/0-9/;
12659:     $txt=~tr/K-T/0-9/;
12660:     $txt=~tr/k-t/0-9/;
12661:     $txt=~tr/U-Z/0-5/;
12662:     $txt=~tr/u-z/0-5/;
12663:     $txt=~s/\D//g;
12664:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
12665:     my $total;
12666:     foreach my $val (@txts) { $total+=$val; }
12667:     if ($_64bit) { if ($total > 2**32) { return -1; } }
12668:     return int($total);
12669: }
12670: 
12671: sub numval3 {
12672:     use integer;
12673:     my $txt=shift;
12674:     $txt=~tr/A-J/0-9/;
12675:     $txt=~tr/a-j/0-9/;
12676:     $txt=~tr/K-T/0-9/;
12677:     $txt=~tr/k-t/0-9/;
12678:     $txt=~tr/U-Z/0-5/;
12679:     $txt=~tr/u-z/0-5/;
12680:     $txt=~s/\D//g;
12681:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
12682:     my $total;
12683:     foreach my $val (@txts) { $total+=$val; }
12684:     if ($_64bit) { $total=(($total<<32)>>32); }
12685:     return $total;
12686: }
12687: 
12688: sub digest {
12689:     my ($data)=@_;
12690:     my $digest=&Digest::MD5::md5($data);
12691:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
12692:     my ($e,$f);
12693:     {
12694:         use integer;
12695:         $e=($a+$b);
12696:         $f=($c+$d);
12697:         if ($_64bit) {
12698:             $e=(($e<<32)>>32);
12699:             $f=(($f<<32)>>32);
12700:         }
12701:     }
12702:     if (wantarray) {
12703: 	return ($e,$f);
12704:     } else {
12705: 	my $g;
12706: 	{
12707: 	    use integer;
12708: 	    $g=($e+$f);
12709: 	    if ($_64bit) {
12710: 		$g=(($g<<32)>>32);
12711: 	    }
12712: 	}
12713: 	return $g;
12714:     }
12715: }
12716: 
12717: sub latest_rnd_algorithm_id {
12718:     return '64bit5';
12719: }
12720: 
12721: sub get_rand_alg {
12722:     my ($courseid)=@_;
12723:     if (!$courseid) { $courseid=(&whichuser())[1]; }
12724:     if ($courseid) {
12725: 	return $env{"course.$courseid.rndseed"};
12726:     }
12727:     return &latest_rnd_algorithm_id();
12728: }
12729: 
12730: sub validCODE {
12731:     my ($CODE)=@_;
12732:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
12733:     return 0;
12734: }
12735: 
12736: sub getCODE {
12737:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
12738:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
12739: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
12740: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
12741: 	return $Apache::lonhomework::history{'resource.CODE'};
12742:     }
12743:     return undef;
12744: }
12745: #
12746: #  Determines the random seed for a specific context:
12747: #
12748: # parameters:
12749: #   symb      - in course context the symb for the seed.
12750: #   course_id - The course id of the form domain_coursenum.
12751: #   domain    - Domain for the user.
12752: #   course    - Course for the user.
12753: #   cenv      - environment of the course.
12754: #
12755: # NOTE:
12756: #   All parameters are picked out of the environment if missing
12757: #   or not defined.
12758: #   If a symb cannot be determined the current time is used instead.
12759: #
12760: #  For a given well defined symb, courside, domain, username,
12761: #  and course environment, the seed is reproducible.
12762: #
12763: sub rndseed {
12764:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
12765:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
12766:     if (!defined($symb)) {
12767: 	unless ($symb=$wsymb) { return time; }
12768:     }
12769:     if (!defined $courseid) { 
12770: 	$courseid=$wcourseid; 
12771:     }
12772:     if (!defined $domain) { $domain=$wdomain; }
12773:     if (!defined $username) { $username=$wusername }
12774: 
12775:     my $which;
12776:     if (defined($cenv->{'rndseed'})) {
12777: 	$which = $cenv->{'rndseed'};
12778:     } else {
12779: 	$which =&get_rand_alg($courseid);
12780:     }
12781:     if (defined(&getCODE())) {
12782: 	if ($which eq '64bit5') {
12783: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
12784: 	} elsif ($which eq '64bit4') {
12785: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
12786: 	} else {
12787: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
12788: 	}
12789:     } elsif ($which eq '64bit5') {
12790: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
12791:     } elsif ($which eq '64bit4') {
12792: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
12793:     } elsif ($which eq '64bit3') {
12794: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
12795:     } elsif ($which eq '64bit2') {
12796: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
12797:     } elsif ($which eq '64bit') {
12798: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
12799:     }
12800:     return &rndseed_32bit($symb,$courseid,$domain,$username);
12801: }
12802: 
12803: sub rndseed_32bit {
12804:     my ($symb,$courseid,$domain,$username)=@_;
12805:     {
12806: 	use integer;
12807: 	my $symbchck=unpack("%32C*",$symb) << 27;
12808: 	my $symbseed=numval($symb) << 22;
12809: 	my $namechck=unpack("%32C*",$username) << 17;
12810: 	my $nameseed=numval($username) << 12;
12811: 	my $domainseed=unpack("%32C*",$domain) << 7;
12812: 	my $courseseed=unpack("%32C*",$courseid);
12813: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
12814: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12815: 	#&logthis("rndseed :$num:$symb");
12816: 	if ($_64bit) { $num=(($num<<32)>>32); }
12817: 	return $num;
12818:     }
12819: }
12820: 
12821: sub rndseed_64bit {
12822:     my ($symb,$courseid,$domain,$username)=@_;
12823:     {
12824: 	use integer;
12825: 	my $symbchck=unpack("%32S*",$symb) << 21;
12826: 	my $symbseed=numval($symb) << 10;
12827: 	my $namechck=unpack("%32S*",$username);
12828: 	
12829: 	my $nameseed=numval($username) << 21;
12830: 	my $domainseed=unpack("%32S*",$domain) << 10;
12831: 	my $courseseed=unpack("%32S*",$courseid);
12832: 	
12833: 	my $num1=$symbchck+$symbseed+$namechck;
12834: 	my $num2=$nameseed+$domainseed+$courseseed;
12835: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12836: 	#&logthis("rndseed :$num:$symb");
12837: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
12838: 	return "$num1,$num2";
12839:     }
12840: }
12841: 
12842: sub rndseed_64bit2 {
12843:     my ($symb,$courseid,$domain,$username)=@_;
12844:     {
12845: 	use integer;
12846: 	# strings need to be an even # of cahracters long, it it is odd the
12847:         # last characters gets thrown away
12848: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
12849: 	my $symbseed=numval($symb) << 10;
12850: 	my $namechck=unpack("%32S*",$username.' ');
12851: 	
12852: 	my $nameseed=numval($username) << 21;
12853: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
12854: 	my $courseseed=unpack("%32S*",$courseid.' ');
12855: 	
12856: 	my $num1=$symbchck+$symbseed+$namechck;
12857: 	my $num2=$nameseed+$domainseed+$courseseed;
12858: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12859: 	#&logthis("rndseed :$num:$symb");
12860: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
12861: 	return "$num1,$num2";
12862:     }
12863: }
12864: 
12865: sub rndseed_64bit3 {
12866:     my ($symb,$courseid,$domain,$username)=@_;
12867:     {
12868: 	use integer;
12869: 	# strings need to be an even # of cahracters long, it it is odd the
12870:         # last characters gets thrown away
12871: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
12872: 	my $symbseed=numval2($symb) << 10;
12873: 	my $namechck=unpack("%32S*",$username.' ');
12874: 	
12875: 	my $nameseed=numval2($username) << 21;
12876: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
12877: 	my $courseseed=unpack("%32S*",$courseid.' ');
12878: 	
12879: 	my $num1=$symbchck+$symbseed+$namechck;
12880: 	my $num2=$nameseed+$domainseed+$courseseed;
12881: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12882: 	#&logthis("rndseed :$num1:$num2:$_64bit");
12883: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
12884: 	
12885: 	return "$num1:$num2";
12886:     }
12887: }
12888: 
12889: sub rndseed_64bit4 {
12890:     my ($symb,$courseid,$domain,$username)=@_;
12891:     {
12892: 	use integer;
12893: 	# strings need to be an even # of cahracters long, it it is odd the
12894:         # last characters gets thrown away
12895: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
12896: 	my $symbseed=numval3($symb) << 10;
12897: 	my $namechck=unpack("%32S*",$username.' ');
12898: 	
12899: 	my $nameseed=numval3($username) << 21;
12900: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
12901: 	my $courseseed=unpack("%32S*",$courseid.' ');
12902: 	
12903: 	my $num1=$symbchck+$symbseed+$namechck;
12904: 	my $num2=$nameseed+$domainseed+$courseseed;
12905: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12906: 	#&logthis("rndseed :$num1:$num2:$_64bit");
12907: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
12908: 	
12909: 	return "$num1:$num2";
12910:     }
12911: }
12912: 
12913: sub rndseed_64bit5 {
12914:     my ($symb,$courseid,$domain,$username)=@_;
12915:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
12916:     return "$num1:$num2";
12917: }
12918: 
12919: sub rndseed_CODE_64bit {
12920:     my ($symb,$courseid,$domain,$username)=@_;
12921:     {
12922: 	use integer;
12923: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
12924: 	my $symbseed=numval2($symb);
12925: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
12926: 	my $CODEseed=numval(&getCODE());
12927: 	my $courseseed=unpack("%32S*",$courseid.' ');
12928: 	my $num1=$symbseed+$CODEchck;
12929: 	my $num2=$CODEseed+$courseseed+$symbchck;
12930: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
12931: 	#&logthis("rndseed :$num1:$num2:$symb");
12932: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
12933: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
12934: 	return "$num1:$num2";
12935:     }
12936: }
12937: 
12938: sub rndseed_CODE_64bit4 {
12939:     my ($symb,$courseid,$domain,$username)=@_;
12940:     {
12941: 	use integer;
12942: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
12943: 	my $symbseed=numval3($symb);
12944: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
12945: 	my $CODEseed=numval3(&getCODE());
12946: 	my $courseseed=unpack("%32S*",$courseid.' ');
12947: 	my $num1=$symbseed+$CODEchck;
12948: 	my $num2=$CODEseed+$courseseed+$symbchck;
12949: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
12950: 	#&logthis("rndseed :$num1:$num2:$symb");
12951: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
12952: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
12953: 	return "$num1:$num2";
12954:     }
12955: }
12956: 
12957: sub rndseed_CODE_64bit5 {
12958:     my ($symb,$courseid,$domain,$username)=@_;
12959:     my $code = &getCODE();
12960:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
12961:     return "$num1:$num2";
12962: }
12963: 
12964: sub setup_random_from_rndseed {
12965:     my ($rndseed)=@_;
12966:     if ($rndseed =~/([,:])/) {
12967: 	my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
12968:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
12969:             &Math::Random::random_set_seed_from_phrase($rndseed);
12970:         } else {
12971:             &Math::Random::random_set_seed($num1,$num2);
12972:         }
12973:     } else {
12974: 	&Math::Random::random_set_seed_from_phrase($rndseed);
12975:     }
12976: }
12977: 
12978: sub latest_receipt_algorithm_id {
12979:     return 'receipt3';
12980: }
12981: 
12982: sub recunique {
12983:     my $fucourseid=shift;
12984:     my $unique;
12985:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
12986: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
12987: 	$unique=$env{"course.$fucourseid.internal.encseed"};
12988:     } else {
12989: 	$unique=$perlvar{'lonReceipt'};
12990:     }
12991:     return unpack("%32C*",$unique);
12992: }
12993: 
12994: sub recprefix {
12995:     my $fucourseid=shift;
12996:     my $prefix;
12997:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
12998: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
12999: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
13000:     } else {
13001: 	$prefix=$perlvar{'lonHostID'};
13002:     }
13003:     return unpack("%32C*",$prefix);
13004: }
13005: 
13006: sub ireceipt {
13007:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
13008: 
13009:     my $return =&recprefix($fucourseid).'-';
13010: 
13011:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
13012: 	$env{'request.state'} eq 'construct') {
13013: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
13014: 	return $return;
13015:     }
13016: 
13017:     my $cuname=unpack("%32C*",$funame);
13018:     my $cudom=unpack("%32C*",$fudom);
13019:     my $cucourseid=unpack("%32C*",$fucourseid);
13020:     my $cusymb=unpack("%32C*",$fusymb);
13021:     my $cunique=&recunique($fucourseid);
13022:     my $cpart=unpack("%32S*",$part);
13023:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
13024: 
13025: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
13026: 			       
13027: 	$return.= ($cunique%$cuname+
13028: 		   $cunique%$cudom+
13029: 		   $cusymb%$cuname+
13030: 		   $cusymb%$cudom+
13031: 		   $cucourseid%$cuname+
13032: 		   $cucourseid%$cudom+
13033: 		   $cpart%$cuname+
13034: 		   $cpart%$cudom);
13035:     } else {
13036: 	$return.= ($cunique%$cuname+
13037: 		   $cunique%$cudom+
13038: 		   $cusymb%$cuname+
13039: 		   $cusymb%$cudom+
13040: 		   $cucourseid%$cuname+
13041: 		   $cucourseid%$cudom);
13042:     }
13043:     return $return;
13044: }
13045: 
13046: sub receipt {
13047:     my ($part)=@_;
13048:     my ($symb,$courseid,$domain,$name) = &whichuser();
13049:     return &ireceipt($name,$domain,$courseid,$symb,$part);
13050: }
13051: 
13052: sub whichuser {
13053:     my ($passedsymb)=@_;
13054:     my ($symb,$courseid,$domain,$name,$publicuser);
13055:     if (defined($env{'form.grade_symb'})) {
13056: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
13057: 	my $allowed=&allowed('vgr',$tmp_courseid);
13058: 	if (!$allowed &&
13059: 	    exists($env{'request.course.sec'}) &&
13060: 	    $env{'request.course.sec'} !~ /^\s*$/) {
13061: 	    $allowed=&allowed('vgr',$tmp_courseid.
13062: 			      '/'.$env{'request.course.sec'});
13063: 	}
13064: 	if ($allowed) {
13065: 	    ($symb)=&get_env_multiple('form.grade_symb');
13066: 	    $courseid=$tmp_courseid;
13067: 	    ($domain)=&get_env_multiple('form.grade_domain');
13068: 	    ($name)=&get_env_multiple('form.grade_username');
13069: 	    return ($symb,$courseid,$domain,$name,$publicuser);
13070: 	}
13071:     }
13072:     if (!$passedsymb) {
13073: 	$symb=&symbread();
13074:     } else {
13075: 	$symb=$passedsymb;
13076:     }
13077:     $courseid=$env{'request.course.id'};
13078:     $domain=$env{'user.domain'};
13079:     $name=$env{'user.name'};
13080:     if ($name eq 'public' && $domain eq 'public') {
13081: 	if (!defined($env{'form.username'})) {
13082: 	    $env{'form.username'}.=time.rand(10000000);
13083: 	}
13084: 	$name.=$env{'form.username'};
13085:     }
13086:     return ($symb,$courseid,$domain,$name,$publicuser);
13087: 
13088: }
13089: 
13090: # ------------------------------------------------------------ Serves up a file
13091: # returns either the contents of the file or 
13092: # -1 if the file doesn't exist
13093: #
13094: # if the target is a file that was uploaded via DOCS, 
13095: # a check will be made to see if a current copy exists on the local server,
13096: # if it does this will be served, otherwise a copy will be retrieved from
13097: # the home server for the course and stored in /home/httpd/html/userfiles on
13098: # the local server.   
13099: 
13100: sub getfile {
13101:     my ($file) = @_;
13102:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
13103:     &repcopy($file);
13104:     return &readfile($file);
13105: }
13106: 
13107: sub repcopy_userfile {
13108:     my ($file)=@_;
13109:     my $londocroot = $perlvar{'lonDocRoot'};
13110:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
13111:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
13112:     my ($cdom,$cnum,$filename) = 
13113: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
13114:     my $uri="/uploaded/$cdom/$cnum/$filename";
13115:     if (-e "$file") {
13116: # we already have a local copy, check it out
13117: 	my @fileinfo = stat($file);
13118: 	my $rtncode;
13119: 	my $info;
13120: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
13121: 	if ($lwpresp ne 'ok') {
13122: # there is no such file anymore, even though we had a local copy
13123: 	    if ($rtncode eq '404') {
13124: 		unlink($file);
13125: 	    }
13126: 	    return -1;
13127: 	}
13128: 	if ($info < $fileinfo[9]) {
13129: # nice, the file we have is up-to-date, just say okay
13130: 	    return 'ok';
13131: 	} else {
13132: # the file is outdated, get rid of it
13133: 	    unlink($file);
13134: 	}
13135:     }
13136: # one way or the other, at this point, we don't have the file
13137: # construct the correct path for the file
13138:     my @parts = ($cdom,$cnum); 
13139:     if ($filename =~ m|^(.+)/[^/]+$|) {
13140: 	push @parts, split(/\//,$1);
13141:     }
13142:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
13143:     foreach my $part (@parts) {
13144: 	$path .= '/'.$part;
13145: 	if (!-e $path) {
13146: 	    mkdir($path,0770);
13147: 	}
13148:     }
13149: # now the path exists for sure
13150: # get a user agent
13151:     my $ua=new LWP::UserAgent;
13152:     my $transferfile=$file.'.in.transfer';
13153: # FIXME: this should flock
13154:     if (-e $transferfile) { return 'ok'; }
13155:     my $request;
13156:     $uri=~s/^\///;
13157:     my $homeserver = &homeserver($cnum,$cdom);
13158:     my $hostname = &hostname($homeserver);
13159:     my $protocol = $protocol{$homeserver};
13160:     $protocol = 'http' if ($protocol ne 'https');
13161:     $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
13162:     my $response=$ua->request($request,$transferfile);
13163: # did it work?
13164:     if ($response->is_error()) {
13165: 	unlink($transferfile);
13166: 	&logthis("Userfile repcopy failed for $uri");
13167: 	return -1;
13168:     }
13169: # worked, rename the transfer file
13170:     rename($transferfile,$file);
13171:     return 'ok';
13172: }
13173: 
13174: sub tokenwrapper {
13175:     my $uri=shift;
13176:     $uri=~s|^https?\://([^/]+)||;
13177:     $uri=~s|^/||;
13178:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
13179:     my $token=$1;
13180:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
13181:     if ($udom && $uname && $file) {
13182: 	$file=~s|(\?\.*)*$||;
13183:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
13184:         my $homeserver = &homeserver($uname,$udom);
13185:         my $hostname = &hostname($homeserver);
13186:         my $protocol = $protocol{$homeserver};
13187:         $protocol = 'http' if ($protocol ne 'https');
13188:         return $protocol.'://'.$hostname.'/'.$uri.
13189:                (($uri=~/\?/)?'&':'?').'token='.$token.
13190:                                '&tokenissued='.$perlvar{'lonHostID'};
13191:     } else {
13192:         return '/adm/notfound.html';
13193:     }
13194: }
13195: 
13196: # call with reqtype HEAD: get last modification time
13197: # call with reqtype GET: get the file contents
13198: # Do not call this with reqtype GET for large files! It loads everything into memory
13199: #
13200: sub getuploaded {
13201:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
13202:     $uri=~s/^\///;
13203:     my $homeserver = &homeserver($cnum,$cdom);
13204:     my $hostname = &hostname($homeserver);
13205:     my $protocol = $protocol{$homeserver};
13206:     $protocol = 'http' if ($protocol ne 'https');
13207:     $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
13208:     my $ua=new LWP::UserAgent;
13209:     my $request=new HTTP::Request($reqtype,$uri);
13210:     my $response=$ua->request($request);
13211:     $$rtncode = $response->code;
13212:     if (! $response->is_success()) {
13213: 	return 'failed';
13214:     }      
13215:     if ($reqtype eq 'HEAD') {
13216: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
13217:     } elsif ($reqtype eq 'GET') {
13218: 	$$info = $response->content;
13219:     }
13220:     return 'ok';
13221: }
13222: 
13223: sub readfile {
13224:     my $file = shift;
13225:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
13226:     my $fh;
13227:     open($fh,"<",$file);
13228:     my $a='';
13229:     while (my $line = <$fh>) { $a .= $line; }
13230:     return $a;
13231: }
13232: 
13233: sub filelocation {
13234:     my ($dir,$file) = @_;
13235:     my $location;
13236:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
13237: 
13238:     if ($file =~ m-^/adm/-) {
13239: 	$file=~s-^/adm/wrapper/-/-;
13240: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
13241:     }
13242: 
13243:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
13244:         $location = $file;
13245:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
13246:         my ($udom,$uname,$filename)=
13247:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
13248:         my $home=&homeserver($uname,$udom);
13249:         my $is_me=0;
13250:         my @ids=&current_machine_ids();
13251:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
13252:         if ($is_me) {
13253:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
13254:         } else {
13255:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
13256:   	      $udom.'/'.$uname.'/'.$filename;
13257:         }
13258:     } elsif ($file =~ m-^/adm/-) {
13259: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
13260:     } else {
13261:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
13262:         $file=~s:^/(res|priv)/:/:;
13263:         my $space=$1;
13264:         if ( !( $file =~ m:^/:) ) {
13265:             $location = $dir. '/'.$file;
13266:         } else {
13267:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
13268:         }
13269:     }
13270:     $location=~s://+:/:g; # remove duplicate /
13271:     while ($location=~m{/\.\./}) {
13272: 	if ($location =~ m{/[^/]+/\.\./}) {
13273: 	    $location=~ s{/[^/]+/\.\./}{/}g;
13274: 	} else {
13275: 	    $location=~ s{/\.\./}{/}g;
13276: 	}
13277:     } #remove dir/..
13278:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
13279:     return $location;
13280: }
13281: 
13282: sub hreflocation {
13283:     my ($dir,$file)=@_;
13284:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
13285: 	$file=filelocation($dir,$file);
13286:     } elsif ($file=~m-^/adm/-) {
13287: 	$file=~s-^/adm/wrapper/-/-;
13288: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
13289:     }
13290:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
13291: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
13292:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
13293: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
13294: 	        {/uploaded/$1/$2/}x;
13295:     }
13296:     if ($file=~ m{^/userfiles/}) {
13297: 	$file =~ s{^/userfiles/}{/uploaded/};
13298:     }
13299:     return $file;
13300: }
13301: 
13302: 
13303: 
13304: 
13305: 
13306: sub current_machine_domains {
13307:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
13308: }
13309: 
13310: sub machine_domains {
13311:     my ($hostname) = @_;
13312:     my @domains;
13313:     my %hostname = &all_hostnames();
13314:     while( my($id, $name) = each(%hostname)) {
13315: #	&logthis("-$id-$name-$hostname-");
13316: 	if ($hostname eq $name) {
13317: 	    push(@domains,&host_domain($id));
13318: 	}
13319:     }
13320:     return @domains;
13321: }
13322: 
13323: sub current_machine_ids {
13324:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
13325: }
13326: 
13327: sub machine_ids {
13328:     my ($hostname) = @_;
13329:     $hostname ||= &hostname($perlvar{'lonHostID'});
13330:     my @ids;
13331:     my %name_to_host = &all_names();
13332:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
13333: 	return @{ $name_to_host{$hostname} };
13334:     }
13335:     return;
13336: }
13337: 
13338: sub additional_machine_domains {
13339:     my @domains;
13340:     open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab");
13341:     while( my $line = <$fh>) {
13342:         $line =~ s/\s//g;
13343:         push(@domains,$line);
13344:     }
13345:     return @domains;
13346: }
13347: 
13348: sub default_login_domain {
13349:     my $domain = $perlvar{'lonDefDomain'};
13350:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
13351:     foreach my $posdom (&current_machine_domains(),
13352:                         &additional_machine_domains()) {
13353:         if (lc($posdom) eq lc($testdomain)) {
13354:             $domain=$posdom;
13355:             last;
13356:         }
13357:     }
13358:     return $domain;
13359: }
13360: 
13361: sub shared_institution {
13362:     my ($dom,$lonhost) = @_;
13363:     if ($lonhost eq '') {
13364:         $lonhost = $perlvar{'lonHostID'};
13365:     }
13366:     my $same_intdom;
13367:     my $hostintdom = &internet_dom($lonhost);
13368:     if ($hostintdom ne '') {
13369:         my %iphost = &get_iphost();
13370:         my $primary_id = &domain($dom,'primary');
13371:         my $primary_ip = &get_host_ip($primary_id);
13372:         if (ref($iphost{$primary_ip}) eq 'ARRAY') {
13373:             foreach my $id (@{$iphost{$primary_ip}}) {
13374:                 my $intdom = &internet_dom($id);
13375:                 if ($intdom eq $hostintdom) {
13376:                     $same_intdom = 1;
13377:                     last;
13378:                 }
13379:             }
13380:         }
13381:     }
13382:     return $same_intdom;
13383: }
13384: 
13385: sub uses_sts {
13386:     my ($ignore_cache) = @_;
13387:     my $lonhost = $perlvar{'lonHostID'};
13388:     my $hostname = &hostname($lonhost);
13389:     my $sts_on;
13390:     if ($protocol{$lonhost} eq 'https') {
13391:         my $cachetime = 12*3600;
13392:         if (!$ignore_cache) {
13393:             ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
13394:             if (defined($cached)) {
13395:                 return $sts_on;
13396:             }
13397:         }
13398:         my $ua=new LWP::UserAgent;
13399:         my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
13400:         my $request=new HTTP::Request('HEAD',$url);
13401:         my $response=$ua->request($request);
13402:         if ($response->is_success) {
13403:             my $has_sts = $response->header('Strict-Transport-Security');
13404:             if ($has_sts eq '') {
13405:                 $sts_on = 0;
13406:             } else {
13407:                 if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
13408:                     my $maxage = $1;
13409:                     if ($maxage) {
13410:                         $sts_on = 1;
13411:                     } else {
13412:                         $sts_on = 0;
13413:                     }
13414:                 } else {
13415:                     $sts_on = 0;
13416:                 }
13417:             }
13418:             return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
13419:         }
13420:     }
13421:     return;
13422: }
13423: 
13424: sub get_requestor_ip {
13425:     my ($r,$nolookup,$noproxy) = @_;
13426:     my $from_ip;
13427:     if (ref($r)) {
13428:         $from_ip = $r->get_remote_host($nolookup);
13429:     } else {
13430:         $from_ip = $ENV{'REMOTE_ADDR'};
13431:     }
13432:     return $from_ip;
13433: }
13434: 
13435: # ------------------------------------------------------------- Declutters URLs
13436: 
13437: sub declutter {
13438:     my $thisfn=shift;
13439:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
13440:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
13441:         $thisfn=~s{^/home/httpd/html}{};
13442:     }
13443:     $thisfn=~s/^\///;
13444:     $thisfn=~s|^adm/wrapper/||;
13445:     $thisfn=~s|^adm/coursedocs/showdoc/||;
13446:     $thisfn=~s/^res\///;
13447:     $thisfn=~s/^priv\///;
13448:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
13449:         $thisfn=~s/\?.+$//;
13450:     }
13451:     return $thisfn;
13452: }
13453: 
13454: # ------------------------------------------------------------- Clutter up URLs
13455: 
13456: sub clutter {
13457:     my $thisfn='/'.&declutter(shift);
13458:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
13459: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
13460:        $thisfn='/res'.$thisfn; 
13461:     }
13462:     if ($thisfn !~m|^/adm|) {
13463: 	if ($thisfn =~ m|^/ext/|) {
13464: 	    $thisfn='/adm/wrapper'.$thisfn;
13465: 	} else {
13466: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
13467: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
13468: 	    if ($embstyle eq 'ssi'
13469: 		|| ($embstyle eq 'hdn')
13470: 		|| ($embstyle eq 'rat')
13471: 		|| ($embstyle eq 'prv')
13472: 		|| ($embstyle eq 'ign')) {
13473: 		#do nothing with these
13474: 	    } elsif (($embstyle eq 'img') 
13475: 		|| ($embstyle eq 'emb')
13476: 		|| ($embstyle eq 'wrp')) {
13477: 		$thisfn='/adm/wrapper'.$thisfn;
13478: 	    } elsif ($embstyle eq 'unk'
13479: 		     && $thisfn!~/\.(sequence|page)$/) {
13480: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
13481: 	    } else {
13482: #		&logthis("Got a blank emb style");
13483: 	    }
13484: 	}
13485:     }
13486:     return $thisfn;
13487: }
13488: 
13489: sub clutter_with_no_wrapper {
13490:     my $uri = &clutter(shift);
13491:     if ($uri =~ m-^/adm/-) {
13492: 	$uri =~ s-^/adm/wrapper/-/-;
13493: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
13494:     }
13495:     return $uri;
13496: }
13497: 
13498: sub freeze_escape {
13499:     my ($value)=@_;
13500:     if (ref($value)) {
13501: 	$value=&nfreeze($value);
13502: 	return '__FROZEN__'.&escape($value);
13503:     }
13504:     return &escape($value);
13505: }
13506: 
13507: 
13508: sub thaw_unescape {
13509:     my ($value)=@_;
13510:     if ($value =~ /^__FROZEN__/) {
13511: 	substr($value,0,10,undef);
13512: 	$value=&unescape($value);
13513: 	return &thaw($value);
13514:     }
13515:     return &unescape($value);
13516: }
13517: 
13518: sub correct_line_ends {
13519:     my ($result)=@_;
13520:     $$result =~s/\r\n/\n/mg;
13521:     $$result =~s/\r/\n/mg;
13522: }
13523: # ================================================================ Main Program
13524: 
13525: sub goodbye {
13526:    &logthis("Starting Shut down");
13527: #not converted to using infrastruture and probably shouldn't be
13528:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
13529: #converted
13530: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
13531:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
13532: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
13533: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
13534: #1.1 only
13535: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
13536: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
13537: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
13538: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
13539:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
13540:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
13541:    &logthis(sprintf("%-20s is %s",'hits',$hits));
13542:    &flushcourselogs();
13543:    &logthis("Shutting down");
13544: }
13545: 
13546: sub get_dns {
13547:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
13548:     if (!$ignore_cache) {
13549: 	my ($content,$cached)=
13550: 	    &Apache::lonnet::is_cached_new('dns',$url);
13551: 	if ($cached) {
13552: 	    &$func($content,$hashref);
13553: 	    return;
13554: 	}
13555:     }
13556: 
13557:     my %alldns;
13558:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
13559:         foreach my $dns (<$config>) {
13560: 	    next if ($dns !~ /^\^(\S*)/x);
13561:             my $line = $1;
13562:             my ($host,$protocol) = split(/:/,$line);
13563:             if ($protocol ne 'https') {
13564:                 $protocol = 'http';
13565:             }
13566: 	    $alldns{$host} = $protocol;
13567:         }
13568:         close($config);
13569:     }
13570:     while (%alldns) {
13571: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
13572: 	my $ua=new LWP::UserAgent;
13573:         $ua->timeout(30);
13574: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
13575: 	my $response=$ua->request($request);
13576:         delete($alldns{$dns});
13577: 	next if ($response->is_error());
13578: 	my @content = split("\n",$response->content);
13579:         unless ($nocache) {
13580: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
13581:         }
13582: 	&$func(\@content,$hashref);
13583: 	return;
13584:     }
13585:     my $which = (split('/',$url))[3];
13586:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
13587:     if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
13588:         my @content = <$config>;
13589:         &$func(\@content,$hashref);
13590:     }
13591:     return;
13592: }
13593: 
13594: # ------------------------------------------------------Get DNS checksums file
13595: sub parse_dns_checksums_tab {
13596:     my ($lines,$hashref) = @_;
13597:     my $lonhost = $perlvar{'lonHostID'};
13598:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
13599:     my $loncaparev = &get_server_loncaparev($machine_dom);
13600:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
13601:     my $webconfdir = '/etc/httpd/conf';
13602:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
13603:         $webconfdir = '/etc/apache2';
13604:     } elsif ($distro =~ /^sles(\d+)$/) {
13605:         if ($1 >= 10) {
13606:             $webconfdir = '/etc/apache2';
13607:         }
13608:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
13609:         if ($1 >= 10.0) {
13610:             $webconfdir = '/etc/apache2';
13611:         }
13612:     }
13613:     my ($release,$timestamp) = split(/\-/,$loncaparev);
13614:     my (%chksum,%revnum);
13615:     if (ref($lines) eq 'ARRAY') {
13616:         chomp(@{$lines});
13617:         my $version = shift(@{$lines});
13618:         if ($version eq $release) {
13619:             foreach my $line (@{$lines}) {
13620:                 my ($file,$version,$shasum) = split(/,/,$line);
13621:                 if ($file =~ m{^/etc/httpd/conf}) {
13622:                     if ($webconfdir eq '/etc/apache2') {
13623:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
13624:                     }
13625:                 }
13626:                 $chksum{$file} = $shasum;
13627:                 $revnum{$file} = $version;
13628:             }
13629:             if (ref($hashref) eq 'HASH') {
13630:                 %{$hashref} = (
13631:                                 sums     => \%chksum,
13632:                                 versions => \%revnum,
13633:                               );
13634:             }
13635:         }
13636:     }
13637:     return;
13638: }
13639: 
13640: sub fetch_dns_checksums {
13641:     my %checksums;
13642:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
13643:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
13644:     my ($release,$timestamp) = split(/\-/,$loncaparev);
13645:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
13646:              \%checksums);
13647:     return \%checksums;
13648: }
13649: 
13650: # ------------------------------------------------------------ Read domain file
13651: {
13652:     my $loaded;
13653:     my %domain;
13654: 
13655:     sub parse_domain_tab {
13656: 	my ($lines) = @_;
13657: 	foreach my $line (@$lines) {
13658: 	    next if ($line =~ /^(\#|\s*$ )/x);
13659: 
13660: 	    chomp($line);
13661: 	    my ($name,@elements) = split(/:/,$line,9);
13662: 	    my %this_domain;
13663: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
13664: 			       'lang_def', 'city', 'longi', 'lati',
13665: 			       'primary') {
13666: 		$this_domain{$field} = shift(@elements);
13667: 	    }
13668: 	    $domain{$name} = \%this_domain;
13669: 	}
13670:     }
13671: 
13672:     sub reset_domain_info {
13673: 	undef($loaded);
13674: 	undef(%domain);
13675:     }
13676: 
13677:     sub load_domain_tab {
13678: 	my ($ignore_cache,$nocache) = @_;
13679: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
13680: 	my $fh;
13681: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
13682: 	    my @lines = <$fh>;
13683: 	    &parse_domain_tab(\@lines);
13684: 	}
13685: 	close($fh);
13686: 	$loaded = 1;
13687:     }
13688: 
13689:     sub domain {
13690: 	&load_domain_tab() if (!$loaded);
13691: 
13692: 	my ($name,$what) = @_;
13693: 	return if ( !exists($domain{$name}) );
13694: 
13695: 	if (!$what) {
13696: 	    return $domain{$name}{'description'};
13697: 	}
13698: 	return $domain{$name}{$what};
13699:     }
13700: 
13701:     sub domain_info {
13702:         &load_domain_tab() if (!$loaded);
13703:         return %domain;
13704:     }
13705: 
13706: }
13707: 
13708: 
13709: # ------------------------------------------------------------- Read hosts file
13710: {
13711:     my %hostname;
13712:     my %hostdom;
13713:     my %libserv;
13714:     my $loaded;
13715:     my %name_to_host;
13716:     my %internetdom;
13717:     my %LC_dns_serv;
13718: 
13719:     sub parse_hosts_tab {
13720: 	my ($file) = @_;
13721: 	foreach my $configline (@$file) {
13722: 	    next if ($configline =~ /^(\#|\s*$ )/x);
13723:             chomp($configline);
13724: 	    if ($configline =~ /^\^/) {
13725:                 if ($configline =~ /^\^([\w.\-]+)/) {
13726:                     $LC_dns_serv{$1} = 1;
13727:                 }
13728:                 next;
13729:             }
13730: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
13731: 	    $name=~s/\s//g;
13732: 	    if ($id && $domain && $role && $name) {
13733:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
13734:                     my $curr = $hostname{$id};
13735:                     my $skip;
13736:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
13737:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
13738:                             $skip = 1;
13739:                         } else {
13740:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
13741:                         }
13742:                     }
13743:                     unless ($skip) {
13744:                         push(@{$name_to_host{$name}},$id);
13745:                     }
13746:                 } else {
13747:                     push(@{$name_to_host{$name}},$id);
13748:                 }
13749: 		$hostname{$id}=$name;
13750: 		$hostdom{$id}=$domain;
13751: 		if ($role eq 'library') { $libserv{$id}=$name; }
13752:                 if (defined($protocol)) {
13753:                     if ($protocol eq 'https') {
13754:                         $protocol{$id} = $protocol;
13755:                     } else {
13756:                         $protocol{$id} = 'http'; 
13757:                     }
13758:                 } else {
13759:                     $protocol{$id} = 'http';
13760:                 }
13761:                 if (defined($intdom)) {
13762:                     $internetdom{$id} = $intdom;
13763:                 }
13764: 	    }
13765: 	}
13766:     }
13767:     
13768:     sub reset_hosts_info {
13769: 	&purge_remembered();
13770: 	&reset_domain_info();
13771: 	&reset_hosts_ip_info();
13772: 	undef(%name_to_host);
13773: 	undef(%hostname);
13774: 	undef(%hostdom);
13775: 	undef(%libserv);
13776: 	undef($loaded);
13777:     }
13778: 
13779:     sub load_hosts_tab {
13780: 	my ($ignore_cache,$nocache) = @_;
13781: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
13782: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
13783: 	my @config = <$config>;
13784: 	&parse_hosts_tab(\@config);
13785: 	close($config);
13786: 	$loaded=1;
13787:     }
13788: 
13789:     sub hostname {
13790: 	&load_hosts_tab() if (!$loaded);
13791: 
13792: 	my ($lonid) = @_;
13793: 	return $hostname{$lonid};
13794:     }
13795: 
13796:     sub all_hostnames {
13797: 	&load_hosts_tab() if (!$loaded);
13798: 
13799: 	return %hostname;
13800:     }
13801: 
13802:     sub all_names {
13803:         my ($ignore_cache,$nocache) = @_;
13804: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
13805: 
13806: 	return %name_to_host;
13807:     }
13808: 
13809:     sub all_host_domain {
13810:         &load_hosts_tab() if (!$loaded);
13811:         return %hostdom;
13812:     }
13813: 
13814:     sub is_library {
13815: 	&load_hosts_tab() if (!$loaded);
13816: 
13817: 	return exists($libserv{$_[0]});
13818:     }
13819: 
13820:     sub all_library {
13821: 	&load_hosts_tab() if (!$loaded);
13822: 
13823: 	return %libserv;
13824:     }
13825: 
13826:     sub unique_library {
13827: 	#2x reverse removes all hostnames that appear more than once
13828:         my %unique = reverse &all_library();
13829:         return reverse %unique;
13830:     }
13831: 
13832:     sub get_servers {
13833: 	&load_hosts_tab() if (!$loaded);
13834: 
13835: 	my ($domain,$type) = @_;
13836: 	my %possible_hosts = ($type eq 'library') ? %libserv
13837: 	                                          : %hostname;
13838: 	my %result;
13839: 	if (ref($domain) eq 'ARRAY') {
13840: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
13841: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
13842: 		    $result{$host} = $hostname;
13843: 		}
13844: 	    }
13845: 	} else {
13846: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
13847: 		if ($hostdom{$host} eq $domain) {
13848: 		    $result{$host} = $hostname;
13849: 		}
13850: 	    }
13851: 	}
13852: 	return %result;
13853:     }
13854: 
13855:     sub get_unique_servers {
13856:         my %unique = reverse &get_servers(@_);
13857: 	return reverse %unique;
13858:     }
13859: 
13860:     sub host_domain {
13861: 	&load_hosts_tab() if (!$loaded);
13862: 
13863: 	my ($lonid) = @_;
13864: 	return $hostdom{$lonid};
13865:     }
13866: 
13867:     sub all_domains {
13868: 	&load_hosts_tab() if (!$loaded);
13869: 
13870: 	my %seen;
13871: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
13872: 	return @uniq;
13873:     }
13874: 
13875:     sub internet_dom {
13876:         &load_hosts_tab() if (!$loaded);
13877: 
13878:         my ($lonid) = @_;
13879:         return $internetdom{$lonid};
13880:     }
13881: 
13882:     sub is_LC_dns {
13883:         &load_hosts_tab() if (!$loaded);
13884: 
13885:         my ($hostname) = @_;
13886:         return exists($LC_dns_serv{$hostname});
13887:     }
13888: 
13889: }
13890: 
13891: { 
13892:     my %iphost;
13893:     my %name_to_ip;
13894:     my %lonid_to_ip;
13895: 
13896:     sub get_hosts_from_ip {
13897: 	my ($ip) = @_;
13898: 	my %iphosts = &get_iphost();
13899: 	if (ref($iphosts{$ip})) {
13900: 	    return @{$iphosts{$ip}};
13901: 	}
13902: 	return;
13903:     }
13904:     
13905:     sub reset_hosts_ip_info {
13906: 	undef(%iphost);
13907: 	undef(%name_to_ip);
13908: 	undef(%lonid_to_ip);
13909:     }
13910: 
13911:     sub get_host_ip {
13912: 	my ($lonid) = @_;
13913: 	if (exists($lonid_to_ip{$lonid})) {
13914: 	    return $lonid_to_ip{$lonid};
13915: 	}
13916: 	my $name=&hostname($lonid);
13917:    	my $ip = gethostbyname($name);
13918: 	return if (!$ip || length($ip) ne 4);
13919: 	$ip=inet_ntoa($ip);
13920: 	$name_to_ip{$name}   = $ip;
13921: 	$lonid_to_ip{$lonid} = $ip;
13922: 	return $ip;
13923:     }
13924:     
13925:     sub get_iphost {
13926: 	my ($ignore_cache,$nocache) = @_;
13927: 
13928: 	if (!$ignore_cache) {
13929: 	    if (%iphost) {
13930: 		return %iphost;
13931: 	    }
13932: 	    my ($ip_info,$cached)=
13933: 		&Apache::lonnet::is_cached_new('iphost','iphost');
13934: 	    if ($cached) {
13935: 		%iphost      = %{$ip_info->[0]};
13936: 		%name_to_ip  = %{$ip_info->[1]};
13937: 		%lonid_to_ip = %{$ip_info->[2]};
13938: 		return %iphost;
13939: 	    }
13940: 	}
13941: 
13942: 	# get yesterday's info for fallback
13943: 	my %old_name_to_ip;
13944: 	my ($ip_info,$cached)=
13945: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
13946: 	if ($cached) {
13947: 	    %old_name_to_ip = %{$ip_info->[1]};
13948: 	}
13949: 
13950: 	my %name_to_host = &all_names($ignore_cache,$nocache);
13951: 	foreach my $name (keys(%name_to_host)) {
13952: 	    my $ip;
13953: 	    if (!exists($name_to_ip{$name})) {
13954: 		$ip = gethostbyname($name);
13955: 		if (!$ip || length($ip) ne 4) {
13956: 		    if (defined($old_name_to_ip{$name})) {
13957: 			$ip = $old_name_to_ip{$name};
13958: 			&logthis("Can't find $name defaulting to old $ip");
13959: 		    } else {
13960: 			&logthis("Name $name no IP found");
13961: 			next;
13962: 		    }
13963: 		} else {
13964: 		    $ip=inet_ntoa($ip);
13965: 		}
13966: 		$name_to_ip{$name} = $ip;
13967: 	    } else {
13968: 		$ip = $name_to_ip{$name};
13969: 	    }
13970: 	    foreach my $id (@{ $name_to_host{$name} }) {
13971: 		$lonid_to_ip{$id} = $ip;
13972: 	    }
13973: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
13974: 	}
13975:         unless ($nocache) {
13976: 	    &do_cache_new('iphost','iphost',
13977: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
13978: 		          48*60*60);
13979:         }
13980: 
13981: 	return %iphost;
13982:     }
13983: 
13984:     #
13985:     #  Given a DNS returns the loncapa host name for that DNS 
13986:     # 
13987:     sub host_from_dns {
13988:         my ($dns) = @_;
13989:         my @hosts;
13990:         my $ip;
13991: 
13992:         if (exists($name_to_ip{$dns})) {
13993:             $ip = $name_to_ip{$dns};
13994:         }
13995:         if (!$ip) {
13996:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
13997:             if (length($ip) == 4) { 
13998: 	        $ip   = &IO::Socket::inet_ntoa($ip);
13999:             }
14000:         }
14001:         if ($ip) {
14002: 	    @hosts = get_hosts_from_ip($ip);
14003: 	    return $hosts[0];
14004:         }
14005:         return undef;
14006:     }
14007: 
14008:     sub get_internet_names {
14009:         my ($lonid) = @_;
14010:         return if ($lonid eq '');
14011:         my ($idnref,$cached)=
14012:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
14013:         if ($cached) {
14014:             return $idnref;
14015:         }
14016:         my $ip = &get_host_ip($lonid);
14017:         my @hosts = &get_hosts_from_ip($ip);
14018:         my %iphost = &get_iphost();
14019:         my (@idns,%seen);
14020:         foreach my $id (@hosts) {
14021:             my $dom = &host_domain($id);
14022:             my $prim_id = &domain($dom,'primary');
14023:             my $prim_ip = &get_host_ip($prim_id);
14024:             next if ($seen{$prim_ip});
14025:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
14026:                 foreach my $id (@{$iphost{$prim_ip}}) {
14027:                     my $intdom = &internet_dom($id);
14028:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
14029:                         push(@idns,$intdom);
14030:                     }
14031:                 }
14032:             }
14033:             $seen{$prim_ip} = 1;
14034:         }
14035:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
14036:     }
14037: 
14038: }
14039: 
14040: sub all_loncaparevs {
14041:     return qw(1.1 1.2 1.3 2.0 2.1 2.2 2.3 2.4 2.5 2.6 2.7 2.8 2.9 2.10 2.11);
14042: }
14043: 
14044: # ------------------------------------------------------- Read loncaparev table
14045: {
14046:     sub load_loncaparevs {
14047:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
14048:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
14049:                 while (my $configline=<$config>) {
14050:                     chomp($configline);
14051:                     my ($hostid,$loncaparev)=split(/:/,$configline);
14052:                     $loncaparevs{$hostid}=$loncaparev;
14053:                 }
14054:                 close($config);
14055:             }
14056:         }
14057:     }
14058: }
14059: 
14060: # ----------------------------------------------------- Read serverhostID table
14061: {
14062:     sub load_serverhomeIDs {
14063:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
14064:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
14065:                 while (my $configline=<$config>) {
14066:                     chomp($configline);
14067:                     my ($name,$id)=split(/:/,$configline);
14068:                     $serverhomeIDs{$name}=$id;
14069:                 }
14070:                 close($config);
14071:             }
14072:         }
14073:     }
14074: }
14075: 
14076: 
14077: BEGIN {
14078: 
14079: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
14080:     unless ($readit) {
14081: {
14082:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
14083:     %perlvar = (%perlvar,%{$configvars});
14084: }
14085: 
14086: 
14087: # ------------------------------------------------------ Read spare server file
14088: {
14089:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
14090: 
14091:     while (my $configline=<$config>) {
14092:        chomp($configline);
14093:        if ($configline) {
14094: 	   my ($host,$type) = split(':',$configline,2);
14095: 	   if (!defined($type) || $type eq '') { $type = 'default' };
14096: 	   push(@{ $spareid{$type} }, $host);
14097:        }
14098:     }
14099:     close($config);
14100: }
14101: # ------------------------------------------------------------ Read permissions
14102: {
14103:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
14104: 
14105:     while (my $configline=<$config>) {
14106: 	chomp($configline);
14107: 	if ($configline) {
14108: 	    my ($role,$perm)=split(/ /,$configline);
14109: 	    if ($perm ne '') { $pr{$role}=$perm; }
14110: 	}
14111:     }
14112:     close($config);
14113: }
14114: 
14115: # -------------------------------------------- Read plain texts for permissions
14116: {
14117:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
14118: 
14119:     while (my $configline=<$config>) {
14120: 	chomp($configline);
14121: 	if ($configline) {
14122: 	    my ($short,@plain)=split(/:/,$configline);
14123:             %{$prp{$short}} = ();
14124: 	    if (@plain > 0) {
14125:                 $prp{$short}{'std'} = $plain[0];
14126:                 for (my $i=1; $i<@plain; $i++) {
14127:                     $prp{$short}{'alt'.$i} = $plain[$i];  
14128:                 }
14129:             }
14130: 	}
14131:     }
14132:     close($config);
14133: }
14134: 
14135: # ---------------------------------------------------------- Read package table
14136: {
14137:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
14138: 
14139:     while (my $configline=<$config>) {
14140: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
14141: 	chomp($configline);
14142: 	my ($short,$plain)=split(/:/,$configline);
14143: 	my ($pack,$name)=split(/\&/,$short);
14144: 	if ($plain ne '') {
14145: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
14146: 	    $packagetab{$short}=$plain; 
14147: 	}
14148:     }
14149:     close($config);
14150: }
14151: 
14152: # --------------------------------------------------------- Read loncaparev table
14153: 
14154: &load_loncaparevs();
14155: 
14156: # ------------------------------------------------------- Read serverhostID table
14157: 
14158: &load_serverhomeIDs();
14159: 
14160: # ---------------------------------------------------------- Read releaseslist XML
14161: {
14162:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
14163:     if (-e $file) {
14164:         my $parser = HTML::LCParser->new($file);
14165:         while (my $token = $parser->get_token()) {
14166:             if ($token->[0] eq 'S') {
14167:                 my $item = $token->[1];
14168:                 my $name = $token->[2]{'name'};
14169:                 my $value = $token->[2]{'value'};
14170:                 if ($item ne '' && $name ne '' && $value ne '') {
14171:                     my $release = $parser->get_text();
14172:                     $release =~ s/(^\s*|\s*$ )//gx;
14173:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
14174:                 }
14175:             }
14176:         }
14177:     }
14178: }
14179: 
14180: # ---------------------------------------------------------- Read managers table
14181: {
14182:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
14183:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
14184:             while (my $configline=<$config>) {
14185:                 chomp($configline);
14186:                 next if ($configline =~ /^\#/);
14187:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
14188:                     $managerstab{$configline} = 1;
14189:                 }
14190:             }
14191:             close($config);
14192:         }
14193:     }
14194: }
14195: 
14196: # ------------- set up temporary directory
14197: {
14198:     $tmpdir = LONCAPA::tempdir();
14199: 
14200: }
14201: 
14202: # ------------- set default texengine (domain default overrides this)
14203: {
14204:     $deftex = LONCAPA::texengine();
14205: }
14206: 
14207: # ------------- set default minimum length for passwords for internal auth users
14208: {
14209:     $passwdmin = LONCAPA::passwd_min();
14210: }
14211: 
14212: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
14213: 				'compress_threshold'=> 20_000,
14214:  			        });
14215: 
14216: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
14217: $dumpcount=0;
14218: $locknum=0;
14219: 
14220: &logtouch();
14221: &logthis('<font color="yellow">INFO: Read configuration</font>');
14222: $readit=1;
14223:     {
14224: 	use integer;
14225: 	my $test=(2**32)+1;
14226: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
14227: 	&logthis(" Detected 64bit platform ($_64bit)");
14228:     }
14229: }
14230: }
14231: 
14232: 1;
14233: __END__
14234: 
14235: =pod
14236: 
14237: =head1 NAME
14238: 
14239: Apache::lonnet - Subroutines to ask questions about things in the network.
14240: 
14241: =head1 SYNOPSIS
14242: 
14243: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
14244: 
14245:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
14246: 
14247: Common parameters:
14248: 
14249: =over 4
14250: 
14251: =item *
14252: 
14253: $uname : an internal username (if $cname expecting a course Id specifically)
14254: 
14255: =item *
14256: 
14257: $udom : a domain (if $cdom expecting a course's domain specifically)
14258: 
14259: =item *
14260: 
14261: $symb : a resource instance identifier
14262: 
14263: =item *
14264: 
14265: $namespace : the name of a .db file that contains the data needed or
14266: being set.
14267: 
14268: =back
14269: 
14270: =head1 OVERVIEW
14271: 
14272: lonnet provides subroutines which interact with the
14273: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
14274: about classes, users, and resources.
14275: 
14276: For many of these objects you can also use this to store data about
14277: them or modify them in various ways.
14278: 
14279: =head2 Symbs
14280: 
14281: To identify a specific instance of a resource, LON-CAPA uses symbols
14282: or "symbs"X<symb>. These identifiers are built from the URL of the
14283: map, the resource number of the resource in the map, and the URL of
14284: the resource itself. The latter is somewhat redundant, but might help
14285: if maps change.
14286: 
14287: An example is
14288: 
14289:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
14290: 
14291: The respective map entry is
14292: 
14293:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
14294:   title="Problem 2">
14295:  </resource>
14296: 
14297: Symbs are used by the random number generator, as well as to store and
14298: restore data specific to a certain instance of for example a problem.
14299: 
14300: =head2 Storing And Retrieving Data
14301: 
14302: X<store()>X<cstore()>X<restore()>Three of the most important functions
14303: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
14304: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
14305: is is the non-critical message twin of cstore. These functions are for
14306: handlers to store a perl hash to a user's permanent data space in an
14307: easy manner, and to retrieve it again on another call. It is expected
14308: that a handler would use this once at the beginning to retrieve data,
14309: and then again once at the end to send only the new data back.
14310: 
14311: The data is stored in the user's data directory on the user's
14312: homeserver under the ID of the course.
14313: 
14314: The hash that is returned by restore will have all of the previous
14315: value for all of the elements of the hash.
14316: 
14317: Example:
14318: 
14319:  #creating a hash
14320:  my %hash;
14321:  $hash{'foo'}='bar';
14322: 
14323:  #storing it
14324:  &Apache::lonnet::cstore(\%hash);
14325: 
14326:  #changing a value
14327:  $hash{'foo'}='notbar';
14328: 
14329:  #adding a new value
14330:  $hash{'bar'}='foo';
14331:  &Apache::lonnet::cstore(\%hash);
14332: 
14333:  #retrieving the hash
14334:  my %history=&Apache::lonnet::restore();
14335: 
14336:  #print the hash
14337:  foreach my $key (sort(keys(%history))) {
14338:    print("\%history{$key} = $history{$key}");
14339:  }
14340: 
14341: Will print out:
14342: 
14343:  %history{1:foo} = bar
14344:  %history{1:keys} = foo:timestamp
14345:  %history{1:timestamp} = 990455579
14346:  %history{2:bar} = foo
14347:  %history{2:foo} = notbar
14348:  %history{2:keys} = foo:bar:timestamp
14349:  %history{2:timestamp} = 990455580
14350:  %history{bar} = foo
14351:  %history{foo} = notbar
14352:  %history{timestamp} = 990455580
14353:  %history{version} = 2
14354: 
14355: Note that the special hash entries C<keys>, C<version> and
14356: C<timestamp> were added to the hash. C<version> will be equal to the
14357: total number of versions of the data that have been stored. The
14358: C<timestamp> attribute will be the UNIX time the hash was
14359: stored. C<keys> is available in every historical section to list which
14360: keys were added or changed at a specific historical revision of a
14361: hash.
14362: 
14363: B<Warning>: do not store the hash that restore returns directly. This
14364: will cause a mess since it will restore the historical keys as if the
14365: were new keys. I.E. 1:foo will become 1:1:foo etc.
14366: 
14367: Calling convention:
14368: 
14369:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
14370:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
14371: 
14372: For more detailed information, see lonnet specific documentation.
14373: 
14374: =head1 RETURN MESSAGES
14375: 
14376: =over 4
14377: 
14378: =item * B<con_lost>: unable to contact remote host
14379: 
14380: =item * B<con_delayed>: unable to contact remote host, message will be delivered
14381: when the connection is brought back up
14382: 
14383: =item * B<con_failed>: unable to contact remote host and unable to save message
14384: for later delivery
14385: 
14386: =item * B<error:>: an error a occurred, a description of the error follows the :
14387: 
14388: =item * B<no_such_host>: unable to fund a host associated with the user/domain
14389: that was requested
14390: 
14391: =back
14392: 
14393: =head1 PUBLIC SUBROUTINES
14394: 
14395: =head2 Session Environment Functions
14396: 
14397: =over 4
14398: 
14399: =item * 
14400: X<appenv()>
14401: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
14402: the user envirnoment file, and will be restored for each access this
14403: user makes during this session, also modifies the %env for the current
14404: process. Optional rolesarrayref - if defined contains a reference to an array
14405: of roles which are exempt from the restriction on modifying user.role entries 
14406: in the user's environment.db and in %env.    
14407: 
14408: =item *
14409: X<delenv()>
14410: B<delenv($delthis,$regexp)>: removes all items from the session
14411: environment file that begin with $delthis. If the 
14412: optional second arg - $regexp - is true, $delthis is treated as a 
14413: regular expression, otherwise \Q$delthis\E is used. 
14414: The values are also deleted from the current processes %env.
14415: 
14416: =item * get_env_multiple($name) 
14417: 
14418: gets $name from the %env hash, it seemlessly handles the cases where multiple
14419: values may be defined and end up as an array ref.
14420: 
14421: returns an array of values
14422: 
14423: =back
14424: 
14425: =head2 User Information
14426: 
14427: =over 4
14428: 
14429: =item *
14430: X<queryauthenticate()>
14431: B<queryauthenticate($uname,$udom)>: try to determine user's current 
14432: authentication scheme
14433: 
14434: =item *
14435: X<authenticate()>
14436: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
14437: authenticate user from domain's lib servers (first use the current
14438: one). C<$upass> should be the users password.
14439: $checkdefauth is optional (value is 1 if a check should be made to
14440:    authenticate user using default authentication method, and allow
14441:    account creation if username does not have account in the domain).
14442: $clientcancheckhost is optional (value is 1 if checking whether the
14443:    server can host will occur on the client side in lonauth.pm).   
14444: 
14445: =item *
14446: X<homeserver()>
14447: B<homeserver($uname,$udom)>: find the server which has
14448: the user's directory and files (there must be only one), this caches
14449: the answer, and also caches if there is a borken connection.
14450: 
14451: =item *
14452: X<idget()>
14453: B<idget($udom,@ids)>: find the usernames behind a list of IDs
14454: (IDs are a unique resource in a domain, there must be only 1 ID per
14455: username, and only 1 username per ID in a specific domain) (returns
14456: hash: id=>name,id=>name)
14457: 
14458: =item *
14459: X<idrget()>
14460: B<idrget($udom,@unames)>: find the IDs behind a list of
14461: usernames (returns hash: name=>id,name=>id)
14462: 
14463: =item *
14464: X<idput()>
14465: B<idput($udom,%ids)>: store away a list of names and associated IDs
14466: 
14467: =item *
14468: X<rolesinit()>
14469: B<rolesinit($udom,$username)>: get user privileges.
14470: returns user role, first access and timer interval hashes
14471: 
14472: =item *
14473: X<privileged()>
14474: B<privileged($username,$domain)>: returns a true if user has a
14475: privileged and active role (i.e. su or dc), false otherwise.
14476: 
14477: =item *
14478: X<getsection()>
14479: B<getsection($udom,$uname,$cname)>: finds the section of student in the
14480: course $cname, return section name/number or '' for "not in course"
14481: and '-1' for "no section"
14482: 
14483: =item *
14484: X<userenvironment()>
14485: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
14486: passed in @what from the requested user's environment, returns a hash
14487: 
14488: =item * 
14489: X<userlog_query()>
14490: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
14491: activity.log file. %filters defines filters applied when parsing the
14492: log file. These can be start or end timestamps, or the type of action
14493: - log to look for Login or Logout events, check for Checkin or
14494: Checkout, role for role selection. The response is in the form
14495: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
14496: escaped strings of the action recorded in the activity.log file.
14497: 
14498: =back
14499: 
14500: =head2 User Roles
14501: 
14502: =over 4
14503: 
14504: =item *
14505: 
14506: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
14507: returns codes for allowed actions.
14508: 
14509: The first argument is required, all others are optional.
14510: 
14511: $priv is the privilege being checked.
14512: $uri contains additional information about what is being checked for access (e.g.,
14513: URL, course ID etc.).
14514: $symb is the unique resource instance identifier in a course; if needed,
14515: but not provided, it will be retrieved via a call to &symbread().
14516: $role is the role for which a priv is being checked (only used if priv is evb).
14517: $clientip is the user's IP address (only used when checking for access to portfolio
14518: files).
14519: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
14520: prevents recursive calls to &allowed.
14521: 
14522:  F: full access
14523:  U,I,K: authentication modes (cxx only)
14524:  '': forbidden
14525:  1: user needs to choose course
14526:  2: browse allowed
14527:  A: passphrase authentication needed
14528:  B: access temporarily blocked because of a blocking event in a course.
14529: 
14530: =item *
14531: 
14532: constructaccess($url,$setpriv) : check for access to construction space URL
14533: 
14534: See if the owner domain and name in the URL match those in the
14535: expected environment.  If so, return three element list
14536: ($ownername,$ownerdomain,$ownerhome).
14537: 
14538: Otherwise return the null string.
14539: 
14540: If second argument 'setpriv' is true, it assigns the privileges,
14541: and returns the same three element list, unless the owner has
14542: blocked "ad hoc" Domain Coordinator access to the Author Space,
14543: in which case the null string is returned.
14544: 
14545: =item *
14546: 
14547: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
14548: define a custom role rolename set privileges in format of lonTabs/roles.tab
14549: for system, domain, and course level. $uname and $udom are optional (current
14550: user's username and domain will be used when either of $uname or $udom are absent.
14551: 
14552: =item *
14553: 
14554: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
14555: (rolesplain.tab); plain text explanation of a user role term.
14556: $type is Course (default) or Community.
14557: If $forcedefault evaluates to true, text returned will be default 
14558: text for $type. Otherwise, if this is a course, the text returned 
14559: will be a custom name for the role (if defined in the course's 
14560: environment).  If no custom name is defined the default is returned.
14561:    
14562: =item *
14563: 
14564: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
14565: All arguments are optional. Returns a hash of a roles, either for
14566: co-author/assistant author roles for a user's Construction Space
14567: (default), or if $context is 'userroles', roles for the user himself,
14568: In the hash, keys are set to colon-separated $uname,$udom,$role, and
14569: (optionally) if $withsec is true, a fourth colon-separated item - $section.
14570: For each key, value is set to colon-separated start and end times for
14571: the role.  If no username and domain are specified, will default to
14572: current user/domain. Types, roles, and roledoms are references to arrays
14573: of role statuses (active, future or previous), roles 
14574: (e.g., cc,in, st etc.) and domains of the roles which can be used
14575: to restrict the list of roles reported. If no array ref is 
14576: provided for types, will default to return only active roles.
14577: 
14578: =item *
14579: 
14580: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
14581: user: $uname:$udom has a role in the course: $cdom_$cnum.
14582: 
14583: Additional optional arguments are: $type (if role checking is to be restricted
14584: to certain user status types -- previous (expired roles), active (currently
14585: available roles) or future (roles available in the future), and
14586: $hideprivileged -- if true will not report course roles for users who
14587: have active Domain Coordinator role in course's domain or in additional
14588: domains (specified in 'Domains to check for privileged users' in course
14589: environment -- set via:  Course Settings -> Classlists and staff listing).
14590: 
14591: =item *
14592: 
14593: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
14594: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
14595: $possdomains and $possroles are optional array refs -- to domains to check and
14596: roles to check.  If $possdomains is not specified, a dump will be done of the
14597: users' roles.db to check for a dc or su role in any domain. This can be
14598: time consuming if &privileged is called repeatedly (e.g., when displaying a
14599: classlist), so in such cases, supplying a $possdomains array is preferred, as
14600: this then allows &privileged_by_domain() to be used, which caches the identity
14601: of privileged users, eliminating the need for repeated calls to &dump().
14602: 
14603: =item *
14604: 
14605: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
14606: where the outer hash keys are domains specified in the $possdomains array ref,
14607: next inner hash keys are privileged roles specified in the $roles array ref,
14608: and the innermost hash contains key = value pairs for username:domain = end:start
14609: for active or future "privileged" users with that role in that domain. To avoid
14610: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
14611: innerhash are cached using priv_$role and $dom as the identifiers.
14612: 
14613: =back
14614: 
14615: =head2 User Modification
14616: 
14617: =over 4
14618: 
14619: =item *
14620: 
14621: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
14622: user for the level given by URL.  Optional start and end dates (leave empty
14623: string or zero for "no date")
14624: 
14625: =item *
14626: 
14627: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
14628: change a users, password, possible return values are: ok,
14629: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
14630: refused
14631: 
14632: =item *
14633: 
14634: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
14635: 
14636: =item *
14637: 
14638: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
14639:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
14640: 
14641: will update user information (firstname,middlename,lastname,generation,
14642: permanentemail), and if forceid is true, student/employee ID also.
14643: A user's institutional affiliation(s) can also be updated.
14644: User information fields will not be overwritten with empty entries 
14645: unless the field is included in the $candelete array reference.
14646: This array is included when a single user is modified via "Manage Users",
14647: or when Autoupdate.pl is run by cron in a domain.
14648: 
14649: =item *
14650: 
14651: modifystudent
14652: 
14653: modify a student's enrollment and identification information.
14654: The course id is resolved based on the current user's environment.  
14655: This means the invoking user must be a course coordinator or otherwise
14656: associated with a course.
14657: 
14658: This call is essentially a wrapper for lonnet::modifyuser and
14659: lonnet::modify_student_enrollment
14660: 
14661: Inputs: 
14662: 
14663: =over 4
14664: 
14665: =item B<$udom> Student's loncapa domain
14666: 
14667: =item B<$uname> Student's loncapa login name
14668: 
14669: =item B<$uid> Student/Employee ID
14670: 
14671: =item B<$umode> Student's authentication mode
14672: 
14673: =item B<$upass> Student's password
14674: 
14675: =item B<$first> Student's first name
14676: 
14677: =item B<$middle> Student's middle name
14678: 
14679: =item B<$last> Student's last name
14680: 
14681: =item B<$gene> Student's generation
14682: 
14683: =item B<$usec> Student's section in course
14684: 
14685: =item B<$end> Unix time of the roles expiration
14686: 
14687: =item B<$start> Unix time of the roles start date
14688: 
14689: =item B<$forceid> If defined, allow $uid to be changed
14690: 
14691: =item B<$desiredhome> server to use as home server for student
14692: 
14693: =item B<$email> Student's permanent e-mail address
14694: 
14695: =item B<$type> Type of enrollment (auto or manual)
14696: 
14697: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
14698: 
14699: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
14700: 
14701: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
14702: 
14703: =item B<$context> role change context (shown in User Management Logs display in a course)
14704: 
14705: =item B<$inststatus> institutional status of user - : separated string of escaped status types
14706: 
14707: =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.
14708: 
14709: =back
14710: 
14711: =item *
14712: 
14713: modify_student_enrollment
14714: 
14715: Change a student's enrollment status in a class.  The environment variable
14716: 'role.request.course' must be defined for this function to proceed.
14717: 
14718: Inputs:
14719: 
14720: =over 4
14721: 
14722: =item $udom, student's domain
14723: 
14724: =item $uname, student's name
14725: 
14726: =item $uid, student's user id
14727: 
14728: =item $first, student's first name
14729: 
14730: =item $middle
14731: 
14732: =item $last
14733: 
14734: =item $gene
14735: 
14736: =item $usec
14737: 
14738: =item $end
14739: 
14740: =item $start
14741: 
14742: =item $type
14743: 
14744: =item $locktype
14745: 
14746: =item $cid
14747: 
14748: =item $selfenroll
14749: 
14750: =item $context
14751: 
14752: =item $credits, number of credits student will earn from this class
14753: 
14754: =item $instsec, institutional course section code for student
14755: 
14756: =back
14757: 
14758: 
14759: =item *
14760: 
14761: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
14762: custom role; give a custom role to a user for the level given by URL.  Specify
14763: name and domain of role author, and role name
14764: 
14765: =item *
14766: 
14767: revokerole($udom,$uname,$url,$role) : revoke a role for url
14768: 
14769: =item *
14770: 
14771: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
14772: 
14773: =back
14774: 
14775: =head2 Course Infomation
14776: 
14777: =over 4
14778: 
14779: =item *
14780: 
14781: coursedescription($courseid,$options) : returns a hash of information about the
14782: specified course id, including all environment settings for the
14783: course, the description of the course will be in the hash under the
14784: key 'description'
14785: 
14786: $options is an optional parameter that if supplied is a hash reference that controls
14787: what how this function works.  It has the following key/values:
14788: 
14789: =over 4
14790: 
14791: =item freshen_cache
14792: 
14793: If defined, and the environment cache for the course is valid, it is 
14794: returned in the returned hash.
14795: 
14796: =item one_time
14797: 
14798: If defined, the last cache time is set to _now_
14799: 
14800: =item user
14801: 
14802: If defined, the supplied username is used instead of the current user.
14803: 
14804: 
14805: =back
14806: 
14807: =item *
14808: 
14809: resdata($name,$domain,$type,@which) : request for current parameter
14810: setting for a specific $type, where $type is either 'course' or 'user',
14811: @what should be a list of parameters to ask about. This routine caches
14812: answers for 10 minutes.
14813: 
14814: =item *
14815: 
14816: get_courseresdata($courseid, $domain) : dump the entire course resource
14817: data base, returning a hash that is keyed by the resource name and has
14818: values that are the resource value.  I believe that the timestamps and
14819: versions are also returned.
14820: 
14821: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
14822: supplemental content area. This routine caches the number of files for
14823: 10 minutes.
14824: 
14825: =back
14826: 
14827: =head2 Course Modification
14828: 
14829: =over 4
14830: 
14831: =item *
14832: 
14833: writecoursepref($courseid,%prefs) : write preferences (environment
14834: database) for a course
14835: 
14836: =item *
14837: 
14838: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
14839: 
14840: =item *
14841: 
14842: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
14843: 
14844: =item *
14845: 
14846: is_course($courseid), is_course($cdom, $cnum)
14847: 
14848: Accepts either a combined $courseid (in the form of domain_courseid) or the
14849: two component version $cdom, $cnum. It checks if the specified course exists.
14850: 
14851: Returns:
14852:     undef if the course doesn't exist, otherwise
14853:     in scalar context the combined courseid.
14854:     in list context the two components of the course identifier, domain and 
14855:     courseid.    
14856: 
14857: =back
14858: 
14859: =head2 Bubblesheet Configuration
14860: 
14861: =over 4
14862: 
14863: =item *
14864: 
14865: get_scantron_config($which)
14866: 
14867: $which - the name of the configuration to parse from the file.
14868: 
14869: Parses and returns the bubblesheet configuration line selected as a
14870: hash of configuration file fields.
14871: 
14872: 
14873: Returns:
14874:     If the named configuration is not in the file, an empty
14875:     hash is returned.
14876: 
14877:     a hash with the fields
14878:       name         - internal name for the this configuration setup
14879:       description  - text to display to operator that describes this config
14880:       CODElocation - if 0 or the string 'none'
14881:                           - no CODE exists for this config
14882:                      if -1 || the string 'letter'
14883:                           - a CODE exists for this config and is
14884:                             a string of letters
14885:                      Unsupported value (but planned for future support)
14886:                           if a positive integer
14887:                                - The CODE exists as the first n items from
14888:                                  the question section of the form
14889:                           if the string 'number'
14890:                                - The CODE exists for this config and is
14891:                                  a string of numbers
14892:       CODEstart   - (only matter if a CODE exists) column in the line where
14893:                      the CODE starts
14894:       CODElength  - length of the CODE
14895:       IDstart     - column where the student/employee ID starts
14896:       IDlength    - length of the student/employee ID info
14897:       Qstart      - column where the information from the bubbled
14898:                     'questions' start
14899:       Qlength     - number of columns comprising a single bubble line from
14900:                     the sheet. (usually either 1 or 10)
14901:       Qon         - either a single character representing the character used
14902:                     to signal a bubble was chosen in the positional setup, or
14903:                     the string 'letter' if the letter of the chosen bubble is
14904:                     in the final, or 'number' if a number representing the
14905:                     chosen bubble is in the file (1->A 0->J)
14906:       Qoff        - the character used to represent that a bubble was
14907:                     left blank
14908:       PaperID     - if the scanning process generates a unique number for each
14909:                     sheet scanned the column that this ID number starts in
14910:       PaperIDlength - number of columns that comprise the unique ID number
14911:                       for the sheet of paper
14912:       FirstName   - column that the first name starts in
14913:       FirstNameLength - number of columns that the first name spans
14914:       LastName    - column that the last name starts in
14915:       LastNameLength - number of columns that the last name spans
14916:       BubblesPerRow - number of bubbles available in each row used to
14917:                       bubble an answer. (If not specified, 10 assumed).
14918: 
14919: 
14920: =item *
14921: 
14922: get_scantronformat_file($cdom)
14923: 
14924: $cdom - the course's domain (optional); if not supplied, uses
14925: domain for current $env{'request.course.id'}.
14926: 
14927: Returns an array containing lines from the scantron format file for
14928: the domain of the course.
14929: 
14930: If a url for a custom.tab file is listed in domain's configuration.db,
14931: lines are from this file.
14932: 
14933: Otherwise, if a default.tab has been published in RES space by the
14934: domainconfig user, lines are from this file.
14935: 
14936: Otherwise, fall back to getting lines from the legacy file on the
14937: local server:  /home/httpd/lonTabs/default_scantronformat.tab
14938: 
14939: =back
14940: 
14941: =head2 Resource Subroutines
14942: 
14943: =over 4
14944: 
14945: =item *
14946: 
14947: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
14948: 
14949: =item *
14950: 
14951: repcopy($filename) : subscribes to the requested file, and attempts to
14952: replicate from the owning library server, Might return
14953: 'unavailable', 'not_found', 'forbidden', 'ok', or
14954: 'bad_request', also attempts to grab the metadata for the
14955: resource. Expects the local filesystem pathname
14956: (/home/httpd/html/res/....)
14957: 
14958: =back
14959: 
14960: =head2 Resource Information
14961: 
14962: =over 4
14963: 
14964: =item *
14965: 
14966: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
14967: and returns the value of a variety of different possible values,
14968: $varname should be a request string, and the other parameters can be
14969: used to specify who and what one is asking about. Ordinarily, $cid 
14970: does not need to be specified, as it is retrived from 
14971: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
14972: within lonuserstate::loadmap() when initializing a course, before
14973: $env{'request.course.id'} has been set, so it needs to be provided
14974: in that one case.
14975: 
14976: Possible values for $varname are environment.lastname (or other item
14977: from the envirnment hash), user.name (or someother aspect about the
14978: user), resource.0.maxtries (or some other part and parameter of a
14979: resource)
14980: 
14981: =item *
14982: 
14983: directcondval($number) : get current value of a condition; reads from a state
14984: string
14985: 
14986: =item *
14987: 
14988: condval($condidx) : value of condition index based on state
14989: 
14990: =item *
14991: 
14992: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
14993: resource's metadata, $what should be either a specific key, or either
14994: 'keys' (to get a list of possible keys) or 'packages' to get a list of
14995: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
14996: 
14997: this function automatically caches all requests
14998: 
14999: =item *
15000: 
15001: metadata_query($query,$custom,$customshow) : make a metadata query against the
15002: network of library servers; returns file handle of where SQL and regex results
15003: will be stored for query
15004: 
15005: =item *
15006: 
15007: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
15008: return symbolic list entry (all arguments optional).
15009: 
15010: Args: filename is the filename (including path) for the file for which a symb
15011: is required; donotrecurse, if true will prevent calls to allowed() being made
15012: to check access status if more than one resource was found in the bighash
15013: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
15014: a randompick); ignorecachednull, if true will prevent a symb of '' being
15015: returned if $env{$cache_str} is defined as ''; checkforblock if true will
15016: cause possible symbs to be checked to determine if they are subject to content
15017: blocking, if so they will not be included as possible symbs; possibles is a
15018: ref to a hash, which, as a side effect, will be populated with all possible
15019: symbs (content blocking not tested).
15020: 
15021: returns the data handle
15022: 
15023: =item *
15024: 
15025: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
15026: and is a possible symb for the URL in $thisfn, and if is an encrypted
15027: resource that the user accessed using /enc/ returns a 1 on success, 0
15028: on failure, user must be in a course, as it assumes the existence of
15029: the course initial hash, and uses $env('request.course.id'}.  The third
15030: arg is an optional reference to a scalar.  If this arg is passed in the
15031: call to symbverify, it will be set to 1 if the symb has been set to be 
15032: encrypted; otherwise it will be null.
15033: 
15034: =item *
15035: 
15036: symbclean($symb) : removes versions numbers from a symb, returns the
15037: cleaned symb
15038: 
15039: =item *
15040: 
15041: is_on_map($uri) : checks if the $uri is somewhere on the current
15042: course map, user must be in a course for it to work.
15043: 
15044: =item *
15045: 
15046: numval($salt) : return random seed value (addend for rndseed)
15047: 
15048: =item *
15049: 
15050: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
15051: a random seed, all arguments are optional, if they aren't sent it uses the
15052: environment to derive them. Note: if symb isn't sent and it can't get one
15053: from &symbread it will use the current time as its return value
15054: 
15055: =item *
15056: 
15057: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
15058: unfakeable, receipt
15059: 
15060: =item *
15061: 
15062: receipt() : API to ireceipt working off of env values; given out to users
15063: 
15064: =item *
15065: 
15066: countacc($url) : count the number of accesses to a given URL
15067: 
15068: =item *
15069: 
15070: 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
15071: 
15072: =item *
15073: 
15074: 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)
15075: 
15076: =item *
15077: 
15078: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
15079: 
15080: =item *
15081: 
15082: devalidate($symb) : devalidate temporary spreadsheet calculations,
15083: forcing spreadsheet to reevaluate the resource scores next time.
15084: 
15085: =item *
15086: 
15087: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
15088: when viewing in course context.
15089: 
15090:  input: six args -- filename (decluttered), course number, course domain,
15091:                     url, symb (if registered) and group (if this is a
15092:                     group item -- e.g., bulletin board, group page etc.).
15093: 
15094:  output: array of five scalars --
15095:          $cfile -- url for file editing if editable on current server
15096:          $home -- homeserver of resource (i.e., for author if published,
15097:                                           or course if uploaded.).
15098:          $switchserver --  1 if server switch will be needed.
15099:          $forceedit -- 1 if icon/link should be to go to edit mode
15100:          $forceview -- 1 if icon/link should be to go to view mode
15101: 
15102: =item *
15103: 
15104: is_course_upload($file,$cnum,$cdom)
15105: 
15106: Used in course context to determine if current file was uploaded to
15107: the course (i.e., would be found in /userfiles/docs on the course's
15108: homeserver.
15109: 
15110:   input: 3 args -- filename (decluttered), course number and course domain.
15111:   output: boolean -- 1 if file was uploaded.
15112: 
15113: =back
15114: 
15115: =head2 Storing/Retreiving Data
15116: 
15117: =over 4
15118: 
15119: =item *
15120: 
15121: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash 
15122: permanently for this url; hashref needs to be given and should be a \%hashname;
15123: the remaining args aren't required and if they aren't passed or are '' they will
15124: be derived from the env (with the exception of $laststore, which is an
15125: optional arg used when a user's submission is stored in grading).
15126: $laststore is $version=$timestamp, where $version is the most recent version
15127: number retrieved for the corresponding $symb in the $namespace db file, and
15128: $timestamp is the timestamp for that transaction (UNIX time).
15129: $laststore is currently only passed when cstore() is called by
15130: structuretags::finalize_storage().
15131: 
15132: =item *
15133: 
15134: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store 
15135: but uses critical subroutine
15136: 
15137: =item *
15138: 
15139: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
15140: all args are optional
15141: 
15142: =item *
15143: 
15144: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
15145: dumps the complete (or key matching regexp) namespace into a hash
15146: ($udom, $uname, $regexp, $range are optional) for a namespace that is
15147: normally &store()ed into
15148: 
15149: $range should be either an integer '100' (give me the first 100
15150:                                            matching records)
15151:               or be  two integers sperated by a - with no spaces
15152:                  '30-50' (give me the 30th through the 50th matching
15153:                           records)
15154: 
15155: 
15156: =item *
15157: 
15158: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
15159: replaces a &store() version of data with a replacement set of data
15160: for a particular resource in a namespace passed in the $storehash hash 
15161: reference. If $tolog is true, the transaction is logged in the courselog
15162: with an action=PUTSTORE.
15163: 
15164: =item *
15165: 
15166: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
15167: works very similar to store/cstore, but all data is stored in a
15168: temporary location and can be reset using tmpreset, $storehash should
15169: be a hash reference, returns nothing on success
15170: 
15171: =item *
15172: 
15173: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
15174: similar to restore, but all data is stored in a temporary location and
15175: can be reset using tmpreset. Returns a hash of values on success,
15176: error string otherwise.
15177: 
15178: =item *
15179: 
15180: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
15181: deltes all keys for $symb form the temporary storage hash.
15182: 
15183: =item *
15184: 
15185: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
15186: reference filled in from namesp ($udom and $uname are optional)
15187: 
15188: =item *
15189: 
15190: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
15191: namesp ($udom and $uname are optional)
15192: 
15193: =item *
15194: 
15195: dump($namespace,$udom,$uname,$regexp,$range) : 
15196: dumps the complete (or key matching regexp) namespace into a hash
15197: ($udom, $uname, $regexp, $range are optional)
15198: 
15199: $range should be either an integer '100' (give me the first 100
15200:                                            matching records)
15201:               or be  two integers sperated by a - with no spaces
15202:                  '30-50' (give me the 30th through the 50th matching
15203:                           records)
15204: =item *
15205: 
15206: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
15207: $store can be a scalar, an array reference, or if the amount to be 
15208: incremented is > 1, a hash reference.
15209: 
15210: ($udom and $uname are optional)
15211: 
15212: =item *
15213: 
15214: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
15215: ($udom and $uname are optional)
15216: 
15217: =item *
15218: 
15219: cput($namespace,$storehash,$udom,$uname) : critical put
15220: ($udom and $uname are optional)
15221: 
15222: =item *
15223: 
15224: newput($namespace,$storehash,$udom,$uname) :
15225: 
15226: Attempts to store the items in the $storehash, but only if they don't
15227: currently exist, if this succeeds you can be certain that you have 
15228: successfully created a new key value pair in the $namespace db.
15229: 
15230: 
15231: Args:
15232:  $namespace: name of database to store values to
15233:  $storehash: hashref to store to the db
15234:  $udom: (optional) domain of user containing the db
15235:  $uname: (optional) name of user caontaining the db
15236: 
15237: Returns:
15238:  'ok' -> succeeded in storing all keys of $storehash
15239:  'key_exists: <key>' -> failed to anything out of $storehash, as at
15240:                         least <key> already existed in the db (other
15241:                         requested keys may also already exist)
15242:  'error: <msg>' -> unable to tie the DB or other error occurred
15243:  'con_lost' -> unable to contact request server
15244:  'refused' -> action was not allowed by remote machine
15245: 
15246: 
15247: =item *
15248: 
15249: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
15250: reference filled in from namesp (encrypts the return communication)
15251: ($udom and $uname are optional)
15252: 
15253: =item *
15254: 
15255: log($udom,$name,$home,$message) : write to permanent log for user; use
15256: critical subroutine
15257: 
15258: =item *
15259: 
15260: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
15261: array reference filled in from namespace found in domain level on either
15262: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
15263: 
15264: =item *
15265: 
15266: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
15267: domain level either on specified domain server ($uhome) or primary domain 
15268: server ($udom and $uhome are optional)
15269: 
15270: =item * 
15271: 
15272: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
15273: for: authentication, language, quotas, timezone, date locale, and portal URL in
15274: the target domain.
15275: 
15276: May also include additional key => value pairs for the following groups:
15277: 
15278: =over
15279: 
15280: =item
15281: disk quotas (MB allocated by default to portfolios and authoring spaces).
15282: 
15283: =over
15284: 
15285: =item defaultquota, authorquota
15286: 
15287: =back
15288: 
15289: =item
15290: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
15291: portfolio for users).
15292: 
15293: =over
15294: 
15295: =item
15296: aboutme, blog, webdav, portfolio
15297: 
15298: =back
15299: 
15300: =item
15301: requestcourses: ability to request courses, and how requests are processed.
15302: 
15303: =over
15304: 
15305: =item
15306: official, unofficial, community, textbook
15307: 
15308: =back
15309: 
15310: =item
15311: inststatus: types of institutional affiliation, and order in which they are displayed.
15312: 
15313: =over
15314: 
15315: =item
15316: inststatustypes, inststatusorder, inststatusguest
15317: 
15318: =back
15319: 
15320: =item
15321: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
15322: for course's uploaded content.
15323: 
15324: =over
15325: 
15326: =item
15327: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
15328: communityquota, textbookquota
15329: 
15330: =back
15331: 
15332: =item
15333: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
15334: on your servers.
15335: 
15336: =over
15337: 
15338: =item
15339: remotesessions, hostedsessions
15340: 
15341: =back
15342: 
15343: =back
15344: 
15345: In cases where a domain coordinator has never used the "Set Domain Configuration"
15346: utility to create a configuration.db file on a domain's primary library server
15347: only the following domain defaults: auth_def, auth_arg_def, lang_def
15348: -- corresponding values are authentication type (internal, krb4, krb5,
15349: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
15350: will be available. Values are retrieved from cache (if current), unless the
15351: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
15352: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
15353: 
15354: Typical usage:
15355: 
15356: %domdefaults = &get_domain_defaults($target_domain);
15357: 
15358: =back
15359: 
15360: =head2 Network Status Functions
15361: 
15362: =over 4
15363: 
15364: =item *
15365: 
15366: dirlist() : return directory list based on URI (first arg).
15367: 
15368: Inputs: 1 required, 5 optional.
15369: 
15370: =over
15371: 
15372: =item 
15373: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
15374: 
15375: =item
15376: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
15377: 
15378: =item
15379: $username -  username of user/course to be listed. Extracted from $uri if absent. 
15380: 
15381: =item
15382: $getpropath - boolean: 1 if prepend path using &propath(). 
15383: 
15384: =item
15385: $getuserdir - boolean: 1 if prepend path for "userfiles".
15386: 
15387: =item 
15388: $alternateRoot - path to prepend in place of path from $uri.
15389: 
15390: =back
15391: 
15392: Returns: Array of up to two items.
15393: 
15394: =over
15395: 
15396: a reference to an array of files/subdirectories
15397: 
15398: =over
15399: 
15400: Each element in the array of files/subdirectories is a & separated list of
15401: item name and the result of running stat on the item.  If dirlist was requested
15402: for a file instead of a directory, the item name will be ''. For a directory 
15403: listing, if the item is a metadata file, the element will end &N&M 
15404: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
15405: default copyright set (1).  
15406: 
15407: =back
15408: 
15409: a scalar containing error condition (if encountered).
15410: 
15411: =over
15412: 
15413: =item 
15414: no_host (no homeserver identified for $username:$domain).
15415: 
15416: =item 
15417: no_such_host (server contacted for listing not identified as valid host).
15418: 
15419: =item 
15420: con_lost (connection to remote server failed).
15421: 
15422: =item 
15423: refused (invalid $username:$domain received on lond side).
15424: 
15425: =item 
15426: no_such_dir (directory at specified path on lond side does not exist). 
15427: 
15428: =item 
15429: empty (directory at specified path on lond side is empty).
15430: 
15431: =over
15432: 
15433: This is currently not encountered because the &ls3, &ls2, 
15434: &ls (_handler) routines on the lond side do not filter out
15435: . and .. from a directory listing. 
15436: 
15437: =back
15438: 
15439: =back
15440: 
15441: =back
15442: 
15443: =item *
15444: 
15445: spareserver() : find server with least workload from spare.tab
15446: 
15447: 
15448: =item *
15449: 
15450: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
15451: if there is no corresponding loncapa host.
15452: 
15453: =back
15454: 
15455: 
15456: =head2 Apache Request
15457: 
15458: =over 4
15459: 
15460: =item *
15461: 
15462: ssi($url,%hash) : server side include, does a complete request cycle on url to
15463: localhost, posts hash
15464: 
15465: =back
15466: 
15467: =head2 Data to String to Data
15468: 
15469: =over 4
15470: 
15471: =item *
15472: 
15473: hash2str(%hash) : convert a hash into a string complete with escaping and '='
15474: and '&' separators, supports elements that are arrayrefs and hashrefs
15475: 
15476: =item *
15477: 
15478: hashref2str($hashref) : convert a hashref into a string complete with
15479: escaping and '=' and '&' separators, supports elements that are
15480: arrayrefs and hashrefs
15481: 
15482: =item *
15483: 
15484: arrayref2str($arrayref) : convert an arrayref into a string complete
15485: with escaping and '&' separators, supports elements that are arrayrefs
15486: and hashrefs
15487: 
15488: =item *
15489: 
15490: str2hash($string) : convert string to hash using unescaping and
15491: splitting on '=' and '&', supports elements that are arrayrefs and
15492: hashrefs
15493: 
15494: =item *
15495: 
15496: str2array($string) : convert string to hash using unescaping and
15497: splitting on '&', supports elements that are arrayrefs and hashrefs
15498: 
15499: =back
15500: 
15501: =head2 Logging Routines
15502: 
15503: 
15504: These routines allow one to make log messages in the lonnet.log and
15505: lonnet.perm logfiles.
15506: 
15507: =over 4
15508: 
15509: =item *
15510: 
15511: logtouch() : make sure the logfile, lonnet.log, exists
15512: 
15513: =item *
15514: 
15515: logthis() : append message to the normal lonnet.log file, it gets
15516: preiodically rolled over and deleted.
15517: 
15518: =item *
15519: 
15520: logperm() : append a permanent message to lonnet.perm.log, this log
15521: file never gets deleted by any automated portion of the system, only
15522: messages of critical importance should go in here.
15523: 
15524: 
15525: =back
15526: 
15527: =head2 General File Helper Routines
15528: 
15529: =over 4
15530: 
15531: =item *
15532: 
15533: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
15534: (a) files in /uploaded
15535:   (i) If a local copy of the file exists - 
15536:       compares modification date of local copy with last-modified date for 
15537:       definitive version stored on home server for course. If local copy is 
15538:       stale, requests a new version from the home server and stores it. 
15539:       If the original has been removed from the home server, then local copy 
15540:       is unlinked.
15541:   (ii) If local copy does not exist -
15542:       requests the file from the home server and stores it. 
15543:   
15544:   If $caller is 'uploadrep':  
15545:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
15546:     for request for files originally uploaded via DOCS. 
15547:      - returns 'ok' if fresh local copy now available, -1 otherwise.
15548:   
15549:   Otherwise:
15550:      This indicates a call from the content generation phase of the request.
15551:      -  returns the entire contents of the file or -1.
15552:      
15553: (b) files in /res
15554:    - returns the entire contents of a file or -1; 
15555:    it properly subscribes to and replicates the file if neccessary.
15556: 
15557: 
15558: =item *
15559: 
15560: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
15561:                   reference
15562: 
15563: returns either a stat() list of data about the file or an empty list
15564: if the file doesn't exist or couldn't find out about it (connection
15565: problems or user unknown)
15566: 
15567: =item *
15568: 
15569: filelocation($dir,$file) : returns file system location of a file
15570: based on URI; meant to be "fairly clean" absolute reference, $dir is a
15571: directory that relative $file lookups are to looked in ($dir of /a/dir
15572: and a file of ../bob will become /a/bob)
15573: 
15574: =item *
15575: 
15576: hreflocation($dir,$file) : returns file system location or a URL; same as
15577: filelocation except for hrefs
15578: 
15579: =item *
15580: 
15581: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
15582: also removes beginning /home/httpd/html unless /priv/ follows it.
15583: 
15584: =back
15585: 
15586: =head2 Usererfile file routines (/uploaded*)
15587: 
15588: =over 4
15589: 
15590: =item *
15591: 
15592: userfileupload(): main rotine for putting a file in a user or course's
15593:                   filespace, arguments are,
15594: 
15595:  formname - required - this is the name of the element in $env where the
15596:            filename, and the contents of the file to create/modifed exist
15597:            the filename is in $env{'form.'.$formname.'.filename'} and the
15598:            contents of the file is located in $env{'form.'.$formname}
15599:  context - if coursedoc, store the file in the course of the active role
15600:              of the current user; 
15601:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
15602:            if 'canceloverwrite': delete file in tmp/overwrites directory
15603:  subdir - required - subdirectory to put the file in under ../userfiles/
15604:          if undefined, it will be placed in "unknown"
15605: 
15606:  (This routine calls clean_filename() to remove any dangerous
15607:  characters from the filename, and then calls finuserfileupload() to
15608:  complete the transaction)
15609: 
15610:  returns either the url of the uploaded file (/uploaded/....) if successful
15611:  and /adm/notfound.html if unsuccessful
15612: 
15613: =item *
15614: 
15615: clean_filename(): routine for cleaing a filename up for storage in
15616:                  userfile space, argument is:
15617: 
15618:  filename - proposed filename
15619: 
15620: returns: the new clean filename
15621: 
15622: =item *
15623: 
15624: finishuserfileupload(): routine that creates and sends the file to
15625: userspace, probably shouldn't be called directly
15626: 
15627:   docuname: username or courseid of destination for the file
15628:   docudom: domain of user/course of destination for the file
15629:   formname: same as for userfileupload()
15630:   fname: filename (including subdirectories) for the file
15631:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
15632:           if hashref, and context is scantron, will convert csv format to standard format
15633:   allfiles: reference to hash used to store objects found by parser
15634:   codebase: reference to hash used for codebases of java objects found by parser
15635:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
15636:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
15637:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
15638:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
15639:   context: if 'overwrite', will move the uploaded file from its temporary location to
15640:             userfiles to facilitate overwriting a previously uploaded file with same name.
15641:   mimetype: reference to scalar to accommodate mime type determined
15642:             from File::MMagic if $parser = parse.
15643: 
15644:  returns either the url of the uploaded file (/uploaded/....) if successful
15645:  and /adm/notfound.html if unsuccessful (or an error message if context 
15646:  was 'overwrite').
15647:  
15648: 
15649: =item *
15650: 
15651: renameuserfile(): renames an existing userfile to a new name
15652: 
15653:   Args:
15654:    docuname: username or courseid of destination for the file
15655:    docudom: domain of user/course of destination for the file
15656:    old: current file name (including any subdirs under userfiles)
15657:    new: desired file name (including any subdirs under userfiles)
15658: 
15659: =item *
15660: 
15661: mkdiruserfile(): creates a directory is a userfiles dir
15662: 
15663:   Args:
15664:    docuname: username or courseid of destination for the file
15665:    docudom: domain of user/course of destination for the file
15666:    dir: dir to create (including any subdirs under userfiles)
15667: 
15668: =item *
15669: 
15670: removeuserfile(): removes a file that exists in userfiles
15671: 
15672:   Args:
15673:    docuname: username or courseid of destination for the file
15674:    docudom: domain of user/course of destination for the file
15675:    fname: filname to delete (including any subdirs under userfiles)
15676: 
15677: =item *
15678: 
15679: removeuploadedurl(): convience function for removeuserfile()
15680: 
15681:   Args:
15682:    url:  a full /uploaded/... url to delete
15683: 
15684: =item * 
15685: 
15686: get_portfile_permissions():
15687:   Args:
15688:     domain: domain of user or course contain the portfolio files
15689:     user: name of user or num of course contain the portfolio files
15690:   Returns:
15691:     hashref of a dump of the proper file_permissions.db
15692:    
15693: 
15694: =item * 
15695: 
15696: get_access_controls():
15697: 
15698: Args:
15699:   current_permissions: the hash ref returned from get_portfile_permissions()
15700:   group: (optional) the group you want the files associated with
15701:   file: (optional) the file you want access info on
15702: 
15703: Returns:
15704:     a hash (keys are file names) of hashes containing
15705:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
15706:         values are XML containing access control settings (see below) 
15707: 
15708: Internal notes:
15709: 
15710:  access controls are stored in file_permissions.db as key=value pairs.
15711:     key -> path to file/file_name\0uniqueID:scope_end_start
15712:         where scope -> public,guest,course,group,domains or users.
15713:               end -> UNIX time for end of access (0 -> no end date)
15714:               start -> UNIX time for start of access
15715: 
15716:     value -> XML description of access control
15717:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
15718:             <start></start>
15719:             <end></end>
15720: 
15721:             <password></password>  for scope type = guest
15722: 
15723:             <domain></domain>     for scope type = course or group
15724:             <number></number>
15725:             <roles id="">
15726:              <role></role>
15727:              <access></access>
15728:              <section></section>
15729:              <group></group>
15730:             </roles>
15731: 
15732:             <dom></dom>         for scope type = domains
15733: 
15734:             <users>             for scope type = users
15735:              <user>
15736:               <uname></uname>
15737:               <udom></udom>
15738:              </user>
15739:             </users>
15740:            </scope> 
15741:               
15742:  Access data is also aggregated for each file in an additional key=value pair:
15743:  key -> path to file/file_name\0accesscontrol 
15744:  value -> reference to hash
15745:           hash contains key = value pairs
15746:           where key = uniqueID:scope_end_start
15747:                 value = UNIX time record was last updated
15748: 
15749:           Used to improve speed of look-ups of access controls for each file.  
15750:  
15751:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
15752: 
15753: =item *
15754: 
15755: modify_access_controls():
15756: 
15757: Modifies access controls for a portfolio file
15758: Args
15759: 1. file name
15760: 2. reference to hash of required changes,
15761: 3. domain
15762: 4. username
15763:   where domain,username are the domain of the portfolio owner 
15764:   (either a user or a course) 
15765: 
15766: Returns:
15767: 1. result of additions or updates ('ok' or 'error', with error message). 
15768: 2. result of deletions ('ok' or 'error', with error message).
15769: 3. reference to hash of any new or updated access controls.
15770: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
15771:    key = integer (inbound ID)
15772:    value = uniqueID
15773: 
15774: =item *
15775: 
15776: get_timebased_id():
15777: 
15778: Attempts to get a unique timestamp-based suffix for use with items added to a
15779: course via the Course Editor (e.g., folders, composite pages,
15780: group bulletin boards).
15781: 
15782: Args: (first three required; six others optional)
15783: 
15784: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
15785:    docssequence, or name of group
15786: 
15787: 2. keyid (alphanumeric): name of temporary locking key in hash,
15788:    e.g., num, boardids
15789: 
15790: 3. namespace: name of gdbm file used to store suffixes already assigned;
15791:    file will be named nohist_namespace.db
15792: 
15793: 4. cdom: domain of course; default is current course domain from %env
15794: 
15795: 5. cnum: course number; default is current course number from %env
15796: 
15797: 6. idtype: set to concat if an additional digit is to be appended to the
15798:    unix timestamp to form the suffix, if the plain timestamp is already
15799:    in use.  Default is to not do this, but simply increment the unix
15800:    timestamp by 1 until a unique key is obtained.
15801: 
15802: 7. who: holder of locking key; defaults to user:domain for user.
15803: 
15804: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
15805:    retrying); default is 3.
15806: 
15807: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
15808: 
15809: Returns:
15810: 
15811: 1. suffix obtained (numeric)
15812: 
15813: 2. result of deleting locking key (ok if deleted, or lock never obtained)
15814: 
15815: 3. error: contains (localized) error message if an error occurred.
15816: 
15817: 
15818: =back
15819: 
15820: =head2 HTTP Helper Routines
15821: 
15822: =over 4
15823: 
15824: =item *
15825: 
15826: escape() : unpack non-word characters into CGI-compatible hex codes
15827: 
15828: =item *
15829: 
15830: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
15831: 
15832: =back
15833: 
15834: =head1 PRIVATE SUBROUTINES
15835: 
15836: =head2 Underlying communication routines (Shouldn't call)
15837: 
15838: =over 4
15839: 
15840: =item *
15841: 
15842: subreply() : tries to pass a message to lonc, returns con_lost if incapable
15843: 
15844: =item *
15845: 
15846: reply() : uses subreply to send a message to remote machine, logs all failures
15847: 
15848: =item *
15849: 
15850: critical() : passes a critical message to another server; if cannot
15851: get through then place message in connection buffer directory and
15852: returns con_delayed, if incapable of saving message, returns
15853: con_failed
15854: 
15855: =item *
15856: 
15857: reconlonc() : tries to reconnect lonc client processes.
15858: 
15859: =back
15860: 
15861: =head2 Resource Access Logging
15862: 
15863: =over 4
15864: 
15865: =item *
15866: 
15867: flushcourselogs() : flush (save) buffer logs and access logs
15868: 
15869: =item *
15870: 
15871: courselog($what) : save message for course in hash
15872: 
15873: =item *
15874: 
15875: courseacclog($what) : save message for course using &courselog().  Perform
15876: special processing for specific resource types (problems, exams, quizzes, etc).
15877: 
15878: =item *
15879: 
15880: goodbye() : flush course logs and log shutting down; it is called in srm.conf
15881: as a PerlChildExitHandler
15882: 
15883: =back
15884: 
15885: =head2 Other
15886: 
15887: =over 4
15888: 
15889: =item *
15890: 
15891: symblist($mapname,%newhash) : update symbolic storage links
15892: 
15893: =back
15894: 
15895: =cut
15896: 

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