File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1172.2.118.2.19: download - view: text, annotated - select for diffs
Thu Feb 11 20:25:43 2021 UTC (3 years, 4 months ago) by raeburn
Branches: version_2_11_3_msu
- For 2.11.3 (modified)
  Include changes in 1.1443

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1172.2.118.2.19 2021/02/11 20:25:43 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;
 1902:         if (grep { $_ eq $uhome } &current_machine_ids()) {
 1903:             # domain information is hosted on this machine
 1904:             my $cmd = 'getdom';
 1905:             if ($namespace =~ /^enc/) {
 1906:                 $cmd = 'egetdom';
 1907:             }
 1908:             $rep = &LONCAPA::Lond::get_dom("$cmd:$udom:$namespace:$items");
 1909:         } else {
 1910:             if ($namespace =~ /^enc/) {
 1911:                 $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
 1912:             } else {
 1913:                 $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
 1914:             }
 1915:         }
 1916:         my %returnhash;
 1917:         if ($rep eq '' || $rep =~ /^error: 2 /) {
 1918:             return %returnhash;
 1919:         }
 1920:         my @pairs=split(/\&/,$rep);
 1921:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 1922:             return @pairs;
 1923:         }
 1924:         my $i=0;
 1925:         foreach my $item (@$storearr) {
 1926:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
 1927:             $i++;
 1928:         }
 1929:         return %returnhash;
 1930:     } else {
 1931:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
 1932:     }
 1933: }
 1934: 
 1935: # -------------------------------------------- put items in domain db files 
 1936: 
 1937: sub put_dom {
 1938:     my ($namespace,$storehash,$udom,$uhome)=@_;
 1939:     if (!$udom) {
 1940:         $udom=$env{'user.domain'};
 1941:         if (defined(&domain($udom,'primary'))) {
 1942:             $uhome=&domain($udom,'primary');
 1943:         } else {
 1944:             undef($uhome);
 1945:         }
 1946:     } else {
 1947:         if (!$uhome) {
 1948:             if (defined(&domain($udom,'primary'))) {
 1949:                 $uhome=&domain($udom,'primary');
 1950:             }
 1951:         }
 1952:     } 
 1953:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1954:         my $items='';
 1955:         foreach my $item (keys(%$storehash)) {
 1956:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 1957:         }
 1958:         $items=~s/\&$//;
 1959:         if ($namespace =~ /^enc/) {
 1960:             return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
 1961:         } else {
 1962:             return &reply("putdom:$udom:$namespace:$items",$uhome);
 1963:         }
 1964:     } else {
 1965:         &logthis("put_dom failed - no homeserver and/or domain");
 1966:     }
 1967: }
 1968: 
 1969: # --------------------- newput for items in db file owned by domainconfig user
 1970: sub newput_dom {
 1971:     my ($namespace,$storehash,$udom) = @_;
 1972:     my $result;
 1973:     if (!$udom) {
 1974:         $udom=$env{'user.domain'};
 1975:     }
 1976:     if ($udom) {
 1977:         my $uname = &get_domainconfiguser($udom);
 1978:         $result = &newput($namespace,$storehash,$udom,$uname);
 1979:     }
 1980:     return $result;
 1981: }
 1982: 
 1983: # --------------------- delete for items in db file owned by domainconfig user
 1984: sub del_dom {
 1985:     my ($namespace,$storearr,$udom)=@_;
 1986:     if (ref($storearr) eq 'ARRAY') {
 1987:         if (!$udom) {
 1988:             $udom=$env{'user.domain'};
 1989:         }
 1990:         if ($udom) {
 1991:             my $uname = &get_domainconfiguser($udom); 
 1992:             return &del($namespace,$storearr,$udom,$uname);
 1993:         }
 1994:     }
 1995: }
 1996: 
 1997: # ----------------------------------construct domainconfig user for a domain 
 1998: sub get_domainconfiguser {
 1999:     my ($udom) = @_;
 2000:     return $udom.'-domainconfig';
 2001: }
 2002: 
 2003: sub retrieve_inst_usertypes {
 2004:     my ($udom) = @_;
 2005:     my (%returnhash,@order);
 2006:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 2007:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
 2008:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
 2009:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
 2010:     } else {
 2011:         if (defined(&domain($udom,'primary'))) {
 2012:             my $uhome=&domain($udom,'primary');
 2013:             my $rep=&reply("inst_usertypes:$udom",$uhome);
 2014:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
 2015:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
 2016:                 return (\%returnhash,\@order);
 2017:             }
 2018:             my ($hashitems,$orderitems) = split(/:/,$rep); 
 2019:             my @pairs=split(/\&/,$hashitems);
 2020:             foreach my $item (@pairs) {
 2021:                 my ($key,$value)=split(/=/,$item,2);
 2022:                 $key = &unescape($key);
 2023:                 next if ($key =~ /^error: 2 /);
 2024:                 $returnhash{$key}=&thaw_unescape($value);
 2025:             }
 2026:             my @esc_order = split(/\&/,$orderitems);
 2027:             foreach my $item (@esc_order) {
 2028:                 push(@order,&unescape($item));
 2029:             }
 2030:         } else {
 2031:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
 2032:         }
 2033:         return (\%returnhash,\@order);
 2034:     }
 2035: }
 2036: 
 2037: sub is_domainimage {
 2038:     my ($url) = @_;
 2039:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
 2040:         if (&domain($1) ne '') {
 2041:             return '1';
 2042:         }
 2043:     }
 2044:     return;
 2045: }
 2046: 
 2047: sub inst_directory_query {
 2048:     my ($srch) = @_;
 2049:     my $udom = $srch->{'srchdomain'};
 2050:     my %results;
 2051:     my $homeserver = &domain($udom,'primary');
 2052:     my $outcome;
 2053:     if ($homeserver ne '') {
 2054:         unless ($homeserver eq $perlvar{'lonHostID'}) {
 2055:             if ($srch->{'srchby'} eq 'email') {
 2056:                 my $lcrev = &get_server_loncaparev($udom,$homeserver);
 2057:                 my ($major,$minor,$subver) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.(\d+)[\w.\-]+\'?$/);
 2058:                 if (($major eq '' && $minor eq '') || ($major < 2) ||
 2059:                     (($major == 2) && ($minor < 11)) ||
 2060:                     (($major == 2) && ($minor == 11) && ($subver < 3))) {
 2061:                     return;
 2062:                 }
 2063:             }
 2064:         }
 2065: 	my $queryid=&reply("querysend:instdirsearch:".
 2066: 			   &escape($srch->{'srchby'}).':'.
 2067: 			   &escape($srch->{'srchterm'}).':'.
 2068: 			   &escape($srch->{'srchtype'}),$homeserver);
 2069: 	my $host=&hostname($homeserver);
 2070: 	if ($queryid !~/^\Q$host\E\_/) {
 2071: 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
 2072: 	    return;
 2073: 	}
 2074: 	my $response = &get_query_reply($queryid);
 2075: 	my $maxtries = 5;
 2076: 	my $tries = 1;
 2077: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 2078: 	    $response = &get_query_reply($queryid);
 2079: 	    $tries ++;
 2080: 	}
 2081: 
 2082:         if (!&error($response) && $response ne 'refused') {
 2083:             if ($response eq 'unavailable') {
 2084:                 $outcome = $response;
 2085:             } else {
 2086:                 $outcome = 'ok';
 2087:                 my @matches = split(/\n/,$response);
 2088:                 foreach my $match (@matches) {
 2089:                     my ($key,$value) = split(/=/,$match);
 2090:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 2091:                 }
 2092:             }
 2093:         }
 2094:     }
 2095:     return ($outcome,%results);
 2096: }
 2097: 
 2098: sub usersearch {
 2099:     my ($srch) = @_;
 2100:     my $dom = $srch->{'srchdomain'};
 2101:     my %results;
 2102:     my %libserv = &all_library();
 2103:     my $query = 'usersearch';
 2104:     foreach my $tryserver (keys(%libserv)) {
 2105:         if (&host_domain($tryserver) eq $dom) {
 2106:             unless ($tryserver eq $perlvar{'lonHostID'}) {
 2107:                 if ($srch->{'srchby'} eq 'email') {
 2108:                     my $lcrev = &get_server_loncaparev($dom,$tryserver);
 2109:                     my ($major,$minor,$subver) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.(\d+)[\w.\-]+\'?$/);
 2110:                     next if (($major eq '' && $minor eq '') || ($major < 2) ||
 2111:                              (($major == 2) && ($minor < 11)) ||
 2112:                              (($major == 2) && ($minor == 11) && ($subver < 3)));
 2113:                 }
 2114:             }
 2115:             my $host=&hostname($tryserver);
 2116:             my $queryid=
 2117:                 &reply("querysend:".&escape($query).':'.
 2118:                        &escape($srch->{'srchby'}).':'.
 2119:                        &escape($srch->{'srchtype'}).':'.
 2120:                        &escape($srch->{'srchterm'}),$tryserver);
 2121:             if ($queryid !~/^\Q$host\E\_/) {
 2122:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 2123:                 next;
 2124:             }
 2125:             my $reply = &get_query_reply($queryid);
 2126:             my $maxtries = 1;
 2127:             my $tries = 1;
 2128:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 2129:                 $reply = &get_query_reply($queryid);
 2130:                 $tries ++;
 2131:             }
 2132:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 2133:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 2134:             } else {
 2135:                 my @matches;
 2136:                 if ($reply =~ /\n/) {
 2137:                     @matches = split(/\n/,$reply);
 2138:                 } else {
 2139:                     @matches = split(/\&/,$reply);
 2140:                 }
 2141:                 foreach my $match (@matches) {
 2142:                     my ($uname,$udom,%userhash);
 2143:                     foreach my $entry (split(/:/,$match)) {
 2144:                         my ($key,$value) =
 2145:                             map {&unescape($_);} split(/=/,$entry);
 2146:                         $userhash{$key} = $value;
 2147:                         if ($key eq 'username') {
 2148:                             $uname = $value;
 2149:                         } elsif ($key eq 'domain') {
 2150:                             $udom = $value;
 2151:                         }
 2152:                     }
 2153:                     $results{$uname.':'.$udom} = \%userhash;
 2154:                 }
 2155:             }
 2156:         }
 2157:     }
 2158:     return %results;
 2159: }
 2160: 
 2161: sub get_instuser {
 2162:     my ($udom,$uname,$id) = @_;
 2163:     my $homeserver = &domain($udom,'primary');
 2164:     my ($outcome,%results);
 2165:     if ($homeserver ne '') {
 2166:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 2167:                            &escape($id).':'.&escape($udom),$homeserver);
 2168:         my $host=&hostname($homeserver);
 2169:         if ($queryid !~/^\Q$host\E\_/) {
 2170:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 2171:             return;
 2172:         }
 2173:         my $response = &get_query_reply($queryid);
 2174:         my $maxtries = 5;
 2175:         my $tries = 1;
 2176:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 2177:             $response = &get_query_reply($queryid);
 2178:             $tries ++;
 2179:         }
 2180:         if (!&error($response) && $response ne 'refused') {
 2181:             if ($response eq 'unavailable') {
 2182:                 $outcome = $response;
 2183:             } else {
 2184:                 $outcome = 'ok';
 2185:                 my @matches = split(/\n/,$response);
 2186:                 foreach my $match (@matches) {
 2187:                     my ($key,$value) = split(/=/,$match);
 2188:                     $results{&unescape($key)} = &thaw_unescape($value);
 2189:                 }
 2190:             }
 2191:         }
 2192:     }
 2193:     my %userinfo;
 2194:     if (ref($results{$uname}) eq 'HASH') {
 2195:         %userinfo = %{$results{$uname}};
 2196:     } 
 2197:     return ($outcome,%userinfo);
 2198: }
 2199: 
 2200: sub get_multiple_instusers {
 2201:     my ($udom,$users,$caller) = @_;
 2202:     my ($outcome,$results);
 2203:     if (ref($users) eq 'HASH') {
 2204:         my $count = keys(%{$users});
 2205:         my $requested = &freeze_escape($users);
 2206:         my $homeserver = &domain($udom,'primary');
 2207:         if ($homeserver ne '') {
 2208:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
 2209:             my $host=&hostname($homeserver);
 2210:             if ($queryid !~/^\Q$host\E\_/) {
 2211:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
 2212:                          ' for host: '.$homeserver.'in domain '.$udom);
 2213:                 return ($outcome,$results);
 2214:             }
 2215:             my $response = &get_query_reply($queryid);
 2216:             my $maxtries = 5;
 2217:             if ($count > 100) {
 2218:                 $maxtries = 1+int($count/20);
 2219:             }
 2220:             my $tries = 1;
 2221:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
 2222:                 $response = &get_query_reply($queryid);
 2223:                 $tries ++;
 2224:             }
 2225:             if ($response eq '') {
 2226:                 $results = {};
 2227:                 foreach my $key (keys(%{$users})) {
 2228:                     my ($uname,$id);
 2229:                     if ($caller eq 'id') {
 2230:                         $id = $key;
 2231:                     } else {
 2232:                         $uname = $key;
 2233:                     }
 2234:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
 2235:                     $outcome = $resp;
 2236:                     if ($resp eq 'ok') {
 2237:                         %{$results} = (%{$results}, %info);
 2238:                     } else {
 2239:                         last;
 2240:                     }
 2241:                 }
 2242:             } elsif(!&error($response) && ($response ne 'refused')) {
 2243:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
 2244:                     $outcome = $response;
 2245:                 } else {
 2246:                     ($outcome,my $userdata) = split(/=/,$response,2);
 2247:                     if ($outcome eq 'ok') {
 2248:                         $results = &thaw_unescape($userdata);
 2249:                     }
 2250:                 }
 2251:             }
 2252:         }
 2253:     }
 2254:     return ($outcome,$results);
 2255: }
 2256: 
 2257: sub inst_rulecheck {
 2258:     my ($udom,$uname,$id,$item,$rules) = @_;
 2259:     my %returnhash;
 2260:     if ($udom ne '') {
 2261:         if (ref($rules) eq 'ARRAY') {
 2262:             @{$rules} = map {&escape($_);} (@{$rules});
 2263:             my $rulestr = join(':',@{$rules});
 2264:             my $homeserver=&domain($udom,'primary');
 2265:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 2266:                 my $response;
 2267:                 if ($item eq 'username') {                
 2268:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 2269:                                               ':'.&escape($uname).':'.$rulestr,
 2270:                                               $homeserver));
 2271:                 } elsif ($item eq 'id') {
 2272:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 2273:                                               ':'.&escape($id).':'.$rulestr,
 2274:                                               $homeserver));
 2275:                 } elsif ($item eq 'selfcreate') {
 2276:                     $response=&unescape(&reply('instselfcreatecheck:'.
 2277:                                                &escape($udom).':'.&escape($uname).
 2278:                                               ':'.$rulestr,$homeserver));
 2279:                 }
 2280:                 if ($response ne 'refused') {
 2281:                     my @pairs=split(/\&/,$response);
 2282:                     foreach my $item (@pairs) {
 2283:                         my ($key,$value)=split(/=/,$item,2);
 2284:                         $key = &unescape($key);
 2285:                         next if ($key =~ /^error: 2 /);
 2286:                         $returnhash{$key}=&thaw_unescape($value);
 2287:                     }
 2288:                 }
 2289:             }
 2290:         }
 2291:     }
 2292:     return %returnhash;
 2293: }
 2294: 
 2295: sub inst_userrules {
 2296:     my ($udom,$check) = @_;
 2297:     my (%ruleshash,@ruleorder);
 2298:     if ($udom ne '') {
 2299:         my $homeserver=&domain($udom,'primary');
 2300:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 2301:             my $response;
 2302:             if ($check eq 'id') {
 2303:                 $response=&reply('instidrules:'.&escape($udom),
 2304:                                  $homeserver);
 2305:             } elsif ($check eq 'email') {
 2306:                 $response=&reply('instemailrules:'.&escape($udom),
 2307:                                  $homeserver);
 2308:             } else {
 2309:                 $response=&reply('instuserrules:'.&escape($udom),
 2310:                                  $homeserver);
 2311:             }
 2312:             if (($response ne 'refused') && ($response ne 'error') && 
 2313:                 ($response ne 'unknown_cmd') && 
 2314:                 ($response ne 'no_such_host')) {
 2315:                 my ($hashitems,$orderitems) = split(/:/,$response);
 2316:                 my @pairs=split(/\&/,$hashitems);
 2317:                 foreach my $item (@pairs) {
 2318:                     my ($key,$value)=split(/=/,$item,2);
 2319:                     $key = &unescape($key);
 2320:                     next if ($key =~ /^error: 2 /);
 2321:                     $ruleshash{$key}=&thaw_unescape($value);
 2322:                 }
 2323:                 my @esc_order = split(/\&/,$orderitems);
 2324:                 foreach my $item (@esc_order) {
 2325:                     push(@ruleorder,&unescape($item));
 2326:                 }
 2327:             }
 2328:         }
 2329:     }
 2330:     return (\%ruleshash,\@ruleorder);
 2331: }
 2332: 
 2333: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 2334: 
 2335: sub get_domain_defaults {
 2336:     my ($domain,$ignore_cache) = @_;
 2337:     return if (($domain eq '') || ($domain eq 'public'));
 2338:     my $cachetime = 60*60*24;
 2339:     unless ($ignore_cache) {
 2340:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 2341:         if (defined($cached)) {
 2342:             if (ref($result) eq 'HASH') {
 2343:                 return %{$result};
 2344:             }
 2345:         }
 2346:     }
 2347:     my %domdefaults;
 2348:     my %domconfig =
 2349:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
 2350:                                   'requestcourses','inststatus',
 2351:                                   'coursedefaults','usersessions',
 2352:                                   'requestauthor','selfenrollment',
 2353:                                   'coursecategories','autoenroll',
 2354:                                   'helpsettings'],$domain);
 2355:     my @coursetypes = ('official','unofficial','community','textbook');
 2356:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 2357:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 2358:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 2359:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 2360:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 2361:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
 2362:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
 2363:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
 2364:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
 2365:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
 2366:     } else {
 2367:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 2368:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 2369:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 2370:     }
 2371:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 2372:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 2373:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 2374:         } else {
 2375:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 2376:         }
 2377:         my @usertools = ('aboutme','blog','webdav','portfolio');
 2378:         foreach my $item (@usertools) {
 2379:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 2380:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 2381:             }
 2382:         }
 2383:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
 2384:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
 2385:         }
 2386:     }
 2387:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 2388:         foreach my $item ('official','unofficial','community','textbook') {
 2389:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
 2390:         }
 2391:     }
 2392:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
 2393:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
 2394:     }
 2395:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
 2396:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
 2397:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
 2398:         }
 2399:     }
 2400:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
 2401:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
 2402:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
 2403:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
 2404:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
 2405:         }
 2406:         foreach my $type (@coursetypes) {
 2407:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
 2408:                 unless ($type eq 'community') {
 2409:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
 2410:                 }
 2411:             }
 2412:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
 2413:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
 2414:             }
 2415:             if ($domdefaults{'postsubmit'} eq 'on') {
 2416:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
 2417:                     $domdefaults{$type.'postsubtimeout'} =
 2418:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
 2419:                 }
 2420:             }
 2421:         }
 2422:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
 2423:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
 2424:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
 2425:                 if (@clonecodes) {
 2426:                     $domdefaults{'canclone'} = join('+',@clonecodes);
 2427:                 }
 2428:             }
 2429:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
 2430:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
 2431:         }
 2432:         if ($domconfig{'coursedefaults'}{'texengine'}) {
 2433:             $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
 2434:         }
 2435:     }
 2436:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
 2437:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
 2438:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
 2439:         }
 2440:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
 2441:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
 2442:         }
 2443:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
 2444:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
 2445:         }
 2446:         if (ref($domconfig{'usersessions'}{'offloadoth'}) eq 'HASH') {
 2447:             $domdefaults{'offloadoth'} = $domconfig{'usersessions'}{'offloadoth'};
 2448:         }
 2449:     }
 2450:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
 2451:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
 2452:             my @settings = ('types','registered','enroll_dates','access_dates','section',
 2453:                             'approval','limit');
 2454:             foreach my $type (@coursetypes) {
 2455:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
 2456:                     my @mgrdc = ();
 2457:                     foreach my $item (@settings) {
 2458:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
 2459:                             push(@mgrdc,$item);
 2460:                         }
 2461:                     }
 2462:                     if (@mgrdc) {
 2463:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
 2464:                     }
 2465:                 }
 2466:             }
 2467:         }
 2468:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
 2469:             foreach my $type (@coursetypes) {
 2470:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
 2471:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
 2472:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
 2473:                     }
 2474:                 }
 2475:             }
 2476:         }
 2477:     }
 2478:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 2479:         $domdefaults{'catauth'} = 'std';
 2480:         $domdefaults{'catunauth'} = 'std';
 2481:         if ($domconfig{'coursecategories'}{'auth'}) {
 2482:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
 2483:         }
 2484:         if ($domconfig{'coursecategories'}{'unauth'}) {
 2485:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
 2486:         }
 2487:     }
 2488:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 2489:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
 2490:     }
 2491:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
 2492:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
 2493:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
 2494:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
 2495:         }
 2496:     }
 2497:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
 2498:     return %domdefaults;
 2499: }
 2500: 
 2501: sub get_dom_cats {
 2502:     my ($dom) = @_;
 2503:     return unless (&domain($dom));
 2504:     my ($cats,$cached)=&is_cached_new('cats',$dom);
 2505:     unless (defined($cached)) {
 2506:         my %domconfig = &get_dom('configuration',['coursecategories'],$dom);
 2507:         if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 2508:             if (ref($domconfig{'coursecategories'}{'cats'}) eq 'HASH') {
 2509:                 %{$cats} = %{$domconfig{'coursecategories'}{'cats'}};
 2510:             } else {
 2511:                 $cats = {};
 2512:             }
 2513:         } else {
 2514:             $cats = {};
 2515:         }
 2516:         &Apache::lonnet::do_cache_new('cats',$dom,$cats,3600);
 2517:     }
 2518:     return $cats;
 2519: }
 2520: 
 2521: sub get_dom_instcats {
 2522:     my ($dom) = @_;
 2523:     return unless (&domain($dom));
 2524:     my ($instcats,$cached)=&is_cached_new('instcats',$dom);
 2525:     unless (defined($cached)) {
 2526:         my (%coursecodes,%codes,@codetitles,%cat_titles,%cat_order);
 2527:         my $totcodes = &retrieve_instcodes(\%coursecodes,$dom);
 2528:         if ($totcodes > 0) {
 2529:             my $caller = 'global';
 2530:             if (&auto_instcode_format($caller,$dom,\%coursecodes,\%codes,
 2531:                                       \@codetitles,\%cat_titles,\%cat_order) eq 'ok') {
 2532:                 $instcats = {
 2533:                                 codes => \%codes,
 2534:                                 codetitles => \@codetitles,
 2535:                                 cat_titles => \%cat_titles,
 2536:                                 cat_order => \%cat_order,
 2537:                             };
 2538:                 &do_cache_new('instcats',$dom,$instcats,3600);
 2539:             }
 2540:         }
 2541:     }
 2542:     return $instcats;
 2543: }
 2544: 
 2545: sub retrieve_instcodes {
 2546:     my ($coursecodes,$dom) = @_;
 2547:     my $totcodes;
 2548:     my %courses = &courseiddump($dom,'.',1,'.','.','.',undef,undef,'Course');
 2549:     foreach my $course (keys(%courses)) {
 2550:         if (ref($courses{$course}) eq 'HASH') {
 2551:             if ($courses{$course}{'inst_code'} ne '') {
 2552:                 $$coursecodes{$course} = $courses{$course}{'inst_code'};
 2553:                 $totcodes ++;
 2554:             }
 2555:         }
 2556:     }
 2557:     return $totcodes;
 2558: }
 2559: 
 2560: # --------------------------------------------- Get domain config for passwords
 2561: 
 2562: sub get_passwdconf {
 2563:     my ($dom) = @_;
 2564:     my (%passwdconf,$gotconf,$lookup);
 2565:     my ($result,$cached)=&is_cached_new('passwdconf',$dom);
 2566:     if (defined($cached)) {
 2567:         if (ref($result) eq 'HASH') {
 2568:             %passwdconf = %{$result};
 2569:             $gotconf = 1;
 2570:         }
 2571:     }
 2572:     unless ($gotconf) {
 2573:         my %domconfig = &get_dom('configuration',['passwords'],$dom);
 2574:         if (ref($domconfig{'passwords'}) eq 'HASH') {
 2575:             %passwdconf = %{$domconfig{'passwords'}};
 2576:         }
 2577:         my $cachetime = 24*60*60;
 2578:         &do_cache_new('passwdconf',$dom,\%passwdconf,$cachetime);
 2579:     }
 2580:     return %passwdconf;
 2581: }
 2582: 
 2583: sub course_portal_url {
 2584:     my ($cnum,$cdom) = @_;
 2585:     my $chome = &homeserver($cnum,$cdom);
 2586:     my $hostname = &hostname($chome);
 2587:     my $protocol = $protocol{$chome};
 2588:     $protocol = 'http' if ($protocol ne 'https');
 2589:     my %domdefaults = &get_domain_defaults($cdom);
 2590:     my $firsturl;
 2591:     if ($domdefaults{'portal_def'}) {
 2592:         $firsturl = $domdefaults{'portal_def'};
 2593:     } else {
 2594:         $firsturl = $protocol.'://'.$hostname;
 2595:     }
 2596:     return $firsturl;
 2597: }
 2598: 
 2599: # --------------------------------------------------- Assign a key to a student
 2600: 
 2601: sub assign_access_key {
 2602: #
 2603: # a valid key looks like uname:udom#comments
 2604: # comments are being appended
 2605: #
 2606:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 2607:     $kdom=
 2608:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 2609:     $knum=
 2610:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 2611:     $cdom=
 2612:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2613:     $cnum=
 2614:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2615:     $udom=$env{'user.name'} unless (defined($udom));
 2616:     $uname=$env{'user.domain'} unless (defined($uname));
 2617:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 2618:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 2619:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 2620:                                                   # assigned to this person
 2621:                                                   # - this should not happen,
 2622:                                                   # unless something went wrong
 2623:                                                   # the first time around
 2624: # ready to assign
 2625:         $logentry=$1.'; '.$logentry;
 2626:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 2627:                                                  $kdom,$knum) eq 'ok') {
 2628: # key now belongs to user
 2629: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 2630:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 2631:                 &appenv({'environment.'.$envkey => $ckey});
 2632:                 return 'ok';
 2633:             } else {
 2634:                 return 
 2635:   'error: Count not permanently assign key, will need to be re-entered later.';
 2636: 	    }
 2637:         } else {
 2638:             return 'error: Could not assign key, try again later.';
 2639:         }
 2640:     } elsif (!$existing{$ckey}) {
 2641: # the key does not exist
 2642: 	return 'error: The key does not exist';
 2643:     } else {
 2644: # the key is somebody else's
 2645: 	return 'error: The key is already in use';
 2646:     }
 2647: }
 2648: 
 2649: # ------------------------------------------ put an additional comment on a key
 2650: 
 2651: sub comment_access_key {
 2652: #
 2653: # a valid key looks like uname:udom#comments
 2654: # comments are being appended
 2655: #
 2656:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 2657:     $cdom=
 2658:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2659:     $cnum=
 2660:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2661:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2662:     if ($existing{$ckey}) {
 2663:         $existing{$ckey}.='; '.$logentry;
 2664: # ready to assign
 2665:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 2666:                                                  $cdom,$cnum) eq 'ok') {
 2667: 	    return 'ok';
 2668:         } else {
 2669: 	    return 'error: Count not store comment.';
 2670:         }
 2671:     } else {
 2672: # the key does not exist
 2673: 	return 'error: The key does not exist';
 2674:     }
 2675: }
 2676: 
 2677: # ------------------------------------------------------ Generate a set of keys
 2678: 
 2679: sub generate_access_keys {
 2680:     my ($number,$cdom,$cnum,$logentry)=@_;
 2681:     $cdom=
 2682:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2683:     $cnum=
 2684:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2685:     unless (&allowed('mky',$cdom)) { return 0; }
 2686:     unless (($cdom) && ($cnum)) { return 0; }
 2687:     if ($number>10000) { return 0; }
 2688:     sleep(2); # make sure don't get same seed twice
 2689:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 2690:     my $total=0;
 2691:     for (my $i=1;$i<=$number;$i++) {
 2692:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 2693:                   sprintf("%lx",int(100000*rand)).'-'.
 2694:                   sprintf("%lx",int(100000*rand));
 2695:        $newkey=~s/1/g/g; # folks mix up 1 and l
 2696:        $newkey=~s/0/h/g; # and also 0 and O
 2697:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 2698:        if ($existing{$newkey}) {
 2699:            $i--;
 2700:        } else {
 2701: 	  if (&put('accesskeys',
 2702:               { $newkey => '# generated '.localtime().
 2703:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 2704:                            '; '.$logentry },
 2705: 		   $cdom,$cnum) eq 'ok') {
 2706:               $total++;
 2707: 	  }
 2708:        }
 2709:     }
 2710:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 2711:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 2712:     return $total;
 2713: }
 2714: 
 2715: # ------------------------------------------------------- Validate an accesskey
 2716: 
 2717: sub validate_access_key {
 2718:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 2719:     $cdom=
 2720:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2721:     $cnum=
 2722:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2723:     $udom=$env{'user.domain'} unless (defined($udom));
 2724:     $uname=$env{'user.name'} unless (defined($uname));
 2725:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2726:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 2727: }
 2728: 
 2729: # ------------------------------------- Find the section of student in a course
 2730: sub devalidate_getsection_cache {
 2731:     my ($udom,$unam,$courseid)=@_;
 2732:     my $hashid="$udom:$unam:$courseid";
 2733:     &devalidate_cache_new('getsection',$hashid);
 2734: }
 2735: 
 2736: sub courseid_to_courseurl {
 2737:     my ($courseid) = @_;
 2738:     #already url style courseid
 2739:     return $courseid if ($courseid =~ m{^/});
 2740: 
 2741:     if (exists($env{'course.'.$courseid.'.num'})) {
 2742: 	my $cnum = $env{'course.'.$courseid.'.num'};
 2743: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 2744: 	return "/$cdom/$cnum";
 2745:     }
 2746: 
 2747:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 2748:     if (exists($courseinfo{'num'})) {
 2749: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 2750:     }
 2751: 
 2752:     return undef;
 2753: }
 2754: 
 2755: sub getsection {
 2756:     my ($udom,$unam,$courseid)=@_;
 2757:     my $cachetime=1800;
 2758: 
 2759:     my $hashid="$udom:$unam:$courseid";
 2760:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 2761:     if (defined($cached)) { return $result; }
 2762: 
 2763:     my %Pending; 
 2764:     my %Expired;
 2765:     #
 2766:     # Each role can either have not started yet (pending), be active, 
 2767:     #    or have expired.
 2768:     #
 2769:     # If there is an active role, we are done.
 2770:     #
 2771:     # If there is more than one role which has not started yet, 
 2772:     #     choose the one which will start sooner
 2773:     # If there is one role which has not started yet, return it.
 2774:     #
 2775:     # If there is more than one expired role, choose the one which ended last.
 2776:     # If there is a role which has expired, return it.
 2777:     #
 2778:     $courseid = &courseid_to_courseurl($courseid);
 2779:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 2780:     foreach my $key (keys(%roleshash)) {
 2781:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 2782:         my $section=$1;
 2783:         if ($key eq $courseid.'_st') { $section=''; }
 2784:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 2785:         my $now=time;
 2786:         if (defined($end) && $end && ($now > $end)) {
 2787:             $Expired{$end}=$section;
 2788:             next;
 2789:         }
 2790:         if (defined($start) && $start && ($now < $start)) {
 2791:             $Pending{$start}=$section;
 2792:             next;
 2793:         }
 2794:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 2795:     }
 2796:     #
 2797:     # Presumedly there will be few matching roles from the above
 2798:     # loop and the sorting time will be negligible.
 2799:     if (scalar(keys(%Pending))) {
 2800:         my ($time) = sort {$a <=> $b} keys(%Pending);
 2801:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 2802:     } 
 2803:     if (scalar(keys(%Expired))) {
 2804:         my @sorted = sort {$a <=> $b} keys(%Expired);
 2805:         my $time = pop(@sorted);
 2806:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 2807:     }
 2808:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 2809: }
 2810: 
 2811: sub save_cache {
 2812:     &purge_remembered();
 2813:     #&Apache::loncommon::validate_page();
 2814:     undef(%env);
 2815:     undef($env_loaded);
 2816: }
 2817: 
 2818: my $to_remember=-1;
 2819: my %remembered;
 2820: my %accessed;
 2821: my $kicks=0;
 2822: my $hits=0;
 2823: sub make_key {
 2824:     my ($name,$id) = @_;
 2825:     if (length($id) > 65 
 2826: 	&& length(&escape($id)) > 200) {
 2827: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 2828:     }
 2829:     return &escape($name.':'.$id);
 2830: }
 2831: 
 2832: sub devalidate_cache_new {
 2833:     my ($name,$id,$debug) = @_;
 2834:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 2835:     my $remembered_id=$name.':'.$id;
 2836:     $id=&make_key($name,$id);
 2837:     $memcache->delete($id);
 2838:     delete($remembered{$remembered_id});
 2839:     delete($accessed{$remembered_id});
 2840: }
 2841: 
 2842: sub is_cached_new {
 2843:     my ($name,$id,$debug) = @_;
 2844:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) for 
 2845:                                      # keys in %remembered hash, which persists for
 2846:                                      # duration of request (no restriction on key length).
 2847:     if (exists($remembered{$remembered_id})) {
 2848: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
 2849: 	$accessed{$remembered_id}=[&gettimeofday()];
 2850: 	$hits++;
 2851: 	return ($remembered{$remembered_id},1);
 2852:     }
 2853:     $id=&make_key($name,$id);
 2854:     my $value = $memcache->get($id);
 2855:     if (!(defined($value))) {
 2856: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 2857: 	return (undef,undef);
 2858:     }
 2859:     if ($value eq '__undef__') {
 2860: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 2861: 	$value=undef;
 2862:     }
 2863:     &make_room($remembered_id,$value,$debug);
 2864:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 2865:     return ($value,1);
 2866: }
 2867: 
 2868: sub do_cache_new {
 2869:     my ($name,$id,$value,$time,$debug) = @_;
 2870:     my $remembered_id=$name.':'.$id;
 2871:     $id=&make_key($name,$id);
 2872:     my $setvalue=$value;
 2873:     if (!defined($setvalue)) {
 2874: 	$setvalue='__undef__';
 2875:     }
 2876:     if (!defined($time) ) {
 2877: 	$time=600;
 2878:     }
 2879:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 2880:     my $result = $memcache->set($id,$setvalue,$time);
 2881:     if (! $result) {
 2882: 	&logthis("caching of id -> $id  failed");
 2883: 	$memcache->disconnect_all();
 2884:     }
 2885:     # need to make a copy of $value
 2886:     &make_room($remembered_id,$value,$debug);
 2887:     return $value;
 2888: }
 2889: 
 2890: sub make_room {
 2891:     my ($remembered_id,$value,$debug)=@_;
 2892: 
 2893:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
 2894:                                     : $value;
 2895:     if ($to_remember<0) { return; }
 2896:     $accessed{$remembered_id}=[&gettimeofday()];
 2897:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 2898:     my $to_kick;
 2899:     my $max_time=0;
 2900:     foreach my $other (keys(%accessed)) {
 2901: 	if (&tv_interval($accessed{$other}) > $max_time) {
 2902: 	    $to_kick=$other;
 2903: 	    $max_time=&tv_interval($accessed{$other});
 2904: 	}
 2905:     }
 2906:     delete($remembered{$to_kick});
 2907:     delete($accessed{$to_kick});
 2908:     $kicks++;
 2909:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 2910:     return;
 2911: }
 2912: 
 2913: sub purge_remembered {
 2914:     #&logthis("Tossing ".scalar(keys(%remembered)));
 2915:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 2916:     undef(%remembered);
 2917:     undef(%accessed);
 2918: }
 2919: # ------------------------------------- Read an entry from a user's environment
 2920: 
 2921: sub userenvironment {
 2922:     my ($udom,$unam,@what)=@_;
 2923:     my $items;
 2924:     foreach my $item (@what) {
 2925:         $items.=&escape($item).'&';
 2926:     }
 2927:     $items=~s/\&$//;
 2928:     my %returnhash=();
 2929:     my $uhome = &homeserver($unam,$udom);
 2930:     unless ($uhome eq 'no_host') {
 2931:         my @answer=split(/\&/, 
 2932:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
 2933:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
 2934:             return %returnhash;
 2935:         }
 2936:         my $i;
 2937:         for ($i=0;$i<=$#what;$i++) {
 2938: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
 2939:         }
 2940:     }
 2941:     return %returnhash;
 2942: }
 2943: 
 2944: # ---------------------------------------------------------- Get a studentphoto
 2945: sub studentphoto {
 2946:     my ($udom,$unam,$ext) = @_;
 2947:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 2948:     if (defined($env{'request.course.id'})) {
 2949:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 2950:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 2951:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 2952:             } else {
 2953:                 my ($result,$perm_reqd)=
 2954: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 2955:                 if ($result eq 'ok') {
 2956:                     if (!($perm_reqd eq 'yes')) {
 2957:                         return(&retrievestudentphoto($udom,$unam,$ext));
 2958:                     }
 2959:                 }
 2960:             }
 2961:         }
 2962:     } else {
 2963:         my ($result,$perm_reqd) = 
 2964: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 2965:         if ($result eq 'ok') {
 2966:             if (!($perm_reqd eq 'yes')) {
 2967:                 return(&retrievestudentphoto($udom,$unam,$ext));
 2968:             }
 2969:         }
 2970:     }
 2971:     return '/adm/lonKaputt/lonlogo_broken.gif';
 2972: }
 2973: 
 2974: sub retrievestudentphoto {
 2975:     my ($udom,$unam,$ext,$type) = @_;
 2976:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 2977:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 2978:     if ($ret eq 'ok') {
 2979:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 2980:         if ($type eq 'thumbnail') {
 2981:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 2982:         }
 2983:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 2984:         return $tokenurl;
 2985:     } else {
 2986:         if ($type eq 'thumbnail') {
 2987:             return '/adm/lonKaputt/genericstudent_tn.gif';
 2988:         } else { 
 2989:             return '/adm/lonKaputt/lonlogo_broken.gif';
 2990:         }
 2991:     }
 2992: }
 2993: 
 2994: # -------------------------------------------------------------------- New chat
 2995: 
 2996: sub chatsend {
 2997:     my ($newentry,$anon,$group)=@_;
 2998:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 2999:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3000:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 3001:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 3002: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 3003: 		   &escape($newentry)).':'.$group,$chome);
 3004: }
 3005: 
 3006: # ------------------------------------------ Find current version of a resource
 3007: 
 3008: sub getversion {
 3009:     my $fname=&clutter(shift);
 3010:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
 3011:     return &currentversion(&filelocation('',$fname));
 3012: }
 3013: 
 3014: sub currentversion {
 3015:     my $fname=shift;
 3016:     my $author=$fname;
 3017:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3018:     my ($udom,$uname)=split(/\//,$author);
 3019:     my $home=&homeserver($uname,$udom);
 3020:     if ($home eq 'no_host') { 
 3021:         return -1; 
 3022:     }
 3023:     my $answer=&reply("currentversion:$fname",$home);
 3024:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 3025: 	return -1;
 3026:     }
 3027:     return $answer;
 3028: }
 3029: 
 3030: #
 3031: # Return special version number of resource if set by override, empty otherwise
 3032: #
 3033: sub usedversion {
 3034:     my $fname=shift;
 3035:     unless ($fname) { $fname=$env{'request.uri'}; }
 3036:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
 3037:     if ($urlversion) { return $urlversion; }
 3038:     return '';
 3039: }
 3040: 
 3041: # ----------------------------- Subscribe to a resource, return URL if possible
 3042: 
 3043: sub subscribe {
 3044:     my $fname=shift;
 3045:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 3046:     $fname=~s/[\n\r]//g;
 3047:     my $author=$fname;
 3048:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3049:     my ($udom,$uname)=split(/\//,$author);
 3050:     my $home=homeserver($uname,$udom);
 3051:     if ($home eq 'no_host') {
 3052:         return 'not_found';
 3053:     }
 3054:     my $answer=reply("sub:$fname",$home);
 3055:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 3056: 	$answer.=' by '.$home;
 3057:     }
 3058:     return $answer;
 3059: }
 3060:     
 3061: # -------------------------------------------------------------- Replicate file
 3062: 
 3063: sub repcopy {
 3064:     my $filename=shift;
 3065:     $filename=~s/\/+/\//g;
 3066:     my $londocroot = $perlvar{'lonDocRoot'};
 3067:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
 3068:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
 3069:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
 3070: 	$filename=~m{^/*(uploaded|editupload)/}) {
 3071: 	return &repcopy_userfile($filename);
 3072:     }
 3073:     $filename=~s/[\n\r]//g;
 3074:     my $transname="$filename.in.transfer";
 3075: # FIXME: this should flock
 3076:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 3077:     my $remoteurl=subscribe($filename);
 3078:     if ($remoteurl =~ /^con_lost by/) {
 3079: 	   &logthis("Subscribe returned $remoteurl: $filename");
 3080:            return 'unavailable';
 3081:     } elsif ($remoteurl eq 'not_found') {
 3082: 	   #&logthis("Subscribe returned not_found: $filename");
 3083: 	   return 'not_found';
 3084:     } elsif ($remoteurl =~ /^rejected by/) {
 3085: 	   &logthis("Subscribe returned $remoteurl: $filename");
 3086:            return 'forbidden';
 3087:     } elsif ($remoteurl eq 'directory') {
 3088:            return 'ok';
 3089:     } else {
 3090:         my $author=$filename;
 3091:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3092:         my ($udom,$uname)=split(/\//,$author);
 3093:         my $home=homeserver($uname,$udom);
 3094:         unless ($home eq $perlvar{'lonHostID'}) {
 3095:            my @parts=split(/\//,$filename);
 3096:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 3097:            if ($path ne "$londocroot/res") {
 3098:                &logthis("Malconfiguration for replication: $filename");
 3099: 	       return 'bad_request';
 3100:            }
 3101:            my $count;
 3102:            for ($count=5;$count<$#parts;$count++) {
 3103:                $path.="/$parts[$count]";
 3104:                if ((-e $path)!=1) {
 3105: 		   mkdir($path,0777);
 3106:                }
 3107:            }
 3108:            my $ua=new LWP::UserAgent;
 3109:            my $request=new HTTP::Request('GET',"$remoteurl");
 3110:            my $response=$ua->request($request,$transname);
 3111:            if ($response->is_error()) {
 3112: 	       unlink($transname);
 3113:                my $message=$response->status_line;
 3114:                &logthis("<font color=\"blue\">WARNING:"
 3115:                        ." LWP get: $message: $filename</font>");
 3116:                return 'unavailable';
 3117:            } else {
 3118: 	       if ($remoteurl!~/\.meta$/) {
 3119:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 3120:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
 3121:                   if ($mresponse->is_error()) {
 3122: 		      unlink($filename.'.meta');
 3123:                       &logthis(
 3124:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 3125:                   }
 3126: 	       }
 3127:                rename($transname,$filename);
 3128:                return 'ok';
 3129:            }
 3130:        }
 3131:     }
 3132: }
 3133: 
 3134: # ------------------------------------------------- Unsubscribe from a resource
 3135: 
 3136: sub unsubscribe {
 3137:     my ($fname) = @_;
 3138:     my $answer;
 3139:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return $answer; }
 3140:     $fname=~s/[\n\r]//g;
 3141:     my $author=$fname;
 3142:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3143:     my ($udom,$uname)=split(/\//,$author);
 3144:     my $home=homeserver($uname,$udom);
 3145:     if ($home eq 'no_host') {
 3146:         $answer = 'no_host';
 3147:     } elsif (grep { $_ eq $home } &current_machine_ids()) {
 3148:         $answer = 'home';
 3149:     } else {
 3150:         $answer = reply("unsub:$fname",$home);
 3151:     }
 3152:     return $answer;
 3153: }
 3154: 
 3155: # ------------------------------------------------ Get server side include body
 3156: sub ssi_body {
 3157:     my ($filelink,%form)=@_;
 3158:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 3159:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 3160:     }
 3161:     my $output='';
 3162:     my $response;
 3163:     if ($filelink=~/^https?\:/) {
 3164:        ($output,$response)=&externalssi($filelink);
 3165:     } else {
 3166:        $filelink .= $filelink=~/\?/ ? '&' : '?';
 3167:        $filelink .= 'inhibitmenu=yes';
 3168:        ($output,$response)=&ssi($filelink,%form);
 3169:     }
 3170:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 3171:     $output=~s/^.*?\<body[^\>]*\>//si;
 3172:     $output=~s/\<\/body\s*\>.*?$//si;
 3173:     if (wantarray) {
 3174:         return ($output, $response);
 3175:     } else {
 3176:         return $output;
 3177:     }
 3178: }
 3179: 
 3180: # --------------------------------------------------------- Server Side Include
 3181: 
 3182: sub absolute_url {
 3183:     my ($host_name) = @_;
 3184:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 3185:     if ($host_name eq '') {
 3186: 	$host_name = $ENV{'SERVER_NAME'};
 3187:     }
 3188:     return $protocol.$host_name;
 3189: }
 3190: 
 3191: #
 3192: #   Server side include.
 3193: # Parameters:
 3194: #  fn     Possibly encrypted resource name/id.
 3195: #  form   Hash that describes how the rendering should be done
 3196: #         and other things.
 3197: # Returns:
 3198: #   Scalar context: The content of the response.
 3199: #   Array context:  2 element list of the content and the full response object.
 3200: #     
 3201: sub ssi {
 3202: 
 3203:     my ($fn,%form)=@_;
 3204:     my ($request,$response);
 3205: 
 3206:     $form{'no_update_last_known'}=1;
 3207:     &Apache::lonenc::check_encrypt(\$fn);
 3208:     if (%form) {
 3209:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 3210:       $request->content(join('&',map {
 3211:             my $name = escape($_);
 3212:             "$name=" . ( ref($form{$_}) eq 'ARRAY'
 3213:             ? join("&$name=", map {escape($_) } @{$form{$_}})
 3214:             : &escape($form{$_}) );
 3215:         } keys(%form)));
 3216:     } else {
 3217:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 3218:     }
 3219: 
 3220:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 3221: 
 3222:     if (($env{'request.course.id'}) &&
 3223:         ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
 3224:         ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
 3225:         ($form{'grade_symb'} ne '') &&
 3226:         (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
 3227:                                  ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
 3228:         if (LWP::UserAgent->VERSION >= 5.834) {
 3229:             my $ua=new LWP::UserAgent;
 3230:             $ua->local_address('127.0.0.1');
 3231:             $response = $ua->request($request);
 3232:         } else {
 3233:             {
 3234:                 require LWP::Protocol::http;
 3235:                 local @LWP::Protocol::http::EXTRA_SOCK_OPTS = (LocalAddr => '127.0.0.1');
 3236:                 my $ua=new LWP::UserAgent;
 3237:                 $response = $ua->request($request);
 3238:                 @LWP::Protocol::http::EXTRA_SOCK_OPTS = ();
 3239:             }
 3240:         }
 3241:     } else {
 3242:         my $ua=new LWP::UserAgent;
 3243:         $response = $ua->request($request);
 3244:     }
 3245:     if (wantarray) {
 3246: 	return ($response->content, $response);
 3247:     } else {
 3248: 	return $response->content;
 3249:     }
 3250: }
 3251: 
 3252: sub externalssi {
 3253:     my ($url)=@_;
 3254:     my $ua=new LWP::UserAgent;
 3255:     my $request=new HTTP::Request('GET',$url);
 3256:     my $response=$ua->request($request);
 3257:     if (wantarray) {
 3258:         return ($response->content, $response);
 3259:     } else {
 3260:         return $response->content;
 3261:     }
 3262: }
 3263: 
 3264: # If the local copy of a replicated resource is outdated, trigger a
 3265: # connection from the homeserver to flush the delayed queue. If no update
 3266: # happens, remove local copies of outdated resource (and corresponding
 3267: # metadata file).
 3268: 
 3269: sub remove_stale_resfile {
 3270:     my ($url) = @_;
 3271:     my $removed;
 3272:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
 3273:         my $audom = $1;
 3274:         my $auname = $2;
 3275:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
 3276:             my $homeserver = &homeserver($auname,$audom);
 3277:             unless (($homeserver eq 'no_host') ||
 3278:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
 3279:                 my $fname = &filelocation('',$url);
 3280:                 if (-e $fname) {
 3281:                     my $hostname = &hostname($homeserver);
 3282:                     if ($hostname) {
 3283:                         my $protocol = $protocol{$homeserver};
 3284:                         $protocol = 'http' if ($protocol ne 'https');
 3285:                         my $uri = $protocol.'://'.$hostname.'/raw/'.&declutter($url);
 3286:                         my $ua=new LWP::UserAgent;
 3287:                         $ua->timeout(5);
 3288:                         my $request=new HTTP::Request('HEAD',$uri);
 3289:                         my $response=$ua->request($request);
 3290:                         if ($response->is_success()) {
 3291:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
 3292:                             my $locmodtime = (stat($fname))[9];
 3293:                             if ($locmodtime < $remmodtime) {
 3294:                                 my $stale;
 3295:                                 my $answer = &reply('pong',$homeserver);
 3296:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
 3297:                                     sleep(0.2);
 3298:                                     $locmodtime = (stat($fname))[9];
 3299:                                     if ($locmodtime < $remmodtime) {
 3300:                                         my $posstransfer = $fname.'.in.transfer';
 3301:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
 3302:                                             $removed = 1;
 3303:                                         } else {
 3304:                                             $stale = 1;
 3305:                                         }
 3306:                                     } else {
 3307:                                         $removed = 1;
 3308:                                     }
 3309:                                 } else {
 3310:                                     $stale = 1;
 3311:                                 }
 3312:                                 if ($stale) {
 3313:                                     if (unlink($fname)) {
 3314:                                         if ($uri!~/\.meta$/) {
 3315:                                             if (-e $fname.'.meta') {
 3316:                                                 unlink($fname.'.meta');
 3317:                                             }
 3318:                                         }
 3319:                                         my $unsubresult = &unsubscribe($fname);
 3320:                                         unless ($unsubresult eq 'ok') {
 3321:                                             &logthis("no unsub of $fname from $homeserver, reason: $unsubresult");
 3322:                                         }
 3323:                                         $removed = 1;
 3324:                                     }
 3325:                                 }
 3326:                             }
 3327:                         }
 3328:                     }
 3329:                 }
 3330:             }
 3331:         }
 3332:     }
 3333:     return $removed;
 3334: }
 3335: 
 3336: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 3337: 
 3338: sub allowuploaded {
 3339:     my ($srcurl,$url)=@_;
 3340:     $url=&clutter(&declutter($url));
 3341:     my $dir=$url;
 3342:     $dir=~s/\/[^\/]+$//;
 3343:     my %httpref=();
 3344:     my $httpurl=&hreflocation('',$url);
 3345:     $httpref{'httpref.'.$httpurl}=$srcurl;
 3346:     &Apache::lonnet::appenv(\%httpref);
 3347: }
 3348: 
 3349: #
 3350: # Determine if the current user should be able to edit a particular resource,
 3351: # when viewing in course context.
 3352: # (a) When viewing resource used to determine if "Edit" item is included in
 3353: #     Functions.
 3354: # (b) When displaying folder contents in course editor, used to determine if
 3355: #     "Edit" link will be displayed alongside resource.
 3356: #
 3357: #  input: six args -- filename (decluttered), course number, course domain,
 3358: #                   url, symb (if registered) and group (if this is a group
 3359: #                   item -- e.g., bulletin board, group page etc.).
 3360: #  output: array of five scalars --
 3361: #          $cfile -- url for file editing if editable on current server
 3362: #          $home -- homeserver of resource (i.e., for author if published,
 3363: #                                           or course if uploaded.).
 3364: #          $switchserver --  1 if server switch will be needed.
 3365: #          $forceedit -- 1 if icon/link should be to go to edit mode
 3366: #          $forceview -- 1 if icon/link should be to go to view mode
 3367: #
 3368: 
 3369: sub can_edit_resource {
 3370:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
 3371:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
 3372: #
 3373: # For aboutme pages user can only edit his/her own.
 3374: #
 3375:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
 3376:         my ($sdom,$sname) = ($1,$2);
 3377:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
 3378:             $home = $env{'user.home'};
 3379:             $cfile = $resurl;
 3380:             if ($env{'form.forceedit'}) {
 3381:                 $forceview = 1;
 3382:             } else {
 3383:                 $forceedit = 1;
 3384:             }
 3385:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
 3386:         } else {
 3387:             return;
 3388:         }
 3389:     }
 3390: 
 3391:     if ($env{'request.course.id'}) {
 3392:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
 3393:         if ($group ne '') {
 3394: # if this is a group homepage or group bulletin board, check group privs
 3395:             my $allowed = 0;
 3396:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
 3397:                 if ((&allowed('mdg',$env{'request.course.id'}.
 3398:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 3399:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 3400:                     $allowed = 1;
 3401:                 }
 3402:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
 3403:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 3404:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 3405:                     $allowed = 1;
 3406:                 }
 3407:             }
 3408:             if ($allowed) {
 3409:                 $home=&homeserver($cnum,$cdom);
 3410:                 if ($env{'form.forceedit'}) {
 3411:                     $forceview = 1;
 3412:                 } else {
 3413:                     $forceedit = 1;
 3414:                 }
 3415:                 $cfile = $resurl;
 3416:             } else {
 3417:                 return;
 3418:             }
 3419:         } else {
 3420:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
 3421:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
 3422:                     return;
 3423:                 }
 3424:             } elsif (!$crsedit) {
 3425: #
 3426: # No edit allowed where CC has switched to student role.
 3427: #
 3428:                 return;
 3429:             }
 3430:         }
 3431:     }
 3432: 
 3433:     if ($file ne '') {
 3434:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
 3435:             if (&is_course_upload($file,$cnum,$cdom)) {
 3436:                 $uploaded = 1;
 3437:                 $incourse = 1;
 3438:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
 3439:                     $cfile = &hreflocation('',$file);
 3440:                     if ($env{'form.forceedit'}) {
 3441:                         $forceview = 1;
 3442:                     } else {
 3443:                         $forceedit = 1;
 3444:                     }
 3445:                 }
 3446:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
 3447:                 $incourse = 1;
 3448:                 if ($env{'form.forceedit'}) {
 3449:                     $forceview = 1;
 3450:                 } else {
 3451:                     $forceedit = 1;
 3452:                 }
 3453:                 $cfile = $resurl;
 3454:             } elsif (($resurl ne '') && (&is_on_map($resurl))) {
 3455:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
 3456:                     $incourse = 1;
 3457:                     if ($env{'form.forceedit'}) {
 3458:                         $forceview = 1;
 3459:                     } else {
 3460:                         $forceedit = 1;
 3461:                     }
 3462:                     $cfile = $resurl;
 3463:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
 3464:                     $incourse = 1;
 3465:                     $cfile = $resurl.'/smpedit';
 3466:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
 3467:                     $incourse = 1;
 3468:                     if ($env{'form.forceedit'}) {
 3469:                         $forceview = 1;
 3470:                     } else {
 3471:                         $forceedit = 1;
 3472:                     }
 3473:                     $cfile = $resurl;
 3474:                 } elsif (($resurl =~ m{^/ext/}) && ($symb ne '')) {
 3475:                     my ($map,$id,$res) = &decode_symb($symb);
 3476:                     if ($map =~ /\.page$/) {
 3477:                         $incourse = 1;
 3478:                         if ($env{'form.forceedit'}) {
 3479:                             $forceview = 1;
 3480:                             $cfile = $map;
 3481:                         } else {
 3482:                             $forceedit = 1;
 3483:                             $cfile =  '/adm/wrapper'.$resurl;
 3484:                         }
 3485:                     }
 3486:                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
 3487:                     $incourse = 1;
 3488:                     if ($env{'form.forceedit'}) {
 3489:                         $forceview = 1;
 3490:                     } else {
 3491:                         $forceedit = 1;
 3492:                     }
 3493:                     $cfile = $resurl;
 3494:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 3495:                     $incourse = 1;
 3496:                     if ($env{'form.forceedit'}) {
 3497:                         $forceview = 1;
 3498:                     } else {
 3499:                         $forceedit = 1;
 3500:                     }
 3501:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 3502:                 }
 3503:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
 3504:                 my $template = '/res/lib/templates/simpleproblem.problem';
 3505:                 if (&is_on_map($template)) {
 3506:                     $incourse = 1;
 3507:                     $forceview = 1;
 3508:                     $cfile = $template;
 3509:                 }
 3510:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 3511:                 $incourse = 1;
 3512:                 if ($env{'form.forceedit'}) {
 3513:                     $forceview = 1;
 3514:                 } else {
 3515:                     $forceedit = 1;
 3516:                 }
 3517:                 $cfile = $resurl;
 3518:             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 3519:                 $incourse = 1;
 3520:                 if ($env{'form.forceedit'}) {
 3521:                     $forceview = 1;
 3522:                 } else {
 3523:                     $forceedit = 1;
 3524:                 }
 3525:                 $cfile = $resurl;
 3526:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
 3527:                 $incourse = 1;
 3528:                 $forceview = 1;
 3529:                 if ($symb) {
 3530:                     my ($map,$id,$res)=&decode_symb($symb);
 3531:                     $env{'request.symb'} = $symb;
 3532:                     $cfile = &clutter($res);
 3533:                 } else {
 3534:                     $cfile = $env{'form.suppurl'};
 3535:                     my $escfile = &unescape($cfile);
 3536:                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
 3537:                         $cfile = '/adm/wrapper'.$escfile;
 3538:                     } else {
 3539:                         $escfile =~ s{^http://}{};
 3540:                         $cfile = &escape("/adm/wrapper/ext/$escfile");
 3541:                     }
 3542:                 }
 3543:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 3544:                 if ($env{'form.forceedit'}) {
 3545:                     $forceview = 1;
 3546:                 } else {
 3547:                     $forceedit = 1;
 3548:                 }
 3549:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 3550:             }
 3551:         }
 3552:         if ($uploaded || $incourse) {
 3553:             $home=&homeserver($cnum,$cdom);
 3554:         } elsif ($file !~ m{/$}) {
 3555:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
 3556:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
 3557:             # Check that the user has permission to edit this resource
 3558:             my $setpriv = 1;
 3559:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
 3560:             if (defined($cfudom)) {
 3561:                 $home=&homeserver($cfuname,$cfudom);
 3562:                 $cfile=$file;
 3563:             }
 3564:         }
 3565:         if (($cfile ne '') && (!$incourse || $uploaded) &&
 3566:             (($home ne '') && ($home ne 'no_host'))) {
 3567:             my @ids=&current_machine_ids();
 3568:             unless (grep(/^\Q$home\E$/,@ids)) {
 3569:                 $switchserver=1;
 3570:             }
 3571:         }
 3572:     }
 3573:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
 3574: }
 3575: 
 3576: sub is_course_upload {
 3577:     my ($file,$cnum,$cdom) = @_;
 3578:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
 3579:     $uploadpath =~ s{^\/}{};
 3580:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
 3581:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
 3582:         return 1;
 3583:     }
 3584:     return;
 3585: }
 3586: 
 3587: sub in_course {
 3588:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
 3589:     if ($hideprivileged) {
 3590:         my $skipuser;
 3591:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
 3592:         my @possdoms = ($cdom);
 3593:         if ($coursehash{'checkforpriv'}) {
 3594:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
 3595:         }
 3596:         if (&privileged($uname,$udom,\@possdoms)) {
 3597:             $skipuser = 1;
 3598:             if ($coursehash{'nothideprivileged'}) {
 3599:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3600:                     my $user;
 3601:                     if ($item =~ /:/) {
 3602:                         $user = $item;
 3603:                     } else {
 3604:                         $user = join(':',split(/[\@]/,$item));
 3605:                     }
 3606:                     if ($user eq $uname.':'.$udom) {
 3607:                         undef($skipuser);
 3608:                         last;
 3609:                     }
 3610:                 }
 3611:             }
 3612:             if ($skipuser) {
 3613:                 return 0;
 3614:             }
 3615:         }
 3616:     }
 3617:     $type ||= 'any';
 3618:     if (!defined($cdom) || !defined($cnum)) {
 3619:         my $cid  = $env{'request.course.id'};
 3620:         $cdom = $env{'course.'.$cid.'.domain'};
 3621:         $cnum = $env{'course.'.$cid.'.num'};
 3622:     }
 3623:     my $typesref;
 3624:     if (($type eq 'any') || ($type eq 'all')) {
 3625:         $typesref = ['active','previous','future'];
 3626:     } elsif ($type eq 'previous' || $type eq 'future') {
 3627:         $typesref = [$type];
 3628:     }
 3629:     my %roles = &get_my_roles($uname,$udom,'userroles',
 3630:                               $typesref,undef,[$cdom]);
 3631:     my ($tmp) = keys(%roles);
 3632:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
 3633:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
 3634:     if (@course_roles > 0) {
 3635:         return 1;
 3636:     }
 3637:     return 0;
 3638: }
 3639: 
 3640: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 3641: # input: action, courseID, current domain, intended
 3642: #        path to file, source of file, instruction to parse file for objects,
 3643: #        ref to hash for embedded objects,
 3644: #        ref to hash for codebase of java objects.
 3645: #        reference to scalar to accommodate mime type determined
 3646: #          from File::MMagic if $parser = parse.
 3647: #
 3648: # output: url to file (if action was uploaddoc), 
 3649: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 3650: #
 3651: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 3652: # course.
 3653: #
 3654: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3655: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 3656: #          course's home server.
 3657: #
 3658: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 3659: #          be copied from $source (current location) to 
 3660: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3661: #         and will then be copied to
 3662: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 3663: #         course's home server.
 3664: #
 3665: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3666: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 3667: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3668: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 3669: #         in course's home server.
 3670: #
 3671: 
 3672: sub process_coursefile {
 3673:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
 3674:         $mimetype)=@_;
 3675:     my $fetchresult;
 3676:     my $home=&homeserver($docuname,$docudom);
 3677:     if ($action eq 'propagate') {
 3678:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3679: 			     $home);
 3680:     } else {
 3681:         my $fpath = '';
 3682:         my $fname = $file;
 3683:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3684:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3685:         my $filepath = &build_filepath($fpath);
 3686:         if ($action eq 'copy') {
 3687:             if ($source eq '') {
 3688:                 $fetchresult = 'no source file';
 3689:                 return $fetchresult;
 3690:             } else {
 3691:                 my $destination = $filepath.'/'.$fname;
 3692:                 rename($source,$destination);
 3693:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3694:                                  $home);
 3695:             }
 3696:         } elsif ($action eq 'uploaddoc') {
 3697:             open(my $fh,'>',$filepath.'/'.$fname);
 3698:             print $fh $env{'form.'.$source};
 3699:             close($fh);
 3700:             if ($parser eq 'parse') {
 3701:                 my $mm = new File::MMagic;
 3702:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
 3703:                 if ($type eq 'text/html') {
 3704:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 3705:                     unless ($parse_result eq 'ok') {
 3706:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 3707:                     }
 3708:                 }
 3709:                 if (ref($mimetype)) {
 3710:                     $$mimetype = $type;
 3711:                 } 
 3712:             }
 3713:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3714:                                  $home);
 3715:             if ($fetchresult eq 'ok') {
 3716:                 return '/uploaded/'.$fpath.'/'.$fname;
 3717:             } else {
 3718:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3719:                         ' to host '.$home.': '.$fetchresult);
 3720:                 return '/adm/notfound.html';
 3721:             }
 3722:         }
 3723:     }
 3724:     unless ( $fetchresult eq 'ok') {
 3725:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3726:              ' to host '.$home.': '.$fetchresult);
 3727:     }
 3728:     return $fetchresult;
 3729: }
 3730: 
 3731: sub build_filepath {
 3732:     my ($fpath) = @_;
 3733:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 3734:     unless ($fpath eq '') {
 3735:         my @parts=split('/',$fpath);
 3736:         foreach my $part (@parts) {
 3737:             $filepath.= '/'.$part;
 3738:             if ((-e $filepath)!=1) {
 3739:                 mkdir($filepath,0777);
 3740:             }
 3741:         }
 3742:     }
 3743:     return $filepath;
 3744: }
 3745: 
 3746: sub store_edited_file {
 3747:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 3748:     my $file = $primary_url;
 3749:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 3750:     my $fpath = '';
 3751:     my $fname = $file;
 3752:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3753:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3754:     my $filepath = &build_filepath($fpath);
 3755:     open(my $fh,'>',$filepath.'/'.$fname);
 3756:     print $fh $content;
 3757:     close($fh);
 3758:     my $home=&homeserver($docuname,$docudom);
 3759:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3760: 			  $home);
 3761:     if ($$fetchresult eq 'ok') {
 3762:         return '/uploaded/'.$fpath.'/'.$fname;
 3763:     } else {
 3764:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3765: 		 ' to host '.$home.': '.$$fetchresult);
 3766:         return '/adm/notfound.html';
 3767:     }
 3768: }
 3769: 
 3770: sub clean_filename {
 3771:     my ($fname,$args)=@_;
 3772: # Replace Windows backslashes by forward slashes
 3773:     $fname=~s/\\/\//g;
 3774:     if (!$args->{'keep_path'}) {
 3775:         # Get rid of everything but the actual filename
 3776: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 3777:     }
 3778: # Replace spaces by underscores
 3779:     $fname=~s/\s+/\_/g;
 3780: # Transliterate non-ascii text to ascii
 3781:     my $lang = &Apache::lonlocal::current_language();
 3782:     $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
 3783: # Replace all other weird characters by nothing
 3784:     $fname=~s{[^/\w\.\-]}{}g;
 3785: # Replace all .\d. sequences with _\d. so they no longer look like version
 3786: # numbers
 3787:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 3788: # Replace three or more adjacent underscores with one for consistency
 3789: # with loncfile::filename_check() so complete url can be extracted by
 3790: # lonnet::decode_symb()
 3791:     $fname=~s/_{3,}/_/g;
 3792:     return $fname;
 3793: }
 3794: 
 3795: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
 3796: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
 3797: # image with the same aspect ratio as the original, but with dimensions which do 
 3798: # not exceed $resizewidth and $resizeheight.
 3799:  
 3800: sub resizeImage {
 3801:     my ($img_path,$resizewidth,$resizeheight) = @_;
 3802:     my $ima = Image::Magick->new;
 3803:     my $resized;
 3804:     if (-e $img_path) {
 3805:         $ima->Read($img_path);
 3806:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
 3807:             my $width = $ima->Get('width');
 3808:             my $height = $ima->Get('height');
 3809:             if ($width > $resizewidth) {
 3810: 	        my $factor = $width/$resizewidth;
 3811:                 my $newheight = $height/$factor;
 3812:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
 3813:                 $resized = 1;
 3814:             }
 3815:         }
 3816:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
 3817:             my $width = $ima->Get('width');
 3818:             my $height = $ima->Get('height');
 3819:             if ($height > $resizeheight) {
 3820:                 my $factor = $height/$resizeheight;
 3821:                 my $newwidth = $width/$factor;
 3822:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
 3823:                 $resized = 1;
 3824:             }
 3825:         }
 3826:         if ($resized) {
 3827:             $ima->Write($img_path);
 3828:         }
 3829:     }
 3830:     return;
 3831: }
 3832: 
 3833: # --------------- Take an uploaded file and put it into the userfiles directory
 3834: # input: $formname - the contents of the file are in $env{"form.$formname"}
 3835: #                    the desired filename is in $env{"form.$formname.filename"}
 3836: #        $context - possible values: coursedoc, existingfile, overwrite, 
 3837: #                                    canceloverwrite, scantron or ''. 
 3838: #                   if 'coursedoc': upload to the current course
 3839: #                   if 'existingfile': write file to tmp/overwrites directory 
 3840: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
 3841: #                   $context is passed as argument to &finishuserfileupload
 3842: #        $subdir - directory in userfile to store the file into
 3843: #        $parser - instruction to parse file for objects ($parser = parse) or
 3844: #                  if context is 'scantron', $parser is hashref of csv column mapping
 3845: #                  (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3,
 3846: #                          Section => 4, CODE => 5, FirstQuestion => 9 }).
 3847: #        $allfiles - reference to hash for embedded objects
 3848: #        $codebase - reference to hash for codebase of java objects
 3849: #        $desuname - username for permanent storage of uploaded file
 3850: #        $dsetudom - domain for permanaent storage of uploaded file
 3851: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 3852: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 3853: #        $resizewidth - width (pixels) to which to resize uploaded image
 3854: #        $resizeheight - height (pixels) to which to resize uploaded image
 3855: #        $mimetype - reference to scalar to accommodate mime type determined
 3856: #                    from File::MMagic.
 3857: # 
 3858: # output: url of file in userspace, or error: <message> 
 3859: #             or /adm/notfound.html if failure to upload occurse
 3860: 
 3861: sub userfileupload {
 3862:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
 3863:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
 3864:     if (!defined($subdir)) { $subdir='unknown'; }
 3865:     my $fname=$env{'form.'.$formname.'.filename'};
 3866:     $fname=&clean_filename($fname);
 3867:     # See if there is anything left
 3868:     unless ($fname) { return 'error: no uploaded file'; }
 3869:     # If filename now begins with a . prepend unix timestamp _ milliseconds
 3870:     if ($fname =~ /^\./) {
 3871:         my ($s,$usec) = &gettimeofday();
 3872:         while (length($usec) < 6) {
 3873:             $usec = '0'.$usec;
 3874:         }
 3875:         $fname = $s.'_'.substr($usec,0,3).$fname;
 3876:     }
 3877:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
 3878:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
 3879:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
 3880:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3881:         my $now = time;
 3882:         my $filepath;
 3883:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
 3884:              $filepath = 'tmp/helprequests/'.$now;
 3885:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
 3886:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 3887:                          '_'.$env{'user.domain'}.'/pending';
 3888:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3889:             my ($docuname,$docudom);
 3890:             if ($destudom =~ /^$match_domain$/) {
 3891:                 $docudom = $destudom;
 3892:             } else {
 3893:                 $docudom = $env{'user.domain'};
 3894:             }
 3895:             if ($destuname =~ /^$match_username$/) { 
 3896:                 $docuname = $destuname;
 3897:             } else {
 3898:                 $docuname = $env{'user.name'};
 3899:             }
 3900:             if (exists($env{'form.group'})) {
 3901:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3902:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3903:             }
 3904:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
 3905:             if ($context eq 'canceloverwrite') {
 3906:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
 3907:                 if (-e  $tempfile) {
 3908:                     my @info = stat($tempfile);
 3909:                     if ($info[9] eq $env{'form.timestamp'}) {
 3910:                         unlink($tempfile);
 3911:                     }
 3912:                 }
 3913:                 return;
 3914:             }
 3915:         }
 3916:         # Create the directory if not present
 3917:         my @parts=split(/\//,$filepath);
 3918:         my $fullpath = $perlvar{'lonDaemons'};
 3919:         for (my $i=0;$i<@parts;$i++) {
 3920:             $fullpath .= '/'.$parts[$i];
 3921:             if ((-e $fullpath)!=1) {
 3922:                 mkdir($fullpath,0777);
 3923:             }
 3924:         }
 3925:         open(my $fh,'>',$fullpath.'/'.$fname);
 3926:         print $fh $env{'form.'.$formname};
 3927:         close($fh);
 3928:         if ($context eq 'existingfile') {
 3929:             my @info = stat($fullpath.'/'.$fname);
 3930:             return ($fullpath.'/'.$fname,$info[9]);
 3931:         } else {
 3932:             return $fullpath.'/'.$fname;
 3933:         }
 3934:     }
 3935:     if ($subdir eq 'scantron') {
 3936:         $fname = 'scantron_orig_'.$fname;
 3937:     } else {
 3938:         $fname="$subdir/$fname";
 3939:     }
 3940:     if ($context eq 'coursedoc') {
 3941: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3942: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3943:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 3944:             return &finishuserfileupload($docuname,$docudom,
 3945: 					 $formname,$fname,$parser,$allfiles,
 3946: 					 $codebase,$thumbwidth,$thumbheight,
 3947:                                          $resizewidth,$resizeheight,$context,$mimetype);
 3948:         } else {
 3949:             if ($env{'form.folder'}) {
 3950:                 $fname=$env{'form.folder'}.'/'.$fname;
 3951:             }
 3952:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 3953: 				       $fname,$formname,$parser,
 3954: 				       $allfiles,$codebase,$mimetype);
 3955:         }
 3956:     } elsif (defined($destuname)) {
 3957:         my $docuname=$destuname;
 3958:         my $docudom=$destudom;
 3959: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 3960: 				     $parser,$allfiles,$codebase,
 3961:                                      $thumbwidth,$thumbheight,
 3962:                                      $resizewidth,$resizeheight,$context,$mimetype);
 3963:     } else {
 3964:         my $docuname=$env{'user.name'};
 3965:         my $docudom=$env{'user.domain'};
 3966:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
 3967:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3968:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3969:         }
 3970: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 3971: 				     $parser,$allfiles,$codebase,
 3972:                                      $thumbwidth,$thumbheight,
 3973:                                      $resizewidth,$resizeheight,$context,$mimetype);
 3974:     }
 3975: }
 3976: 
 3977: sub finishuserfileupload {
 3978:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 3979:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
 3980:     my $path=$docudom.'/'.$docuname.'/';
 3981:     my $filepath=$perlvar{'lonDocRoot'};
 3982:   
 3983:     my ($fnamepath,$file,$fetchthumb);
 3984:     $file=$fname;
 3985:     if ($fname=~m|/|) {
 3986:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 3987: 	$path.=$fnamepath.'/';
 3988:     }
 3989:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 3990:     my $count;
 3991:     for ($count=4;$count<=$#parts;$count++) {
 3992:         $filepath.="/$parts[$count]";
 3993:         if ((-e $filepath)!=1) {
 3994: 	    mkdir($filepath,0777);
 3995:         }
 3996:     }
 3997: 
 3998: # Save the file
 3999:     {
 4000: 	if (!open(FH,'>',$filepath.'/'.$file)) {
 4001: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 4002: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 4003: 	    return '/adm/notfound.html';
 4004: 	}
 4005:         if ($context eq 'overwrite') {
 4006:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
 4007:             my $target = $filepath.'/'.$file;
 4008:             if (-e $source) {
 4009:                 my @info = stat($source);
 4010:                 if ($info[9] eq $env{'form.timestamp'}) {   
 4011:                     unless (&File::Copy::move($source,$target)) {
 4012:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
 4013:                         return "Moving from $source failed";
 4014:                     }
 4015:                 } else {
 4016:                     return "Temporary file: $source had unexpected date/time for last modification";
 4017:                 }
 4018:             } else {
 4019:                 return "Temporary file: $source missing";
 4020:             }
 4021:         } elsif (!print FH ($env{'form.'.$formname})) {
 4022: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 4023: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 4024: 	    return '/adm/notfound.html';
 4025: 	}
 4026: 	close(FH);
 4027:         if ($resizewidth && $resizeheight) {
 4028:             my $mm = new File::MMagic;
 4029:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
 4030:             if ($mime_type =~ m{^image/}) {
 4031: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
 4032:             }  
 4033: 	}
 4034:     }
 4035:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
 4036:         if (ref($mimetype)) {
 4037:             if ($$mimetype eq '') {
 4038:                 my $mm = new File::MMagic;
 4039:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
 4040:                 $$mimetype = $type;
 4041:             }
 4042:         }
 4043:     }
 4044:     if (($context ne 'scantron') && ($parser eq 'parse')) {
 4045:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
 4046:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
 4047:                                                        $allfiles,$codebase);
 4048:             unless ($parse_result eq 'ok') {
 4049:                 &logthis('Failed to parse '.$filepath.$file.
 4050: 	   	         ' for embedded media: '.$parse_result); 
 4051:             }
 4052:         }
 4053:     } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
 4054:         my $format = $env{'form.scantron_format'};
 4055:         &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
 4056:     }
 4057:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 4058:         my $input = $filepath.'/'.$file;
 4059:         my $output = $filepath.'/'.'tn-'.$file;
 4060:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 4061:         my @args = ('convert','-sample',$thumbsize,$input,$output);
 4062:         system({$args[0]} @args);
 4063:         if (-e $filepath.'/'.'tn-'.$file) {
 4064:             $fetchthumb  = 1; 
 4065:         }
 4066:     }
 4067:  
 4068: # Notify homeserver to grep it
 4069: #
 4070:     my $docuhome=&homeserver($docuname,$docudom);	
 4071:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 4072:     if ($fetchresult eq 'ok') {
 4073:         if ($fetchthumb) {
 4074:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 4075:             if ($thumbresult ne 'ok') {
 4076:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 4077:                          $docuhome.': '.$thumbresult);
 4078:             }
 4079:         }
 4080: #
 4081: # Return the URL to it
 4082:         return '/uploaded/'.$path.$file;
 4083:     } else {
 4084:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 4085: 		 ': '.$fetchresult);
 4086:         return '/adm/notfound.html';
 4087:     }
 4088: }
 4089: 
 4090: sub extract_embedded_items {
 4091:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 4092:     my @state = ();
 4093:     my (%lastids,%related,%shockwave,%flashvars);
 4094:     my %javafiles = (
 4095:                       codebase => '',
 4096:                       code => '',
 4097:                       archive => ''
 4098:                     );
 4099:     my %mediafiles = (
 4100:                       src => '',
 4101:                       movie => '',
 4102:                      );
 4103:     my $p;
 4104:     if ($content) {
 4105:         $p = HTML::LCParser->new($content);
 4106:     } else {
 4107:         $p = HTML::LCParser->new($fullpath);
 4108:     }
 4109:     while (my $t=$p->get_token()) {
 4110: 	if ($t->[0] eq 'S') {
 4111: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 4112: 	    push(@state, $tagname);
 4113:             if (lc($tagname) eq 'allow') {
 4114:                 &add_filetype($allfiles,$attr->{'src'},'src');
 4115:             }
 4116: 	    if (lc($tagname) eq 'img') {
 4117: 		&add_filetype($allfiles,$attr->{'src'},'src');
 4118: 	    }
 4119: 	    if (lc($tagname) eq 'a') {
 4120:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
 4121: 		    &add_filetype($allfiles,$attr->{'href'},'href');
 4122:                 }
 4123: 	    }
 4124:             if (lc($tagname) eq 'script') {
 4125:                 my $src;
 4126:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 4127:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 4128:                 } else {
 4129:                     if ($attr->{'src'} ne '') {
 4130:                         $src = $attr->{'src'};
 4131:                         &add_filetype($allfiles,$src,'src');
 4132:                     }
 4133:                 }
 4134:                 my $text = $p->get_trimmed_text();
 4135:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
 4136:                     my @swfargs = split(/,/,$1);
 4137:                     foreach my $item (@swfargs) {
 4138:                         $item =~ s/["']//g;
 4139:                         $item =~ s/^\s+//;
 4140:                         $item =~ s/\s+$//;
 4141:                     }
 4142:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
 4143:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
 4144:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
 4145:                         } else {
 4146:                             $related{$swfargs[0]} = [$swfargs[2]];
 4147:                         }
 4148:                     }
 4149:                 }
 4150:             }
 4151:             if (lc($tagname) eq 'link') {
 4152:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 4153:                     &add_filetype($allfiles,$attr->{'href'},'href');
 4154:                 }
 4155:             }
 4156: 	    if (lc($tagname) eq 'object' ||
 4157: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 4158: 		foreach my $item (keys(%javafiles)) {
 4159: 		    $javafiles{$item} = '';
 4160: 		}
 4161:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
 4162:                     $lastids{lc($tagname)} = $attr->{'id'};
 4163:                 }
 4164: 	    }
 4165: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 4166: 		my $name = lc($attr->{'name'});
 4167: 		foreach my $item (keys(%javafiles)) {
 4168: 		    if ($name eq $item) {
 4169: 			$javafiles{$item} = $attr->{'value'};
 4170: 			last;
 4171: 		    }
 4172: 		}
 4173:                 my $pathfrom;
 4174: 		foreach my $item (keys(%mediafiles)) {
 4175: 		    if ($name eq $item) {
 4176:                         $pathfrom = $attr->{'value'};
 4177:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
 4178: 			&add_filetype($allfiles,$pathfrom,$name);
 4179: 			last;
 4180: 		    }
 4181: 		}
 4182:                 if ($name eq 'flashvars') {
 4183:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
 4184:                 }
 4185:                 if ($pathfrom ne '') {
 4186:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
 4187:                                          $pathfrom);
 4188:                 }
 4189: 	    }
 4190: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 4191: 		foreach my $item (keys(%javafiles)) {
 4192: 		    if ($attr->{$item}) {
 4193: 			$javafiles{$item} = $attr->{$item};
 4194: 			last;
 4195: 		    }
 4196: 		}
 4197: 		foreach my $item (keys(%mediafiles)) {
 4198: 		    if ($attr->{$item}) {
 4199: 			&add_filetype($allfiles,$attr->{$item},$item);
 4200: 			last;
 4201: 		    }
 4202: 		}
 4203:                 if (lc($tagname) eq 'embed') {
 4204:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
 4205:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
 4206:                                              $attr->{'src'});
 4207:                     }
 4208:                 }
 4209: 	    }
 4210:             if (lc($tagname) eq 'iframe') {
 4211:                 my $src = $attr->{'src'} ;
 4212:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
 4213:                     &add_filetype($allfiles,$src,'src');
 4214:                 } elsif ($src =~ m{^/}) {
 4215:                     if ($env{'request.course.id'}) {
 4216:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4217:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4218:                         my $url = &hreflocation('',$fullpath);
 4219:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
 4220:                             my $relpath = $1;
 4221:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
 4222:                                 &add_filetype($allfiles,$1,'src');
 4223:                             }
 4224:                         }
 4225:                     }
 4226:                 }
 4227:             }
 4228:             if ($t->[4] =~ m{/>$}) {
 4229:                 pop(@state);
 4230:             }
 4231: 	} elsif ($t->[0] eq 'E') {
 4232: 	    my ($tagname) = ($t->[1]);
 4233: 	    if ($javafiles{'codebase'} ne '') {
 4234: 		$javafiles{'codebase'} .= '/';
 4235: 	    }  
 4236: 	    if (lc($tagname) eq 'applet' ||
 4237: 		lc($tagname) eq 'object' ||
 4238: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 4239: 		) {
 4240: 		foreach my $item (keys(%javafiles)) {
 4241: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 4242: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 4243: 			&add_filetype($allfiles,$file,$item);
 4244: 		    }
 4245: 		}
 4246: 	    } 
 4247: 	    pop @state;
 4248: 	}
 4249:     }
 4250:     foreach my $id (sort(keys(%flashvars))) {
 4251:         if ($shockwave{$id} ne '') {
 4252:             my @pairs = split(/\&/,$flashvars{$id});
 4253:             foreach my $pair (@pairs) {
 4254:                 my ($key,$value) = split(/\=/,$pair);
 4255:                 if ($key eq 'thumb') {
 4256:                     &add_filetype($allfiles,$value,$key);
 4257:                 } elsif ($key eq 'content') {
 4258:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
 4259:                     my ($ext) = ($value =~ /\.([^.]+)$/);
 4260:                     if ($ext ne '') {
 4261:                         &add_filetype($allfiles,$path.$value,$ext);
 4262:                     }
 4263:                 }
 4264:             }
 4265:         }
 4266:     }
 4267:     return 'ok';
 4268: }
 4269: 
 4270: sub add_filetype {
 4271:     my ($allfiles,$file,$type)=@_;
 4272:     if (exists($allfiles->{$file})) {
 4273: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 4274: 	    push(@{$allfiles->{$file}}, &escape($type));
 4275: 	}
 4276:     } else {
 4277: 	@{$allfiles->{$file}} = (&escape($type));
 4278:     }
 4279: }
 4280: 
 4281: sub embedded_dependency {
 4282:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
 4283:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
 4284:         if (($identifier ne '') &&
 4285:             (ref($related->{$identifier}) eq 'ARRAY') &&
 4286:             ($pathfrom ne '')) {
 4287:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
 4288:             foreach my $dep (@{$related->{$identifier}}) {
 4289:                 &add_filetype($allfiles,$path.$dep,'object');
 4290:             }
 4291:         }
 4292:     }
 4293:     return;
 4294: }
 4295: 
 4296: sub bubblesheet_converter {
 4297:     my ($cdom,$fullpath,$config,$format) = @_;
 4298:     if ((&domain($cdom) ne '') &&
 4299:         ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
 4300:         (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
 4301:         my (%csvcols,%csvoptions);
 4302:         if (ref($config->{'fields'}) eq 'HASH') {
 4303:             %csvcols = %{$config->{'fields'}};
 4304:         }
 4305:         if (ref($config->{'options'}) eq 'HASH') {
 4306:             %csvoptions = %{$config->{'options'}};
 4307:         }
 4308:         my %csvbynum = reverse(%csvcols);
 4309:         my %scantronconf = &get_scantron_config($format,$cdom);
 4310:         if (keys(%scantronconf)) {
 4311:             my %bynum = (
 4312:                           $scantronconf{CODEstart} => 'CODEstart',
 4313:                           $scantronconf{IDstart}   => 'IDstart',
 4314:                           $scantronconf{PaperID}   => 'PaperID',
 4315:                           $scantronconf{FirstName} => 'FirstName',
 4316:                           $scantronconf{LastName}  => 'LastName',
 4317:                           $scantronconf{Qstart}    => 'Qstart',
 4318:                         );
 4319:             my @ordered;
 4320:             foreach my $item (sort { $a <=> $b } keys(%bynum)) {
 4321:                 push(@ordered,$bynum{$item});
 4322:             }
 4323:             my %mapstart = (
 4324:                               CODEstart => 'CODE',
 4325:                               IDstart   => 'ID',
 4326:                               PaperID   => 'PaperID',
 4327:                               FirstName => 'FirstName',
 4328:                               LastName  => 'LastName',
 4329:                               Qstart    => 'FirstQuestion',
 4330:                            );
 4331:             my %maplength = (
 4332:                               CODEstart => 'CODElength',
 4333:                               IDstart   => 'IDlength',
 4334:                               PaperID   => 'PaperIDlength',
 4335:                               FirstName => 'FirstNamelength',
 4336:                               LastName  => 'LastNamelength',
 4337:             );
 4338:             if (open(my $fh,'<',$fullpath)) {
 4339:                 my $output;
 4340:                 my %lettdig = &letter_to_digits();
 4341:                 my %diglett = reverse(%lettdig);
 4342:                 my $numletts = scalar(keys(%lettdig));
 4343:                 my $num = 0;
 4344:                 while (my $line=<$fh>) {
 4345:                     $num ++;
 4346:                     next if (($num == 1) && ($csvoptions{'hdr'} == 1));
 4347:                     $line =~ s{[\r\n]+$}{};
 4348:                     my %found;
 4349:                     my @values = split(/,/,$line);
 4350:                     my ($qstart,$record);
 4351:                     for (my $i=0; $i<@values; $i++) {
 4352:                         if ((($qstart ne '') && ($i > $qstart)) ||
 4353:                             ($csvbynum{$i} eq 'FirstQuestion')) {
 4354:                             if ($values[$i] eq '') {
 4355:                                 $values[$i] = $scantronconf{'Qoff'};
 4356:                             } elsif ($scantronconf{'Qon'} eq 'number') {
 4357:                                 if ($values[$i] =~ /^[A-Ja-j]$/) {
 4358:                                     $values[$i] = $lettdig{uc($values[$i])};
 4359:                                 }
 4360:                             } elsif ($scantronconf{'Qon'} eq 'letter') {
 4361:                                 if ($values[$i] =~ /^[0-9]$/) {
 4362:                                     $values[$i] = $diglett{$values[$i]};
 4363:                                 }
 4364:                             } else {
 4365:                                 if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
 4366:                                     my $digit;
 4367:                                     if ($values[$i] =~ /^[A-Ja-j]$/) {
 4368:                                         $digit = $lettdig{uc($values[$i])}-1;
 4369:                                         if ($values[$i] eq 'J') {
 4370:                                             $digit += $numletts;
 4371:                                         }
 4372:                                     } elsif ($values[$i] =~ /^[0-9]$/) {
 4373:                                         $digit = $values[$i]-1;
 4374:                                         if ($values[$i] eq '0') {
 4375:                                             $digit += $numletts;
 4376:                                         }
 4377:                                     }
 4378:                                     my $qval='';
 4379:                                     for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
 4380:                                         if ($j == $digit) {
 4381:                                             $qval .= $scantronconf{'Qon'};
 4382:                                         } else {
 4383:                                             $qval .= $scantronconf{'Qoff'};
 4384:                                         }
 4385:                                     }
 4386:                                     $values[$i] = $qval;
 4387:                                 }
 4388:                             }
 4389:                             if (length($values[$i]) > $scantronconf{'Qlength'}) {
 4390:                                 $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
 4391:                             }
 4392:                             my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
 4393:                             if ($numblank > 0) {
 4394:                                  $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
 4395:                             }
 4396:                             if ($csvbynum{$i} eq 'FirstQuestion') {
 4397:                                 $qstart = $i;
 4398:                                 $found{$csvbynum{$i}} = $values[$i];
 4399:                             } else {
 4400:                                 $found{'FirstQuestion'} .= $values[$i];
 4401:                             }
 4402:                         } elsif (exists($csvbynum{$i})) {
 4403:                             if ($csvoptions{'rem'}) {
 4404:                                 $values[$i] =~ s/^\s+//;
 4405:                             }
 4406:                             if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
 4407:                                 while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
 4408:                                     $values[$i] = '0'.$values[$i];
 4409:                                 }
 4410:                             }
 4411:                             $found{$csvbynum{$i}} = $values[$i];
 4412:                         }
 4413:                     }
 4414:                     foreach my $item (@ordered) {
 4415:                         my $currlength = 1+length($record);
 4416:                         my $numspaces = $scantronconf{$item} - $currlength;
 4417:                         if ($numspaces > 0) {
 4418:                             $record .= (' ' x $numspaces);
 4419:                         }
 4420:                         if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
 4421:                             unless ($item eq 'Qstart') {
 4422:                                 if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
 4423:                                     $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
 4424:                                 }
 4425:                             }
 4426:                             $record .= $found{$mapstart{$item}};
 4427:                         }
 4428:                     }
 4429:                     $output .= "$record\n";
 4430:                 }
 4431:                 close($fh);
 4432:                 if ($output) {
 4433:                     if (open(my $fh,'>',$fullpath)) {
 4434:                         print $fh $output;
 4435:                         close($fh);
 4436:                     }
 4437:                 }
 4438:             }
 4439:         }
 4440:         return;
 4441:     }
 4442: }
 4443: 
 4444: sub letter_to_digits {
 4445:     my %lettdig = (
 4446:                     A => 1,
 4447:                     B => 2,
 4448:                     C => 3,
 4449:                     D => 4,
 4450:                     E => 5,
 4451:                     F => 6,
 4452:                     G => 7,
 4453:                     H => 8,
 4454:                     I => 9,
 4455:                     J => 0,
 4456:                   );
 4457:     return %lettdig;
 4458: }
 4459: 
 4460: sub get_scantron_config {
 4461:     my ($which,$cdom) = @_;
 4462:     my @lines = &get_scantronformat_file($cdom);
 4463:     my %config;
 4464:     #FIXME probably should move to XML it has already gotten a bit much now
 4465:     foreach my $line (@lines) {
 4466:         my ($name,$descrip)=split(/:/,$line);
 4467:         if ($name ne $which ) { next; }
 4468:         chomp($line);
 4469:         my @config=split(/:/,$line);
 4470:         $config{'name'}=$config[0];
 4471:         $config{'description'}=$config[1];
 4472:         $config{'CODElocation'}=$config[2];
 4473:         $config{'CODEstart'}=$config[3];
 4474:         $config{'CODElength'}=$config[4];
 4475:         $config{'IDstart'}=$config[5];
 4476:         $config{'IDlength'}=$config[6];
 4477:         $config{'Qstart'}=$config[7];
 4478:         $config{'Qlength'}=$config[8];
 4479:         $config{'Qoff'}=$config[9];
 4480:         $config{'Qon'}=$config[10];
 4481:         $config{'PaperID'}=$config[11];
 4482:         $config{'PaperIDlength'}=$config[12];
 4483:         $config{'FirstName'}=$config[13];
 4484:         $config{'FirstNamelength'}=$config[14];
 4485:         $config{'LastName'}=$config[15];
 4486:         $config{'LastNamelength'}=$config[16];
 4487:         $config{'BubblesPerRow'}=$config[17];
 4488:         last;
 4489:     }
 4490:     return %config;
 4491: }
 4492: 
 4493: sub get_scantronformat_file {
 4494:     my ($cdom) = @_;
 4495:     if ($cdom eq '') {
 4496:         $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 4497:     }
 4498:     my %domconfig = &get_dom('configuration',['scantron'],$cdom);
 4499:     my $gottab = 0;
 4500:     my @lines;
 4501:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 4502:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
 4503:             my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
 4504:             if ($formatfile ne '-1') {
 4505:                 @lines = split("\n",$formatfile,-1);
 4506:                 $gottab = 1;
 4507:             }
 4508:         }
 4509:     }
 4510:     if (!$gottab) {
 4511:         my $confname = $cdom.'-domainconfig';
 4512:         my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
 4513:         my $formatfile = &getfile($default);
 4514:         if ($formatfile ne '-1') {
 4515:             @lines = split("\n",$formatfile,-1);
 4516:             $gottab = 1;
 4517:         }
 4518:     }
 4519:     if (!$gottab) {
 4520:         my @domains = &current_machine_domains();
 4521:         if (grep(/^\Q$cdom\E$/,@domains)) {
 4522:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
 4523:                 @lines = <$fh>;
 4524:                 close($fh);
 4525:             }
 4526:         } else {
 4527:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
 4528:                 @lines = <$fh>;
 4529:                 close($fh);
 4530:             }
 4531:         }
 4532:     }
 4533:     return @lines;
 4534: }
 4535: 
 4536: sub removeuploadedurl {
 4537:     my ($url)=@_;	
 4538:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 4539:     return &removeuserfile($uname,$udom,$fname);
 4540: }
 4541: 
 4542: sub removeuserfile {
 4543:     my ($docuname,$docudom,$fname)=@_;
 4544:     my $home=&homeserver($docuname,$docudom);    
 4545:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 4546:     if ($result eq 'ok') {	
 4547:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 4548:             my $metafile = $fname.'.meta';
 4549:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 4550: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 4551:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 4552:             my $sqlresult = 
 4553:                 &update_portfolio_table($docuname,$docudom,$file,
 4554:                                         'portfolio_metadata',$group,
 4555:                                         'delete');
 4556:         }
 4557:     }
 4558:     return $result;
 4559: }
 4560: 
 4561: sub mkdiruserfile {
 4562:     my ($docuname,$docudom,$dir)=@_;
 4563:     my $home=&homeserver($docuname,$docudom);
 4564:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 4565: }
 4566: 
 4567: sub renameuserfile {
 4568:     my ($docuname,$docudom,$old,$new)=@_;
 4569:     my $home=&homeserver($docuname,$docudom);
 4570:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 4571:                         &escape("$old").':'.&escape("$new"),$home);
 4572:     if ($result eq 'ok') {
 4573:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 4574:             my $oldmeta = $old.'.meta';
 4575:             my $newmeta = $new.'.meta';
 4576:             my $metaresult = 
 4577:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 4578: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 4579:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 4580:             my $sqlresult = 
 4581:                 &update_portfolio_table($docuname,$docudom,$file,
 4582:                                         'portfolio_metadata',$group,
 4583:                                         'delete');
 4584:         }
 4585:     }
 4586:     return $result;
 4587: }
 4588: 
 4589: # ------------------------------------------------------------------------- Log
 4590: 
 4591: sub log {
 4592:     my ($dom,$nam,$hom,$what)=@_;
 4593:     return critical("log:$dom:$nam:$what",$hom);
 4594: }
 4595: 
 4596: # ------------------------------------------------------------------ Course Log
 4597: #
 4598: # This routine flushes several buffers of non-mission-critical nature
 4599: #
 4600: 
 4601: sub flushcourselogs {
 4602:     &logthis('Flushing log buffers');
 4603: #
 4604: # course logs
 4605: # This is a log of all transactions in a course, which can be used
 4606: # for data mining purposes
 4607: #
 4608: # It also collects the courseid database, which lists last transaction
 4609: # times and course titles for all courseids
 4610: #
 4611:     my %courseidbuffer=();
 4612:     foreach my $crsid (keys(%courselogs)) {
 4613:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 4614: 		          &escape($courselogs{$crsid}),
 4615: 		          $coursehombuf{$crsid}) eq 'ok') {
 4616: 	    delete $courselogs{$crsid};
 4617:         } else {
 4618:             &logthis('Failed to flush log buffer for '.$crsid);
 4619:             if (length($courselogs{$crsid})>40000) {
 4620:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 4621:                         " exceeded maximum size, deleting.</font>");
 4622:                delete $courselogs{$crsid};
 4623:             }
 4624:         }
 4625:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 4626:             'description' => $coursedescrbuf{$crsid},
 4627:             'inst_code'    => $courseinstcodebuf{$crsid},
 4628:             'type'        => $coursetypebuf{$crsid},
 4629:             'owner'       => $courseownerbuf{$crsid},
 4630:         };
 4631:     }
 4632: #
 4633: # Write course id database (reverse lookup) to homeserver of courses 
 4634: # Is used in pickcourse
 4635: #
 4636:     foreach my $crs_home (keys(%courseidbuffer)) {
 4637:         my $response = &courseidput(&host_domain($crs_home),
 4638:                                     $courseidbuffer{$crs_home},
 4639:                                     $crs_home,'timeonly');
 4640:     }
 4641: #
 4642: # File accesses
 4643: # Writes to the dynamic metadata of resources to get hit counts, etc.
 4644: #
 4645:     foreach my $entry (keys(%accesshash)) {
 4646:         if ($entry =~ /___count$/) {
 4647:             my ($dom,$name);
 4648:             ($dom,$name,undef)=
 4649: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 4650:             if (! defined($dom) || $dom eq '' || 
 4651:                 ! defined($name) || $name eq '') {
 4652:                 my $cid = $env{'request.course.id'};
 4653:                 $dom  = $env{'request.'.$cid.'.domain'};
 4654:                 $name = $env{'request.'.$cid.'.num'};
 4655:             }
 4656:             my $value = $accesshash{$entry};
 4657:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 4658:             my %temphash=($url => $value);
 4659:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 4660:             if ($result eq 'ok') {
 4661:                 delete $accesshash{$entry};
 4662:             }
 4663:         } else {
 4664:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 4665:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
 4666:             my %temphash=($entry => $accesshash{$entry});
 4667:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 4668:                 delete $accesshash{$entry};
 4669:             }
 4670:         }
 4671:     }
 4672: #
 4673: # Roles
 4674: # Reverse lookup of user roles for course faculty/staff and co-authorship
 4675: #
 4676:     foreach my $entry (keys(%userrolehash)) {
 4677:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 4678: 	    split(/\:/,$entry);
 4679:         if (&Apache::lonnet::put('nohist_userroles',
 4680:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 4681:                 $rudom,$runame) eq 'ok') {
 4682: 	    delete $userrolehash{$entry};
 4683:         }
 4684:     }
 4685: #
 4686: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
 4687: #
 4688:     my %domrolebuffer = ();
 4689:     foreach my $entry (keys(%domainrolehash)) {
 4690:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 4691:         if ($domrolebuffer{$rudom}) {
 4692:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 4693:                       '='.&escape($domainrolehash{$entry});
 4694:         } else {
 4695:             $domrolebuffer{$rudom}.=&escape($entry).
 4696:                       '='.&escape($domainrolehash{$entry});
 4697:         }
 4698:         delete $domainrolehash{$entry};
 4699:     }
 4700:     foreach my $dom (keys(%domrolebuffer)) {
 4701:         my %servers;
 4702:         if (defined(&domain($dom,'primary'))) {
 4703:             my $primary=&domain($dom,'primary');
 4704:             my $hostname=&hostname($primary);
 4705:             $servers{$primary} = $hostname;
 4706:         } else {
 4707:             %servers = &get_servers($dom,'library');
 4708:         }
 4709: 	foreach my $tryserver (keys(%servers)) {
 4710: 	    if (&reply('domroleput:'.$dom.':'.
 4711: 	               $domrolebuffer{$dom},$tryserver) eq 'ok') {
 4712: 	        last;
 4713: 	    } else {
 4714: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 4715: 	    }
 4716:         }
 4717:     }
 4718:     $dumpcount++;
 4719: }
 4720: 
 4721: sub courselog {
 4722:     my $what=shift;
 4723:     $what=time.':'.$what;
 4724:     unless ($env{'request.course.id'}) { return ''; }
 4725:     $coursedombuf{$env{'request.course.id'}}=
 4726:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 4727:     $coursenumbuf{$env{'request.course.id'}}=
 4728:        $env{'course.'.$env{'request.course.id'}.'.num'};
 4729:     $coursehombuf{$env{'request.course.id'}}=
 4730:        $env{'course.'.$env{'request.course.id'}.'.home'};
 4731:     $coursedescrbuf{$env{'request.course.id'}}=
 4732:        $env{'course.'.$env{'request.course.id'}.'.description'};
 4733:     $courseinstcodebuf{$env{'request.course.id'}}=
 4734:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 4735:     $courseownerbuf{$env{'request.course.id'}}=
 4736:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 4737:     $coursetypebuf{$env{'request.course.id'}}=
 4738:        $env{'course.'.$env{'request.course.id'}.'.type'};
 4739:     if (defined $courselogs{$env{'request.course.id'}}) {
 4740: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 4741:     } else {
 4742: 	$courselogs{$env{'request.course.id'}}.=$what;
 4743:     }
 4744:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 4745: 	&flushcourselogs();
 4746:     }
 4747: }
 4748: 
 4749: sub courseacclog {
 4750:     my $fnsymb=shift;
 4751:     unless ($env{'request.course.id'}) { return ''; }
 4752:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 4753:     if ($fnsymb=~/$LONCAPA::assess_re/) {
 4754:         $what.=':POST';
 4755:         # FIXME: Probably ought to escape things....
 4756: 	foreach my $key (keys(%env)) {
 4757:             if ($key=~/^form\.(.*)/) {
 4758:                 my $formitem = $1;
 4759:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 4760:                     $what.=':'.$formitem.'='.$env{$key};
 4761:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 4762:                     if ($formitem eq 'proctorpassword') {
 4763:                         $what.=':'.$formitem.'=' . '*' x length($env{$key});
 4764:                     } else {
 4765:                         $what.=':'.$formitem.'='.$env{$key};
 4766:                     }
 4767:                 }
 4768:             }
 4769:         }
 4770:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 4771:         # FIXME: We should not be depending on a form parameter that someone
 4772:         # editing lonsearchcat.pm might change in the future.
 4773:         if ($env{'form.phase'} eq 'course_search') {
 4774:             $what.= ':POST';
 4775:             # FIXME: Probably ought to escape things....
 4776:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 4777:                                  'crsdiscuss') {
 4778:                 $what.=':'.$element.'='.$env{'form.'.$element};
 4779:             }
 4780:         }
 4781:     }
 4782:     &courselog($what);
 4783: }
 4784: 
 4785: sub countacc {
 4786:     my $url=&declutter(shift);
 4787:     return if (! defined($url) || $url eq '');
 4788:     unless ($env{'request.course.id'}) { return ''; }
 4789: #
 4790: # Mark that this url was used in this course
 4791: #
 4792:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 4793: #
 4794: # Increase the access count for this resource in this child process
 4795: #
 4796:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 4797:     $accesshash{$key}++;
 4798: }
 4799: 
 4800: sub linklog {
 4801:     my ($from,$to)=@_;
 4802:     $from=&declutter($from);
 4803:     $to=&declutter($to);
 4804:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 4805:     $accesshash{$to.'___'.$from.'___goto'}=1;
 4806: }
 4807: 
 4808: sub statslog {
 4809:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
 4810:     if ($users<2) { return; }
 4811:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
 4812:             'course'       => $env{'request.course.id'},
 4813:             'sections'     => '"all"',
 4814:             'num_students' => $users,
 4815:             'part'         => $part,
 4816:             'symb'         => $symb,
 4817:             'mean_tries'   => $av_attempts,
 4818:             'deg_of_diff'  => $degdiff});
 4819:     foreach my $key (keys(%dynstore)) {
 4820:         $accesshash{$key}=$dynstore{$key};
 4821:     }
 4822: }
 4823:   
 4824: sub userrolelog {
 4825:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 4826:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
 4827:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 4828:        $userrolehash
 4829:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 4830:                     =$tend.':'.$tstart;
 4831:     }
 4832:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
 4833:        $userrolehash
 4834:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 4835:                     =$tend.':'.$tstart;
 4836:     }
 4837:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
 4838:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 4839:        $domainrolehash
 4840:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 4841:                     = $tend.':'.$tstart;
 4842:     }
 4843: }
 4844: 
 4845: sub courserolelog {
 4846:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 4847:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 4848:         my $cdom = $1;
 4849:         my $cnum = $2;
 4850:         my $sec = $3;
 4851:         my $namespace = 'rolelog';
 4852:         my %storehash = (
 4853:                            role    => $trole,
 4854:                            start   => $tstart,
 4855:                            end     => $tend,
 4856:                            selfenroll => $selfenroll,
 4857:                            context    => $context,
 4858:                         );
 4859:         if ($trole eq 'gr') {
 4860:             $namespace = 'groupslog';
 4861:             $storehash{'group'} = $sec;
 4862:         } else {
 4863:             $storehash{'section'} = $sec;
 4864:         }
 4865:         &write_log('course',$namespace,\%storehash,$delflag,$username,
 4866:                    $domain,$cnum,$cdom);
 4867:         if (($trole ne 'st') || ($sec ne '')) {
 4868:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 4869:         }
 4870:     }
 4871:     return;
 4872: }
 4873: 
 4874: sub domainrolelog {
 4875:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 4876:     if ($area =~ m{^/($match_domain)/$}) {
 4877:         my $cdom = $1;
 4878:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
 4879:         my $namespace = 'rolelog';
 4880:         my %storehash = (
 4881:                            role    => $trole,
 4882:                            start   => $tstart,
 4883:                            end     => $tend,
 4884:                            context => $context,
 4885:                         );
 4886:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
 4887:                    $domain,$domconfiguser,$cdom);
 4888:     }
 4889:     return;
 4890: 
 4891: }
 4892: 
 4893: sub coauthorrolelog {
 4894:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 4895:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
 4896:         my $audom = $1;
 4897:         my $auname = $2;
 4898:         my $namespace = 'rolelog';
 4899:         my %storehash = (
 4900:                            role    => $trole,
 4901:                            start   => $tstart,
 4902:                            end     => $tend,
 4903:                            context => $context,
 4904:                         );
 4905:         &write_log('author',$namespace,\%storehash,$delflag,$username,
 4906:                    $domain,$auname,$audom);
 4907:     }
 4908:     return;
 4909: }
 4910: 
 4911: sub get_course_adv_roles {
 4912:     my ($cid,$codes) = @_;
 4913:     $cid=$env{'request.course.id'} unless (defined($cid));
 4914:     my %coursehash=&coursedescription($cid);
 4915:     my $crstype = &Apache::loncommon::course_type($cid);
 4916:     my %nothide=();
 4917:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 4918:         if ($user !~ /:/) {
 4919: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 4920:         } else {
 4921:             $nothide{$user}=1;
 4922:         }
 4923:     }
 4924:     my @possdoms = ($coursehash{'domain'});
 4925:     if ($coursehash{'checkforpriv'}) {
 4926:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
 4927:     }
 4928:     my %returnhash=();
 4929:     my %dumphash=
 4930:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 4931:     my $now=time;
 4932:     my %privileged;
 4933:     foreach my $entry (keys(%dumphash)) {
 4934: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 4935:         if (($tstart) && ($tstart<0)) { next; }
 4936:         if (($tend) && ($tend<$now)) { next; }
 4937:         if (($tstart) && ($now<$tstart)) { next; }
 4938:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 4939: 	if ($username eq '' || $domain eq '') { next; }
 4940:         if ((&privileged($username,$domain,\@possdoms)) &&
 4941:             (!$nothide{$username.':'.$domain})) { next; }
 4942: 	if ($role eq 'cr') { next; }
 4943:         if ($codes) {
 4944:             if ($section) { $role .= ':'.$section; }
 4945:             if ($returnhash{$role}) {
 4946:                 $returnhash{$role}.=','.$username.':'.$domain;
 4947:             } else {
 4948:                 $returnhash{$role}=$username.':'.$domain;
 4949:             }
 4950:         } else {
 4951:             my $key=&plaintext($role,$crstype);
 4952:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 4953:             if ($returnhash{$key}) {
 4954: 	        $returnhash{$key}.=','.$username.':'.$domain;
 4955:             } else {
 4956:                 $returnhash{$key}=$username.':'.$domain;
 4957:             }
 4958:         }
 4959:     }
 4960:     return %returnhash;
 4961: }
 4962: 
 4963: sub get_my_roles {
 4964:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 4965:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 4966:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 4967:     my (%dumphash,%nothide);
 4968:     if ($context eq 'userroles') {
 4969:         %dumphash = &dump('roles',$udom,$uname);
 4970:     } else {
 4971:         %dumphash = &dump('nohist_userroles',$udom,$uname);
 4972:         if ($hidepriv) {
 4973:             my %coursehash=&coursedescription($udom.'_'.$uname);
 4974:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 4975:                 if ($user !~ /:/) {
 4976:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 4977:                 } else {
 4978:                     $nothide{$user} = 1;
 4979:                 }
 4980:             }
 4981:         }
 4982:     }
 4983:     my %returnhash=();
 4984:     my $now=time;
 4985:     my %privileged;
 4986:     foreach my $entry (keys(%dumphash)) {
 4987:         my ($role,$tend,$tstart);
 4988:         if ($context eq 'userroles') {
 4989:             next if ($entry =~ /^rolesdef/);
 4990: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 4991:         } else {
 4992:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 4993:         }
 4994:         if (($tstart) && ($tstart<0)) { next; }
 4995:         my $status = 'active';
 4996:         if (($tend) && ($tend<=$now)) {
 4997:             $status = 'previous';
 4998:         } 
 4999:         if (($tstart) && ($now<$tstart)) {
 5000:             $status = 'future';
 5001:         }
 5002:         if (ref($types) eq 'ARRAY') {
 5003:             if (!grep(/^\Q$status\E$/,@{$types})) {
 5004:                 next;
 5005:             } 
 5006:         } else {
 5007:             if ($status ne 'active') {
 5008:                 next;
 5009:             }
 5010:         }
 5011:         my ($rolecode,$username,$domain,$section,$area);
 5012:         if ($context eq 'userroles') {
 5013:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
 5014:             (undef,$domain,$username,$section) = split(/\//,$area);
 5015:         } else {
 5016:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 5017:         }
 5018:         if (ref($roledoms) eq 'ARRAY') {
 5019:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 5020:                 next;
 5021:             }
 5022:         }
 5023:         if (ref($roles) eq 'ARRAY') {
 5024:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 5025:                 if ($role =~ /^cr\//) {
 5026:                     if (!grep(/^cr$/,@{$roles})) {
 5027:                         next;
 5028:                     }
 5029:                 } elsif ($role =~ /^gr\//) {
 5030:                     if (!grep(/^gr$/,@{$roles})) {
 5031:                         next;
 5032:                     }
 5033:                 } else {
 5034:                     next;
 5035:                 }
 5036:             }
 5037:         }
 5038:         if ($hidepriv) {
 5039:             my @privroles = ('dc','su');
 5040:             if ($context eq 'userroles') {
 5041:                 next if (grep(/^\Q$role\E$/,@privroles));
 5042:             } else {
 5043:                 my $possdoms = [$domain];
 5044:                 if (ref($roledoms) eq 'ARRAY') {
 5045:                    push(@{$possdoms},@{$roledoms});
 5046:                 }
 5047:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
 5048:                     if (!$nothide{$username.':'.$domain}) {
 5049:                         next;
 5050:                     }
 5051:                 }
 5052:             }
 5053:         }
 5054:         if ($withsec) {
 5055:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 5056:                 $tstart.':'.$tend;
 5057:         } else {
 5058:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 5059:         }
 5060:     }
 5061:     return %returnhash;
 5062: }
 5063: 
 5064: sub get_all_adhocroles {
 5065:     my ($dom) = @_;
 5066:     my @roles_by_num = ();
 5067:     my %domdefaults = &get_domain_defaults($dom);
 5068:     my (%description,%access_in_dom,%access_info);
 5069:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
 5070:         my $count = 0;
 5071:         my %domcurrent = %{$domdefaults{'adhocroles'}};
 5072:         my %ordered;
 5073:         foreach my $role (sort(keys(%domcurrent))) {
 5074:             my ($order,$desc,$access_in_dom);
 5075:             if (ref($domcurrent{$role}) eq 'HASH') {
 5076:                 $order = $domcurrent{$role}{'order'};
 5077:                 $desc = $domcurrent{$role}{'desc'};
 5078:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
 5079:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
 5080:             }
 5081:             if ($order eq '') {
 5082:                 $order = $count;
 5083:             }
 5084:             $ordered{$order} = $role;
 5085:             if ($desc ne '') {
 5086:                 $description{$role} = $desc;
 5087:             } else {
 5088:                 $description{$role}= $role;
 5089:             }
 5090:             $count++;
 5091:         }
 5092:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 5093:             push(@roles_by_num,$ordered{$item});
 5094:         }
 5095:     }
 5096:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
 5097: }
 5098: 
 5099: sub get_my_adhocroles {
 5100:     my ($cid,$checkreg) = @_;
 5101:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
 5102:     if ($env{'request.course.id'} eq $cid) {
 5103:         $cdom = $env{'course.'.$cid.'.domain'};
 5104:         $cnum = $env{'course.'.$cid.'.num'};
 5105:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
 5106:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
 5107:         $cdom = $1;
 5108:         $cnum = $2;
 5109:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
 5110:                                      $cdom,$cnum);
 5111:     }
 5112:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
 5113:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
 5114:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
 5115:         if ($rosterhash{$user} ne '') {
 5116:             my $type = (split(/:/,$rosterhash{$user}))[5];
 5117:             return ([],{}) if ($type eq 'auto');
 5118:         }
 5119:     }
 5120:     if (($cdom ne '') && ($cnum ne ''))  {
 5121:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
 5122:             my $then=$env{'user.login.time'};
 5123:             my $update=$env{'user.update.time'};
 5124:             if (!$update) {
 5125:                 $update = $then;
 5126:             }
 5127:             my @liveroles;
 5128:             foreach my $role ('dh','da') {
 5129:                 if ($env{"user.role.$role./$cdom/"}) {
 5130:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
 5131:                     my $limit = $update;
 5132:                     if ($env{'request.role'} eq "$role./$cdom/") {
 5133:                         $limit = $then;
 5134:                     }
 5135:                     my $activerole = 1;
 5136:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
 5137:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
 5138:                     if ($activerole) {
 5139:                         push(@liveroles,$role);
 5140:                     }
 5141:                 }
 5142:             }
 5143:             if (@liveroles) {
 5144:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
 5145:                     my ($accessref,$accessinfo,%access_in_dom);
 5146:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
 5147:                     if (ref($roles_by_num) eq 'ARRAY') {
 5148:                         if (@{$roles_by_num}) {
 5149:                             my %settings;
 5150:                             if ($env{'request.course.id'} eq $cid) {
 5151:                                 foreach my $envkey (keys(%env)) {
 5152:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
 5153:                                         $settings{$1} = $env{$envkey};
 5154:                                     }
 5155:                                 }
 5156:                             } else {
 5157:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
 5158:                             }
 5159:                             my %setincrs;
 5160:                             if ($settings{'internal.adhocaccess'}) {
 5161:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
 5162:                             }
 5163:                             my @statuses;
 5164:                             if ($env{'environment.inststatus'}) {
 5165:                                 @statuses = split(/,/,$env{'environment.inststatus'});
 5166:                             }
 5167:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
 5168:                             if (ref($accessref) eq 'HASH') {
 5169:                                 %access_in_dom = %{$accessref};
 5170:                             }
 5171:                             foreach my $role (@{$roles_by_num}) {
 5172:                                 my ($curraccess,@okstatus,@personnel);
 5173:                                 if ($setincrs{$role}) {
 5174:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
 5175:                                     if ($curraccess eq 'status') {
 5176:                                         @okstatus = split(/\&/,$rest);
 5177:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5178:                                         @personnel = split(/\&/,$rest);
 5179:                                     }
 5180:                                 } else {
 5181:                                     $curraccess = $access_in_dom{$role};
 5182:                                     if (ref($accessinfo) eq 'HASH') {
 5183:                                         if ($curraccess eq 'status') {
 5184:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
 5185:                                                 @okstatus = @{$accessinfo->{$role}};
 5186:                                             }
 5187:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5188:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
 5189:                                                 @personnel = @{$accessinfo->{$role}};
 5190:                                             }
 5191:                                         }
 5192:                                     }
 5193:                                 }
 5194:                                 if ($curraccess eq 'none') {
 5195:                                     next;
 5196:                                 } elsif ($curraccess eq 'all') {
 5197:                                     push(@possroles,$role);
 5198:                                 } elsif ($curraccess eq 'dh') {
 5199:                                     if (grep(/^dh$/,@liveroles)) {
 5200:                                         push(@possroles,$role);
 5201:                                     } else {
 5202:                                         next;
 5203:                                     }
 5204:                                 } elsif ($curraccess eq 'da') {
 5205:                                     if (grep(/^da$/,@liveroles)) {
 5206:                                         push(@possroles,$role);
 5207:                                     } else {
 5208:                                         next;
 5209:                                     }
 5210:                                 } elsif ($curraccess eq 'status') {
 5211:                                     if (@okstatus) {
 5212:                                         if (!@statuses) {
 5213:                                             if (grep(/^default$/,@okstatus)) {
 5214:                                                 push(@possroles,$role);
 5215:                                             }
 5216:                                         } else {
 5217:                                             foreach my $status (@okstatus) {
 5218:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
 5219:                                                     push(@possroles,$role);
 5220:                                                     last;
 5221:                                                 }
 5222:                                             }
 5223:                                         }
 5224:                                     }
 5225:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5226:                                     if (grep(/^\Q$user\E$/,@personnel)) {
 5227:                                         if ($curraccess eq 'exc') {
 5228:                                             push(@possroles,$role);
 5229:                                         }
 5230:                                     } elsif ($curraccess eq 'inc') {
 5231:                                         push(@possroles,$role);
 5232:                                     }
 5233:                                 }
 5234:                             }
 5235:                         }
 5236:                     }
 5237:                 }
 5238:             }
 5239:         }
 5240:     }
 5241:     unless (ref($description) eq 'HASH') {
 5242:         if (ref($roles_by_num) eq 'ARRAY') {
 5243:             my %desc;
 5244:             map { $desc{$_} = $_; } (@{$roles_by_num});
 5245:             $description = \%desc;
 5246:         } else {
 5247:             $description = {};
 5248:         }
 5249:     }
 5250:     return (\@possroles,$description);
 5251: }
 5252: 
 5253: # ----------------------------------------------------- Frontpage Announcements
 5254: #
 5255: #
 5256: 
 5257: sub postannounce {
 5258:     my ($server,$text)=@_;
 5259:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 5260:     unless ($text=~/\w/) { $text=''; }
 5261:     return &reply('setannounce:'.&escape($text),$server);
 5262: }
 5263: 
 5264: sub getannounce {
 5265: 
 5266:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 5267: 	my $announcement='';
 5268: 	while (my $line = <$fh>) { $announcement .= $line; }
 5269: 	close($fh);
 5270: 	if ($announcement=~/\w/) { 
 5271: 	    return 
 5272:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 5273:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 5274: 	} else {
 5275: 	    return '';
 5276: 	}
 5277:     } else {
 5278: 	return '';
 5279:     }
 5280: }
 5281: 
 5282: # ---------------------------------------------------------- Course ID routines
 5283: # Deal with domain's nohist_courseid.db files
 5284: #
 5285: 
 5286: sub courseidput {
 5287:     my ($domain,$storehash,$coursehome,$caller) = @_;
 5288:     return unless (ref($storehash) eq 'HASH');
 5289:     my $outcome;
 5290:     if ($caller eq 'timeonly') {
 5291:         my $cids = '';
 5292:         foreach my $item (keys(%$storehash)) {
 5293:             $cids.=&escape($item).'&';
 5294:         }
 5295:         $cids=~s/\&$//;
 5296:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 5297:                           $coursehome);       
 5298:     } else {
 5299:         my $items = '';
 5300:         foreach my $item (keys(%$storehash)) {
 5301:             $items.= &escape($item).'='.
 5302:                      &freeze_escape($$storehash{$item}).'&';
 5303:         }
 5304:         $items=~s/\&$//;
 5305:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 5306:                           $coursehome);
 5307:     }
 5308:     if ($outcome eq 'unknown_cmd') {
 5309:         my $what;
 5310:         foreach my $cid (keys(%$storehash)) {
 5311:             $what .= &escape($cid).'=';
 5312:             foreach my $item ('description','inst_code','owner','type') {
 5313:                 $what .= &escape($storehash->{$cid}{$item}).':';
 5314:             }
 5315:             $what =~ s/\:$/&/;
 5316:         }
 5317:         $what =~ s/\&$//;  
 5318:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 5319:     } else {
 5320:         return $outcome;
 5321:     }
 5322: }
 5323: 
 5324: sub courseiddump {
 5325:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 5326:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 5327:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
 5328:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
 5329:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
 5330:     my $as_hash = 1;
 5331:     my %returnhash;
 5332:     if (!$domfilter) { $domfilter=''; }
 5333:     my %libserv = &all_library();
 5334:     foreach my $tryserver (keys(%libserv)) {
 5335:         if ( (  $hostidflag == 1 
 5336: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 5337: 	     || (!defined($hostidflag)) ) {
 5338: 
 5339: 	    if (($domfilter eq '') ||
 5340: 		(&host_domain($tryserver) eq $domfilter)) {
 5341:                 my $rep;
 5342:                 if (grep { $_ eq $tryserver } &current_machine_ids()) {
 5343:                     $rep = &LONCAPA::Lond::dump_course_id_handler(
 5344:                         join(":", (&host_domain($tryserver), $sincefilter,
 5345:                                 &escape($descfilter), &escape($instcodefilter),
 5346:                                 &escape($ownerfilter), &escape($coursefilter),
 5347:                                 &escape($typefilter), &escape($regexp_ok),
 5348:                                 $as_hash, &escape($selfenrollonly),
 5349:                                 &escape($catfilter), $showhidden, $caller,
 5350:                                 &escape($cloner), &escape($cc_clone), $cloneonly,
 5351:                                 &escape($createdbefore), &escape($createdafter),
 5352:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
 5353:                                 $reqcrsdom,&escape($reqinstcode))));
 5354:                 } else {
 5355:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
 5356:                              $sincefilter.':'.&escape($descfilter).':'.
 5357:                              &escape($instcodefilter).':'.&escape($ownerfilter).
 5358:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
 5359:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
 5360:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
 5361:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
 5362:                              &escape($cc_clone).':'.$cloneonly.':'.
 5363:                              &escape($createdbefore).':'.&escape($createdafter).':'.
 5364:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
 5365:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
 5366:                 }
 5367: 
 5368:                 my @pairs=split(/\&/,$rep);
 5369:                 foreach my $item (@pairs) {
 5370:                     my ($key,$value)=split(/\=/,$item,2);
 5371:                     $key = &unescape($key);
 5372:                     next if ($key =~ /^error: 2 /);
 5373:                     my $result = &thaw_unescape($value);
 5374:                     if (ref($result) eq 'HASH') {
 5375:                         $returnhash{$key}=$result;
 5376:                     } else {
 5377:                         my @responses = split(/:/,$value);
 5378:                         my @items = ('description','inst_code','owner','type');
 5379:                         for (my $i=0; $i<@responses; $i++) {
 5380:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 5381:                         }
 5382:                     }
 5383:                 }
 5384:             }
 5385:         }
 5386:     }
 5387:     return %returnhash;
 5388: }
 5389: 
 5390: sub courselastaccess {
 5391:     my ($cdom,$cnum,$hostidref) = @_;
 5392:     my %returnhash;
 5393:     if ($cdom && $cnum) {
 5394:         my $chome = &homeserver($cnum,$cdom);
 5395:         if ($chome ne 'no_host') {
 5396:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
 5397:             &extract_lastaccess(\%returnhash,$rep);
 5398:         }
 5399:     } else {
 5400:         if (!$cdom) { $cdom=''; }
 5401:         my %libserv = &all_library();
 5402:         foreach my $tryserver (keys(%libserv)) {
 5403:             if (ref($hostidref) eq 'ARRAY') {
 5404:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
 5405:             } 
 5406:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
 5407:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
 5408:                 &extract_lastaccess(\%returnhash,$rep);
 5409:             }
 5410:         }
 5411:     }
 5412:     return %returnhash;
 5413: }
 5414: 
 5415: sub extract_lastaccess {
 5416:     my ($returnhash,$rep) = @_;
 5417:     if (ref($returnhash) eq 'HASH') {
 5418:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
 5419:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
 5420:                  $rep eq '') {
 5421:             my @pairs=split(/\&/,$rep);
 5422:             foreach my $item (@pairs) {
 5423:                 my ($key,$value)=split(/\=/,$item,2);
 5424:                 $key = &unescape($key);
 5425:                 next if ($key =~ /^error: 2 /);
 5426:                 $returnhash->{$key} = &thaw_unescape($value);
 5427:             }
 5428:         }
 5429:     }
 5430:     return;
 5431: }
 5432: 
 5433: # ---------------------------------------------------------- DC e-mail
 5434: 
 5435: sub dcmailput {
 5436:     my ($domain,$msgid,$message,$server)=@_;
 5437:     my $status = &Apache::lonnet::critical(
 5438:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 5439:        &escape($message),$server);
 5440:     return $status;
 5441: }
 5442: 
 5443: sub dcmaildump {
 5444:     my ($dom,$startdate,$enddate,$senders) = @_;
 5445:     my %returnhash=();
 5446: 
 5447:     if (defined(&domain($dom,'primary'))) {
 5448:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 5449:                                                          &escape($enddate).':';
 5450: 	my @esc_senders=map { &escape($_)} @$senders;
 5451: 	$cmd.=&escape(join('&',@esc_senders));
 5452: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 5453:             my ($key,$value) = split(/\=/,$line,2);
 5454:             if (($key) && ($value)) {
 5455:                 $returnhash{&unescape($key)} = &unescape($value);
 5456:             }
 5457:         }
 5458:     }
 5459:     return %returnhash;
 5460: }
 5461: # ---------------------------------------------------------- Domain roles
 5462: 
 5463: sub get_domain_roles {
 5464:     my ($dom,$roles,$startdate,$enddate)=@_;
 5465:     if ((!defined($startdate)) || ($startdate eq '')) {
 5466:         $startdate = '.';
 5467:     }
 5468:     if ((!defined($enddate)) || ($enddate eq '')) {
 5469:         $enddate = '.';
 5470:     }
 5471:     my $rolelist;
 5472:     if (ref($roles) eq 'ARRAY') {
 5473:         $rolelist = join('&',@{$roles});
 5474:     }
 5475:     my %personnel = ();
 5476: 
 5477:     my %servers = &get_servers($dom,'library');
 5478:     foreach my $tryserver (keys(%servers)) {
 5479: 	%{$personnel{$tryserver}}=();
 5480: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 5481: 					    &escape($startdate).':'.
 5482: 					    &escape($enddate).':'.
 5483: 					    &escape($rolelist), $tryserver))) {
 5484: 	    my ($key,$value) = split(/\=/,$line,2);
 5485: 	    if (($key) && ($value)) {
 5486: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 5487: 	    }
 5488: 	}
 5489:     }
 5490:     return %personnel;
 5491: }
 5492: 
 5493: sub get_active_domroles {
 5494:     my ($dom,$roles) = @_;
 5495:     return () unless (ref($roles) eq 'ARRAY');
 5496:     my $now = time;
 5497:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
 5498:     my %domroles;
 5499:     foreach my $server (keys(%dompersonnel)) {
 5500:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
 5501:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
 5502:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
 5503:         }
 5504:     }
 5505:     return %domroles;
 5506: }
 5507: 
 5508: # ----------------------------------------------------------- Interval timing 
 5509: 
 5510: {
 5511: # Caches needed for speedup of navmaps
 5512: # We don't want to cache this for very long at all (5 seconds at most)
 5513: # 
 5514: # The user for whom we cache
 5515: my $cachedkey='';
 5516: # The cached times for this user
 5517: my %cachedtimes=();
 5518: # When this was last done
 5519: my $cachedtime='';
 5520: 
 5521: sub load_all_first_access {
 5522:     my ($uname,$udom,$ignorecache)=@_;
 5523:     if (($cachedkey eq $uname.':'.$udom) &&
 5524:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
 5525:         (!$ignorecache)) {
 5526:         return;
 5527:     }
 5528:     $cachedtime=time;
 5529:     $cachedkey=$uname.':'.$udom;
 5530:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
 5531: }
 5532: 
 5533: sub get_first_access {
 5534:     my ($type,$argsymb,$argmap,$ignorecache)=@_;
 5535:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 5536:     if ($argsymb) { $symb=$argsymb; }
 5537:     my ($map,$id,$res)=&decode_symb($symb);
 5538:     if ($argmap) { $map = $argmap; }
 5539:     if ($type eq 'course') {
 5540: 	$res='course';
 5541:     } elsif ($type eq 'map') {
 5542: 	$res=&symbread($map);
 5543:     } else {
 5544: 	$res=$symb;
 5545:     }
 5546:     &load_all_first_access($uname,$udom,$ignorecache);
 5547:     return $cachedtimes{"$courseid\0$res"};
 5548: }
 5549: 
 5550: sub set_first_access {
 5551:     my ($type,$interval)=@_;
 5552:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 5553:     my ($map,$id,$res)=&decode_symb($symb);
 5554:     if ($type eq 'course') {
 5555: 	$res='course';
 5556:     } elsif ($type eq 'map') {
 5557: 	$res=&symbread($map);
 5558:     } else {
 5559: 	$res=$symb;
 5560:     }
 5561:     $cachedkey='';
 5562:     my $firstaccess=&get_first_access($type,$symb,$map);
 5563:     if ($firstaccess) {
 5564:         &logthis("First access time already set ($firstaccess) when attempting ".
 5565:                  "to set new value (type: $type, extent: $res) for $uname:$udom ".
 5566:                  "in $courseid");
 5567:         return 'already_set';
 5568:     } else {
 5569:         my $start = time;
 5570: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
 5571:                           $udom,$uname);
 5572:         if ($putres eq 'ok') {
 5573:             &put('timerinterval',{"$courseid\0$res"=>$interval},
 5574:                  $udom,$uname); 
 5575:             &appenv(
 5576:                      {
 5577:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
 5578:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
 5579:                      }
 5580:                   );
 5581:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
 5582:                 $cachedtimes{"$courseid\0$res"} = $start;
 5583:             }
 5584:         } elsif ($putres ne 'refused') {
 5585:             &logthis("Result: $putres when attempting to set first access time ".
 5586:                      "(type: $type, extent: $res) for $uname:$udom in $courseid");
 5587:         }
 5588:         return $putres;
 5589:     }
 5590:     return 'already_set';
 5591: }
 5592: }
 5593: 
 5594: sub checkout {
 5595:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
 5596:     my $now=time;
 5597:     my $lonhost=$perlvar{'lonHostID'};
 5598:     my $ip = &get_requestor_ip();
 5599:     my $infostr=&escape(
 5600:                  'CHECKOUTTOKEN&'.
 5601:                  $tuname.'&'.
 5602:                  $tudom.'&'.
 5603:                  $tcrsid.'&'.
 5604:                  $symb.'&'.
 5605:                  $now.'&'.$ip);
 5606:     my $token=&reply('tmpput:'.$infostr,$lonhost);
 5607:     if ($token=~/^error\:/) {
 5608:         &logthis("<font color=\"blue\">WARNING: ".
 5609:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
 5610:                  "</font>");
 5611:         return '';
 5612:     }
 5613: 
 5614:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
 5615:     $token=~tr/a-z/A-Z/;
 5616: 
 5617:     my %infohash=('resource.0.outtoken' => $token,
 5618:                   'resource.0.checkouttime' => $now,
 5619:                   'resource.0.outremote' => $ip);
 5620: 
 5621:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 5622:        return '';
 5623:     } else {
 5624:         &logthis("<font color=\"blue\">WARNING: ".
 5625:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
 5626:                  "</font>");
 5627:     }
 5628: 
 5629:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 5630:                          &escape('Checkout '.$infostr.' - '.
 5631:                                                  $token)) ne 'ok') {
 5632:         return '';
 5633:     } else {
 5634:         &logthis("<font color=\"blue\">WARNING: ".
 5635:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
 5636:                  "</font>");
 5637:     }
 5638:     return $token;
 5639: }
 5640: 
 5641: # ------------------------------------------------------------ Check in an item
 5642: 
 5643: sub checkin {
 5644:     my $token=shift;
 5645:     my $now=time;
 5646:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
 5647:     $lonhost=~tr/A-Z/a-z/;
 5648:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
 5649:     $dtoken=~s/\W/\_/g;
 5650:     my $ip = &get_requestor_ip();
 5651:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
 5652:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
 5653: 
 5654:     unless (($tuname) && ($tudom)) {
 5655:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
 5656:         return '';
 5657:     }
 5658: 
 5659:     unless (&allowed('mgr',$tcrsid)) {
 5660:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
 5661:                  $env{'user.name'}.' - '.$env{'user.domain'});
 5662:         return '';
 5663:     }
 5664: 
 5665:     my %infohash=('resource.0.intoken' => $token,
 5666:                   'resource.0.checkintime' => $now,
 5667:                   'resource.0.inremote' => $ip);
 5668: 
 5669:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 5670:        return '';
 5671:     }
 5672: 
 5673:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 5674:                          &escape('Checkin - '.$token)) ne 'ok') {
 5675:         return '';
 5676:     }
 5677: 
 5678:     return ($symb,$tuname,$tudom,$tcrsid);
 5679: }
 5680: 
 5681: # --------------------------------------------- Set Expire Date for Spreadsheet
 5682: 
 5683: sub expirespread {
 5684:     my ($uname,$udom,$stype,$usymb)=@_;
 5685:     my $cid=$env{'request.course.id'}; 
 5686:     if ($cid) {
 5687:        my $now=time;
 5688:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 5689:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 5690:                             $env{'course.'.$cid.'.num'}.
 5691: 	        	    ':nohist_expirationdates:'.
 5692:                             &escape($key).'='.$now,
 5693:                             $env{'course.'.$cid.'.home'})
 5694:     }
 5695:     return 'ok';
 5696: }
 5697: 
 5698: # ----------------------------------------------------- Devalidate Spreadsheets
 5699: 
 5700: sub devalidate {
 5701:     my ($symb,$uname,$udom)=@_;
 5702:     my $cid=$env{'request.course.id'}; 
 5703:     if ($cid) {
 5704:         # delete the stored spreadsheets for
 5705:         # - the student level sheet of this user in course's homespace
 5706:         # - the assessment level sheet for this resource 
 5707:         #   for this user in user's homespace
 5708: 	# - current conditional state info
 5709: 	my $key=$uname.':'.$udom.':';
 5710:         my $status=
 5711: 	    &del('nohist_calculatedsheets',
 5712: 		 [$key.'studentcalc:'],
 5713: 		 $env{'course.'.$cid.'.domain'},
 5714: 		 $env{'course.'.$cid.'.num'})
 5715: 		.' '.
 5716: 	    &del('nohist_calculatedsheets_'.$cid,
 5717: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 5718:         unless ($status eq 'ok ok') {
 5719:            &logthis('Could not devalidate spreadsheet '.
 5720:                     $uname.' at '.$udom.' for '.
 5721: 		    $symb.': '.$status);
 5722:         }
 5723: 	&delenv('user.state.'.$cid);
 5724:     }
 5725: }
 5726: 
 5727: sub get_scalar {
 5728:     my ($string,$end) = @_;
 5729:     my $value;
 5730:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 5731: 	$value = $1;
 5732:     } elsif ($$string =~ s/^([^&]*?)&//) {
 5733: 	$value = $1;
 5734:     }
 5735:     return &unescape($value);
 5736: }
 5737: 
 5738: sub array2str {
 5739:   my (@array) = @_;
 5740:   my $result=&arrayref2str(\@array);
 5741:   $result=~s/^__ARRAY_REF__//;
 5742:   $result=~s/__END_ARRAY_REF__$//;
 5743:   return $result;
 5744: }
 5745: 
 5746: sub arrayref2str {
 5747:   my ($arrayref) = @_;
 5748:   my $result='__ARRAY_REF__';
 5749:   foreach my $elem (@$arrayref) {
 5750:     if(ref($elem) eq 'ARRAY') {
 5751:       $result.=&arrayref2str($elem).'&';
 5752:     } elsif(ref($elem) eq 'HASH') {
 5753:       $result.=&hashref2str($elem).'&';
 5754:     } elsif(ref($elem)) {
 5755:       #print("Got a ref of ".(ref($elem))." skipping.");
 5756:     } else {
 5757:       $result.=&escape($elem).'&';
 5758:     }
 5759:   }
 5760:   $result=~s/\&$//;
 5761:   $result .= '__END_ARRAY_REF__';
 5762:   return $result;
 5763: }
 5764: 
 5765: sub hash2str {
 5766:   my (%hash) = @_;
 5767:   my $result=&hashref2str(\%hash);
 5768:   $result=~s/^__HASH_REF__//;
 5769:   $result=~s/__END_HASH_REF__$//;
 5770:   return $result;
 5771: }
 5772: 
 5773: sub hashref2str {
 5774:   my ($hashref)=@_;
 5775:   my $result='__HASH_REF__';
 5776:   foreach my $key (sort(keys(%$hashref))) {
 5777:     if (ref($key) eq 'ARRAY') {
 5778:       $result.=&arrayref2str($key).'=';
 5779:     } elsif (ref($key) eq 'HASH') {
 5780:       $result.=&hashref2str($key).'=';
 5781:     } elsif (ref($key)) {
 5782:       $result.='=';
 5783:       #print("Got a ref of ".(ref($key))." skipping.");
 5784:     } else {
 5785: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
 5786:     }
 5787: 
 5788:     if(ref($hashref->{$key}) eq 'ARRAY') {
 5789:       $result.=&arrayref2str($hashref->{$key}).'&';
 5790:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 5791:       $result.=&hashref2str($hashref->{$key}).'&';
 5792:     } elsif(ref($hashref->{$key})) {
 5793:        $result.='&';
 5794:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 5795:     } else {
 5796:       $result.=&escape($hashref->{$key}).'&';
 5797:     }
 5798:   }
 5799:   $result=~s/\&$//;
 5800:   $result .= '__END_HASH_REF__';
 5801:   return $result;
 5802: }
 5803: 
 5804: sub str2hash {
 5805:     my ($string)=@_;
 5806:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 5807:     return %$hash;
 5808: }
 5809: 
 5810: sub str2hashref {
 5811:   my ($string) = @_;
 5812: 
 5813:   my %hash;
 5814: 
 5815:   if($string !~ /^__HASH_REF__/) {
 5816:       if (! ($string eq '' || !defined($string))) {
 5817: 	  $hash{'error'}='Not hash reference';
 5818:       }
 5819:       return (\%hash, $string);
 5820:   }
 5821: 
 5822:   $string =~ s/^__HASH_REF__//;
 5823: 
 5824:   while($string !~ /^__END_HASH_REF__/) {
 5825:       #key
 5826:       my $key='';
 5827:       if($string =~ /^__HASH_REF__/) {
 5828:           ($key, $string)=&str2hashref($string);
 5829:           if(defined($key->{'error'})) {
 5830:               $hash{'error'}='Bad data';
 5831:               return (\%hash, $string);
 5832:           }
 5833:       } elsif($string =~ /^__ARRAY_REF__/) {
 5834:           ($key, $string)=&str2arrayref($string);
 5835:           if($key->[0] eq 'Array reference error') {
 5836:               $hash{'error'}='Bad data';
 5837:               return (\%hash, $string);
 5838:           }
 5839:       } else {
 5840:           $string =~ s/^(.*?)=//;
 5841: 	  $key=&unescape($1);
 5842:       }
 5843:       $string =~ s/^=//;
 5844: 
 5845:       #value
 5846:       my $value='';
 5847:       if($string =~ /^__HASH_REF__/) {
 5848:           ($value, $string)=&str2hashref($string);
 5849:           if(defined($value->{'error'})) {
 5850:               $hash{'error'}='Bad data';
 5851:               return (\%hash, $string);
 5852:           }
 5853:       } elsif($string =~ /^__ARRAY_REF__/) {
 5854:           ($value, $string)=&str2arrayref($string);
 5855:           if($value->[0] eq 'Array reference error') {
 5856:               $hash{'error'}='Bad data';
 5857:               return (\%hash, $string);
 5858:           }
 5859:       } else {
 5860: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 5861:       }
 5862:       $string =~ s/^&//;
 5863: 
 5864:       $hash{$key}=$value;
 5865:   }
 5866: 
 5867:   $string =~ s/^__END_HASH_REF__//;
 5868: 
 5869:   return (\%hash, $string);
 5870: }
 5871: 
 5872: sub str2array {
 5873:     my ($string)=@_;
 5874:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 5875:     return @$array;
 5876: }
 5877: 
 5878: sub str2arrayref {
 5879:   my ($string) = @_;
 5880:   my @array;
 5881: 
 5882:   if($string !~ /^__ARRAY_REF__/) {
 5883:       if (! ($string eq '' || !defined($string))) {
 5884: 	  $array[0]='Array reference error';
 5885:       }
 5886:       return (\@array, $string);
 5887:   }
 5888: 
 5889:   $string =~ s/^__ARRAY_REF__//;
 5890: 
 5891:   while($string !~ /^__END_ARRAY_REF__/) {
 5892:       my $value='';
 5893:       if($string =~ /^__HASH_REF__/) {
 5894:           ($value, $string)=&str2hashref($string);
 5895:           if(defined($value->{'error'})) {
 5896:               $array[0] ='Array reference error';
 5897:               return (\@array, $string);
 5898:           }
 5899:       } elsif($string =~ /^__ARRAY_REF__/) {
 5900:           ($value, $string)=&str2arrayref($string);
 5901:           if($value->[0] eq 'Array reference error') {
 5902:               $array[0] ='Array reference error';
 5903:               return (\@array, $string);
 5904:           }
 5905:       } else {
 5906: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 5907:       }
 5908:       $string =~ s/^&//;
 5909: 
 5910:       push(@array, $value);
 5911:   }
 5912: 
 5913:   $string =~ s/^__END_ARRAY_REF__//;
 5914: 
 5915:   return (\@array, $string);
 5916: }
 5917: 
 5918: # -------------------------------------------------------------------Temp Store
 5919: 
 5920: sub tmpreset {
 5921:   my ($symb,$namespace,$domain,$stuname) = @_;
 5922:   if (!$symb) {
 5923:     $symb=&symbread();
 5924:     if (!$symb) { $symb= $env{'request.url'}; }
 5925:   }
 5926:   $symb=escape($symb);
 5927: 
 5928:   if (!$namespace) { $namespace=$env{'request.state'}; }
 5929:   $namespace=~s/\//\_/g;
 5930:   $namespace=~s/\W//g;
 5931: 
 5932:   if (!$domain) { $domain=$env{'user.domain'}; }
 5933:   if (!$stuname) { $stuname=$env{'user.name'}; }
 5934:   if ($domain eq 'public' && $stuname eq 'public') {
 5935:       $stuname=&get_requestor_ip();
 5936:   }
 5937:   my $path=LONCAPA::tempdir();
 5938:   my %hash;
 5939:   if (tie(%hash,'GDBM_File',
 5940: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 5941: 	  &GDBM_WRCREAT(),0640)) {
 5942:     foreach my $key (keys(%hash)) {
 5943:       if ($key=~ /:$symb/) {
 5944: 	delete($hash{$key});
 5945:       }
 5946:     }
 5947:   }
 5948: }
 5949: 
 5950: sub tmpstore {
 5951:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 5952: 
 5953:   if (!$symb) {
 5954:     $symb=&symbread();
 5955:     if (!$symb) { $symb= $env{'request.url'}; }
 5956:   }
 5957:   $symb=escape($symb);
 5958: 
 5959:   if (!$namespace) {
 5960:     # I don't think we would ever want to store this for a course.
 5961:     # it seems this will only be used if we don't have a course.
 5962:     #$namespace=$env{'request.course.id'};
 5963:     #if (!$namespace) {
 5964:       $namespace=$env{'request.state'};
 5965:     #}
 5966:   }
 5967:   $namespace=~s/\//\_/g;
 5968:   $namespace=~s/\W//g;
 5969:   if (!$domain) { $domain=$env{'user.domain'}; }
 5970:   if (!$stuname) { $stuname=$env{'user.name'}; }
 5971:   if ($domain eq 'public' && $stuname eq 'public') {
 5972:       $stuname=&get_requestor_ip();
 5973:   }
 5974:   my $now=time;
 5975:   my %hash;
 5976:   my $path=LONCAPA::tempdir();
 5977:   if (tie(%hash,'GDBM_File',
 5978: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 5979: 	  &GDBM_WRCREAT(),0640)) {
 5980:     $hash{"version:$symb"}++;
 5981:     my $version=$hash{"version:$symb"};
 5982:     my $allkeys=''; 
 5983:     foreach my $key (keys(%$storehash)) {
 5984:       $allkeys.=$key.':';
 5985:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 5986:     }
 5987:     $hash{"$version:$symb:timestamp"}=$now;
 5988:     $allkeys.='timestamp';
 5989:     $hash{"$version:keys:$symb"}=$allkeys;
 5990:     if (untie(%hash)) {
 5991:       return 'ok';
 5992:     } else {
 5993:       return "error:$!";
 5994:     }
 5995:   } else {
 5996:     return "error:$!";
 5997:   }
 5998: }
 5999: 
 6000: # -----------------------------------------------------------------Temp Restore
 6001: 
 6002: sub tmprestore {
 6003:   my ($symb,$namespace,$domain,$stuname) = @_;
 6004: 
 6005:   if (!$symb) {
 6006:     $symb=&symbread();
 6007:     if (!$symb) { $symb= $env{'request.url'}; }
 6008:   }
 6009:   $symb=escape($symb);
 6010: 
 6011:   if (!$namespace) { $namespace=$env{'request.state'}; }
 6012: 
 6013:   if (!$domain) { $domain=$env{'user.domain'}; }
 6014:   if (!$stuname) { $stuname=$env{'user.name'}; }
 6015:   if ($domain eq 'public' && $stuname eq 'public') {
 6016:       $stuname=&get_requestor_ip();
 6017:   }
 6018:   my %returnhash;
 6019:   $namespace=~s/\//\_/g;
 6020:   $namespace=~s/\W//g;
 6021:   my %hash;
 6022:   my $path=LONCAPA::tempdir();
 6023:   if (tie(%hash,'GDBM_File',
 6024: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 6025: 	  &GDBM_READER(),0640)) {
 6026:     my $version=$hash{"version:$symb"};
 6027:     $returnhash{'version'}=$version;
 6028:     my $scope;
 6029:     for ($scope=1;$scope<=$version;$scope++) {
 6030:       my $vkeys=$hash{"$scope:keys:$symb"};
 6031:       my @keys=split(/:/,$vkeys);
 6032:       my $key;
 6033:       $returnhash{"$scope:keys"}=$vkeys;
 6034:       foreach $key (@keys) {
 6035: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 6036: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 6037:       }
 6038:     }
 6039:     if (!(untie(%hash))) {
 6040:       return "error:$!";
 6041:     }
 6042:   } else {
 6043:     return "error:$!";
 6044:   }
 6045:   return %returnhash;
 6046: }
 6047: 
 6048: # ----------------------------------------------------------------------- Store
 6049: 
 6050: sub store {
 6051:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 6052:     my $home='';
 6053: 
 6054:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 6055: 
 6056:     $symb=&symbclean($symb);
 6057:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 6058: 
 6059:     if (!$domain) { $domain=$env{'user.domain'}; }
 6060:     if (!$stuname) { $stuname=$env{'user.name'}; }
 6061: 
 6062:     &devalidate($symb,$stuname,$domain);
 6063: 
 6064:     $symb=escape($symb);
 6065:     if (!$namespace) { 
 6066:        unless ($namespace=$env{'request.course.id'}) { 
 6067:           return ''; 
 6068:        } 
 6069:     }
 6070:     if (!$home) { $home=$env{'user.home'}; }
 6071: 
 6072:     $$storehash{'ip'}=&get_requestor_ip();
 6073:     $$storehash{'host'}=$perlvar{'lonHostID'};
 6074: 
 6075:     my $namevalue='';
 6076:     foreach my $key (keys(%$storehash)) {
 6077:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 6078:     }
 6079:     $namevalue=~s/\&$//;
 6080:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 6081:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 6082: }
 6083: 
 6084: # -------------------------------------------------------------- Critical Store
 6085: 
 6086: sub cstore {
 6087:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 6088:     my $home='';
 6089: 
 6090:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 6091: 
 6092:     $symb=&symbclean($symb);
 6093:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 6094: 
 6095:     if (!$domain) { $domain=$env{'user.domain'}; }
 6096:     if (!$stuname) { $stuname=$env{'user.name'}; }
 6097: 
 6098:     &devalidate($symb,$stuname,$domain);
 6099: 
 6100:     $symb=escape($symb);
 6101:     if (!$namespace) { 
 6102:        unless ($namespace=$env{'request.course.id'}) { 
 6103:           return ''; 
 6104:        } 
 6105:     }
 6106:     if (!$home) { $home=$env{'user.home'}; }
 6107: 
 6108:     $$storehash{'ip'}=&get_requestor_ip();
 6109:     $$storehash{'host'}=$perlvar{'lonHostID'};
 6110: 
 6111:     my $namevalue='';
 6112:     foreach my $key (keys(%$storehash)) {
 6113:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 6114:     }
 6115:     $namevalue=~s/\&$//;
 6116:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 6117:     return critical
 6118:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 6119: }
 6120: 
 6121: # --------------------------------------------------------------------- Restore
 6122: 
 6123: sub restore {
 6124:     my ($symb,$namespace,$domain,$stuname) = @_;
 6125:     my $home='';
 6126: 
 6127:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 6128: 
 6129:     if (!$symb) {
 6130:         return if ($namespace eq 'courserequests');
 6131:         unless ($symb=escape(&symbread())) { return ''; }
 6132:     } else {
 6133:         unless ($namespace eq 'courserequests') {
 6134:             $symb=&escape(&symbclean($symb));
 6135:         }
 6136:     }
 6137:     if (!$namespace) { 
 6138:        unless ($namespace=$env{'request.course.id'}) { 
 6139:           return ''; 
 6140:        } 
 6141:     }
 6142:     if (!$domain) { $domain=$env{'user.domain'}; }
 6143:     if (!$stuname) { $stuname=$env{'user.name'}; }
 6144:     if (!$home) { $home=$env{'user.home'}; }
 6145:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 6146: 
 6147:     my %returnhash=();
 6148:     foreach my $line (split(/\&/,$answer)) {
 6149: 	my ($name,$value)=split(/\=/,$line);
 6150:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 6151:     }
 6152:     my $version;
 6153:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 6154:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 6155:           $returnhash{$item}=$returnhash{$version.':'.$item};
 6156:        }
 6157:     }
 6158:     return %returnhash;
 6159: }
 6160: 
 6161: # ---------------------------------------------------------- Course Description
 6162: #
 6163: #  
 6164: 
 6165: sub coursedescription {
 6166:     my ($courseid,$args)=@_;
 6167:     $courseid=~s/^\///;
 6168:     $courseid=~s/\_/\//g;
 6169:     my ($cdomain,$cnum)=split(/\//,$courseid);
 6170:     my $chome=&homeserver($cnum,$cdomain);
 6171:     my $normalid=$cdomain.'_'.$cnum;
 6172:     # need to always cache even if we get errors otherwise we keep 
 6173:     # trying and trying and trying to get the course description.
 6174:     my %envhash=();
 6175:     my %returnhash=();
 6176:     
 6177:     my $expiretime=600;
 6178:     if ($env{'request.course.id'} eq $normalid) {
 6179: 	$expiretime=120;
 6180:     }
 6181: 
 6182:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 6183:     if (!$args->{'freshen_cache'}
 6184: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 6185: 	foreach my $key (keys(%env)) {
 6186: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 6187: 	    my ($setting) = $1;
 6188: 	    $returnhash{$setting} = $env{$key};
 6189: 	}
 6190: 	return %returnhash;
 6191:     }
 6192: 
 6193:     # get the data again
 6194: 
 6195:     if (!$args->{'one_time'}) {
 6196: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 6197:     }
 6198: 
 6199:     if ($chome ne 'no_host') {
 6200:        %returnhash=&dump('environment',$cdomain,$cnum);
 6201:        if (!exists($returnhash{'con_lost'})) {
 6202: 	   my $username = $env{'user.name'}; # Defult username
 6203: 	   if(defined $args->{'user'}) {
 6204: 	       $username = $args->{'user'};
 6205: 	   }
 6206:            $returnhash{'home'}= $chome;
 6207: 	   $returnhash{'domain'} = $cdomain;
 6208: 	   $returnhash{'num'} = $cnum;
 6209:            if (!defined($returnhash{'type'})) {
 6210:                $returnhash{'type'} = 'Course';
 6211:            }
 6212:            while (my ($name,$value) = each %returnhash) {
 6213:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 6214:            }
 6215:            $returnhash{'url'}=&clutter($returnhash{'url'});
 6216:            $returnhash{'fn'}=LONCAPA::tempdir() .
 6217: 	       $username.'_'.$cdomain.'_'.$cnum;
 6218:            $envhash{'course.'.$normalid.'.home'}=$chome;
 6219:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 6220:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 6221:        }
 6222:     }
 6223:     if (!$args->{'one_time'}) {
 6224: 	&appenv(\%envhash);
 6225:     }
 6226:     return %returnhash;
 6227: }
 6228: 
 6229: sub update_released_required {
 6230:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
 6231:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
 6232:         $cid = $env{'request.course.id'};
 6233:         $cdom = $env{'course.'.$cid.'.domain'};
 6234:         $cnum = $env{'course.'.$cid.'.num'};
 6235:         $chome = $env{'course.'.$cid.'.home'};
 6236:     }
 6237:     if ($needsrelease) {
 6238:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
 6239:         my $needsupdate;
 6240:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
 6241:             $needsupdate = 1;
 6242:         } else {
 6243:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
 6244:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
 6245:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
 6246:                 $needsupdate = 1;
 6247:             }
 6248:         }
 6249:         if ($needsupdate) {
 6250:             my %needshash = (
 6251:                              'internal.releaserequired' => $needsrelease,
 6252:                             );
 6253:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
 6254:             if ($putresult eq 'ok') {
 6255:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
 6256:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 6257:                 if (ref($crsinfo{$cid}) eq 'HASH') {
 6258:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
 6259:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
 6260:                 }
 6261:             }
 6262:         }
 6263:     }
 6264:     return;
 6265: }
 6266: 
 6267: # -------------------------------------------------See if a user is privileged
 6268: 
 6269: sub privileged {
 6270:     my ($username,$domain,$possdomains,$possroles)=@_;
 6271:     my $now = time;
 6272:     my $roles;
 6273:     if (ref($possroles) eq 'ARRAY') {
 6274:         $roles = $possroles;
 6275:     } else {
 6276:         $roles = ['dc','su'];
 6277:     }
 6278:     if (ref($possdomains) eq 'ARRAY') {
 6279:         my %privileged = &privileged_by_domain($possdomains,$roles);
 6280:         foreach my $dom (@{$possdomains}) {
 6281:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
 6282:                 (ref($privileged{$dom}) eq 'HASH')) {
 6283:                 foreach my $role (@{$roles}) {
 6284:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 6285:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
 6286:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
 6287:                             return 1 unless (($end && $end < $now) ||
 6288:                                              ($start && $start > $now));
 6289:                         }
 6290:                     }
 6291:                 }
 6292:             }
 6293:         }
 6294:     } else {
 6295:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
 6296:         my $now = time;
 6297: 
 6298:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
 6299:             my ($trole, $tend, $tstart) = split(/_/, $role);
 6300:             if (grep(/^\Q$trole\E$/,@{$roles})) {
 6301:                 return 1 unless ($tend && $tend < $now)
 6302:                         or ($tstart && $tstart > $now);
 6303:             }
 6304:         }
 6305:     }
 6306:     return 0;
 6307: }
 6308: 
 6309: sub privileged_by_domain {
 6310:     my ($domains,$roles) = @_;
 6311:     my %privileged = ();
 6312:     my $cachetime = 60*60*24;
 6313:     my $now = time;
 6314:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
 6315:         return %privileged;
 6316:     }
 6317:     foreach my $dom (@{$domains}) {
 6318:         next if (ref($privileged{$dom}) eq 'HASH');
 6319:         my $needroles;
 6320:         foreach my $role (@{$roles}) {
 6321:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
 6322:             if (defined($cached)) {
 6323:                 if (ref($result) eq 'HASH') {
 6324:                     $privileged{$dom}{$role} = $result;
 6325:                 }
 6326:             } else {
 6327:                 $needroles = 1;
 6328:             }
 6329:         }
 6330:         if ($needroles) {
 6331:             my %dompersonnel = &get_domain_roles($dom,$roles);
 6332:             $privileged{$dom} = {};
 6333:             foreach my $server (keys(%dompersonnel)) {
 6334:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 6335:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
 6336:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
 6337:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
 6338:                         next if ($end && $end < $now);
 6339:                         $privileged{$dom}{$trole}{$uname.':'.$udom} =
 6340:                             $dompersonnel{$server}{$item};
 6341:                     }
 6342:                 }
 6343:             }
 6344:             if (ref($privileged{$dom}) eq 'HASH') {
 6345:                 foreach my $role (@{$roles}) {
 6346:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 6347:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
 6348:                     } else {
 6349:                         my %hash = ();
 6350:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
 6351:                     }
 6352:                 }
 6353:             }
 6354:         }
 6355:     }
 6356:     return %privileged;
 6357: }
 6358: 
 6359: # -------------------------------------------------------- Get user privileges
 6360: 
 6361: sub rolesinit {
 6362:     my ($domain, $username) = @_;
 6363:     my %userroles = ('user.login.time' => time);
 6364:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
 6365: 
 6366:     # firstaccess and timerinterval are related to timed maps/resources. 
 6367:     # also, blocking can be triggered by an activating timer
 6368:     # it's saved in the user's %env.
 6369:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
 6370:     my %timerinterval = &dump('timerinterval', $domain, $username);
 6371:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
 6372:         %timerintchk, %timerintenv);
 6373: 
 6374:     foreach my $key (keys(%firstaccess)) {
 6375:         my ($cid, $rest) = split(/\0/, $key);
 6376:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
 6377:     }
 6378: 
 6379:     foreach my $key (keys(%timerinterval)) {
 6380:         my ($cid,$rest) = split(/\0/,$key);
 6381:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
 6382:     }
 6383: 
 6384:     my %allroles=();
 6385:     my %allgroups=();
 6386: 
 6387:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
 6388:         my $role = $rolesdump{$area};
 6389:         $area =~ s/\_\w\w$//;
 6390: 
 6391:         my ($trole, $tend, $tstart, $group_privs);
 6392: 
 6393:         if ($role =~ /^cr/) {
 6394:         # Custom role, defined by a user 
 6395:         # e.g., user.role.cr/msu/smith/mynewrole
 6396:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 6397:                 $trole = $1;
 6398:                 ($tend, $tstart) = split('_', $2);
 6399:             } else {
 6400:                 $trole = $role;
 6401:             }
 6402:         } elsif ($role =~ m|^gr/|) {
 6403:         # Role of member in a group, defined within a course/community
 6404:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
 6405:             ($trole, $tend, $tstart) = split(/_/, $role);
 6406:             next if $tstart eq '-1';
 6407:             ($trole, $group_privs) = split(/\//, $trole);
 6408:             $group_privs = &unescape($group_privs);
 6409:         } else {
 6410:         # Just a normal role, defined in roles.tab
 6411:             ($trole, $tend, $tstart) = split(/_/,$role);
 6412:         }
 6413: 
 6414:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 6415:                  $username);
 6416:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 6417: 
 6418:         # role expired or not available yet?
 6419:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
 6420:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
 6421: 
 6422:         next if $area eq '' or $trole eq '';
 6423: 
 6424:         my $spec = "$trole.$area";
 6425:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
 6426: 
 6427:         if ($trole =~ /^cr\//) {
 6428:         # Custom role, defined by a user
 6429:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 6430:         } elsif ($trole eq 'gr') {
 6431:         # Role of a member in a group, defined within a course/community
 6432:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 6433:             next;
 6434:         } else {
 6435:         # Normal role, defined in roles.tab
 6436:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 6437:         }
 6438: 
 6439:         my $cid = $tdomain.'_'.$trest;
 6440:         unless ($firstaccchk{$cid}) {
 6441:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
 6442:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
 6443:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
 6444:                         $coursetimerstarts{$cid}{$item}; 
 6445:                 }
 6446:             }
 6447:             $firstaccchk{$cid} = 1;
 6448:         }
 6449:         unless ($timerintchk{$cid}) {
 6450:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
 6451:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
 6452:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
 6453:                        $coursetimerintervals{$cid}{$item};
 6454:                 }
 6455:             }
 6456:             $timerintchk{$cid} = 1;
 6457:         }
 6458:     }
 6459: 
 6460:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
 6461:                                                           \%allroles, \%allgroups);
 6462:     $env{'user.adv'} = $userroles{'user.adv'};
 6463:     $env{'user.rar'} = $userroles{'user.rar'};
 6464: 
 6465:     return (\%userroles,\%firstaccenv,\%timerintenv);
 6466: }
 6467: 
 6468: sub set_arearole {
 6469:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
 6470:     unless ($nolog) {
 6471: # log the associated role with the area
 6472:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 6473:     }
 6474:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 6475: }
 6476: 
 6477: sub custom_roleprivs {
 6478:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 6479:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 6480:     my $homsvr = &homeserver($rauthor,$rdomain);
 6481:     if (&hostname($homsvr) ne '') {
 6482:         my ($rdummy,$roledef)=
 6483:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 6484:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 6485:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 6486:             if (defined($syspriv)) {
 6487:                 if ($trest =~ /^$match_community$/) {
 6488:                     $syspriv =~ s/bre\&S//; 
 6489:                 }
 6490:                 $$allroles{'cm./'}.=':'.$syspriv;
 6491:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 6492:             }
 6493:             if ($tdomain ne '') {
 6494:                 if (defined($dompriv)) {
 6495:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 6496:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 6497:                 }
 6498:                 if (($trest ne '') && (defined($coursepriv))) {
 6499:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
 6500:                         my $rolename = $1;
 6501:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
 6502:                     }
 6503:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 6504:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 6505:                 }
 6506:             }
 6507:         }
 6508:     }
 6509: }
 6510: 
 6511: sub course_adhocrole_privs {
 6512:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
 6513:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
 6514:     if ($overrides{"internal.adhocpriv.$rolename"}) {
 6515:         my (%currprivs,%storeprivs);
 6516:         foreach my $item (split(/:/,$coursepriv)) {
 6517:             my ($priv,$restrict) = split(/\&/,$item);
 6518:             $currprivs{$priv} = $restrict;
 6519:         }
 6520:         my (%possadd,%possremove,%full);
 6521:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
 6522:             my ($priv,$restrict)=split(/\&/,$item);
 6523:             $full{$priv} = $restrict;
 6524:         }
 6525:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
 6526:              next if ($item eq '');
 6527:              my ($rule,$rest) = split(/=/,$item);
 6528:              next unless (($rule eq 'off') || ($rule eq 'on'));
 6529:              foreach my $priv (split(/:/,$rest)) {
 6530:                  if ($priv ne '') {
 6531:                      if ($rule eq 'off') {
 6532:                          $possremove{$priv} = 1;
 6533:                      } else {
 6534:                          $possadd{$priv} = 1;
 6535:                      }
 6536:                  }
 6537:              }
 6538:          }
 6539:          foreach my $priv (sort(keys(%full))) {
 6540:              if (exists($currprivs{$priv})) {
 6541:                  unless (exists($possremove{$priv})) {
 6542:                      $storeprivs{$priv} = $currprivs{$priv};
 6543:                  }
 6544:              } elsif (exists($possadd{$priv})) {
 6545:                  $storeprivs{$priv} = $full{$priv};
 6546:              }
 6547:          }
 6548:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
 6549:      }
 6550:      return $coursepriv;
 6551: }
 6552: 
 6553: sub group_roleprivs {
 6554:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 6555:     my $access = 1;
 6556:     my $now = time;
 6557:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 6558:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 6559:     if ($access) {
 6560:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 6561:         $$allgroups{$course}{$group} .=':'.$group_privs;
 6562:     }
 6563: }
 6564: 
 6565: sub standard_roleprivs {
 6566:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 6567:     if (defined($pr{$trole.':s'})) {
 6568:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 6569:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 6570:     }
 6571:     if ($tdomain ne '') {
 6572:         if (defined($pr{$trole.':d'})) {
 6573:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 6574:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 6575:         }
 6576:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 6577:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 6578:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 6579:         }
 6580:     }
 6581: }
 6582: 
 6583: sub set_userprivs {
 6584:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
 6585:     my $author=0;
 6586:     my $adv=0;
 6587:     my $rar=0;
 6588:     my %grouproles = ();
 6589:     if (keys(%{$allgroups}) > 0) {
 6590:         my @groupkeys; 
 6591:         foreach my $role (keys(%{$allroles})) {
 6592:             push(@groupkeys,$role);
 6593:         }
 6594:         if (ref($groups_roles) eq 'HASH') {
 6595:             foreach my $key (keys(%{$groups_roles})) {
 6596:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
 6597:                     push(@groupkeys,$key);
 6598:                 }
 6599:             }
 6600:         }
 6601:         if (@groupkeys > 0) {
 6602:             foreach my $role (@groupkeys) {
 6603:                 my ($trole,$area,$sec,$extendedarea);
 6604:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 6605:                     $trole = $1;
 6606:                     $area = $2;
 6607:                     $sec = $3;
 6608:                     $extendedarea = $area.$sec;
 6609:                     if (exists($$allgroups{$area})) {
 6610:                         foreach my $group (keys(%{$$allgroups{$area}})) {
 6611:                             my $spec = $trole.'.'.$extendedarea;
 6612:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
 6613:                                                 $$allgroups{$area}{$group};
 6614:                         }
 6615:                     }
 6616:                 }
 6617:             }
 6618:         }
 6619:     }
 6620:     foreach my $group (keys(%grouproles)) {
 6621:         $$allroles{$group} = $grouproles{$group};
 6622:     }
 6623:     foreach my $role (keys(%{$allroles})) {
 6624:         my %thesepriv;
 6625:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 6626:         foreach my $item (split(/:/,$$allroles{$role})) {
 6627:             if ($item ne '') {
 6628:                 my ($privilege,$restrictions)=split(/&/,$item);
 6629:                 if ($restrictions eq '') {
 6630:                     $thesepriv{$privilege}='F';
 6631:                 } elsif ($thesepriv{$privilege} ne 'F') {
 6632:                     $thesepriv{$privilege}.=$restrictions;
 6633:                 }
 6634:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 6635:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
 6636:             }
 6637:         }
 6638:         my $thesestr='';
 6639:         foreach my $priv (sort(keys(%thesepriv))) {
 6640: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 6641: 	}
 6642:         $userroles->{'user.priv.'.$role} = $thesestr;
 6643:     }
 6644:     return ($author,$adv,$rar);
 6645: }
 6646: 
 6647: sub role_status {
 6648:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 6649:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 6650:         my ($one,$two) = split(m{\./},$rolekey,2);
 6651:         (undef,undef,$$role) = split(/\./,$one,3);
 6652:         unless (!defined($$role) || $$role eq '') {
 6653:             $$where = '/'.$two;
 6654:             $$trolecode=$$role.'.'.$$where;
 6655:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 6656:             $$tstatus='is';
 6657:             if ($$tstart && $$tstart>$update) {
 6658:                 $$tstatus='future';
 6659:                 if ($$tstart<$now) {
 6660:                     if ($$tstart && $$tstart>$refresh) {
 6661:                         if (($$where ne '') && ($$role ne '')) {
 6662:                             my (%allroles,%allgroups,$group_privs,
 6663:                                 %groups_roles,@rolecodes);
 6664:                             my %userroles = (
 6665:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 6666:                             );
 6667:                             @rolecodes = ('cm'); 
 6668:                             my $spec=$$role.'.'.$$where;
 6669:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 6670:                             if ($$role =~ /^cr\//) {
 6671:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 6672:                                 push(@rolecodes,'cr');
 6673:                             } elsif ($$role eq 'gr') {
 6674:                                 push(@rolecodes,$$role);
 6675:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 6676:                                                     $env{'user.name'});
 6677:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
 6678:                                 (undef,my $group_privs) = split(/\//,$trole);
 6679:                                 $group_privs = &unescape($group_privs);
 6680:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 6681:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
 6682:                                 &get_groups_roles($tdomain,$trest,
 6683:                                                   \%course_roles,\@rolecodes,
 6684:                                                   \%groups_roles);
 6685:                             } else {
 6686:                                 push(@rolecodes,$$role);
 6687:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 6688:                             }
 6689:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
 6690:                                                                    \%groups_roles);
 6691:                             &appenv(\%userroles,\@rolecodes);
 6692:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
 6693:                         }
 6694:                     }
 6695:                     $$tstatus = 'is';
 6696:                 }
 6697:             }
 6698:             if ($$tend) {
 6699:                 if ($$tend<$update) {
 6700:                     $$tstatus='expired';
 6701:                 } elsif ($$tend<$now) {
 6702:                     $$tstatus='will_not';
 6703:                 }
 6704:             }
 6705:         }
 6706:     }
 6707: }
 6708: 
 6709: sub get_groups_roles {
 6710:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
 6711:     return unless((ref($cdom_courseroles) eq 'HASH') && 
 6712:                   (ref($rolecodes) eq 'ARRAY') && 
 6713:                   (ref($groups_roles) eq 'HASH')); 
 6714:     if (keys(%{$cdom_courseroles}) > 0) {
 6715:         my ($cnum) = ($rest =~ /^($match_courseid)/);
 6716:         if ($cdom ne '' && $cnum ne '') {
 6717:             foreach my $key (keys(%{$cdom_courseroles})) {
 6718:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
 6719:                     my $crsrole = $1;
 6720:                     my $crssec = $2;
 6721:                     if ($crsrole =~ /^cr/) {
 6722:                         unless (grep(/^cr$/,@{$rolecodes})) {
 6723:                             push(@{$rolecodes},'cr');
 6724:                         }
 6725:                     } else {
 6726:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
 6727:                             push(@{$rolecodes},$crsrole);
 6728:                         }
 6729:                     }
 6730:                     my $rolekey = "$crsrole./$cdom/$cnum";
 6731:                     if ($crssec ne '') {
 6732:                         $rolekey .= "/$crssec";
 6733:                     }
 6734:                     $rolekey .= './';
 6735:                     $groups_roles->{$rolekey} = $rolecodes;
 6736:                 }
 6737:             }
 6738:         }
 6739:     }
 6740:     return;
 6741: }
 6742: 
 6743: sub delete_env_groupprivs {
 6744:     my ($where,$courseroles,$possroles) = @_;
 6745:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
 6746:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
 6747:     unless (ref($courseroles->{$udom}) eq 'HASH') {
 6748:         %{$courseroles->{$udom}} =
 6749:             &get_my_roles('','','userroles',['active'],
 6750:                           $possroles,[$udom],1);
 6751:     }
 6752:     if (ref($courseroles->{$udom}) eq 'HASH') {
 6753:         foreach my $item (keys(%{$courseroles->{$udom}})) {
 6754:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
 6755:             my $area = '/'.$cdom.'/'.$cnum;
 6756:             my $privkey = "user.priv.$crsrole.$area";
 6757:             if ($crssec ne '') {
 6758:                 $privkey .= '/'.$crssec;
 6759:             }
 6760:             $privkey .= ".$area/$group";
 6761:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
 6762:         }
 6763:     }
 6764:     return;
 6765: }
 6766: 
 6767: sub check_adhoc_privs {
 6768:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
 6769:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 6770:     if ($sec) {
 6771:         $cckey .= '/'.$sec;
 6772:     }
 6773:     my $setprivs;
 6774:     if ($env{$cckey}) {
 6775:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 6776:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 6777:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 6778:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
 6779:             $setprivs = 1;
 6780:         }
 6781:     } else {
 6782:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
 6783:         $setprivs = 1;
 6784:     }
 6785:     return $setprivs;
 6786: }
 6787: 
 6788: sub set_adhoc_privileges {
 6789: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
 6790:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
 6791:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 6792:     if ($sec ne '') {
 6793:         $area .= '/'.$sec;
 6794:     }
 6795:     my $spec = $role.'.'.$area;
 6796:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 6797:                                   $env{'user.name'},1);
 6798:     my %rolehash = ();
 6799:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
 6800:         my $rolename = $1;
 6801:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
 6802:         my %domdef = &get_domain_defaults($dcdom);
 6803:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
 6804:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
 6805:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
 6806:             }
 6807:         }
 6808:     } else {
 6809:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
 6810:     }
 6811:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
 6812:     &appenv(\%userroles,[$role,'cm']);
 6813:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
 6814:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
 6815:         &appenv( {'request.role'        => $spec,
 6816:                   'request.role.domain' => $dcdom,
 6817:                   'request.course.sec'  => $sec, 
 6818:                  }
 6819:                );
 6820:         my $tadv=0;
 6821:         if (&allowed('adv') eq 'F') { $tadv=1; }
 6822:         &appenv({'request.role.adv'    => $tadv});
 6823:     }
 6824: }
 6825: 
 6826: # --------------------------------------------------------------- get interface
 6827: 
 6828: sub get {
 6829:    my ($namespace,$storearr,$udomain,$uname)=@_;
 6830:    my $items='';
 6831:    foreach my $item (@$storearr) {
 6832:        $items.=&escape($item).'&';
 6833:    }
 6834:    $items=~s/\&$//;
 6835:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6836:    if (!$uname) { $uname=$env{'user.name'}; }
 6837:    my $uhome=&homeserver($uname,$udomain);
 6838: 
 6839:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 6840:    my @pairs=split(/\&/,$rep);
 6841:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 6842:      return @pairs;
 6843:    }
 6844:    my %returnhash=();
 6845:    my $i=0;
 6846:    foreach my $item (@$storearr) {
 6847:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 6848:       $i++;
 6849:    }
 6850:    return %returnhash;
 6851: }
 6852: 
 6853: # --------------------------------------------------------------- del interface
 6854: 
 6855: sub del {
 6856:    my ($namespace,$storearr,$udomain,$uname)=@_;
 6857:    my $items='';
 6858:    foreach my $item (@$storearr) {
 6859:        $items.=&escape($item).'&';
 6860:    }
 6861: 
 6862:    $items=~s/\&$//;
 6863:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6864:    if (!$uname) { $uname=$env{'user.name'}; }
 6865:    my $uhome=&homeserver($uname,$udomain);
 6866:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 6867: }
 6868: 
 6869: # -------------------------------------------------------------- dump interface
 6870: 
 6871: sub unserialize {
 6872:     my ($rep, $escapedkeys) = @_;
 6873: 
 6874:     return {} if $rep =~ /^error/;
 6875: 
 6876:     my %returnhash=();
 6877:     foreach my $item (split(/\&/,$rep)) {
 6878:         my ($key, $value) = split(/=/, $item, 2);
 6879:         $key = unescape($key) unless $escapedkeys;
 6880:         next if $key =~ /^error: 2 /;
 6881:         $returnhash{$key} = &thaw_unescape($value);
 6882:     }
 6883:     return \%returnhash;
 6884: }
 6885: 
 6886: # see Lond::dump_with_regexp
 6887: # if $escapedkeys hash keys won't get unescaped.
 6888: sub dump {
 6889:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
 6890:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 6891:     if (!$uname) { $uname=$env{'user.name'}; }
 6892:     my $uhome=&homeserver($uname,$udomain);
 6893: 
 6894:     if ($regexp) {
 6895:         $regexp=&escape($regexp);
 6896:     } else {
 6897:         $regexp='.';
 6898:     }
 6899:     if (grep { $_ eq $uhome } &current_machine_ids()) {
 6900:         # user is hosted on this machine
 6901:         my $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
 6902:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
 6903:         return %{&unserialize($reply, $escapedkeys)};
 6904:     }
 6905:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 6906:     my @pairs=split(/\&/,$rep);
 6907:     my %returnhash=();
 6908:     if (!($rep =~ /^error/ )) {
 6909: 	foreach my $item (@pairs) {
 6910: 	    my ($key,$value)=split(/=/,$item,2);
 6911:             $key = &unescape($key) unless ($escapedkeys);
 6912: 	    next if ($key =~ /^error: 2 /);
 6913: 	    $returnhash{$key}=&thaw_unescape($value);
 6914: 	}
 6915:     }
 6916:     return %returnhash;
 6917: }
 6918: 
 6919: 
 6920: # --------------------------------------------------------- dumpstore interface
 6921: 
 6922: sub dumpstore {
 6923:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 6924:    # same as dump but keys must be escaped. They may contain colon separated
 6925:    # lists of values that may themself contain colons (e.g. symbs).
 6926:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
 6927: }
 6928: 
 6929: # -------------------------------------------------------------- keys interface
 6930: 
 6931: sub getkeys {
 6932:    my ($namespace,$udomain,$uname)=@_;
 6933:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6934:    if (!$uname) { $uname=$env{'user.name'}; }
 6935:    my $uhome=&homeserver($uname,$udomain);
 6936:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 6937:    my @keyarray=();
 6938:    foreach my $key (split(/\&/,$rep)) {
 6939:       next if ($key =~ /^error: 2 /);
 6940:       push(@keyarray,&unescape($key));
 6941:    }
 6942:    return @keyarray;
 6943: }
 6944: 
 6945: # --------------------------------------------------------------- currentdump
 6946: sub currentdump {
 6947:    my ($courseid,$sdom,$sname)=@_;
 6948:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 6949:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 6950:    $sname    = $env{'user.name'}         if (! defined($sname));
 6951:    my $uhome = &homeserver($sname,$sdom);
 6952:    my $rep;
 6953: 
 6954:    if (grep { $_ eq $uhome } current_machine_ids()) {
 6955:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
 6956:                    $courseid)));
 6957:    } else {
 6958:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 6959:    }
 6960: 
 6961:    return if ($rep =~ /^(error:|no_such_host)/);
 6962:    #
 6963:    my %returnhash=();
 6964:    #
 6965:    if ($rep eq 'unknown_cmd') {
 6966:        # an old lond will not know currentdump
 6967:        # Do a dump and make it look like a currentdump
 6968:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 6969:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 6970:        my %hash = @tmp;
 6971:        @tmp=();
 6972:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 6973:    } else {
 6974:        my @pairs=split(/\&/,$rep);
 6975:        foreach my $pair (@pairs) {
 6976:            my ($key,$value)=split(/=/,$pair,2);
 6977:            my ($symb,$param) = split(/:/,$key);
 6978:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 6979:                                                         &thaw_unescape($value);
 6980:        }
 6981:    }
 6982:    return %returnhash;
 6983: }
 6984: 
 6985: sub convert_dump_to_currentdump{
 6986:     my %hash = %{shift()};
 6987:     my %returnhash;
 6988:     # Code ripped from lond, essentially.  The only difference
 6989:     # here is the unescaping done by lonnet::dump().  Conceivably
 6990:     # we might run in to problems with parameter names =~ /^v\./
 6991:     while (my ($key,$value) = each(%hash)) {
 6992:         my ($v,$symb,$param) = split(/:/,$key);
 6993: 	$symb  = &unescape($symb);
 6994: 	$param = &unescape($param);
 6995:         next if ($v eq 'version' || $symb eq 'keys');
 6996:         next if (exists($returnhash{$symb}) &&
 6997:                  exists($returnhash{$symb}->{$param}) &&
 6998:                  $returnhash{$symb}->{'v.'.$param} > $v);
 6999:         $returnhash{$symb}->{$param}=$value;
 7000:         $returnhash{$symb}->{'v.'.$param}=$v;
 7001:     }
 7002:     #
 7003:     # Remove all of the keys in the hashes which keep track of
 7004:     # the version of the parameter.
 7005:     while (my ($symb,$param_hash) = each(%returnhash)) {
 7006:         # use a foreach because we are going to delete from the hash.
 7007:         foreach my $key (keys(%$param_hash)) {
 7008:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 7009:         }
 7010:     }
 7011:     return \%returnhash;
 7012: }
 7013: 
 7014: # ------------------------------------------------------ critical inc interface
 7015: 
 7016: sub cinc {
 7017:     return &inc(@_,'critical');
 7018: }
 7019: 
 7020: # --------------------------------------------------------------- inc interface
 7021: 
 7022: sub inc {
 7023:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 7024:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 7025:     if (!$uname) { $uname=$env{'user.name'}; }
 7026:     my $uhome=&homeserver($uname,$udomain);
 7027:     my $items='';
 7028:     if (! ref($store)) {
 7029:         # got a single value, so use that instead
 7030:         $items = &escape($store).'=&';
 7031:     } elsif (ref($store) eq 'SCALAR') {
 7032:         $items = &escape($$store).'=&';        
 7033:     } elsif (ref($store) eq 'ARRAY') {
 7034:         $items = join('=&',map {&escape($_);} @{$store});
 7035:     } elsif (ref($store) eq 'HASH') {
 7036:         while (my($key,$value) = each(%{$store})) {
 7037:             $items.= &escape($key).'='.&escape($value).'&';
 7038:         }
 7039:     }
 7040:     $items=~s/\&$//;
 7041:     if ($critical) {
 7042: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 7043:     } else {
 7044: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 7045:     }
 7046: }
 7047: 
 7048: # --------------------------------------------------------------- put interface
 7049: 
 7050: sub put {
 7051:    my ($namespace,$storehash,$udomain,$uname)=@_;
 7052:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7053:    if (!$uname) { $uname=$env{'user.name'}; }
 7054:    my $uhome=&homeserver($uname,$udomain);
 7055:    my $items='';
 7056:    foreach my $item (keys(%$storehash)) {
 7057:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 7058:    }
 7059:    $items=~s/\&$//;
 7060:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 7061: }
 7062: 
 7063: # ------------------------------------------------------------ newput interface
 7064: 
 7065: sub newput {
 7066:    my ($namespace,$storehash,$udomain,$uname)=@_;
 7067:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7068:    if (!$uname) { $uname=$env{'user.name'}; }
 7069:    my $uhome=&homeserver($uname,$udomain);
 7070:    my $items='';
 7071:    foreach my $key (keys(%$storehash)) {
 7072:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 7073:    }
 7074:    $items=~s/\&$//;
 7075:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 7076: }
 7077: 
 7078: # ---------------------------------------------------------  putstore interface
 7079: 
 7080: sub putstore {
 7081:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
 7082:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7083:    if (!$uname) { $uname=$env{'user.name'}; }
 7084:    my $uhome=&homeserver($uname,$udomain);
 7085:    my $items='';
 7086:    foreach my $key (keys(%$storehash)) {
 7087:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 7088:    }
 7089:    $items=~s/\&$//;
 7090:    my $esc_symb=&escape($symb);
 7091:    my $esc_v=&escape($version);
 7092:    my $reply =
 7093:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 7094: 	      $uhome);
 7095:    if (($tolog) && ($reply eq 'ok')) {
 7096:        my $namevalue='';
 7097:        foreach my $key (keys(%{$storehash})) {
 7098:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 7099:        }
 7100:        my $ip = &get_requestor_ip();
 7101:        $namevalue .= 'ip='.&escape($ip).
 7102:                      '&host='.&escape($perlvar{'lonHostID'}).
 7103:                      '&version='.$esc_v.
 7104:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
 7105:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
 7106:    }
 7107:    if ($reply eq 'unknown_cmd') {
 7108:        # gfall back to way things use to be done
 7109:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 7110: 			    $uname);
 7111:    }
 7112:    return $reply;
 7113: }
 7114: 
 7115: sub old_putstore {
 7116:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 7117:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 7118:     if (!$uname) { $uname=$env{'user.name'}; }
 7119:     my $uhome=&homeserver($uname,$udomain);
 7120:     my %newstorehash;
 7121:     foreach my $item (keys(%$storehash)) {
 7122: 	my $key = $version.':'.&escape($symb).':'.$item;
 7123: 	$newstorehash{$key} = $storehash->{$item};
 7124:     }
 7125:     my $items='';
 7126:     my %allitems = ();
 7127:     foreach my $item (keys(%newstorehash)) {
 7128: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 7129: 	    my $key = $1.':keys:'.$2;
 7130: 	    $allitems{$key} .= $3.':';
 7131: 	}
 7132: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 7133:     }
 7134:     foreach my $item (keys(%allitems)) {
 7135: 	$allitems{$item} =~ s/\:$//;
 7136: 	$items.= $item.'='.$allitems{$item}.'&';
 7137:     }
 7138:     $items=~s/\&$//;
 7139:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 7140: }
 7141: 
 7142: # ------------------------------------------------------ critical put interface
 7143: 
 7144: sub cput {
 7145:    my ($namespace,$storehash,$udomain,$uname)=@_;
 7146:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7147:    if (!$uname) { $uname=$env{'user.name'}; }
 7148:    my $uhome=&homeserver($uname,$udomain);
 7149:    my $items='';
 7150:    foreach my $item (keys(%$storehash)) {
 7151:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 7152:    }
 7153:    $items=~s/\&$//;
 7154:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 7155: }
 7156: 
 7157: # -------------------------------------------------------------- eget interface
 7158: 
 7159: sub eget {
 7160:    my ($namespace,$storearr,$udomain,$uname)=@_;
 7161:    my $items='';
 7162:    foreach my $item (@$storearr) {
 7163:        $items.=&escape($item).'&';
 7164:    }
 7165:    $items=~s/\&$//;
 7166:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7167:    if (!$uname) { $uname=$env{'user.name'}; }
 7168:    my $uhome=&homeserver($uname,$udomain);
 7169:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 7170:    my @pairs=split(/\&/,$rep);
 7171:    my %returnhash=();
 7172:    my $i=0;
 7173:    foreach my $item (@$storearr) {
 7174:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 7175:       $i++;
 7176:    }
 7177:    return %returnhash;
 7178: }
 7179: 
 7180: # ------------------------------------------------------------ tmpput interface
 7181: sub tmpput {
 7182:     my ($storehash,$server,$context)=@_;
 7183:     my $items='';
 7184:     foreach my $item (keys(%$storehash)) {
 7185: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 7186:     }
 7187:     $items=~s/\&$//;
 7188:     if (defined($context)) {
 7189:         $items .= ':'.&escape($context);
 7190:     }
 7191:     return &reply("tmpput:$items",$server);
 7192: }
 7193: 
 7194: # ------------------------------------------------------------ tmpget interface
 7195: sub tmpget {
 7196:     my ($token,$server)=@_;
 7197:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 7198:     my $rep=&reply("tmpget:$token",$server);
 7199:     my %returnhash;
 7200:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
 7201:         return %returnhash;
 7202:     }
 7203:     foreach my $item (split(/\&/,$rep)) {
 7204: 	my ($key,$value)=split(/=/,$item);
 7205: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 7206:     }
 7207:     return %returnhash;
 7208: }
 7209: 
 7210: # ------------------------------------------------------------ tmpdel interface
 7211: sub tmpdel {
 7212:     my ($token,$server)=@_;
 7213:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 7214:     return &reply("tmpdel:$token",$server);
 7215: }
 7216: 
 7217: # ------------------------------------------------------------ get_timebased_id
 7218: 
 7219: sub get_timebased_id {
 7220:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
 7221:         $maxtries) = @_;
 7222:     my ($newid,$error,$dellock);
 7223:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
 7224:         return ('','ok','invalid call to get suffix');
 7225:     }
 7226: 
 7227: # set defaults for any optional args for which values were not supplied
 7228:     if ($who eq '') {
 7229:         $who = $env{'user.name'}.':'.$env{'user.domain'};
 7230:     }
 7231:     if (!$locktries) {
 7232:         $locktries = 3;
 7233:     }
 7234:     if (!$maxtries) {
 7235:         $maxtries = 10;
 7236:     }
 7237: 
 7238:     if (($cdom eq '') || ($cnum eq '')) {
 7239:         if ($env{'request.course.id'}) {
 7240:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7241:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7242:         }
 7243:         if (($cdom eq '') || ($cnum eq '')) {
 7244:             return ('','ok','call to get suffix not in course context');
 7245:         }
 7246:     }
 7247: 
 7248: # construct locking item
 7249:     my $lockhash = {
 7250:                       $prefix."\0".'locked_'.$keyid => $who,
 7251:                    };
 7252:     my $tries = 0;
 7253: 
 7254: # attempt to get lock on nohist_$namespace file
 7255:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 7256:     while (($gotlock ne 'ok') && $tries <$locktries) {
 7257:         $tries ++;
 7258:         sleep 1;
 7259:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 7260:     }
 7261: 
 7262: # attempt to get unique identifier, based on current timestamp
 7263:     if ($gotlock eq 'ok') {
 7264:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
 7265:         my $id = time;
 7266:         $newid = $id;
 7267:         if ($idtype eq 'addcode') {
 7268:             $newid .= &sixnum_code();
 7269:         }
 7270:         my $idtries = 0;
 7271:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
 7272:             if ($idtype eq 'concat') {
 7273:                 $newid = $id.$idtries;
 7274:             } elsif ($idtype eq 'addcode') {
 7275:                 $newid = $newid.&sixnum_code();
 7276:             } else {
 7277:                 $newid ++;
 7278:             }
 7279:             $idtries ++;
 7280:         }
 7281:         if (!exists($inuse{$prefix."\0".$newid})) {
 7282:             my %new_item =  (
 7283:                               $prefix."\0".$newid => $who,
 7284:                             );
 7285:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
 7286:                                                  $cdom,$cnum);
 7287:             if ($putresult ne 'ok') {
 7288:                 undef($newid);
 7289:                 $error = 'error saving new item: '.$putresult;
 7290:             }
 7291:         } else {
 7292:              undef($newid);
 7293:              $error = ('error: no unique suffix available for the new item ');
 7294:         }
 7295: #  remove lock
 7296:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
 7297:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
 7298:     } else {
 7299:         $error = "error: could not obtain lockfile\n";
 7300:         $dellock = 'ok';
 7301:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
 7302:             $dellock = 'nolock';
 7303:         }
 7304:     }
 7305:     return ($newid,$dellock,$error);
 7306: }
 7307: 
 7308: sub sixnum_code {
 7309:     my $code;
 7310:     for (0..6) {
 7311:         $code .= int( rand(9) );
 7312:     }
 7313:     return $code;
 7314: }
 7315: 
 7316: # -------------------------------------------------- portfolio access checking
 7317: 
 7318: sub portfolio_access {
 7319:     my ($requrl,$clientip) = @_;
 7320:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 7321:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
 7322:     if ($result) {
 7323:         my %setters;
 7324:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 7325:             my ($startblock,$endblock) =
 7326:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 7327:             if ($startblock && $endblock) {
 7328:                 return 'B';
 7329:             }
 7330:         } else {
 7331:             my ($startblock,$endblock) =
 7332:                 &Apache::loncommon::blockcheck(\%setters,'port');
 7333:             if ($startblock && $endblock) {
 7334:                 return 'B';
 7335:             }
 7336:         }
 7337:     }
 7338:     if ($result eq 'ok') {
 7339:        return 'F';
 7340:     } elsif ($result =~ /^[^:]+:guest_/) {
 7341:        return 'A';
 7342:     }
 7343:     return '';
 7344: }
 7345: 
 7346: sub get_portfolio_access {
 7347:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
 7348: 
 7349:     if (!ref($access_hash)) {
 7350: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 7351: 	my %access_controls = &get_access_controls($current_perms,$group,
 7352: 						   $file_name);
 7353: 	$access_hash = $access_controls{$file_name};
 7354:     }
 7355: 
 7356:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
 7357:     my $now = time;
 7358:     if (ref($access_hash) eq 'HASH') {
 7359:         foreach my $key (keys(%{$access_hash})) {
 7360:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 7361:             if ($start > $now) {
 7362:                 next;
 7363:             }
 7364:             if ($end && $end<$now) {
 7365:                 next;
 7366:             }
 7367:             if ($scope eq 'public') {
 7368:                 $public = $key;
 7369:                 last;
 7370:             } elsif ($scope eq 'guest') {
 7371:                 $guest = $key;
 7372:             } elsif ($scope eq 'domains') {
 7373:                 push(@domains,$key);
 7374:             } elsif ($scope eq 'users') {
 7375:                 push(@users,$key);
 7376:             } elsif ($scope eq 'course') {
 7377:                 push(@courses,$key);
 7378:             } elsif ($scope eq 'group') {
 7379:                 push(@groups,$key);
 7380:             } elsif ($scope eq 'ip') {
 7381:                 push(@ips,$key);
 7382:             }
 7383:         }
 7384:         if ($public) {
 7385:             return 'ok';
 7386:         } elsif (@ips > 0) {
 7387:             my $allowed;
 7388:             foreach my $ipkey (@ips) {
 7389:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
 7390:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
 7391:                         $allowed = 1;
 7392:                         last;
 7393:                     }
 7394:                 }
 7395:             }
 7396:             if ($allowed) {
 7397:                 return 'ok';
 7398:             }
 7399:         }
 7400:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 7401:             if ($guest) {
 7402:                 return $guest;
 7403:             }
 7404:         } else {
 7405:             if (@domains > 0) {
 7406:                 foreach my $domkey (@domains) {
 7407:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 7408:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 7409:                             return 'ok';
 7410:                         }
 7411:                     }
 7412:                 }
 7413:             }
 7414:             if (@users > 0) {
 7415:                 foreach my $userkey (@users) {
 7416:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 7417:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 7418:                             if (ref($item) eq 'HASH') {
 7419:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 7420:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 7421:                                     return 'ok';
 7422:                                 }
 7423:                             }
 7424:                         }
 7425:                     } 
 7426:                 }
 7427:             }
 7428:             my %roleshash;
 7429:             my @courses_and_groups = @courses;
 7430:             push(@courses_and_groups,@groups); 
 7431:             if (@courses_and_groups > 0) {
 7432:                 my (%allgroups,%allroles); 
 7433:                 my ($start,$end,$role,$sec,$group);
 7434:                 foreach my $envkey (%env) {
 7435:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 7436:                         my $cid = $2.'_'.$3; 
 7437:                         if ($1 eq 'gr') {
 7438:                             $group = $4;
 7439:                             $allgroups{$cid}{$group} = $env{$envkey};
 7440:                         } else {
 7441:                             if ($4 eq '') {
 7442:                                 $sec = 'none';
 7443:                             } else {
 7444:                                 $sec = $4;
 7445:                             }
 7446:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 7447:                         }
 7448:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 7449:                         my $cid = $2.'_'.$3;
 7450:                         if ($4 eq '') {
 7451:                             $sec = 'none';
 7452:                         } else {
 7453:                             $sec = $4;
 7454:                         }
 7455:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 7456:                     }
 7457:                 }
 7458:                 if (keys(%allroles) == 0) {
 7459:                     return;
 7460:                 }
 7461:                 foreach my $key (@courses_and_groups) {
 7462:                     my %content = %{$$access_hash{$key}};
 7463:                     my $cnum = $content{'number'};
 7464:                     my $cdom = $content{'domain'};
 7465:                     my $cid = $cdom.'_'.$cnum;
 7466:                     if (!exists($allroles{$cid})) {
 7467:                         next;
 7468:                     }    
 7469:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 7470:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 7471:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 7472:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 7473:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 7474:                         foreach my $role (keys(%{$allroles{$cid}})) {
 7475:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 7476:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 7477:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 7478:                                         if (grep/^all$/,@sections) {
 7479:                                             return 'ok';
 7480:                                         } else {
 7481:                                             if (grep/^$sec$/,@sections) {
 7482:                                                 return 'ok';
 7483:                                             }
 7484:                                         }
 7485:                                     }
 7486:                                 }
 7487:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 7488:                                     if (grep/^none$/,@groups) {
 7489:                                         return 'ok';
 7490:                                     }
 7491:                                 } else {
 7492:                                     if (grep/^all$/,@groups) {
 7493:                                         return 'ok';
 7494:                                     } 
 7495:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 7496:                                         if (grep/^$group$/,@groups) {
 7497:                                             return 'ok';
 7498:                                         }
 7499:                                     }
 7500:                                 } 
 7501:                             }
 7502:                         }
 7503:                     }
 7504:                 }
 7505:             }
 7506:             if ($guest) {
 7507:                 return $guest;
 7508:             }
 7509:         }
 7510:     }
 7511:     return;
 7512: }
 7513: 
 7514: sub course_group_datechecker {
 7515:     my ($dates,$now,$status) = @_;
 7516:     my ($start,$end) = split(/\./,$dates);
 7517:     if (!$start && !$end) {
 7518:         return 'ok';
 7519:     }
 7520:     if (grep/^active$/,@{$status}) {
 7521:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 7522:             return 'ok';
 7523:         }
 7524:     }
 7525:     if (grep/^previous$/,@{$status}) {
 7526:         if ($end > $now ) {
 7527:             return 'ok';
 7528:         }
 7529:     }
 7530:     if (grep/^future$/,@{$status}) {
 7531:         if ($start > $now) {
 7532:             return 'ok';
 7533:         }
 7534:     }
 7535:     return; 
 7536: }
 7537: 
 7538: sub parse_portfolio_url {
 7539:     my ($url) = @_;
 7540: 
 7541:     my ($type,$udom,$unum,$group,$file_name);
 7542:     
 7543:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 7544: 	$type = 1;
 7545:         $udom = $1;
 7546:         $unum = $2;
 7547:         $file_name = $3;
 7548:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 7549: 	$type = 2;
 7550:         $udom = $1;
 7551:         $unum = $2;
 7552:         $group = $3;
 7553:         $file_name = $3.'/'.$4;
 7554:     }
 7555:     if (wantarray) {
 7556: 	return ($type,$udom,$unum,$file_name,$group);
 7557:     }
 7558:     return $type;
 7559: }
 7560: 
 7561: sub is_portfolio_url {
 7562:     my ($url) = @_;
 7563:     return scalar(&parse_portfolio_url($url));
 7564: }
 7565: 
 7566: sub is_portfolio_file {
 7567:     my ($file) = @_;
 7568:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 7569:         return 1;
 7570:     }
 7571:     return;
 7572: }
 7573: 
 7574: sub usertools_access {
 7575:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
 7576:     my ($access,%tools);
 7577:     if ($context eq '') {
 7578:         $context = 'tools';
 7579:     }
 7580:     if ($context eq 'requestcourses') {
 7581:         %tools = (
 7582:                       official   => 1,
 7583:                       unofficial => 1,
 7584:                       community  => 1,
 7585:                       textbook   => 1,
 7586:                  );
 7587:     } elsif ($context eq 'requestauthor') {
 7588:         %tools = (
 7589:                       requestauthor => 1,
 7590:                  );
 7591:     } else {
 7592:         %tools = (
 7593:                       aboutme   => 1,
 7594:                       blog      => 1,
 7595:                       webdav    => 1,
 7596:                       portfolio => 1,
 7597:                  );
 7598:     }
 7599:     return if (!defined($tools{$tool}));
 7600: 
 7601:     if (($udom eq '') || ($uname eq '')) {
 7602:         $udom = $env{'user.domain'};
 7603:         $uname = $env{'user.name'};
 7604:     }
 7605: 
 7606:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 7607:         if ($action ne 'reload') {
 7608:             if ($context eq 'requestcourses') {
 7609:                 return $env{'environment.canrequest.'.$tool};
 7610:             } elsif ($context eq 'requestauthor') {
 7611:                 return $env{'environment.canrequest.author'};
 7612:             } else {
 7613:                 return $env{'environment.availabletools.'.$tool};
 7614:             }
 7615:         }
 7616:     }
 7617: 
 7618:     my ($toolstatus,$inststatus,$envkey);
 7619:     if ($context eq 'requestauthor') {
 7620:         $envkey = $context;
 7621:     } else {
 7622:         $envkey = $context.'.'.$tool;
 7623:     }
 7624: 
 7625:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 7626:          ($action ne 'reload')) {
 7627:         $toolstatus = $env{'environment.'.$envkey};
 7628:         $inststatus = $env{'environment.inststatus'};
 7629:     } else {
 7630:         if (ref($userenvref) eq 'HASH') {
 7631:             $toolstatus = $userenvref->{$envkey};
 7632:             $inststatus = $userenvref->{'inststatus'};
 7633:         } else {
 7634:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
 7635:             $toolstatus = $userenv{$envkey};
 7636:             $inststatus = $userenv{'inststatus'};
 7637:         }
 7638:     }
 7639: 
 7640:     if ($toolstatus ne '') {
 7641:         if ($toolstatus) {
 7642:             $access = 1;
 7643:         } else {
 7644:             $access = 0;
 7645:         }
 7646:         return $access;
 7647:     }
 7648: 
 7649:     my ($is_adv,%domdef);
 7650:     if (ref($is_advref) eq 'HASH') {
 7651:         $is_adv = $is_advref->{'is_adv'};
 7652:     } else {
 7653:         $is_adv = &is_advanced_user($udom,$uname);
 7654:     }
 7655:     if (ref($domdefref) eq 'HASH') {
 7656:         %domdef = %{$domdefref};
 7657:     } else {
 7658:         %domdef = &get_domain_defaults($udom);
 7659:     }
 7660:     if (ref($domdef{$tool}) eq 'HASH') {
 7661:         if ($is_adv) {
 7662:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 7663:                 if ($domdef{$tool}{'_LC_adv'}) { 
 7664:                     $access = 1;
 7665:                 } else {
 7666:                     $access = 0;
 7667:                 }
 7668:                 return $access;
 7669:             }
 7670:         }
 7671:         if ($inststatus ne '') {
 7672:             my ($hasaccess,$hasnoaccess);
 7673:             foreach my $affiliation (split(/:/,$inststatus)) {
 7674:                 if ($domdef{$tool}{$affiliation} ne '') { 
 7675:                     if ($domdef{$tool}{$affiliation}) {
 7676:                         $hasaccess = 1;
 7677:                     } else {
 7678:                         $hasnoaccess = 1;
 7679:                     }
 7680:                 }
 7681:             }
 7682:             if ($hasaccess || $hasnoaccess) {
 7683:                 if ($hasaccess) {
 7684:                     $access = 1;
 7685:                 } elsif ($hasnoaccess) {
 7686:                     $access = 0; 
 7687:                 }
 7688:                 return $access;
 7689:             }
 7690:         } else {
 7691:             if ($domdef{$tool}{'default'} ne '') {
 7692:                 if ($domdef{$tool}{'default'}) {
 7693:                     $access = 1;
 7694:                 } elsif ($domdef{$tool}{'default'} == 0) {
 7695:                     $access = 0;
 7696:                 }
 7697:                 return $access;
 7698:             }
 7699:         }
 7700:     } else {
 7701:         if (($context eq 'tools') && ($tool ne 'webdav')) {
 7702:             $access = 1;
 7703:         } else {
 7704:             $access = 0;
 7705:         }
 7706:         return $access;
 7707:     }
 7708: }
 7709: 
 7710: sub is_course_owner {
 7711:     my ($cdom,$cnum,$udom,$uname) = @_;
 7712:     if (($udom eq '') || ($uname eq '')) {
 7713:         $udom = $env{'user.domain'};
 7714:         $uname = $env{'user.name'};
 7715:     }
 7716:     unless (($udom eq '') || ($uname eq '')) {
 7717:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
 7718:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
 7719:                 return 1;
 7720:             } else {
 7721:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
 7722:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
 7723:                     return 1;
 7724:                 }
 7725:             }
 7726:         }
 7727:     }
 7728:     return;
 7729: }
 7730: 
 7731: sub is_advanced_user {
 7732:     my ($udom,$uname) = @_;
 7733:     if ($udom ne '' && $uname ne '') {
 7734:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 7735:             if (wantarray) {
 7736:                 return ($env{'user.adv'},$env{'user.author'});
 7737:             } else {
 7738:                 return $env{'user.adv'};
 7739:             }
 7740:         }
 7741:     }
 7742:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 7743:     my %allroles;
 7744:     my ($is_adv,$is_author);
 7745:     foreach my $role (keys(%roleshash)) {
 7746:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 7747:         my $area = '/'.$tdomain.'/'.$trest;
 7748:         if ($sec ne '') {
 7749:             $area .= '/'.$sec;
 7750:         }
 7751:         if (($area ne '') && ($trole ne '')) {
 7752:             my $spec=$trole.'.'.$area;
 7753:             if ($trole =~ /^cr\//) {
 7754:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 7755:             } elsif ($trole ne 'gr') {
 7756:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 7757:             }
 7758:             if ($trole eq 'au') {
 7759:                 $is_author = 1;
 7760:             }
 7761:         }
 7762:     }
 7763:     foreach my $role (keys(%allroles)) {
 7764:         last if ($is_adv);
 7765:         foreach my $item (split(/:/,$allroles{$role})) {
 7766:             if ($item ne '') {
 7767:                 my ($privilege,$restrictions)=split(/&/,$item);
 7768:                 if ($privilege eq 'adv') {
 7769:                     $is_adv = 1;
 7770:                     last;
 7771:                 }
 7772:             }
 7773:         }
 7774:     }
 7775:     if (wantarray) {
 7776:         return ($is_adv,$is_author);
 7777:     }
 7778:     return $is_adv;
 7779: }
 7780: 
 7781: sub check_can_request {
 7782:     my ($dom,$can_request,$request_domains) = @_;
 7783:     my $canreq = 0;
 7784:     my ($types,$typename) = &Apache::loncommon::course_types();
 7785:     my @options = ('approval','validate','autolimit');
 7786:     my $optregex = join('|',@options);
 7787:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
 7788:         foreach my $type (@{$types}) {
 7789:             if (&usertools_access($env{'user.name'},
 7790:                                   $env{'user.domain'},
 7791:                                   $type,undef,'requestcourses')) {
 7792:                 $canreq ++;
 7793:                 if (ref($request_domains) eq 'HASH') {
 7794:                     push(@{$request_domains->{$type}},$env{'user.domain'});
 7795:                 }
 7796:                 if ($dom eq $env{'user.domain'}) {
 7797:                     $can_request->{$type} = 1;
 7798:                 }
 7799:             }
 7800:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
 7801:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
 7802:                 if (@curr > 0) {
 7803:                     foreach my $item (@curr) {
 7804:                         if (ref($request_domains) eq 'HASH') {
 7805:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
 7806:                             if ($otherdom ne '') {
 7807:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
 7808:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
 7809:                                         push(@{$request_domains->{$type}},$otherdom);
 7810:                                     }
 7811:                                 } else {
 7812:                                     push(@{$request_domains->{$type}},$otherdom);
 7813:                                 }
 7814:                             }
 7815:                         }
 7816:                     }
 7817:                     unless($dom eq $env{'user.domain'}) {
 7818:                         $canreq ++;
 7819:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
 7820:                             $can_request->{$type} = 1;
 7821:                         }
 7822:                     }
 7823:                 }
 7824:             }
 7825:         }
 7826:     }
 7827:     return $canreq;
 7828: }
 7829: 
 7830: # ---------------------------------------------- Custom access rule evaluation
 7831: 
 7832: sub customaccess {
 7833:     my ($priv,$uri)=@_;
 7834:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 7835:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 7836:     $udom = &LONCAPA::clean_domain($udom);
 7837:     $ucrs = &LONCAPA::clean_username($ucrs);
 7838:     my $access=0;
 7839:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 7840: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 7841: 	if ($type eq 'user') {
 7842: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 7843: 		my ($tdom,$tuname)=split(m{/},$scope);
 7844: 		if ($tdom) {
 7845: 		    if ($tdom ne $env{'user.domain'}) { next; }
 7846: 		}
 7847: 		if ($tuname) {
 7848: 		    if ($tuname ne $env{'user.name'}) { next; }
 7849: 		}
 7850: 		$access=($effect eq 'allow');
 7851: 		last;
 7852: 	    }
 7853: 	} else {
 7854: 	    if ($role) {
 7855: 		if ($role ne $urole) { next; }
 7856: 	    }
 7857: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 7858: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 7859: 		if ($tdom) {
 7860: 		    if ($tdom ne $udom) { next; }
 7861: 		}
 7862: 		if ($tcrs) {
 7863: 		    if ($tcrs ne $ucrs) { next; }
 7864: 		}
 7865: 		if ($tsec) {
 7866: 		    if ($tsec ne $usec) { next; }
 7867: 		}
 7868: 		$access=($effect eq 'allow');
 7869: 		last;
 7870: 	    }
 7871: 	    if ($realm eq '' && $role eq '') {
 7872: 		$access=($effect eq 'allow');
 7873: 	    }
 7874: 	}
 7875:     }
 7876:     return $access;
 7877: }
 7878: 
 7879: # ------------------------------------------------- Check for a user privilege
 7880: 
 7881: sub allowed {
 7882:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck,$ignorecache)=@_;
 7883:     my $ver_orguri=$uri;
 7884:     $uri=&deversion($uri);
 7885:     my $orguri=$uri;
 7886:     $uri=&declutter($uri);
 7887: 
 7888:     if ($priv eq 'evb') {
 7889: # Evade communication block restrictions for specified role in a course
 7890:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 7891:             return $1;
 7892:         } else {
 7893:             return;
 7894:         }
 7895:     }
 7896: 
 7897:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 7898: # Free bre access to adm and meta resources
 7899:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|viewclasslist|aboutme|ext\.tool)$})) 
 7900: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 7901: 	&& ($priv eq 'bre')) {
 7902: 	return 'F';
 7903:     }
 7904: 
 7905: # Free bre access to user's own portfolio contents
 7906:     my ($space,$domain,$name,@dir)=split('/',$uri);
 7907:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 7908: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 7909:         my %setters;
 7910:         my ($startblock,$endblock) = 
 7911:             &Apache::loncommon::blockcheck(\%setters,'port');
 7912:         if ($startblock && $endblock) {
 7913:             return 'B';
 7914:         } else {
 7915:             return 'F';
 7916:         }
 7917:     }
 7918: 
 7919: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 7920:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 7921:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 7922:         if (exists($env{'request.course.id'})) {
 7923:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7924:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7925:             if (($domain eq $cdom) && ($name eq $cnum)) {
 7926:                 my $courseprivid=$env{'request.course.id'};
 7927:                 $courseprivid=~s/\_/\//;
 7928:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 7929:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 7930:                     return $1; 
 7931:                 } else {
 7932:                     if ($env{'request.course.sec'}) {
 7933:                         $courseprivid.='/'.$env{'request.course.sec'};
 7934:                     }
 7935:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 7936:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 7937:                         return $2;
 7938:                     }
 7939:                 }
 7940:             }
 7941:         }
 7942:     }
 7943: 
 7944: # Free bre to public access
 7945: 
 7946:     if ($priv eq 'bre') {
 7947:         my $copyright=&metadata($uri,'copyright');
 7948: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 7949:            return 'F'; 
 7950:         }
 7951:         if ($copyright eq 'priv') {
 7952:             $uri=~/([^\/]+)\/([^\/]+)\//;
 7953: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 7954: 		return '';
 7955:             }
 7956:         }
 7957:         if ($copyright eq 'domain') {
 7958:             $uri=~/([^\/]+)\/([^\/]+)\//;
 7959: 	    unless (($env{'user.domain'} eq $1) ||
 7960:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 7961: 		return '';
 7962:             }
 7963:         }
 7964:         if ($env{'request.role'}=~ /li\.\//) {
 7965:             # Library role, so allow browsing of resources in this domain.
 7966:             return 'F';
 7967:         }
 7968:         if ($copyright eq 'custom') {
 7969: 	    unless (&customaccess($priv,$uri)) { return ''; }
 7970:         }
 7971:     }
 7972:     # Domain coordinator is trying to create a course
 7973:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 7974:         # uri is the requested domain in this case.
 7975:         # comparison to 'request.role.domain' shows if the user has selected
 7976:         # a role of dc for the domain in question.
 7977:         return 'F' if ($uri eq $env{'request.role.domain'});
 7978:     }
 7979: 
 7980:     my $thisallowed='';
 7981:     my $statecond=0;
 7982:     my $courseprivid='';
 7983: 
 7984:     my $ownaccess;
 7985:     # Community Coordinator or Assistant Co-author browsing resource space.
 7986:     if (($priv eq 'bro') && ($env{'user.author'})) {
 7987:         if ($uri eq '') {
 7988:             $ownaccess = 1;
 7989:         } else {
 7990:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
 7991:                 my $udom = $env{'user.domain'};
 7992:                 my $uname = $env{'user.name'};
 7993:                 if ($uri =~ m{^\Q$udom\E/?$}) {
 7994:                     $ownaccess = 1;
 7995:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
 7996:                     unless ($uri =~ m{\.\./}) {
 7997:                         $ownaccess = 1;
 7998:                     }
 7999:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
 8000:                     my $now = time;
 8001:                     if ($uri =~ m{^([^/]+)/?$}) {
 8002:                         my $adom = $1;
 8003:                         foreach my $key (keys(%env)) {
 8004:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
 8005:                                 my ($start,$end) = split('.',$env{$key});
 8006:                                 if (($now >= $start) && (!$end || $end < $now)) {
 8007:                                     $ownaccess = 1;
 8008:                                     last;
 8009:                                 }
 8010:                             }
 8011:                         }
 8012:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
 8013:                         my $adom = $1;
 8014:                         my $aname = $2;
 8015:                         foreach my $role ('ca','aa') { 
 8016:                             if ($env{"user.role.$role./$adom/$aname"}) {
 8017:                                 my ($start,$end) =
 8018:                                     split('.',$env{"user.role.$role./$adom/$aname"});
 8019:                                 if (($now >= $start) && (!$end || $end < $now)) {
 8020:                                     $ownaccess = 1;
 8021:                                     last;
 8022:                                 }
 8023:                             }
 8024:                         }
 8025:                     }
 8026:                 }
 8027:             }
 8028:         }
 8029:     }
 8030: 
 8031: # Course
 8032: 
 8033:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 8034:         unless (($priv eq 'bro') && (!$ownaccess)) {
 8035:             $thisallowed.=$1;
 8036:         }
 8037:     }
 8038: 
 8039: # Domain
 8040: 
 8041:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 8042:        =~/\Q$priv\E\&([^\:]*)/) {
 8043:         unless (($priv eq 'bro') && (!$ownaccess)) {
 8044:             $thisallowed.=$1;
 8045:         }
 8046:     }
 8047: 
 8048: # User who is not author or co-author might still be able to edit
 8049: # resource of an author in the domain (e.g., if Domain Coordinator).
 8050:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
 8051:         (&allowed('mdc',$env{'request.course.id'}))) {
 8052:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
 8053:             $thisallowed.=$1;
 8054:         }
 8055:     }
 8056: 
 8057: # Course: uri itself is a course
 8058:     my $courseuri=$uri;
 8059:     $courseuri=~s/\_(\d)/\/$1/;
 8060:     $courseuri=~s/^([^\/])/\/$1/;
 8061: 
 8062:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 8063:        =~/\Q$priv\E\&([^\:]*)/) {
 8064:         if ($priv eq 'mip') {
 8065:             my $rem = $1;
 8066:             if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
 8067:                 ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
 8068:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8069:                 if ($cdom ne '') {
 8070:                     my %passwdconf = &get_passwdconf($cdom);
 8071:                     if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
 8072:                         if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
 8073:                             if (@{$passwdconf{'crsownerchg'}{'by'}}) {
 8074:                                 my @inststatuses = split(':',$env{'environment.inststatus'});
 8075:                                 unless (@inststatuses) {
 8076:                                     @inststatuses = ('default');
 8077:                                 }
 8078:                                 foreach my $status (@inststatuses) {
 8079:                                     if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
 8080:                                         $thisallowed.=$rem;
 8081:                                     }
 8082:                                 }
 8083:                             }
 8084:                         }
 8085:                     }
 8086:                 }
 8087:             }
 8088:         } else {
 8089:             unless (($priv eq 'bro') && (!$ownaccess)) {
 8090:                 $thisallowed.=$1;
 8091:             }
 8092:         }
 8093:     }
 8094: 
 8095: # URI is an uploaded document for this course, default permissions don't matter
 8096: # not allowing 'edit' access (editupload) to uploaded course docs
 8097:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 8098: 	$thisallowed='';
 8099:         my ($match)=&is_on_map($uri);
 8100:         if ($match) {
 8101:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 8102:                   =~/\Q$priv\E\&([^\:]*)/) {
 8103:                 my $value = $1;
 8104:                 if ($noblockcheck) {
 8105:                     $thisallowed.=$value;
 8106:                 } else {
 8107:                     my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
 8108:                     if (@blockers > 0) {
 8109:                         $thisallowed = 'B';
 8110:                     } else {
 8111:                         $thisallowed.=$value;
 8112:                     }
 8113:                 }
 8114:             }
 8115:         } else {
 8116:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 8117:             if ($refuri) {
 8118:                 if ($refuri =~ m|^/adm/|) {
 8119:                     $thisallowed='F';
 8120:                 } else {
 8121:                     $refuri=&declutter($refuri);
 8122:                     my ($match) = &is_on_map($refuri);
 8123:                     if ($match) {
 8124:                         if ($noblockcheck) {
 8125:                             $thisallowed='F';
 8126:                         } else {
 8127:                             my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
 8128:                             if (@blockers > 0) {
 8129:                                 $thisallowed = 'B';
 8130:                             } else {
 8131:                                 $thisallowed='F';
 8132:                             }
 8133:                         }
 8134:                     }
 8135:                 }
 8136:             }
 8137:         }
 8138:     }
 8139: 
 8140:     if ($priv eq 'bre'
 8141: 	&& $thisallowed ne 'F' 
 8142: 	&& $thisallowed ne '2'
 8143: 	&& &is_portfolio_url($uri)) {
 8144: 	$thisallowed = &portfolio_access($uri,$clientip);
 8145:     }
 8146: 
 8147: # Full access at system, domain or course-wide level? Exit.
 8148:     if ($thisallowed=~/F/) {
 8149: 	return 'F';
 8150:     }
 8151: 
 8152: # If this is generating or modifying users, exit with special codes
 8153: 
 8154:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 8155: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 8156: 	    my ($audom,$auname)=split('/',$uri);
 8157: # no author name given, so this just checks on the general right to make a co-author in this domain
 8158: 	    unless ($auname) { return $thisallowed; }
 8159: # an author name is given, so we are about to actually make a co-author for a certain account
 8160: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 8161: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 8162: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 8163: 	}
 8164: 	return $thisallowed;
 8165:     }
 8166: #
 8167: # Gathered so far: system, domain and course wide privileges
 8168: #
 8169: # Course: See if uri or referer is an individual resource that is part of 
 8170: # the course
 8171: 
 8172:     if ($env{'request.course.id'}) {
 8173: 
 8174: # If this is modifying password (internal auth) domains must match for user and user's role.
 8175: 
 8176:         if ($priv eq 'mip') {
 8177:             if ($env{'user.domain'} eq $env{'request.role.domain'}) {
 8178:                 return $thisallowed;
 8179:             } else {
 8180:                 return '';
 8181:             }
 8182:         }
 8183: 
 8184:        $courseprivid=$env{'request.course.id'};
 8185:        if ($env{'request.course.sec'}) {
 8186:           $courseprivid.='/'.$env{'request.course.sec'};
 8187:        }
 8188:        $courseprivid=~s/\_/\//;
 8189:        my $checkreferer=1;
 8190:        my ($match,$cond)=&is_on_map($uri);
 8191:        if ($match) {
 8192:            $statecond=$cond;
 8193:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 8194:                =~/\Q$priv\E\&([^\:]*)/) {
 8195:                my $value = $1;
 8196:                if ($priv eq 'bre') {
 8197:                    if ($noblockcheck) {
 8198:                        $thisallowed.=$value;
 8199:                    } else {
 8200:                        my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
 8201:                        if (@blockers > 0) {
 8202:                            $thisallowed = 'B';
 8203:                        } else {
 8204:                            $thisallowed.=$value;
 8205:                        }
 8206:                    }
 8207:                } else {
 8208:                    $thisallowed.=$value;
 8209:                }
 8210:                $checkreferer=0;
 8211:            }
 8212:        }
 8213: 
 8214:        if ($checkreferer) {
 8215: 	  my $refuri=$env{'httpref.'.$orguri};
 8216:             unless ($refuri) {
 8217:                 foreach my $key (keys(%env)) {
 8218: 		    if ($key=~/^httpref\..*\*/) {
 8219: 			my $pattern=$key;
 8220:                         $pattern=~s/^httpref\.\/res\///;
 8221:                         $pattern=~s/\*/\[\^\/\]\+/g;
 8222:                         $pattern=~s/\//\\\//g;
 8223:                         if ($orguri=~/$pattern/) {
 8224: 			    $refuri=$env{$key};
 8225:                         }
 8226:                     }
 8227:                 }
 8228:             }
 8229: 
 8230:          if ($refuri) { 
 8231: 	  $refuri=&declutter($refuri);
 8232:           my ($match,$cond)=&is_on_map($refuri);
 8233:             if ($match) {
 8234:               my $refstatecond=$cond;
 8235:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 8236:                   =~/\Q$priv\E\&([^\:]*)/) {
 8237:                   my $value = $1;
 8238:                   if ($priv eq 'bre') {
 8239:                       if ($noblockcheck) {
 8240:                           $thisallowed.=$value;
 8241:                       } else {
 8242:                           my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
 8243:                           if (@blockers > 0) {
 8244:                               $thisallowed = 'B';
 8245:                           } else {
 8246:                               $thisallowed.=$value;
 8247:                           }
 8248:                       }
 8249:                   } else {
 8250:                       $thisallowed.=$value;
 8251:                   }
 8252:                   $uri=$refuri;
 8253:                   $statecond=$refstatecond;
 8254:               }
 8255:           }
 8256:         }
 8257:        }
 8258:    }
 8259: 
 8260: #
 8261: # Gathered now: all privileges that could apply, and condition number
 8262: # 
 8263: #
 8264: # Full or no access?
 8265: #
 8266: 
 8267:     if ($thisallowed=~/F/) {
 8268: 	return 'F';
 8269:     }
 8270: 
 8271:     unless ($thisallowed) {
 8272:         return '';
 8273:     }
 8274: 
 8275: # Restrictions exist, deal with them
 8276: #
 8277: #   C:according to course preferences
 8278: #   R:according to resource settings
 8279: #   L:unless locked
 8280: #   X:according to user session state
 8281: #
 8282: 
 8283: # Possibly locked functionality, check all courses
 8284: # Locks might take effect only after 10 minutes cache expiration for other
 8285: # courses, and 2 minutes for current course
 8286: 
 8287:     my $envkey;
 8288:     if ($thisallowed=~/L/) {
 8289:         foreach $envkey (keys(%env)) {
 8290:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 8291:                my $courseid=$2;
 8292:                my $roleid=$1.'.'.$2;
 8293:                $courseid=~s/^\///;
 8294:                my $expiretime=600;
 8295:                if ($env{'request.role'} eq $roleid) {
 8296: 		  $expiretime=120;
 8297:                }
 8298: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 8299:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 8300:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 8301: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 8302:                }
 8303:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 8304:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 8305: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 8306:                        &log($env{'user.domain'},$env{'user.name'},
 8307:                             $env{'user.home'},
 8308:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 8309:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 8310:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 8311: 		       return '';
 8312:                    }
 8313:                }
 8314:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 8315:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 8316: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 8317:                        &log($env{'user.domain'},$env{'user.name'},
 8318:                             $env{'user.home'},
 8319:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 8320:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 8321:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 8322: 		       return '';
 8323:                    }
 8324:                }
 8325: 	   }
 8326:        }
 8327:     }
 8328: 
 8329: #
 8330: # Rest of the restrictions depend on selected course
 8331: #
 8332: 
 8333:     unless ($env{'request.course.id'}) {
 8334: 	if ($thisallowed eq 'A') {
 8335: 	    return 'A';
 8336:         } elsif ($thisallowed eq 'B') {
 8337:             return 'B';
 8338: 	} else {
 8339: 	    return '1';
 8340: 	}
 8341:     }
 8342: 
 8343: #
 8344: # Now user is definitely in a course
 8345: #
 8346: 
 8347: 
 8348: # Course preferences
 8349: 
 8350:    if ($thisallowed=~/C/) {
 8351:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 8352:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 8353:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 8354: 	   =~/\Q$rolecode\E/) {
 8355: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 8356: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 8357: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 8358: 			$env{'request.course.id'});
 8359: 	   }
 8360:            return '';
 8361:        }
 8362: 
 8363:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 8364: 	   =~/\Q$unamedom\E/) {
 8365: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 8366: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 8367: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 8368: 			$env{'request.course.id'});
 8369: 	   }
 8370:            return '';
 8371:        }
 8372:    }
 8373: 
 8374: # Resource preferences
 8375: 
 8376:    if ($thisallowed=~/R/) {
 8377:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 8378:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 8379: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 8380: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 8381: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 8382: 	   }
 8383: 	   return '';
 8384:        }
 8385:    }
 8386: 
 8387: # Restricted by state or randomout?
 8388: 
 8389:    if ($thisallowed=~/X/) {
 8390:       if ($env{'acc.randomout'}) {
 8391: 	 if (!$symb) { $symb=&symbread($uri,1); }
 8392:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 8393:             return ''; 
 8394:          }
 8395:       }
 8396:       if (&condval($statecond)) {
 8397: 	 return '2';
 8398:       } else {
 8399:          return '';
 8400:       }
 8401:    }
 8402: 
 8403:     if ($thisallowed eq 'A') {
 8404: 	return 'A';
 8405:     } elsif ($thisallowed eq 'B') {
 8406:         return 'B';
 8407:     }
 8408:    return 'F';
 8409: }
 8410: 
 8411: # ------------------------------------------- Check construction space access
 8412: 
 8413: sub constructaccess {
 8414:     my ($url,$setpriv)=@_;
 8415: 
 8416: # We do not allow editing of previous versions of files
 8417:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
 8418: 
 8419: # Get username and domain from URL
 8420:     my ($ownername,$ownerdomain,$ownerhome);
 8421: 
 8422:     ($ownerdomain,$ownername) =
 8423:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)(?:/|$)});
 8424: 
 8425: # The URL does not really point to any authorspace, forget it
 8426:     unless (($ownername) && ($ownerdomain)) { return ''; }
 8427: 
 8428: # Now we need to see if the user has access to the authorspace of
 8429: # $ownername at $ownerdomain
 8430: 
 8431:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
 8432: # Real author for this?
 8433:        $ownerhome = $env{'user.home'};
 8434:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
 8435:           return ($ownername,$ownerdomain,$ownerhome);
 8436:        }
 8437:     } else {
 8438: # Co-author for this?
 8439:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
 8440:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
 8441:             $ownerhome = &homeserver($ownername,$ownerdomain);
 8442:             return ($ownername,$ownerdomain,$ownerhome);
 8443:         }
 8444:     }
 8445: 
 8446: # We don't have any access right now. If we are not possibly going to do anything about this,
 8447: # we might as well leave
 8448:    unless ($setpriv) { return ''; }
 8449: 
 8450: # Backdoor access?
 8451:     my $allowed=&allowed('eco',$ownerdomain);
 8452: # Nope
 8453:     unless ($allowed) { return ''; }
 8454: # Looks like we may have access, but could be locked by the owner of the construction space
 8455:     if ($allowed eq 'U') {
 8456:         my %blocked=&get('environment',['domcoord.author'],
 8457:                          $ownerdomain,$ownername);
 8458: # Is blocked by owner
 8459:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
 8460:     }
 8461:     if (($allowed eq 'F') || ($allowed eq 'U')) {
 8462: # Grant temporary access
 8463:         my $then=$env{'user.login.time'};
 8464:         my $update=$env{'user.update.time'};
 8465:         if (!$update) { $update = $then; }
 8466:         my $refresh=$env{'user.refresh.time'};
 8467:         if (!$refresh) { $refresh = $update; }
 8468:         my $now = time;
 8469:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
 8470:                            $now,'ca','constructaccess');
 8471:         $ownerhome = &homeserver($ownername,$ownerdomain);
 8472:         return($ownername,$ownerdomain,$ownerhome);
 8473:     }
 8474: # No business here
 8475:     return '';
 8476: }
 8477: 
 8478: # ----------------------------------------------------------- Content Blocking
 8479: 
 8480: {
 8481: # Caches for faster Course Contents display where content blocking
 8482: # is in operation (i.e., interval param set) for timed quiz.
 8483: #
 8484: # User for whom data are being temporarily cached.
 8485: my $cacheduser='';
 8486: # Course for which data are being temporarily cached.
 8487: my $cachedcid='';
 8488: # Cached blockers for this user (a hash of blocking items).
 8489: my %cachedblockers=();
 8490: # When the data were last cached.
 8491: my $cachedlast='';
 8492: 
 8493: sub load_all_blockers {
 8494:     my ($uname,$udom)=@_;
 8495:     if (($uname ne '') && ($udom ne '')) {
 8496:         if (($cacheduser eq $uname.':'.$udom) &&
 8497:             ($cachedcid eq $env{'request.course.id'}) &&
 8498:             (abs($cachedlast-time)<5)) {
 8499:             return;
 8500:         }
 8501:     }
 8502:     $cachedlast=time;
 8503:     $cacheduser=$uname.':'.$udom;
 8504:     $cachedcid=$env{'request.course.id'};
 8505:     %cachedblockers = &get_commblock_resources();
 8506:     return;
 8507: }
 8508: 
 8509: sub get_comm_blocks {
 8510:     my ($cdom,$cnum) = @_;
 8511:     if ($cdom eq '' || $cnum eq '') {
 8512:         return unless ($env{'request.course.id'});
 8513:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8514:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8515:     }
 8516:     my %commblocks;
 8517:     my $hashid=$cdom.'_'.$cnum;
 8518:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
 8519:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
 8520:         %commblocks = %{$blocksref};
 8521:     } else {
 8522:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
 8523:         my $cachetime = 600;
 8524:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
 8525:     }
 8526:     return %commblocks;
 8527: }
 8528: 
 8529: sub get_commblock_resources {
 8530:     my ($blocks) = @_;
 8531:     my %blockers = ();
 8532:     return %blockers unless ($env{'request.course.id'});
 8533:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 8534:     my %commblocks;
 8535:     if (ref($blocks) eq 'HASH') {
 8536:         %commblocks = %{$blocks};
 8537:     } else {
 8538:         %commblocks = &get_comm_blocks();
 8539:     }
 8540:     return %blockers unless (keys(%commblocks) > 0);
 8541:     my $navmap = Apache::lonnavmaps::navmap->new();
 8542:     return %blockers unless (ref($navmap));
 8543:     my $now = time;
 8544:     foreach my $block (keys(%commblocks)) {
 8545:         if ($block =~ /^(\d+)____(\d+)$/) {
 8546:             my ($start,$end) = ($1,$2);
 8547:             if ($start <= $now && $end >= $now) {
 8548:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 8549:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 8550:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 8551:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 8552:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
 8553:                             }
 8554:                         }
 8555:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 8556:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 8557:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 8558:                             }
 8559:                         }
 8560:                     }
 8561:                 }
 8562:             }
 8563:         } elsif ($block =~ /^firstaccess____(.+)$/) {
 8564:             my $item = $1;
 8565:             my @to_test;
 8566:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 8567:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 8568:                     my @interval;
 8569:                     my $type = 'map';
 8570:                     if ($item eq 'course') {
 8571:                         $type = 'course';
 8572:                         @interval=&EXT("resource.0.interval");
 8573:                     } else {
 8574:                         if ($item =~ /___\d+___/) {
 8575:                             $type = 'resource';
 8576:                             @interval=&EXT("resource.0.interval",$item);
 8577:                             if (ref($navmap)) {
 8578:                                 my $res = $navmap->getBySymb($item);
 8579:                                 push(@to_test,$res);
 8580:                             }
 8581:                         } else {
 8582:                             my $mapsymb = &symbread($item,1);
 8583:                             if ($mapsymb) {
 8584:                                 if (ref($navmap)) {
 8585:                                     my $mapres = $navmap->getBySymb($mapsymb);
 8586:                                     if (ref($mapres)) {
 8587:                                         my $first = $mapres->map_start();
 8588:                                         my $finish = $mapres->map_finish();
 8589:                                         my $it = $navmap->getIterator($first,$finish,undef,0,0);
 8590:                                         if (ref($it)) {
 8591:                                             my $res;
 8592:                                             while ($res = $it->next(undef,1)) {
 8593:                                                 next unless (ref($res));
 8594:                                                 my $symb = $res->symb();
 8595:                                                 next if (($symb eq $mapsymb) || ($symb eq ''));
 8596:                                                 @interval=&EXT("resource.0.interval",$symb);
 8597:                                                 if ($interval[1] eq 'map') {
 8598:                                                     if ($res->answerable()) {
 8599:                                                         push(@to_test,$res);
 8600:                                                         last;
 8601:                                                     }
 8602:                                                 }
 8603:                                             }
 8604:                                         }
 8605:                                     }
 8606:                                 }
 8607:                             }
 8608:                         }
 8609:                     }
 8610:                     if ($interval[0] =~ /^(\d+)/) {
 8611:                         my $timelimit = $1; 
 8612:                         my $first_access;
 8613:                         if ($type eq 'resource') {
 8614:                             $first_access=&get_first_access($interval[1],$item);
 8615:                         } elsif ($type eq 'map') {
 8616:                             $first_access=&get_first_access($interval[1],undef,$item);
 8617:                         } else {
 8618:                             $first_access=&get_first_access($interval[1]);
 8619:                         }
 8620:                         if ($first_access) {
 8621:                             my $timesup = $first_access+$timelimit;
 8622:                             if ($timesup > $now) {
 8623:                                 my $activeblock;
 8624:                                 foreach my $res (@to_test) {
 8625:                                     if ($res->answerable()) {
 8626:                                         $activeblock = 1;
 8627:                                         last;
 8628:                                     }
 8629:                                 }
 8630:                                 if ($activeblock) {
 8631:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 8632:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 8633:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
 8634:                                          }
 8635:                                     }
 8636:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 8637:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 8638:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 8639:                                         }
 8640:                                     }
 8641:                                 }
 8642:                             }
 8643:                         }
 8644:                     }
 8645:                 }
 8646:             }
 8647:         }
 8648:     }
 8649:     return %blockers;
 8650: }
 8651: 
 8652: sub has_comm_blocking {
 8653:     my ($priv,$symb,$uri,$ignoresymbdb,$noenccheck,$blocked,$blocks) = @_;
 8654:     my @blockers;
 8655:     return unless ($env{'request.course.id'});
 8656:     return unless ($priv eq 'bre');
 8657:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 8658:     return if ($env{'request.state'} eq 'construct');
 8659:     my %blockinfo;
 8660:     if (ref($blocks) eq 'HASH') {
 8661:         %blockinfo = &get_commblock_resources($blocks);
 8662:     } else {
 8663:         &load_all_blockers($env{'user.name'},$env{'user.domain'});
 8664:         %blockinfo = %cachedblockers;
 8665:     }
 8666:     return unless (keys(%blockinfo) > 0);
 8667:     my (%possibles,@symbs);
 8668:     if (!$symb) {
 8669:         $symb = &symbread($uri,1,1,1,\%possibles,$ignoresymbdb,$noenccheck);
 8670:     }
 8671:     if ($symb) {
 8672:         @symbs = ($symb);
 8673:     } elsif (keys(%possibles)) {
 8674:         @symbs = keys(%possibles);
 8675:     }
 8676:     my $noblock;
 8677:     foreach my $symb (@symbs) {
 8678:         last if ($noblock);
 8679:         my ($map,$resid,$resurl)=&decode_symb($symb);
 8680:         foreach my $block (keys(%blockinfo)) {
 8681:             if ($block =~ /^firstaccess____(.+)$/) {
 8682:                 my $item = $1;
 8683:                 unless ($blocked) {
 8684:                     if (($item eq $map) || ($item eq $symb)) {
 8685:                         $noblock = 1;
 8686:                         last;
 8687:                     }
 8688:                 }
 8689:             }
 8690:             if (ref($blockinfo{$block}) eq 'HASH') {
 8691:                 if (ref($blockinfo{$block}{'resources'}) eq 'HASH') {
 8692:                     if ($blockinfo{$block}{'resources'}{$symb}) {
 8693:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 8694:                             push(@blockers,$block);
 8695:                         }
 8696:                     }
 8697:                 }
 8698:                 if (ref($blockinfo{$block}{'maps'}) eq 'HASH') {
 8699:                     if ($blockinfo{$block}{'maps'}{$map}) {
 8700:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 8701:                             push(@blockers,$block);
 8702:                         }
 8703:                     }
 8704:                 }
 8705:             }
 8706:         }
 8707:     }
 8708:     unless ($noblock) {
 8709:         return @blockers;
 8710:     }
 8711:     return;
 8712: }
 8713: }
 8714: 
 8715: # -------------------------------- Deversion and split uri into path an filename
 8716: 
 8717: #
 8718: #   Removes the version from a URI and
 8719: #   splits it in to its filename and path to the filename.
 8720: #   Seems like File::Basename could have done this more clearly.
 8721: #   Parameters:
 8722: #      $uri   - input URI
 8723: #   Returns:
 8724: #     Two element list consisting of 
 8725: #     $pathname  - the URI up to and excluding the trailing /
 8726: #     $filename  - The part of the URI following the last /
 8727: #  NOTE:
 8728: #    Another realization of this is simply:
 8729: #    use File::Basename;
 8730: #    ...
 8731: #    $uri = shift;
 8732: #    $filename = basename($uri);
 8733: #    $path     = dirname($uri);
 8734: #    return ($filename, $path);
 8735: #
 8736: #     The implementation below is probably faster however.
 8737: #
 8738: sub split_uri_for_cond {
 8739:     my $uri=&deversion(&declutter(shift));
 8740:     my @uriparts=split(/\//,$uri);
 8741:     my $filename=pop(@uriparts);
 8742:     my $pathname=join('/',@uriparts);
 8743:     return ($pathname,$filename);
 8744: }
 8745: # --------------------------------------------------- Is a resource on the map?
 8746: 
 8747: sub is_on_map {
 8748:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 8749:     #Trying to find the conditional for the file
 8750:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 8751: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 8752:     if ($match) {
 8753: 	return (1,$1);
 8754:     } else {
 8755: 	return (0,0);
 8756:     }
 8757: }
 8758: 
 8759: # --------------------------------------------------------- Get symb from alias
 8760: 
 8761: sub get_symb_from_alias {
 8762:     my $symb=shift;
 8763:     my ($map,$resid,$url)=&decode_symb($symb);
 8764: # Already is a symb
 8765:     if ($url) { return $symb; }
 8766: # Must be an alias
 8767:     my $aliassymb='';
 8768:     my %bighash;
 8769:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 8770:                             &GDBM_READER(),0640)) {
 8771:         my $rid=$bighash{'mapalias_'.$symb};
 8772: 	if ($rid) {
 8773: 	    my ($mapid,$resid)=split(/\./,$rid);
 8774: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 8775: 				    $resid,$bighash{'src_'.$rid});
 8776: 	}
 8777:         untie %bighash;
 8778:     }
 8779:     return $aliassymb;
 8780: }
 8781: 
 8782: # ----------------------------------------------------------------- Define Role
 8783: 
 8784: sub definerole {
 8785:   if (allowed('mcr','/')) {
 8786:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
 8787:     foreach my $role (split(':',$sysrole)) {
 8788: 	my ($crole,$cqual)=split(/\&/,$role);
 8789:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 8790:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 8791: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 8792:                return "refused:s:$crole&$cqual"; 
 8793:             }
 8794:         }
 8795:     }
 8796:     foreach my $role (split(':',$domrole)) {
 8797: 	my ($crole,$cqual)=split(/\&/,$role);
 8798:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 8799:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 8800: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 8801:                return "refused:d:$crole&$cqual"; 
 8802:             }
 8803:         }
 8804:     }
 8805:     foreach my $role (split(':',$courole)) {
 8806: 	my ($crole,$cqual)=split(/\&/,$role);
 8807:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 8808:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 8809: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 8810:                return "refused:c:$crole&$cqual"; 
 8811:             }
 8812:         }
 8813:     }
 8814:     my $uhome;
 8815:     if (($uname ne '') && ($udom ne '')) {
 8816:         $uhome = &homeserver($uname,$udom);
 8817:         return $uhome if ($uhome eq 'no_host');
 8818:     } else {
 8819:         $uname = $env{'user.name'};
 8820:         $udom = $env{'user.domain'};
 8821:         $uhome = $env{'user.home'};
 8822:     }
 8823:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 8824:                 "$udom:$uname:rolesdef_$rolename=".
 8825:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 8826:     return reply($command,$uhome);
 8827:   } else {
 8828:     return 'refused';
 8829:   }
 8830: }
 8831: 
 8832: # ---------------- Make a metadata query against the network of library servers
 8833: 
 8834: sub metadata_query {
 8835:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
 8836:     my %rhash;
 8837:     my %libserv = &all_library();
 8838:     my @server_list = (defined($server_array) ? @$server_array
 8839:                                               : keys(%libserv) );
 8840:     for my $server (@server_list) {
 8841:         my $domains = '';
 8842:         if (ref($domains_hash) eq 'HASH') {
 8843:             $domains = $domains_hash->{$server};    
 8844:         }
 8845: 	unless ($custom or $customshow) {
 8846: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
 8847: 	    $rhash{$server}=$reply;
 8848: 	}
 8849: 	else {
 8850: 	    my $reply=&reply("querysend:".&escape($query).':'.
 8851: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
 8852: 			     $server);
 8853: 	    $rhash{$server}=$reply;
 8854: 	}
 8855:     }
 8856:     return \%rhash;
 8857: }
 8858: 
 8859: # ----------------------------------------- Send log queries and wait for reply
 8860: 
 8861: sub log_query {
 8862:     my ($uname,$udom,$query,%filters)=@_;
 8863:     my $uhome=&homeserver($uname,$udom);
 8864:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 8865:     my $uhost=&hostname($uhome);
 8866:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 8867:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 8868:                        $uhome);
 8869:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 8870:     return get_query_reply($queryid);
 8871: }
 8872: 
 8873: # -------------------------- Update MySQL table for portfolio file
 8874: 
 8875: sub update_portfolio_table {
 8876:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 8877:     if ($group ne '') {
 8878:         $file_name =~s /^\Q$group\E//;
 8879:     }
 8880:     my $homeserver = &homeserver($uname,$udom);
 8881:     my $queryid=
 8882:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 8883:                ':'.&escape($file_name).':'.$action,$homeserver);
 8884:     my $reply = &get_query_reply($queryid);
 8885:     return $reply;
 8886: }
 8887: 
 8888: # -------------------------- Update MySQL allusers table
 8889: 
 8890: sub update_allusers_table {
 8891:     my ($uname,$udom,$names) = @_;
 8892:     my $homeserver = &homeserver($uname,$udom);
 8893:     my $queryid=
 8894:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 8895:                'lastname='.&escape($names->{'lastname'}).'%%'.
 8896:                'firstname='.&escape($names->{'firstname'}).'%%'.
 8897:                'middlename='.&escape($names->{'middlename'}).'%%'.
 8898:                'generation='.&escape($names->{'generation'}).'%%'.
 8899:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 8900:                'id='.&escape($names->{'id'}),$homeserver);
 8901:     return;
 8902: }
 8903: 
 8904: # ------- Request retrieval of institutional classlists for course(s)
 8905: 
 8906: sub fetch_enrollment_query {
 8907:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 8908:     my ($homeserver,$sleep,$loopmax);
 8909:     my $maxtries = 1;
 8910:     if ($context eq 'automated') {
 8911:         $homeserver = $perlvar{'lonHostID'};
 8912:         $sleep = 2;
 8913:         $loopmax = 100;
 8914:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 8915:     } else {
 8916:         $homeserver = &homeserver($cnum,$dom);
 8917:     }
 8918:     my $host=&hostname($homeserver);
 8919:     my $cmd = '';
 8920:     foreach my $affiliate (keys(%{$affiliatesref})) {
 8921:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 8922:     }
 8923:     $cmd =~ s/%%$//;
 8924:     $cmd = &escape($cmd);
 8925:     my $query = 'fetchenrollment';
 8926:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 8927:     unless ($queryid=~/^\Q$host\E\_/) { 
 8928:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 8929:         return 'error: '.$queryid;
 8930:     }
 8931:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
 8932:     my $tries = 1;
 8933:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 8934:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
 8935:         $tries ++;
 8936:     }
 8937:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 8938:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 8939:     } else {
 8940:         my @responses = split(/:/,$reply);
 8941:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
 8942:             foreach my $line (@responses) {
 8943:                 my ($key,$value) = split(/=/,$line,2);
 8944:                 $$replyref{$key} = $value;
 8945:             }
 8946:         } else {
 8947:             my $pathname = LONCAPA::tempdir();
 8948:             foreach my $line (@responses) {
 8949:                 my ($key,$value) = split(/=/,$line);
 8950:                 $$replyref{$key} = $value;
 8951:                 if ($value > 0) {
 8952:                     foreach my $item (@{$$affiliatesref{$key}}) {
 8953:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 8954:                         my $destname = $pathname.'/'.$filename;
 8955:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 8956:                         if ($xml_classlist =~ /^error/) {
 8957:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 8958:                         } else {
 8959:                             if ( open(FILE,">",$destname) ) {
 8960:                                 print FILE &unescape($xml_classlist);
 8961:                                 close(FILE);
 8962:                             } else {
 8963:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 8964:                             }
 8965:                         }
 8966:                     }
 8967:                 }
 8968:             }
 8969:         }
 8970:         return 'ok';
 8971:     }
 8972:     return 'error';
 8973: }
 8974: 
 8975: sub get_query_reply {
 8976:     my ($queryid,$sleep,$loopmax) = @_;
 8977:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
 8978:         $sleep = 0.2;
 8979:     }
 8980:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
 8981:         $loopmax = 100;
 8982:     }
 8983:     my $replyfile=LONCAPA::tempdir().$queryid;
 8984:     my $reply='';
 8985:     for (1..$loopmax) {
 8986: 	sleep($sleep);
 8987:         if (-e $replyfile.'.end') {
 8988: 	    if (open(my $fh,"<",$replyfile)) {
 8989: 		$reply = join('',<$fh>);
 8990: 		close($fh);
 8991: 	   } else { return 'error: reply_file_error'; }
 8992:            return &unescape($reply);
 8993: 	}
 8994:     }
 8995:     return 'timeout:'.$queryid;
 8996: }
 8997: 
 8998: sub courselog_query {
 8999: #
 9000: # possible filters:
 9001: # url: url or symb
 9002: # username
 9003: # domain
 9004: # action: view, submit, grade
 9005: # start: timestamp
 9006: # end: timestamp
 9007: #
 9008:     my (%filters)=@_;
 9009:     unless ($env{'request.course.id'}) { return 'no_course'; }
 9010:     if ($filters{'url'}) {
 9011: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 9012:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 9013:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 9014:     }
 9015:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 9016:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 9017:     return &log_query($cname,$cdom,'courselog',%filters);
 9018: }
 9019: 
 9020: sub userlog_query {
 9021: #
 9022: # possible filters:
 9023: # action: log check role
 9024: # start: timestamp
 9025: # end: timestamp
 9026: #
 9027:     my ($uname,$udom,%filters)=@_;
 9028:     return &log_query($uname,$udom,'userlog',%filters);
 9029: }
 9030: 
 9031: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 9032: 
 9033: sub auto_run {
 9034:     my ($cnum,$cdom) = @_;
 9035:     my $response = 0;
 9036:     my $settings;
 9037:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 9038:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 9039:         $settings = $domconfig{'autoenroll'};
 9040:         if ($settings->{'run'} eq '1') {
 9041:             $response = 1;
 9042:         }
 9043:     } else {
 9044:         my $homeserver;
 9045:         if (&is_course($cdom,$cnum)) {
 9046:             $homeserver = &homeserver($cnum,$cdom);
 9047:         } else {
 9048:             $homeserver = &domain($cdom,'primary');
 9049:         }
 9050:         if ($homeserver ne 'no_host') {
 9051:             $response = &reply('autorun:'.$cdom,$homeserver);
 9052:         }
 9053:     }
 9054:     return $response;
 9055: }
 9056: 
 9057: sub auto_get_sections {
 9058:     my ($cnum,$cdom,$inst_coursecode) = @_;
 9059:     my $homeserver;
 9060:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
 9061:         $homeserver = &homeserver($cnum,$cdom);
 9062:     }
 9063:     if (!defined($homeserver)) { 
 9064:         if ($cdom =~ /^$match_domain$/) {
 9065:             $homeserver = &domain($cdom,'primary');
 9066:         }
 9067:     }
 9068:     my @secs;
 9069:     if (defined($homeserver)) {
 9070:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 9071:         unless ($response eq 'refused') {
 9072:             @secs = split(/:/,$response);
 9073:         }
 9074:     }
 9075:     return @secs;
 9076: }
 9077: 
 9078: sub auto_new_course {
 9079:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
 9080:     my $homeserver = &homeserver($cnum,$cdom);
 9081:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
 9082:     return $response;
 9083: }
 9084: 
 9085: sub auto_validate_courseID {
 9086:     my ($cnum,$cdom,$inst_course_id) = @_;
 9087:     my $homeserver = &homeserver($cnum,$cdom);
 9088:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 9089:     return $response;
 9090: }
 9091: 
 9092: sub auto_validate_instcode {
 9093:     my ($cnum,$cdom,$instcode,$owner) = @_;
 9094:     my ($homeserver,$response);
 9095:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 9096:         $homeserver = &homeserver($cnum,$cdom);
 9097:     }
 9098:     if (!defined($homeserver)) {
 9099:         if ($cdom =~ /^$match_domain$/) {
 9100:             $homeserver = &domain($cdom,'primary');
 9101:         }
 9102:     }
 9103:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
 9104:                         &escape($instcode).':'.&escape($owner),$homeserver));
 9105:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
 9106:     return ($outcome,$description,$defaultcredits);
 9107: }
 9108: 
 9109: sub auto_create_password {
 9110:     my ($cnum,$cdom,$authparam,$udom) = @_;
 9111:     my ($homeserver,$response);
 9112:     my $create_passwd = 0;
 9113:     my $authchk = '';
 9114:     if ($udom =~ /^$match_domain$/) {
 9115:         $homeserver = &domain($udom,'primary');
 9116:     }
 9117:     if ($homeserver eq '') {
 9118:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 9119:             $homeserver = &homeserver($cnum,$cdom);
 9120:         }
 9121:     }
 9122:     if ($homeserver eq '') {
 9123:         $authchk = 'nodomain';
 9124:     } else {
 9125:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 9126:         if ($response eq 'refused') {
 9127:             $authchk = 'refused';
 9128:         } else {
 9129:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 9130:         }
 9131:     }
 9132:     return ($authparam,$create_passwd,$authchk);
 9133: }
 9134: 
 9135: sub auto_photo_permission {
 9136:     my ($cnum,$cdom,$students) = @_;
 9137:     my $homeserver = &homeserver($cnum,$cdom);
 9138:     my ($outcome,$perm_reqd,$conditions) = 
 9139: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 9140:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 9141: 	return (undef,undef);
 9142:     }
 9143:     return ($outcome,$perm_reqd,$conditions);
 9144: }
 9145: 
 9146: sub auto_checkphotos {
 9147:     my ($uname,$udom,$pid) = @_;
 9148:     my $homeserver = &homeserver($uname,$udom);
 9149:     my ($result,$resulttype);
 9150:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 9151: 				   &escape($uname).':'.&escape($pid),
 9152: 				   $homeserver));
 9153:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 9154: 	return (undef,undef);
 9155:     }
 9156:     if ($outcome) {
 9157:         ($result,$resulttype) = split(/:/,$outcome);
 9158:     } 
 9159:     return ($result,$resulttype);
 9160: }
 9161: 
 9162: sub auto_photochoice {
 9163:     my ($cnum,$cdom) = @_;
 9164:     my $homeserver = &homeserver($cnum,$cdom);
 9165:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 9166: 						       &escape($cdom),
 9167: 						       $homeserver)));
 9168:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 9169: 	return (undef,undef);
 9170:     }
 9171:     return ($update,$comment);
 9172: }
 9173: 
 9174: sub auto_photoupdate {
 9175:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 9176:     my $homeserver = &homeserver($cnum,$dom);
 9177:     my $host=&hostname($homeserver);
 9178:     my $cmd = '';
 9179:     my $maxtries = 1;
 9180:     foreach my $affiliate (keys(%{$affiliatesref})) {
 9181:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 9182:     }
 9183:     $cmd =~ s/%%$//;
 9184:     $cmd = &escape($cmd);
 9185:     my $query = 'institutionalphotos';
 9186:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 9187:     unless ($queryid=~/^\Q$host\E\_/) {
 9188:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 9189:         return 'error: '.$queryid;
 9190:     }
 9191:     my $reply = &get_query_reply($queryid);
 9192:     my $tries = 1;
 9193:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 9194:         $reply = &get_query_reply($queryid);
 9195:         $tries ++;
 9196:     }
 9197:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 9198:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 9199:     } else {
 9200:         my @responses = split(/:/,$reply);
 9201:         my $outcome = shift(@responses); 
 9202:         foreach my $item (@responses) {
 9203:             my ($key,$value) = split(/=/,$item);
 9204:             $$photo{$key} = $value;
 9205:         }
 9206:         return $outcome;
 9207:     }
 9208:     return 'error';
 9209: }
 9210: 
 9211: sub auto_instcode_format {
 9212:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 9213: 	$cat_order) = @_;
 9214:     my $courses = '';
 9215:     my @homeservers;
 9216:     if ($caller eq 'global') {
 9217: 	my %servers = &get_servers($codedom,'library');
 9218: 	foreach my $tryserver (keys(%servers)) {
 9219: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 9220: 		push(@homeservers,$tryserver);
 9221: 	    }
 9222:         }
 9223:     } elsif ($caller eq 'requests') {
 9224:         if ($codedom =~ /^$match_domain$/) {
 9225:             my $chome = &domain($codedom,'primary');
 9226:             unless ($chome eq 'no_host') {
 9227:                 push(@homeservers,$chome);
 9228:             }
 9229:         }
 9230:     } else {
 9231:         push(@homeservers,&homeserver($caller,$codedom));
 9232:     }
 9233:     foreach my $code (keys(%{$instcodes})) {
 9234:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 9235:     }
 9236:     chop($courses);
 9237:     my $ok_response = 0;
 9238:     my $response;
 9239:     while (@homeservers > 0 && $ok_response == 0) {
 9240:         my $server = shift(@homeservers); 
 9241:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 9242:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 9243:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 9244: 		split(/:/,$response);
 9245:             %{$codes} = (%{$codes},&str2hash($codes_str));
 9246:             push(@{$codetitles},&str2array($codetitles_str));
 9247:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 9248:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 9249:             $ok_response = 1;
 9250:         }
 9251:     }
 9252:     if ($ok_response) {
 9253:         return 'ok';
 9254:     } else {
 9255:         return $response;
 9256:     }
 9257: }
 9258: 
 9259: sub auto_instcode_defaults {
 9260:     my ($domain,$returnhash,$code_order) = @_;
 9261:     my @homeservers;
 9262: 
 9263:     my %servers = &get_servers($domain,'library');
 9264:     foreach my $tryserver (keys(%servers)) {
 9265: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 9266: 	    push(@homeservers,$tryserver);
 9267: 	}
 9268:     }
 9269: 
 9270:     my $response;
 9271:     foreach my $server (@homeservers) {
 9272:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 9273:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 9274: 	
 9275: 	foreach my $pair (split(/\&/,$response)) {
 9276: 	    my ($name,$value)=split(/\=/,$pair);
 9277: 	    if ($name eq 'code_order') {
 9278: 		@{$code_order} = split(/\&/,&unescape($value));
 9279: 	    } else {
 9280: 		$returnhash->{&unescape($name)}=&unescape($value);
 9281: 	    }
 9282: 	}
 9283: 	return 'ok';
 9284:     }
 9285: 
 9286:     return $response;
 9287: }
 9288: 
 9289: sub auto_possible_instcodes {
 9290:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
 9291:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
 9292:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 9293:         return;
 9294:     }
 9295:     my (@homeservers,$uhome);
 9296:     if (defined(&domain($domain,'primary'))) {
 9297:         $uhome=&domain($domain,'primary');
 9298:         push(@homeservers,&domain($domain,'primary'));
 9299:     } else {
 9300:         my %servers = &get_servers($domain,'library');
 9301:         foreach my $tryserver (keys(%servers)) {
 9302:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 9303:                 push(@homeservers,$tryserver);
 9304:             }
 9305:         }
 9306:     }
 9307:     my $response;
 9308:     foreach my $server (@homeservers) {
 9309:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
 9310:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 9311:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
 9312:             split(':',$response);
 9313:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
 9314:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
 9315:         foreach my $item (split('&',$cat_title)) {   
 9316:             my ($name,$value)=split('=',$item);
 9317:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
 9318:         }
 9319:         foreach my $item (split('&',$cat_order)) {
 9320:             my ($name,$value)=split('=',$item);
 9321:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
 9322:         }
 9323:         return 'ok';
 9324:     }
 9325:     return $response;
 9326: }
 9327: 
 9328: sub auto_courserequest_checks {
 9329:     my ($dom) = @_;
 9330:     my ($homeserver,%validations);
 9331:     if ($dom =~ /^$match_domain$/) {
 9332:         $homeserver = &domain($dom,'primary');
 9333:     }
 9334:     unless ($homeserver eq 'no_host') {
 9335:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
 9336:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 9337:             my @items = split(/&/,$response);
 9338:             foreach my $item (@items) {
 9339:                 my ($key,$value) = split('=',$item);
 9340:                 $validations{&unescape($key)} = &thaw_unescape($value);
 9341:             }
 9342:         }
 9343:     }
 9344:     return %validations; 
 9345: }
 9346: 
 9347: sub auto_courserequest_validation {
 9348:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
 9349:     my ($homeserver,$response);
 9350:     if ($dom =~ /^$match_domain$/) {
 9351:         $homeserver = &domain($dom,'primary');
 9352:     }
 9353:     unless ($homeserver eq 'no_host') {
 9354:         my $customdata;
 9355:         if (ref($custominfo) eq 'HASH') {
 9356:             $customdata = &freeze_escape($custominfo);
 9357:         }
 9358:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
 9359:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
 9360:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
 9361:                                     $customdata,$homeserver));
 9362:     }
 9363:     return $response;
 9364: }
 9365: 
 9366: sub auto_validate_class_sec {
 9367:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 9368:     my $homeserver = &homeserver($cnum,$cdom);
 9369:     my $ownerlist;
 9370:     if (ref($owners) eq 'ARRAY') {
 9371:         $ownerlist = join(',',@{$owners});
 9372:     } else {
 9373:         $ownerlist = $owners;
 9374:     }
 9375:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 9376:                         &escape($ownerlist).':'.$cdom,$homeserver);
 9377:     return $response;
 9378: }
 9379: 
 9380: sub auto_validate_instclasses {
 9381:     my ($cdom,$cnum,$owners,$classesref) = @_;
 9382:     my ($homeserver,%validations);
 9383:     $homeserver = &homeserver($cnum,$cdom);
 9384:     unless ($homeserver eq 'no_host') {
 9385:         my $ownerlist;
 9386:         if (ref($owners) eq 'ARRAY') {
 9387:             $ownerlist = join(',',@{$owners});
 9388:         } else {
 9389:             $ownerlist = $owners;
 9390:         }
 9391:         if (ref($classesref) eq 'HASH') {
 9392:             my $classes = &freeze_escape($classesref);
 9393:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
 9394:                                 ':'.$cdom.':'.$classes,$homeserver);
 9395:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 9396:                 my @items = split(/&/,$response);
 9397:                 foreach my $item (@items) {
 9398:                     my ($key,$value) = split('=',$item);
 9399:                     $validations{&unescape($key)} = &thaw_unescape($value);
 9400:                 }
 9401:             }
 9402:         }
 9403:     }
 9404:     return %validations;
 9405: }
 9406: 
 9407: sub auto_crsreq_update {
 9408:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
 9409:         $code,$accessstart,$accessend,$inbound) = @_;
 9410:     my ($homeserver,%crsreqresponse);
 9411:     if ($cdom =~ /^$match_domain$/) {
 9412:         $homeserver = &domain($cdom,'primary');
 9413:     }
 9414:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
 9415:         my $info;
 9416:         if (ref($inbound) eq 'HASH') {
 9417:             $info = &freeze_escape($inbound);
 9418:         }
 9419:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
 9420:                             ':'.&escape($action).':'.&escape($ownername).':'.
 9421:                             &escape($ownerdomain).':'.&escape($fullname).':'.
 9422:                             &escape($title).':'.&escape($code).':'.
 9423:                             &escape($accessstart).':'.&escape($accessend).':'.$info,$homeserver);
 9424:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 9425:             my @items = split(/&/,$response);
 9426:             foreach my $item (@items) {
 9427:                 my ($key,$value) = split('=',$item);
 9428:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
 9429:             }
 9430:         }
 9431:     }
 9432:     return \%crsreqresponse;
 9433: }
 9434: 
 9435: sub auto_export_grades {
 9436:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
 9437:     my ($homeserver,%exportresponse);
 9438:     if ($cdom =~ /^$match_domain$/) {
 9439:         $homeserver = &domain($cdom,'primary');
 9440:     }
 9441:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
 9442:         my $info;
 9443:         if (ref($inforef) eq 'HASH') {
 9444:             $info = &freeze_escape($inforef);
 9445:         }
 9446:         if (ref($gradesref) eq 'HASH') {
 9447:             my $grades = &freeze_escape($gradesref);
 9448:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
 9449:                                 $info.':'.$grades,$homeserver);
 9450:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
 9451:                 my @items = split(/&/,$response);
 9452:                 foreach my $item (@items) {
 9453:                     my ($key,$value) = split('=',$item);
 9454:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
 9455:                 }
 9456:             }
 9457:         }
 9458:     }
 9459:     return \%exportresponse;
 9460: }
 9461: 
 9462: sub check_instcode_cloning {
 9463:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
 9464:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 9465:         return;
 9466:     }
 9467:     my $canclone;
 9468:     if (@{$code_order} > 0) {
 9469:         my $instcoderegexp ='^';
 9470:         my @clonecodes = split(/\&/,$cloner);
 9471:         foreach my $item (@{$code_order}) {
 9472:             if (grep(/^\Q$item\E=/,@clonecodes)) {
 9473:                 foreach my $pair (@clonecodes) {
 9474:                     my ($key,$val) = split(/\=/,$pair,2);
 9475:                     $val = &unescape($val);
 9476:                     if ($key eq $item) {
 9477:                         $instcoderegexp .= '('.$val.')';
 9478:                         last;
 9479:                     }
 9480:                 }
 9481:             } else {
 9482:                 $instcoderegexp .= $codedefaults->{$item};
 9483:             }
 9484:         }
 9485:         $instcoderegexp .= '$';
 9486:         my (@from,@to);
 9487:         eval {
 9488:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
 9489:                (@to) = ($clonetocode =~ /$instcoderegexp/);
 9490:         };
 9491:         if ((@from > 0) && (@to > 0)) {
 9492:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
 9493:             if (!@diffs) {
 9494:                 $canclone = 1;
 9495:             }
 9496:         }
 9497:     }
 9498:     return $canclone;
 9499: }
 9500: 
 9501: sub default_instcode_cloning {
 9502:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
 9503:     my (%codedefaults,@code_order,$canclone);
 9504:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
 9505:         %codedefaults = %{$codedefaultsref};
 9506:         @code_order = @{$codeorderref};
 9507:     } elsif ($clonedom) {
 9508:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
 9509:     }
 9510:     if (($domdefclone) && (@code_order)) {
 9511:         my @clonecodes = split(/\+/,$domdefclone);
 9512:         my $instcoderegexp ='^';
 9513:         foreach my $item (@code_order) {
 9514:             if (grep(/^\Q$item\E$/,@clonecodes)) {
 9515:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
 9516:             } else {
 9517:                 $instcoderegexp .= $codedefaults{$item};
 9518:             }
 9519:         }
 9520:         $instcoderegexp .= '$';
 9521:         my (@from,@to);
 9522:         eval {
 9523:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
 9524:             (@to) = ($clonetocode =~ /$instcoderegexp/);
 9525:         };
 9526:         if ((@from > 0) && (@to > 0)) {
 9527:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
 9528:             if (!@diffs) {
 9529:                 $canclone = 1;
 9530:             }
 9531:         }
 9532:     }
 9533:     return $canclone;
 9534: }
 9535: 
 9536: # ------------------------------------------------------- Course Group routines
 9537: 
 9538: sub get_coursegroups {
 9539:     my ($cdom,$cnum,$group,$namespace) = @_;
 9540:     return(&dump($namespace,$cdom,$cnum,$group));
 9541: }
 9542: 
 9543: sub modify_coursegroup {
 9544:     my ($cdom,$cnum,$groupsettings) = @_;
 9545:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 9546: }
 9547: 
 9548: sub toggle_coursegroup_status {
 9549:     my ($cdom,$cnum,$group,$action) = @_;
 9550:     my ($from_namespace,$to_namespace);
 9551:     if ($action eq 'delete') {
 9552:         $from_namespace = 'coursegroups';
 9553:         $to_namespace = 'deleted_groups';
 9554:     } else {
 9555:         $from_namespace = 'deleted_groups';
 9556:         $to_namespace = 'coursegroups';
 9557:     }
 9558:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 9559:     if (my $tmp = &error(%curr_group)) {
 9560:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 9561:         return ('read error',$tmp);
 9562:     } else {
 9563:         my %savedsettings = %curr_group; 
 9564:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 9565:         my $deloutcome;
 9566:         if ($result eq 'ok') {
 9567:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 9568:         } else {
 9569:             return ('write error',$result);
 9570:         }
 9571:         if ($deloutcome eq 'ok') {
 9572:             return 'ok';
 9573:         } else {
 9574:             return ('delete error',$deloutcome);
 9575:         }
 9576:     }
 9577: }
 9578: 
 9579: sub modify_group_roles {
 9580:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 9581:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 9582:     my $role = 'gr/'.&escape($userprivs);
 9583:     my ($uname,$udom) = split(/:/,$user);
 9584:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 9585:     if ($result eq 'ok') {
 9586:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 9587:     }
 9588:     return $result;
 9589: }
 9590: 
 9591: sub modify_coursegroup_membership {
 9592:     my ($cdom,$cnum,$membership) = @_;
 9593:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 9594:     return $result;
 9595: }
 9596: 
 9597: sub get_active_groups {
 9598:     my ($udom,$uname,$cdom,$cnum) = @_;
 9599:     my $now = time;
 9600:     my %groups = ();
 9601:     foreach my $key (keys(%env)) {
 9602:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 9603:             my ($start,$end) = split(/\./,$env{$key});
 9604:             if (($end!=0) && ($end<$now)) { next; }
 9605:             if (($start!=0) && ($start>$now)) { next; }
 9606:             if ($1 eq $cdom && $2 eq $cnum) {
 9607:                 $groups{$3} = $env{$key} ;
 9608:             }
 9609:         }
 9610:     }
 9611:     return %groups;
 9612: }
 9613: 
 9614: sub get_group_membership {
 9615:     my ($cdom,$cnum,$group) = @_;
 9616:     return(&dump('groupmembership',$cdom,$cnum,$group));
 9617: }
 9618: 
 9619: sub get_users_groups {
 9620:     my ($udom,$uname,$courseid) = @_;
 9621:     my @usersgroups;
 9622:     my $cachetime=1800;
 9623: 
 9624:     my $hashid="$udom:$uname:$courseid";
 9625:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 9626:     if (defined($cached)) {
 9627:         @usersgroups = split(/:/,$grouplist);
 9628:     } else {  
 9629:         $grouplist = '';
 9630:         my $courseurl = &courseid_to_courseurl($courseid);
 9631:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 9632:         my $access_end = $env{'course.'.$courseid.
 9633:                               '.default_enrollment_end_date'};
 9634:         my $now = time;
 9635:         foreach my $key (keys(%roleshash)) {
 9636:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 9637:                 my $group = $1;
 9638:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 9639:                     my $start = $2;
 9640:                     my $end = $1;
 9641:                     if ($start == -1) { next; } # deleted from group
 9642:                     if (($start!=0) && ($start>$now)) { next; }
 9643:                     if (($end!=0) && ($end<$now)) {
 9644:                         if ($access_end && $access_end < $now) {
 9645:                             if ($access_end - $end < 86400) {
 9646:                                 push(@usersgroups,$group);
 9647:                             }
 9648:                         }
 9649:                         next;
 9650:                     }
 9651:                     push(@usersgroups,$group);
 9652:                 }
 9653:             }
 9654:         }
 9655:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 9656:         $grouplist = join(':',@usersgroups);
 9657:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 9658:     }
 9659:     return @usersgroups;
 9660: }
 9661: 
 9662: sub devalidate_getgroups_cache {
 9663:     my ($udom,$uname,$cdom,$cnum)=@_;
 9664:     my $courseid = $cdom.'_'.$cnum;
 9665: 
 9666:     my $hashid="$udom:$uname:$courseid";
 9667:     &devalidate_cache_new('getgroups',$hashid);
 9668: }
 9669: 
 9670: # ------------------------------------------------------------------ Plain Text
 9671: 
 9672: sub plaintext {
 9673:     my ($short,$type,$cid,$forcedefault) = @_;
 9674:     if ($short =~ m{^cr/}) {
 9675: 	return (split('/',$short))[-1];
 9676:     }
 9677:     if (!defined($cid)) {
 9678:         $cid = $env{'request.course.id'};
 9679:     }
 9680:     my %rolenames = (
 9681:                       Course    => 'std',
 9682:                       Community => 'alt1',
 9683:                     );
 9684:     if ($cid ne '') {
 9685:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
 9686:             unless ($forcedefault) {
 9687:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
 9688:                 &Apache::lonlocal::mt_escape(\$roletext);
 9689:                 return &Apache::lonlocal::mt($roletext);
 9690:             }
 9691:         }
 9692:     }
 9693:     if ((defined($type)) && (defined($rolenames{$type})) &&
 9694:         (defined($rolenames{$type})) && 
 9695:         (defined($prp{$short}{$rolenames{$type}}))) {
 9696:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 9697:     } elsif ($cid ne '') {
 9698:         my $crstype = $env{'course.'.$cid.'.type'};
 9699:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
 9700:             (defined($prp{$short}{$rolenames{$crstype}}))) {
 9701:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
 9702:         }
 9703:     }
 9704:     return &Apache::lonlocal::mt($prp{$short}{'std'});
 9705: }
 9706: 
 9707: # ----------------------------------------------------------------- Assign Role
 9708: 
 9709: sub assignrole {
 9710:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
 9711:         $context)=@_;
 9712:     my $mrole;
 9713:     if ($role =~ /^cr\//) {
 9714:         my $cwosec=$url;
 9715:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 9716: 	unless (&allowed('ccr',$cwosec)) {
 9717:            my $refused = 1;
 9718:            if ($context eq 'requestcourses') {
 9719:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 9720:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
 9721:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
 9722:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 9723:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 9724:                            if ($crsenv{'internal.courseowner'} eq
 9725:                                $env{'user.name'}.':'.$env{'user.domain'}) {
 9726:                                $refused = '';
 9727:                            }
 9728:                        }
 9729:                    }
 9730:                }
 9731:            }
 9732:            if ($refused) {
 9733:                &logthis('Refused custom assignrole: '.
 9734:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
 9735:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
 9736:                return 'refused';
 9737:            }
 9738:         }
 9739:         $mrole='cr';
 9740:     } elsif ($role =~ /^gr\//) {
 9741:         my $cwogrp=$url;
 9742:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 9743:         unless (&allowed('mdg',$cwogrp)) {
 9744:             &logthis('Refused group assignrole: '.
 9745:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 9746:                     $env{'user.name'}.' at '.$env{'user.domain'});
 9747:             return 'refused';
 9748:         }
 9749:         $mrole='gr';
 9750:     } else {
 9751:         my $cwosec=$url;
 9752:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 9753:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 9754:             my $refused;
 9755:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 9756:                 if (!(&allowed('c'.$role,$url))) {
 9757:                     $refused = 1;
 9758:                 }
 9759:             } else {
 9760:                 $refused = 1;
 9761:             }
 9762:             if ($refused) {
 9763:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 9764:                 if (!$selfenroll && $context eq 'course') {
 9765:                     my %crsenv;
 9766:                     if ($role eq 'cc' || $role eq 'co') {
 9767:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 9768:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
 9769:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
 9770:                                 if ($crsenv{'internal.courseowner'} eq 
 9771:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 9772:                                     $refused = '';
 9773:                                 }
 9774:                             }
 9775:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
 9776:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
 9777:                                 if ($crsenv{'internal.courseowner'} eq 
 9778:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 9779:                                     $refused = '';
 9780:                                 }
 9781:                             }
 9782:                         }
 9783:                     }
 9784:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 9785:                     $refused = '';
 9786:                 } elsif ($context eq 'requestcourses') {
 9787:                     my @possroles = ('st','ta','ep','in','cc','co');
 9788:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
 9789:                         my $wrongcc;
 9790:                         if ($cnum =~ /^$match_community$/) {
 9791:                             $wrongcc = 1 if ($role eq 'cc');
 9792:                         } else {
 9793:                             $wrongcc = 1 if ($role eq 'co');
 9794:                         }
 9795:                         unless ($wrongcc) {
 9796:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 9797:                             if ($crsenv{'internal.courseowner'} eq 
 9798:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
 9799:                                 $refused = '';
 9800:                             }
 9801:                         }
 9802:                     }
 9803:                 } elsif ($context eq 'requestauthor') {
 9804:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 9805:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
 9806:                         if ($env{'environment.requestauthor'} eq 'automatic') {
 9807:                             $refused = '';
 9808:                         } else {
 9809:                             my %domdefaults = &get_domain_defaults($udom);
 9810:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
 9811:                                 my $checkbystatus;
 9812:                                 if ($env{'user.adv'}) {
 9813:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
 9814:                                     if ($disposition eq 'automatic') {
 9815:                                         $refused = '';
 9816:                                     } elsif ($disposition eq '') {
 9817:                                         $checkbystatus = 1;
 9818:                                     }
 9819:                                 } else {
 9820:                                     $checkbystatus = 1;
 9821:                                 }
 9822:                                 if ($checkbystatus) {
 9823:                                     if ($env{'environment.inststatus'}) {
 9824:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
 9825:                                         foreach my $type (@inststatuses) {
 9826:                                             if (($type ne '') &&
 9827:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
 9828:                                                 $refused = '';
 9829:                                             }
 9830:                                         }
 9831:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
 9832:                                         $refused = '';
 9833:                                     }
 9834:                                 }
 9835:                             }
 9836:                         }
 9837:                     }
 9838:                 }
 9839:                 if ($refused) {
 9840:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 9841:                              ' '.$role.' '.$end.' '.$start.' by '.
 9842: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
 9843:                     return 'refused';
 9844:                 }
 9845:             }
 9846:         } elsif ($role eq 'au') {
 9847:             if ($url ne '/'.$udom.'/') {
 9848:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
 9849:                          ' to assign author role for '.$uname.':'.$udom.
 9850:                          ' in domain: '.$url.' refused (wrong domain).');
 9851:                 return 'refused';
 9852:             }
 9853:         }
 9854:         $mrole=$role;
 9855:     }
 9856:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 9857:                 "$udom:$uname:$url".'_'."$mrole=$role";
 9858:     if ($end) { $command.='_'.$end; }
 9859:     if ($start) {
 9860: 	if ($end) { 
 9861:            $command.='_'.$start; 
 9862:         } else {
 9863:            $command.='_0_'.$start;
 9864:         }
 9865:     }
 9866:     my $origstart = $start;
 9867:     my $origend = $end;
 9868:     my $delflag;
 9869: # actually delete
 9870:     if ($deleteflag) {
 9871: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 9872: # modify command to delete the role
 9873:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 9874:                 "$udom:$uname:$url".'_'."$mrole";
 9875: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 9876: # set start and finish to negative values for userrolelog
 9877:            $start=-1;
 9878:            $end=-1;
 9879:            $delflag = 1;
 9880:         }
 9881:     }
 9882: # send command
 9883:     my $answer=&reply($command,&homeserver($uname,$udom));
 9884: # log new user role if status is ok
 9885:     if ($answer eq 'ok') {
 9886: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 9887:         if (($role eq 'cc') || ($role eq 'in') ||
 9888:             ($role eq 'ep') || ($role eq 'ad') ||
 9889:             ($role eq 'ta') || ($role eq 'st') ||
 9890:             ($role=~/^cr/) || ($role eq 'gr') ||
 9891:             ($role eq 'co')) {
 9892: # for course roles, perform group memberships changes triggered by role change.
 9893:             unless ($role =~ /^gr/) {
 9894:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 9895:                                                  $origstart,$selfenroll,$context);
 9896:             }
 9897:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 9898:                            $selfenroll,$context);
 9899:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
 9900:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
 9901:                  ($role eq 'da')) {
 9902:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 9903:                            $context);
 9904:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
 9905:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 9906:                              $context);
 9907:         }
 9908:         if ($role eq 'cc') {
 9909:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
 9910:         }
 9911:     }
 9912:     return $answer;
 9913: }
 9914: 
 9915: sub autoupdate_coowners {
 9916:     my ($url,$end,$start,$uname,$udom) = @_;
 9917:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
 9918:     if (($cdom ne '') && ($cnum ne '')) {
 9919:         my $now = time;
 9920:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
 9921:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
 9922:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
 9923:             my $instcode = $coursehash{'internal.coursecode'};
 9924:             if ($instcode ne '') {
 9925:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
 9926:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
 9927:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
 9928:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
 9929:                         if ($result eq 'valid') {
 9930:                             if ($coursehash{'internal.co-owners'}) {
 9931:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 9932:                                     push(@newcoowners,$coowner);
 9933:                                 }
 9934:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
 9935:                                     push(@newcoowners,$uname.':'.$udom);
 9936:                                 }
 9937:                                 @newcoowners = sort(@newcoowners);
 9938:                             } else {
 9939:                                 push(@newcoowners,$uname.':'.$udom);
 9940:                             }
 9941:                         } else {
 9942:                             if ($coursehash{'internal.co-owners'}) {
 9943:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 9944:                                     unless ($coowner eq $uname.':'.$udom) {
 9945:                                         push(@newcoowners,$coowner);
 9946:                                     }
 9947:                                 }
 9948:                                 unless (@newcoowners > 0) {
 9949:                                     $delcoowners = 1;
 9950:                                     $coowners = '';
 9951:                                 }
 9952:                             }
 9953:                         }
 9954:                         if (@newcoowners || $delcoowners) {
 9955:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
 9956:                                             $delcoowners,@newcoowners);
 9957:                         }
 9958:                     }
 9959:                 }
 9960:             }
 9961:         }
 9962:     }
 9963: }
 9964: 
 9965: sub store_coowners {
 9966:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
 9967:     my $cid = $cdom.'_'.$cnum;
 9968:     my ($coowners,$delresult,$putresult);
 9969:     if (@newcoowners) {
 9970:         $coowners = join(',',@newcoowners);
 9971:         my %coownershash = (
 9972:                             'internal.co-owners' => $coowners,
 9973:                            );
 9974:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
 9975:         if ($putresult eq 'ok') {
 9976:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
 9977:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
 9978:             }
 9979:         }
 9980:     }
 9981:     if ($delcoowners) {
 9982:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
 9983:         if ($delresult eq 'ok') {
 9984:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
 9985:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
 9986:             }
 9987:         }
 9988:     }
 9989:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
 9990:         my %crsinfo =
 9991:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 9992:         if (ref($crsinfo{$cid}) eq 'HASH') {
 9993:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
 9994:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
 9995:         }
 9996:     }
 9997: }
 9998: 
 9999: # -------------------------------------------------- Modify user authentication
10000: # Overrides without validation
10001: 
10002: sub modifyuserauth {
10003:     my ($udom,$uname,$umode,$upass)=@_;
10004:     my $uhome=&homeserver($uname,$udom);
10005:     my $allowed;
10006:     if (&allowed('mau',$udom)) {
10007:         $allowed = 1;
10008:     } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
10009:              ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
10010:              (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
10011:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10012:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10013:         if (($cdom ne '') && ($cnum ne '')) {
10014:             my $is_owner = &is_course_owner($cdom,$cnum);
10015:             if ($is_owner) {
10016:                 $allowed = 1;
10017:             }
10018:         }
10019:     }
10020:     unless ($allowed) { return 'refused'; }
10021:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
10022:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
10023:              ' in domain '.$env{'request.role.domain'});  
10024:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
10025: 		     &escape($upass),$uhome);
10026:     my $ip = &get_requestor_ip();
10027:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
10028:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
10029:          '(Remote '.$ip.'): '.$reply);
10030:     &log($udom,,$uname,$uhome,
10031:         'Authentication changed by '.$env{'user.domain'}.', '.
10032:                                      $env{'user.name'}.', '.$umode.
10033:          '(Remote '.$ip.'): '.$reply);
10034:     unless ($reply eq 'ok') {
10035:         &logthis('Authentication mode error: '.$reply);
10036: 	return 'error: '.$reply;
10037:     }   
10038:     return 'ok';
10039: }
10040: 
10041: # --------------------------------------------------------------- Modify a user
10042: 
10043: sub modifyuser {
10044:     my ($udom,    $uname, $uid,
10045:         $umode,   $upass, $first,
10046:         $middle,  $last,  $gene,
10047:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
10048:     $udom= &LONCAPA::clean_domain($udom);
10049:     $uname=&LONCAPA::clean_username($uname);
10050:     my $showcandelete = 'none';
10051:     if (ref($candelete) eq 'ARRAY') {
10052:         if (@{$candelete} > 0) {
10053:             $showcandelete = join(', ',@{$candelete});
10054:         }
10055:     }
10056:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
10057:              $umode.', '.$first.', '.$middle.', '.
10058: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
10059:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
10060:                                      ' desiredhome not specified'). 
10061:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
10062:              ' in domain '.$env{'request.role.domain'});
10063:     my $uhome=&homeserver($uname,$udom,'true');
10064:     my $newuser;
10065:     if ($uhome eq 'no_host') {
10066:         $newuser = 1;
10067:     }
10068: # ----------------------------------------------------------------- Create User
10069:     if (($uhome eq 'no_host') && 
10070: 	(($umode && $upass) || ($umode eq 'localauth'))) {
10071:         my $unhome='';
10072:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
10073:             $unhome = $desiredhome;
10074: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
10075: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
10076:         } else { # load balancing routine for determining $unhome
10077:             my $loadm=10000000;
10078: 	    my %servers = &get_servers($udom,'library');
10079: 	    foreach my $tryserver (keys(%servers)) {
10080: 		my $answer=reply('load',$tryserver);
10081: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
10082: 		    $loadm=$answer;
10083: 		    $unhome=$tryserver;
10084: 		}
10085: 	    }
10086:         }
10087:         if (($unhome eq '') || ($unhome eq 'no_host')) {
10088: 	    return 'error: unable to find a home server for '.$uname.
10089:                    ' in domain '.$udom;
10090:         }
10091:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
10092:                          &escape($upass),$unhome);
10093: 	unless ($reply eq 'ok') {
10094:             return 'error: '.$reply;
10095:         }   
10096:         $uhome=&homeserver($uname,$udom,'true');
10097:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
10098: 	    return 'error: unable verify users home machine.';
10099:         }
10100:     }   # End of creation of new user
10101: # ---------------------------------------------------------------------- Add ID
10102:     if ($uid) {
10103:        $uid=~tr/A-Z/a-z/;
10104:        my %uidhash=&idrget($udom,$uname);
10105:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
10106:          && (!$forceid)) {
10107: 	  unless ($uid eq $uidhash{$uname}) {
10108: 	      return 'error: user id "'.$uid.'" does not match '.
10109:                   'current user id "'.$uidhash{$uname}.'".';
10110:           }
10111:        } else {
10112: 	  &idput($udom,($uname => $uid));
10113:        }
10114:     }
10115: # -------------------------------------------------------------- Add names, etc
10116:     my @tmp=&get('environment',
10117: 		   ['firstname','middlename','lastname','generation','id',
10118:                     'permanentemail','inststatus'],
10119: 		   $udom,$uname);
10120:     my (%names,%oldnames);
10121:     if ($tmp[0] =~ m/^error:.*/) { 
10122:         %names=(); 
10123:     } else {
10124:         %names = @tmp;
10125:         %oldnames = %names;
10126:     }
10127: #
10128: # If name, email and/or uid are blank (e.g., because an uploaded file
10129: # of users did not contain them), do not overwrite existing values
10130: # unless field is in $candelete array ref.  
10131: #
10132: 
10133:     my @fields = ('firstname','middlename','lastname','generation',
10134:                   'permanentemail','id');
10135:     my %newvalues;
10136:     if (ref($candelete) eq 'ARRAY') {
10137:         foreach my $field (@fields) {
10138:             if (grep(/^\Q$field\E$/,@{$candelete})) {
10139:                 if ($field eq 'firstname') {
10140:                     $names{$field} = $first;
10141:                 } elsif ($field eq 'middlename') {
10142:                     $names{$field} = $middle;
10143:                 } elsif ($field eq 'lastname') {
10144:                     $names{$field} = $last;
10145:                 } elsif ($field eq 'generation') { 
10146:                     $names{$field} = $gene;
10147:                 } elsif ($field eq 'permanentemail') {
10148:                     $names{$field} = $email;
10149:                 } elsif ($field eq 'id') {
10150:                     $names{$field}  = $uid;
10151:                 }
10152:             }
10153:         }
10154:     }
10155:     if ($first)  { $names{'firstname'}  = $first; }
10156:     if (defined($middle)) { $names{'middlename'} = $middle; }
10157:     if ($last)   { $names{'lastname'}   = $last; }
10158:     if (defined($gene))   { $names{'generation'} = $gene; }
10159:     if ($email) {
10160:        $email=~s/[^\w\@\.\-\,]//gs;
10161:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
10162:     }
10163:     if ($uid) { $names{'id'}  = $uid; }
10164:     if (defined($inststatus)) {
10165:         $names{'inststatus'} = '';
10166:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
10167:         if (ref($usertypes) eq 'HASH') {
10168:             my @okstatuses; 
10169:             foreach my $item (split(/:/,$inststatus)) {
10170:                 if (defined($usertypes->{$item})) {
10171:                     push(@okstatuses,$item);  
10172:                 }
10173:             }
10174:             if (@okstatuses) {
10175:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
10176:             }
10177:         }
10178:     }
10179:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
10180:                  $umode.', '.$first.', '.$middle.', '.
10181:                  $last.', '.$gene.', '.$email.', '.$inststatus;
10182:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
10183:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
10184:     } else {
10185:         $logmsg .= ' during self creation';
10186:     }
10187:     my $changed;
10188:     if ($newuser) {
10189:         $changed = 1;
10190:     } else {
10191:         foreach my $field (@fields) {
10192:             if ($names{$field} ne $oldnames{$field}) {
10193:                 $changed = 1;
10194:                 last;
10195:             }
10196:         }
10197:     }
10198:     unless ($changed) {
10199:         $logmsg = 'No changes in user information needed for: '.$logmsg;
10200:         &logthis($logmsg);
10201:         return 'ok';
10202:     }
10203:     my $reply = &put('environment', \%names, $udom,$uname);
10204:     if ($reply ne 'ok') { 
10205:         return 'error: '.$reply;
10206:     }
10207:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
10208:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
10209:     }
10210:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
10211:     &devalidate_cache_new('namescache',$uname.':'.$udom);
10212:     $logmsg = 'Success modifying user '.$logmsg;
10213:     &logthis($logmsg);
10214:     return 'ok';
10215: }
10216: 
10217: # -------------------------------------------------------------- Modify student
10218: 
10219: sub modifystudent {
10220:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
10221:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
10222:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
10223:     if (!$cid) {
10224: 	unless ($cid=$env{'request.course.id'}) {
10225: 	    return 'not_in_class';
10226: 	}
10227:     }
10228: # --------------------------------------------------------------- Make the user
10229:     my $reply=&modifyuser
10230: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
10231:          $desiredhome,$email,$inststatus);
10232:     unless ($reply eq 'ok') { return $reply; }
10233:     # This will cause &modify_student_enrollment to get the uid from the
10234:     # student's environment
10235:     $uid = undef if (!$forceid);
10236:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
10237: 					$gene,$usec,$end,$start,$type,$locktype,
10238:                                         $cid,$selfenroll,$context,$credits,$instsec);
10239:     return $reply;
10240: }
10241: 
10242: sub modify_student_enrollment {
10243:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
10244:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
10245:     my ($cdom,$cnum,$chome);
10246:     if (!$cid) {
10247: 	unless ($cid=$env{'request.course.id'}) {
10248: 	    return 'not_in_class';
10249: 	}
10250: 	$cdom=$env{'course.'.$cid.'.domain'};
10251: 	$cnum=$env{'course.'.$cid.'.num'};
10252:     } else {
10253: 	($cdom,$cnum)=split(/_/,$cid);
10254:     }
10255:     $chome=$env{'course.'.$cid.'.home'};
10256:     if (!$chome) {
10257: 	$chome=&homeserver($cnum,$cdom);
10258:     }
10259:     if (!$chome) { return 'unknown_course'; }
10260:     # Make sure the user exists
10261:     my $uhome=&homeserver($uname,$udom);
10262:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
10263: 	return 'error: no such user';
10264:     }
10265:     # Get student data if we were not given enough information
10266:     if (!defined($first)  || $first  eq '' || 
10267:         !defined($last)   || $last   eq '' || 
10268:         !defined($uid)    || $uid    eq '' || 
10269:         !defined($middle) || $middle eq '' || 
10270:         !defined($gene)   || $gene   eq '') {
10271:         # They did not supply us with enough data to enroll the student, so
10272:         # we need to pick up more information.
10273:         my %tmp = &get('environment',
10274:                        ['firstname','middlename','lastname', 'generation','id']
10275:                        ,$udom,$uname);
10276: 
10277:         #foreach my $key (keys(%tmp)) {
10278:         #    &logthis("key $key = ".$tmp{$key});
10279:         #}
10280:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
10281:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
10282:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
10283:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
10284:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
10285:     }
10286:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
10287:     my $user = "$uname:$udom";
10288:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
10289:     my $reply=cput('classlist',
10290: 		   {$user => 
10291: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
10292: 		   $cdom,$cnum);
10293:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
10294:         &devalidate_getsection_cache($udom,$uname,$cid);
10295:     } else { 
10296: 	return 'error: '.$reply;
10297:     }
10298:     # Add student role to user
10299:     my $uurl='/'.$cid;
10300:     $uurl=~s/\_/\//g;
10301:     if ($usec) {
10302: 	$uurl.='/'.$usec;
10303:     }
10304:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
10305:                              $selfenroll,$context);
10306:     if ($result ne 'ok') {
10307:         if ($old_entry{$user} ne '') {
10308:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
10309:         } else {
10310:             $reply = &del('classlist',[$user],$cdom,$cnum);
10311:         }
10312:     }
10313:     return $result; 
10314: }
10315: 
10316: sub format_name {
10317:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
10318:     my $name;
10319:     if ($first ne 'lastname') {
10320: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
10321:     } else {
10322: 	if ($lastname=~/\S/) {
10323: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
10324: 	    $name=~s/\s+,/,/;
10325: 	} else {
10326: 	    $name.= $firstname.' '.$middlename.' '.$generation;
10327: 	}
10328:     }
10329:     $name=~s/^\s+//;
10330:     $name=~s/\s+$//;
10331:     $name=~s/\s+/ /g;
10332:     return $name;
10333: }
10334: 
10335: # ------------------------------------------------- Write to course preferences
10336: 
10337: sub writecoursepref {
10338:     my ($courseid,%prefs)=@_;
10339:     $courseid=~s/^\///;
10340:     $courseid=~s/\_/\//g;
10341:     my ($cdomain,$cnum)=split(/\//,$courseid);
10342:     my $chome=homeserver($cnum,$cdomain);
10343:     if (($chome eq '') || ($chome eq 'no_host')) { 
10344: 	return 'error: no such course';
10345:     }
10346:     my $cstring='';
10347:     foreach my $pref (keys(%prefs)) {
10348: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
10349:     }
10350:     $cstring=~s/\&$//;
10351:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
10352: }
10353: 
10354: # ---------------------------------------------------------- Make/modify course
10355: 
10356: sub createcourse {
10357:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
10358:         $course_owner,$crstype,$cnum,$context,$category,$callercontext)=@_;
10359:     $url=&declutter($url);
10360:     my $cid='';
10361:     if ($context eq 'requestcourses') {
10362:         my $can_create = 0;
10363:         my ($ownername,$ownerdom) = split(':',$course_owner);
10364:         if ($udom eq $ownerdom) {
10365:             my $reload;
10366:             if (($callercontext eq 'auto') &&
10367:                ($ownerdom eq $env{'user.domain'}) && ($ownername eq $env{'user.name'})) {
10368:                 $reload = 'reload';
10369:             }
10370:             if (&usertools_access($ownername,$ownerdom,$category,$reload,
10371:                                   $context)) {
10372:                 $can_create = 1;
10373:             }
10374:         } else {
10375:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
10376:                                            $category);
10377:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
10378:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
10379:                 if (@curr > 0) {
10380:                     my @options = qw(approval validate autolimit);
10381:                     my $optregex = join('|',@options);
10382:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
10383:                         $can_create = 1;
10384:                     }
10385:                 }
10386:             }
10387:         }
10388:         if ($can_create) {
10389:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
10390:                 unless (&allowed('ccc',$udom)) {
10391:                     return 'refused'; 
10392:                 }
10393:             }
10394:         } else {
10395:             return 'refused';
10396:         }
10397:     } elsif (!&allowed('ccc',$udom)) {
10398:         return 'refused';
10399:     }
10400: # --------------------------------------------------------------- Get Unique ID
10401:     my $uname;
10402:     if ($cnum =~ /^$match_courseid$/) {
10403:         my $chome=&homeserver($cnum,$udom,'true');
10404:         if (($chome eq '') || ($chome eq 'no_host')) {
10405:             $uname = $cnum;
10406:         } else {
10407:             $uname = &generate_coursenum($udom,$crstype);
10408:         }
10409:     } else {
10410:         $uname = &generate_coursenum($udom,$crstype);
10411:     }
10412:     return $uname if ($uname =~ /^error/);
10413: # -------------------------------------------------- Check supplied server name
10414:     if (!defined($course_server)) {
10415:         if (defined(&domain($udom,'primary'))) {
10416:             $course_server = &domain($udom,'primary');
10417:         } else {
10418:             $course_server = $env{'user.home'}; 
10419:         }
10420:     }
10421:     my %host_servers =
10422:         &Apache::lonnet::get_servers($udom,'library');
10423:     unless ($host_servers{$course_server}) {
10424:         return 'error: invalid home server for course: '.$course_server;
10425:     }
10426: # ------------------------------------------------------------- Make the course
10427:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
10428:                       $course_server);
10429:     unless ($reply eq 'ok') { return 'error: '.$reply; }
10430:     my $uhome=&homeserver($uname,$udom,'true');
10431:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
10432: 	return 'error: no such course';
10433:     }
10434: # ----------------------------------------------------------------- Course made
10435: # log existence
10436:     my $now = time;
10437:     my $newcourse = {
10438:                     $udom.'_'.$uname => {
10439:                                      description => $description,
10440:                                      inst_code   => $inst_code,
10441:                                      owner       => $course_owner,
10442:                                      type        => $crstype,
10443:                                      creator     => $env{'user.name'}.':'.
10444:                                                     $env{'user.domain'},
10445:                                      created     => $now,
10446:                                      context     => $context,
10447:                                                 },
10448:                     };
10449:     &courseidput($udom,$newcourse,$uhome,'notime');
10450: # set toplevel url
10451:     my $topurl=$url;
10452:     unless ($nonstandard) {
10453: # ------------------------------------------ For standard courses, make top url
10454:         my $mapurl=&clutter($url);
10455:         if ($mapurl eq '/res/') { $mapurl=''; }
10456:         $env{'form.initmap'}=(<<ENDINITMAP);
10457: <map>
10458: <resource id="1" type="start"></resource>
10459: <resource id="2" src="$mapurl"></resource>
10460: <resource id="3" type="finish"></resource>
10461: <link index="1" from="1" to="2"></link>
10462: <link index="2" from="2" to="3"></link>
10463: </map>
10464: ENDINITMAP
10465:         $topurl=&declutter(
10466:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
10467:                           );
10468:     }
10469: # ----------------------------------------------------------- Write preferences
10470:     &writecoursepref($udom.'_'.$uname,
10471:                      ('description'              => $description,
10472:                       'url'                      => $topurl,
10473:                       'internal.creator'         => $env{'user.name'}.':'.
10474:                                                     $env{'user.domain'},
10475:                       'internal.created'         => $now,
10476:                       'internal.creationcontext' => $context)
10477:                     );
10478:     return '/'.$udom.'/'.$uname;
10479: }
10480: 
10481: # ------------------------------------------------------------------- Create ID
10482: sub generate_coursenum {
10483:     my ($udom,$crstype) = @_;
10484:     my $domdesc = &domain($udom);
10485:     return 'error: invalid domain' if ($domdesc eq '');
10486:     my $first;
10487:     if ($crstype eq 'Community') {
10488:         $first = '0';
10489:     } else {
10490:         $first = int(1+rand(9)); 
10491:     } 
10492:     my $uname=$first.
10493:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
10494:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
10495:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
10496: # ----------------------------------------------- Make sure that does not exist
10497:     my $uhome=&homeserver($uname,$udom,'true');
10498:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
10499:         if ($crstype eq 'Community') {
10500:             $first = '0';
10501:         } else {
10502:             $first = int(1+rand(9));
10503:         }
10504:         $uname=$first.
10505:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
10506:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
10507:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
10508:         $uhome=&homeserver($uname,$udom,'true');
10509:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
10510:             return 'error: unable to generate unique course-ID';
10511:         }
10512:     }
10513:     return $uname;
10514: }
10515: 
10516: sub is_course {
10517:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
10518:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
10519:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
10520:     my $uhome=&homeserver($cnum,$cdom);
10521:     my $iscourse;
10522:     if (grep { $_ eq $uhome } current_machine_ids()) {
10523:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
10524:     } else {
10525:         my $hashid = $cdom.':'.$cnum;
10526:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
10527:         unless (defined($cached)) {
10528:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
10529:                                         $cnum,undef,undef,'.');
10530:             $iscourse = 0;
10531:             if (exists($courses{$cdom.'_'.$cnum})) {
10532:                 $iscourse = 1;
10533:             }
10534:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
10535:         }
10536:     }
10537:     return unless($iscourse);
10538:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
10539: }
10540: 
10541: sub store_userdata {
10542:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
10543:     my $result;
10544:     if ($datakey ne '') {
10545:         if (ref($storehash) eq 'HASH') {
10546:             if ($udom eq '' || $uname eq '') {
10547:                 $udom = $env{'user.domain'};
10548:                 $uname = $env{'user.name'};
10549:             }
10550:             my $uhome=&homeserver($uname,$udom);
10551:             if (($uhome eq '') || ($uhome eq 'no_host')) {
10552:                 $result = 'error: no_host';
10553:             } else {
10554:                 $storehash->{'ip'} = &get_requestor_ip();
10555:                 $storehash->{'host'} = $perlvar{'lonHostID'};
10556: 
10557:                 my $namevalue='';
10558:                 foreach my $key (keys(%{$storehash})) {
10559:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
10560:                 }
10561:                 $namevalue=~s/\&$//;
10562:                 unless ($namespace eq 'courserequests') {
10563:                     $datakey = &escape($datakey);
10564:                 }
10565:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
10566:                                   $namevalue,$uhome);
10567:             }
10568:         } else {
10569:             $result = 'error: data to store was not a hash reference'; 
10570:         }
10571:     } else {
10572:         $result= 'error: invalid requestkey'; 
10573:     }
10574:     return $result;
10575: }
10576: 
10577: # ---------------------------------------------------------- Assign Custom Role
10578: 
10579: sub assigncustomrole {
10580:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
10581:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
10582:                        $end,$start,$deleteflag,$selfenroll,$context);
10583: }
10584: 
10585: # ----------------------------------------------------------------- Revoke Role
10586: 
10587: sub revokerole {
10588:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
10589:     my $now=time;
10590:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
10591: }
10592: 
10593: # ---------------------------------------------------------- Revoke Custom Role
10594: 
10595: sub revokecustomrole {
10596:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
10597:     my $now=time;
10598:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
10599:            $deleteflag,$selfenroll,$context);
10600: }
10601: 
10602: # ------------------------------------------------------------ Disk usage
10603: sub diskusage {
10604:     my ($udom,$uname,$directorypath,$getpropath)=@_;
10605:     $directorypath =~ s/\/$//;
10606:     my $listing=&reply('du2:'.&escape($directorypath).':'
10607:                        .&escape($getpropath).':'.&escape($uname).':'
10608:                        .&escape($udom),homeserver($uname,$udom));
10609:     if ($listing eq 'unknown_cmd') {
10610:         if ($getpropath) {
10611:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
10612:         }
10613:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
10614:     }
10615:     return $listing;
10616: }
10617: 
10618: sub is_locked {
10619:     my ($file_name, $domain, $user, $which) = @_;
10620:     my @check;
10621:     my $is_locked;
10622:     push (@check,$file_name);
10623:     my %locked = &get('file_permissions',\@check,
10624: 		      $env{'user.domain'},$env{'user.name'});
10625:     my ($tmp)=keys(%locked);
10626:     if ($tmp=~/^error:/) { undef(%locked); }
10627:     
10628:     if (ref($locked{$file_name}) eq 'ARRAY') {
10629:         $is_locked = 'false';
10630:         foreach my $entry (@{$locked{$file_name}}) {
10631:            if (ref($entry) eq 'ARRAY') {
10632:                $is_locked = 'true';
10633:                if (ref($which) eq 'ARRAY') {
10634:                    push(@{$which},$entry);
10635:                } else {
10636:                    last;
10637:                }
10638:            }
10639:        }
10640:     } else {
10641:         $is_locked = 'false';
10642:     }
10643:     return $is_locked;
10644: }
10645: 
10646: sub declutter_portfile {
10647:     my ($file) = @_;
10648:     $file =~ s{^(/portfolio/|portfolio/)}{/};
10649:     return $file;
10650: }
10651: 
10652: # ------------------------------------------------------------- Mark as Read Only
10653: 
10654: sub mark_as_readonly {
10655:     my ($domain,$user,$files,$what) = @_;
10656:     my %current_permissions = &dump('file_permissions',$domain,$user);
10657:     my ($tmp)=keys(%current_permissions);
10658:     if ($tmp=~/^error:/) { undef(%current_permissions); }
10659:     foreach my $file (@{$files}) {
10660: 	$file = &declutter_portfile($file);
10661:         push(@{$current_permissions{$file}},$what);
10662:     }
10663:     &put('file_permissions',\%current_permissions,$domain,$user);
10664:     return;
10665: }
10666: 
10667: # ------------------------------------------------------------Save Selected Files
10668: 
10669: sub save_selected_files {
10670:     my ($user, $path, @files) = @_;
10671:     my $filename = $user."savedfiles";
10672:     my @other_files = &files_not_in_path($user, $path);
10673:     open (OUT,'>',LONCAPA::tempdir().$filename);
10674:     foreach my $file (@files) {
10675:         print (OUT $env{'form.currentpath'}.$file."\n");
10676:     }
10677:     foreach my $file (@other_files) {
10678:         print (OUT $file."\n");
10679:     }
10680:     close (OUT);
10681:     return 'ok';
10682: }
10683: 
10684: sub clear_selected_files {
10685:     my ($user) = @_;
10686:     my $filename = $user."savedfiles";
10687:     open (OUT,'>',LONCAPA::tempdir().$filename);
10688:     print (OUT undef);
10689:     close (OUT);
10690:     return ("ok");    
10691: }
10692: 
10693: sub files_in_path {
10694:     my ($user, $path) = @_;
10695:     my $filename = $user."savedfiles";
10696:     my %return_files;
10697:     open (IN,'<',LONCAPA::tempdir().$filename);
10698:     while (my $line_in = <IN>) {
10699:         chomp ($line_in);
10700:         my @paths_and_file = split (m!/!, $line_in);
10701:         my $file_part = pop (@paths_and_file);
10702:         my $path_part = join ('/', @paths_and_file);
10703:         $path_part.='/';
10704:         my $path_and_file = $path_part.$file_part;
10705:         if ($path_part eq $path) {
10706:             $return_files{$file_part}= 'selected';
10707:         }
10708:     }
10709:     close (IN);
10710:     return (\%return_files);
10711: }
10712: 
10713: # called in portfolio select mode, to show files selected NOT in current directory
10714: sub files_not_in_path {
10715:     my ($user, $path) = @_;
10716:     my $filename = $user."savedfiles";
10717:     my @return_files;
10718:     my $path_part;
10719:     open(IN, '<',LONCAPA::tempdir().$filename);
10720:     while (my $line = <IN>) {
10721:         #ok, I know it's clunky, but I want it to work
10722:         my @paths_and_file = split(m|/|, $line);
10723:         my $file_part = pop(@paths_and_file);
10724:         chomp($file_part);
10725:         my $path_part = join('/', @paths_and_file);
10726:         $path_part .= '/';
10727:         my $path_and_file = $path_part.$file_part;
10728:         if ($path_part ne $path) {
10729:             push(@return_files, ($path_and_file));
10730:         }
10731:     }
10732:     close(OUT);
10733:     return (@return_files);
10734: }
10735: 
10736: #----------------------------------------------Get portfolio file permissions
10737: 
10738: sub get_portfile_permissions {
10739:     my ($domain,$user) = @_;
10740:     my %current_permissions = &dump('file_permissions',$domain,$user);
10741:     my ($tmp)=keys(%current_permissions);
10742:     if ($tmp=~/^error:/) { undef(%current_permissions); }
10743:     return \%current_permissions;
10744: }
10745: 
10746: #---------------------------------------------Get portfolio file access controls
10747: 
10748: sub get_access_controls {
10749:     my ($current_permissions,$group,$file) = @_;
10750:     my %access;
10751:     my $real_file = $file;
10752:     $file =~ s/\.meta$//;
10753:     if (defined($file)) {
10754:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
10755:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
10756:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
10757:             }
10758:         }
10759:     } else {
10760:         foreach my $key (keys(%{$current_permissions})) {
10761:             if ($key =~ /\0accesscontrol$/) {
10762:                 if (defined($group)) {
10763:                     if ($key !~ m-^\Q$group\E/-) {
10764:                         next;
10765:                     }
10766:                 }
10767:                 my ($fullpath) = split(/\0/,$key);
10768:                 if (ref($$current_permissions{$key}) eq 'HASH') {
10769:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
10770:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
10771:                     }
10772:                 }
10773:             }
10774:         }
10775:     }
10776:     return %access;
10777: }
10778: 
10779: sub modify_access_controls {
10780:     my ($file_name,$changes,$domain,$user)=@_;
10781:     my ($outcome,$deloutcome);
10782:     my %store_permissions;
10783:     my %new_values;
10784:     my %new_control;
10785:     my %translation;
10786:     my @deletions = ();
10787:     my $now = time;
10788:     if (exists($$changes{'activate'})) {
10789:         if (ref($$changes{'activate'}) eq 'HASH') {
10790:             my @newitems = sort(keys(%{$$changes{'activate'}}));
10791:             my $numnew = scalar(@newitems);
10792:             for (my $i=0; $i<$numnew; $i++) {
10793:                 my $newkey = $newitems[$i];
10794:                 my $newid = &Apache::loncommon::get_cgi_id();
10795:                 if ($newkey =~ /^\d+:/) { 
10796:                     $newkey =~ s/^(\d+)/$newid/;
10797:                     $translation{$1} = $newid;
10798:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
10799:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
10800:                     $translation{$1} = $newid;
10801:                 }
10802:                 $new_values{$file_name."\0".$newkey} = 
10803:                                           $$changes{'activate'}{$newitems[$i]};
10804:                 $new_control{$newkey} = $now;
10805:             }
10806:         }
10807:     }
10808:     my %todelete;
10809:     my %changed_items;
10810:     foreach my $action ('delete','update') {
10811:         if (exists($$changes{$action})) {
10812:             if (ref($$changes{$action}) eq 'HASH') {
10813:                 foreach my $key (keys(%{$$changes{$action}})) {
10814:                     my ($itemnum) = ($key =~ /^([^:]+):/);
10815:                     if ($action eq 'delete') { 
10816:                         $todelete{$itemnum} = 1;
10817:                     } else {
10818:                         $changed_items{$itemnum} = $key;
10819:                     }
10820:                 }
10821:             }
10822:         }
10823:     }
10824:     # get lock on access controls for file.
10825:     my $lockhash = {
10826:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
10827:                                                        ':'.$env{'user.domain'},
10828:                    }; 
10829:     my $tries = 0;
10830:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
10831:    
10832:     while (($gotlock ne 'ok') && $tries < 10) {
10833:         $tries ++;
10834:         sleep(0.1);
10835:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
10836:     }
10837:     if ($gotlock eq 'ok') {
10838:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
10839:         my ($tmp)=keys(%curr_permissions);
10840:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
10841:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
10842:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
10843:             if (ref($curr_controls) eq 'HASH') {
10844:                 foreach my $control_item (keys(%{$curr_controls})) {
10845:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
10846:                     if (defined($todelete{$itemnum})) {
10847:                         push(@deletions,$file_name."\0".$control_item);
10848:                     } else {
10849:                         if (defined($changed_items{$itemnum})) {
10850:                             $new_control{$changed_items{$itemnum}} = $now;
10851:                             push(@deletions,$file_name."\0".$control_item);
10852:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
10853:                         } else {
10854:                             $new_control{$control_item} = $$curr_controls{$control_item};
10855:                         }
10856:                     }
10857:                 }
10858:             }
10859:         }
10860:         my ($group);
10861:         if (&is_course($domain,$user)) {
10862:             ($group,my $file) = split(/\//,$file_name,2);
10863:         }
10864:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
10865:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
10866:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
10867:         #  remove lock
10868:         my @del_lock = ($file_name."\0".'locked_access_records');
10869:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
10870:         my $sqlresult =
10871:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
10872:                                     $group);
10873:     } else {
10874:         $outcome = "error: could not obtain lockfile\n";  
10875:     }
10876:     return ($outcome,$deloutcome,\%new_values,\%translation);
10877: }
10878: 
10879: sub make_public_indefinitely {
10880:     my ($requrl) = @_;
10881:     my $now = time;
10882:     my $action = 'activate';
10883:     my $aclnum = 0;
10884:     if (&is_portfolio_url($requrl)) {
10885:         my (undef,$udom,$unum,$file_name,$group) =
10886:             &parse_portfolio_url($requrl);
10887:         my $current_perms = &get_portfile_permissions($udom,$unum);
10888:         my %access_controls = &get_access_controls($current_perms,
10889:                                                    $group,$file_name);
10890:         foreach my $key (keys(%{$access_controls{$file_name}})) {
10891:             my ($num,$scope,$end,$start) = 
10892:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
10893:             if ($scope eq 'public') {
10894:                 if ($start <= $now && $end == 0) {
10895:                     $action = 'none';
10896:                 } else {
10897:                     $action = 'update';
10898:                     $aclnum = $num;
10899:                 }
10900:                 last;
10901:             }
10902:         }
10903:         if ($action eq 'none') {
10904:              return 'ok';
10905:         } else {
10906:             my %changes;
10907:             my $newend = 0;
10908:             my $newstart = $now;
10909:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
10910:             $changes{$action}{$newkey} = {
10911:                 type => 'public',
10912:                 time => {
10913:                     start => $newstart,
10914:                     end   => $newend,
10915:                 },
10916:             };
10917:             my ($outcome,$deloutcome,$new_values,$translation) =
10918:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
10919:             return $outcome;
10920:         }
10921:     } else {
10922:         return 'invalid';
10923:     }
10924: }
10925: 
10926: #------------------------------------------------------Get Marked as Read Only
10927: 
10928: sub get_marked_as_readonly {
10929:     my ($domain,$user,$what,$group) = @_;
10930:     my $current_permissions = &get_portfile_permissions($domain,$user);
10931:     my @readonly_files;
10932:     my $cmp1=$what;
10933:     if (ref($what)) { $cmp1=join('',@{$what}) };
10934:     while (my ($file_name,$value) = each(%{$current_permissions})) {
10935:         if (defined($group)) {
10936:             if ($file_name !~ m-^\Q$group\E/-) {
10937:                 next;
10938:             }
10939:         }
10940:         if (ref($value) eq "ARRAY"){
10941:             foreach my $stored_what (@{$value}) {
10942:                 my $cmp2=$stored_what;
10943:                 if (ref($stored_what) eq 'ARRAY') {
10944:                     $cmp2=join('',@{$stored_what});
10945:                 }
10946:                 if ($cmp1 eq $cmp2) {
10947:                     push(@readonly_files, $file_name);
10948:                     last;
10949:                 } elsif (!defined($what)) {
10950:                     push(@readonly_files, $file_name);
10951:                     last;
10952:                 }
10953:             }
10954:         }
10955:     }
10956:     return @readonly_files;
10957: }
10958: #-----------------------------------------------------------Get Marked as Read Only Hash
10959: 
10960: sub get_marked_as_readonly_hash {
10961:     my ($current_permissions,$group,$what) = @_;
10962:     my %readonly_files;
10963:     while (my ($file_name,$value) = each(%{$current_permissions})) {
10964:         if (defined($group)) {
10965:             if ($file_name !~ m-^\Q$group\E/-) {
10966:                 next;
10967:             }
10968:         }
10969:         if (ref($value) eq "ARRAY"){
10970:             foreach my $stored_what (@{$value}) {
10971:                 if (ref($stored_what) eq 'ARRAY') {
10972:                     foreach my $lock_descriptor(@{$stored_what}) {
10973:                         if ($lock_descriptor eq 'graded') {
10974:                             $readonly_files{$file_name} = 'graded';
10975:                         } elsif ($lock_descriptor eq 'handback') {
10976:                             $readonly_files{$file_name} = 'handback';
10977:                         } else {
10978:                             if (!exists($readonly_files{$file_name})) {
10979:                                 $readonly_files{$file_name} = 'locked';
10980:                             }
10981:                         }
10982:                     }
10983:                 } 
10984:             }
10985:         } 
10986:     }
10987:     return %readonly_files;
10988: }
10989: # ------------------------------------------------------------ Unmark as Read Only
10990: 
10991: sub unmark_as_readonly {
10992:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
10993:     # for portfolio submissions, $what contains [$symb,$crsid] 
10994:     my ($domain,$user,$what,$file_name,$group) = @_;
10995:     $file_name = &declutter_portfile($file_name);
10996:     my $symb_crs = $what;
10997:     if (ref($what)) { $symb_crs=join('',@$what); }
10998:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
10999:     my ($tmp)=keys(%current_permissions);
11000:     if ($tmp=~/^error:/) { undef(%current_permissions); }
11001:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
11002:     foreach my $file (@readonly_files) {
11003: 	my $clean_file = &declutter_portfile($file);
11004: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
11005: 	my $current_locks = $current_permissions{$file};
11006:         my @new_locks;
11007:         my @del_keys;
11008:         if (ref($current_locks) eq "ARRAY"){
11009:             foreach my $locker (@{$current_locks}) {
11010:                 my $compare=$locker;
11011:                 if (ref($locker) eq 'ARRAY') {
11012:                     $compare=join('',@{$locker});
11013:                     if ($compare ne $symb_crs) {
11014:                         push(@new_locks, $locker);
11015:                     }
11016:                 }
11017:             }
11018:             if (scalar(@new_locks) > 0) {
11019:                 $current_permissions{$file} = \@new_locks;
11020:             } else {
11021:                 push(@del_keys, $file);
11022:                 &del('file_permissions',\@del_keys, $domain, $user);
11023:                 delete($current_permissions{$file});
11024:             }
11025:         }
11026:     }
11027:     &put('file_permissions',\%current_permissions,$domain,$user);
11028:     return;
11029: }
11030: 
11031: # ------------------------------------------------------------ Directory lister
11032: 
11033: sub dirlist {
11034:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
11035:     $uri=~s/^\///;
11036:     $uri=~s/\/$//;
11037:     my ($udom, $uname);
11038:     if ($getuserdir) {
11039:         $udom = $userdomain;
11040:         $uname = $username;
11041:     } else {
11042:         (undef,$udom,$uname)=split(/\//,$uri);
11043:         if(defined($userdomain)) {
11044:             $udom = $userdomain;
11045:         }
11046:         if(defined($username)) {
11047:             $uname = $username;
11048:         }
11049:     }
11050:     my ($dirRoot,$listing,@listing_results);
11051: 
11052:     $dirRoot = $perlvar{'lonDocRoot'};
11053:     if (defined($getpropath)) {
11054:         $dirRoot = &propath($udom,$uname);
11055:         $dirRoot =~ s/\/$//;
11056:     } elsif (defined($getuserdir)) {
11057:         my $subdir=$uname.'__';
11058:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
11059:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
11060:                    ."/$udom/$subdir/$uname";
11061:     } elsif (defined($alternateRoot)) {
11062:         $dirRoot = $alternateRoot;
11063:     }
11064: 
11065:     if($udom) {
11066:         if($uname) {
11067:             my $uhome = &homeserver($uname,$udom);
11068:             if ($uhome eq 'no_host') {
11069:                 return ([],'no_host');
11070:             }
11071:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
11072:                               .$getuserdir.':'.&escape($dirRoot)
11073:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
11074:             if ($listing eq 'unknown_cmd') {
11075:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
11076:             } else {
11077:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
11078:             }
11079:             if ($listing eq 'unknown_cmd') {
11080:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
11081:                 @listing_results = split(/:/,$listing);
11082:             } else {
11083:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
11084:             }
11085:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
11086:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
11087:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11088:                 return ([],$listing);
11089:             } else {
11090:                 return (\@listing_results);
11091:             }
11092:         } elsif(!$alternateRoot) {
11093:             my (%allusers,%listerror);
11094: 	    my %servers = &get_servers($udom,'library');
11095:  	    foreach my $tryserver (keys(%servers)) {
11096:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
11097:                                   &escape($udom),$tryserver);
11098:                 if ($listing eq 'unknown_cmd') {
11099: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
11100: 				      $udom, $tryserver);
11101:                 } else {
11102:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
11103:                 }
11104: 		if ($listing eq 'unknown_cmd') {
11105: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
11106: 				      $udom, $tryserver);
11107: 		    @listing_results = split(/:/,$listing);
11108: 		} else {
11109: 		    @listing_results =
11110: 			map { &unescape($_); } split(/:/,$listing);
11111: 		}
11112:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
11113:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
11114:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11115:                     $listerror{$tryserver} = $listing;
11116:                 } else {
11117: 		    foreach my $line (@listing_results) {
11118: 			my ($entry) = split(/&/,$line,2);
11119: 			$allusers{$entry} = 1;
11120: 		    }
11121: 		}
11122:             }
11123:             my @alluserslist=();
11124:             foreach my $user (sort(keys(%allusers))) {
11125:                 push(@alluserslist,$user.'&user');
11126:             }
11127:             if (!%listerror) {
11128:                 # no errors
11129:                 return (\@alluserslist);
11130:             } elsif (scalar(keys(%servers)) == 1) {
11131:                 # one library server, one error
11132:                 my ($key) = keys(%listerror);
11133:                 return (\@alluserslist, $listerror{$key});
11134:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
11135:                 # con_lost indicates that we might miss data from at least one
11136:                 # library server
11137:                 return (\@alluserslist, 'con_lost');
11138:             } else {
11139:                 # multiple library servers and no con_lost -> data should be
11140:                 # complete.
11141:                 return (\@alluserslist);
11142:             }
11143: 
11144:         } else {
11145:             return ([],'missing username');
11146:         }
11147:     } elsif(!defined($getpropath)) {
11148:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
11149:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
11150:         return (\@all_domains);
11151:     } else {
11152:         return ([],'missing domain');
11153:     }
11154: }
11155: 
11156: # --------------------------------------------- GetFileTimestamp
11157: # This function utilizes dirlist and returns the date stamp for
11158: # when it was last modified.  It will also return an error of -1
11159: # if an error occurs
11160: 
11161: sub GetFileTimestamp {
11162:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
11163:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
11164:     $studentName   = &LONCAPA::clean_username($studentName);
11165:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
11166:                                     undef,$getuserdir);
11167:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11168:         return -1;
11169:     }
11170:     if (ref($fileref) eq 'ARRAY') {
11171:         my @stats = split('&',$fileref->[0]);
11172:         # @stats contains first the filename, then the stat output
11173:         return $stats[10]; # so this is 10 instead of 9.
11174:     } else {
11175:         return -1;
11176:     }
11177: }
11178: 
11179: sub stat_file {
11180:     my ($uri) = @_;
11181:     $uri = &clutter_with_no_wrapper($uri);
11182: 
11183:     my ($udom,$uname,$file);
11184:     if ($uri =~ m-^/(uploaded|editupload)/-) {
11185: 	($udom,$uname,$file) =
11186: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
11187: 	$file = 'userfiles/'.$file;
11188:     }
11189:     if ($uri =~ m-^/res/-) {
11190: 	($udom,$uname) = 
11191: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
11192: 	$file = $uri;
11193:     }
11194: 
11195:     if (!$udom || !$uname || !$file) {
11196: 	# unable to handle the uri
11197: 	return ();
11198:     }
11199:     my $getpropath;
11200:     if ($file =~ /^userfiles\//) {
11201:         $getpropath = 1;
11202:     }
11203:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
11204:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11205:         return ();
11206:     } else {
11207:         if (ref($listref) eq 'ARRAY') {
11208:             my @stats = split('&',$listref->[0]);
11209: 	    shift(@stats); #filename is first
11210: 	    return @stats;
11211:         }
11212:     }
11213:     return ();
11214: }
11215: 
11216: # -------------------------------------------------------- Value of a Condition
11217: 
11218: # gets the value of a specific preevaluated condition
11219: #    stored in the string  $env{user.state.<cid>}
11220: # or looks up a condition reference in the bighash and if if hasn't
11221: # already been evaluated recurses into docondval to get the value of
11222: # the condition, then memoizing it to 
11223: #   $env{user.state.<cid>.<condition>}
11224: sub directcondval {
11225:     my $number=shift;
11226:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
11227: 	&Apache::lonuserstate::evalstate();
11228:     }
11229:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
11230: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
11231:     } elsif ($number =~ /^_/) {
11232: 	my $sub_condition;
11233: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
11234: 		&GDBM_READER(),0640)) {
11235: 	    $sub_condition=$bighash{'conditions'.$number};
11236: 	    untie(%bighash);
11237: 	}
11238: 	my $value = &docondval($sub_condition);
11239: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
11240: 	return $value;
11241:     }
11242:     if ($env{'user.state.'.$env{'request.course.id'}}) {
11243:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
11244:     } else {
11245:        return 2;
11246:     }
11247: }
11248: 
11249: # get the collection of conditions for this resource
11250: sub condval {
11251:     my $condidx=shift;
11252:     my $allpathcond='';
11253:     foreach my $cond (split(/\|/,$condidx)) {
11254: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
11255: 	    $allpathcond.=
11256: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
11257: 	}
11258:     }
11259:     $allpathcond=~s/\|$//;
11260:     return &docondval($allpathcond);
11261: }
11262: 
11263: #evaluates an expression of conditions
11264: sub docondval {
11265:     my ($allpathcond) = @_;
11266:     my $result=0;
11267:     if ($env{'request.course.id'}
11268: 	&& defined($allpathcond)) {
11269: 	my $operand='|';
11270: 	my @stack;
11271: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
11272: 	    if ($chunk eq '(') {
11273: 		push @stack,($operand,$result);
11274: 	    } elsif ($chunk eq ')') {
11275: 		my $before=pop @stack;
11276: 		if (pop @stack eq '&') {
11277: 		    $result=$result>$before?$before:$result;
11278: 		} else {
11279: 		    $result=$result>$before?$result:$before;
11280: 		}
11281: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
11282: 		$operand=$chunk;
11283: 	    } else {
11284: 		my $new=directcondval($chunk);
11285: 		if ($operand eq '&') {
11286: 		    $result=$result>$new?$new:$result;
11287: 		} else {
11288: 		    $result=$result>$new?$result:$new;
11289: 		}
11290: 	    }
11291: 	}
11292:     }
11293:     return $result;
11294: }
11295: 
11296: # ---------------------------------------------------- Devalidate courseresdata
11297: 
11298: sub devalidatecourseresdata {
11299:     my ($coursenum,$coursedomain)=@_;
11300:     my $hashid=$coursenum.':'.$coursedomain;
11301:     &devalidate_cache_new('courseres',$hashid);
11302: }
11303: 
11304: 
11305: # --------------------------------------------------- Course Resourcedata Query
11306: #
11307: #  Parameters:
11308: #      $coursenum    - Number of the course.
11309: #      $coursedomain - Domain at which the course was created.
11310: #  Returns:
11311: #     A hash of the course parameters along (I think) with timestamps
11312: #     and version info.
11313: 
11314: sub get_courseresdata {
11315:     my ($coursenum,$coursedomain)=@_;
11316:     my $coursehom=&homeserver($coursenum,$coursedomain);
11317:     my $hashid=$coursenum.':'.$coursedomain;
11318:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
11319:     my %dumpreply;
11320:     unless (defined($cached)) {
11321: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
11322: 	$result=\%dumpreply;
11323: 	my ($tmp) = keys(%dumpreply);
11324: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
11325: 	    &do_cache_new('courseres',$hashid,$result,600);
11326: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
11327: 	    return $tmp;
11328: 	} elsif ($tmp =~ /^(error)/) {
11329: 	    $result=undef;
11330: 	    &do_cache_new('courseres',$hashid,$result,600);
11331: 	}
11332:     }
11333:     return $result;
11334: }
11335: 
11336: sub devalidateuserresdata {
11337:     my ($uname,$udom)=@_;
11338:     my $hashid="$udom:$uname";
11339:     &devalidate_cache_new('userres',$hashid);
11340: }
11341: 
11342: sub get_userresdata {
11343:     my ($uname,$udom)=@_;
11344:     #most student don\'t have any data set, check if there is some data
11345:     if (&EXT_cache_status($udom,$uname)) { return undef; }
11346: 
11347:     my $hashid="$udom:$uname";
11348:     my ($result,$cached)=&is_cached_new('userres',$hashid);
11349:     if (!defined($cached)) {
11350: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
11351: 	$result=\%resourcedata;
11352: 	&do_cache_new('userres',$hashid,$result,600);
11353:     }
11354:     my ($tmp)=keys(%$result);
11355:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
11356: 	return $result;
11357:     }
11358:     #error 2 occurs when the .db doesn't exist
11359:     if ($tmp!~/error: 2 /) {
11360:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
11361: 	    &logthis("<font color=\"blue\">WARNING:".
11362: 		     " Trying to get resource data for ".
11363: 		     $uname." at ".$udom.": ".
11364: 		     $tmp."</font>");
11365:         }
11366:     } elsif ($tmp=~/error: 2 /) {
11367: 	#&EXT_cache_set($udom,$uname);
11368: 	&do_cache_new('userres',$hashid,undef,600);
11369: 	undef($tmp); # not really an error so don't send it back
11370:     }
11371:     return $tmp;
11372: }
11373: #----------------------------------------------- resdata - return resource data
11374: #  Purpose:
11375: #    Return resource data for either users or for a course.
11376: #  Parameters:
11377: #     $name      - Course/user name.
11378: #     $domain    - Name of the domain the user/course is registered on.
11379: #     $type      - Type of thing $name is (must be 'course' or 'user')
11380: #     @which     - Array of names of resources desired.
11381: #  Returns:
11382: #     The value of the first reasource in @which that is found in the
11383: #     resource hash.
11384: #  Exceptional Conditions:
11385: #     If the $type passed in is not valid (not the string 'course' or 
11386: #     'user', an undefined  reference is returned.
11387: #     If none of the resources are found, an undef is returned
11388: sub resdata {
11389:     my ($name,$domain,$type,@which)=@_;
11390:     my $result;
11391:     if ($type eq 'course') {
11392: 	$result=&get_courseresdata($name,$domain);
11393:     } elsif ($type eq 'user') {
11394: 	$result=&get_userresdata($name,$domain);
11395:     }
11396:     if (!ref($result)) { return $result; }    
11397:     foreach my $item (@which) {
11398: 	if (defined($result->{$item->[0]})) {
11399: 	    return [$result->{$item->[0]},$item->[1]];
11400:         }
11401:     }
11402:     return undef;
11403: }
11404: 
11405: sub get_domain_lti {
11406:     my ($cdom,$context) = @_;
11407:     my ($name,%lti);
11408:     if ($context eq 'consumer') {
11409:         $name = 'ltitools';
11410:     } elsif ($context eq 'provider') {
11411:         $name = 'lti';
11412:     } else {
11413:         return %lti;
11414:     }
11415:     my ($result,$cached)=&is_cached_new($name,$cdom);
11416:     if (defined($cached)) {
11417:         if (ref($result) eq 'HASH') {
11418:             %lti = %{$result};
11419:         }
11420:     } else {
11421:         my %domconfig = &get_dom('configuration',[$name],$cdom);
11422:         if (ref($domconfig{$name}) eq 'HASH') {
11423:             %lti = %{$domconfig{$name}};
11424:             my %encdomconfig = &get_dom('encconfig',[$name],$cdom);
11425:             if (ref($encdomconfig{$name}) eq 'HASH') {
11426:                 foreach my $id (keys(%lti)) {
11427:                     if (ref($encdomconfig{$name}{$id}) eq 'HASH') {
11428:                         foreach my $item ('key','secret') {
11429:                             $lti{$id}{$item} = $encdomconfig{$name}{$id}{$item};
11430:                         }
11431:                     }
11432:                 }
11433:             }
11434:         }
11435:         my $cachetime = 24*60*60;
11436:         &do_cache_new($name,$cdom,\%lti,$cachetime);
11437:     }
11438:     return %lti;
11439: }
11440: 
11441: sub get_numsuppfiles {
11442:     my ($cnum,$cdom,$ignorecache)=@_;
11443:     my $hashid=$cnum.':'.$cdom;
11444:     my ($suppcount,$cached);
11445:     unless ($ignorecache) {
11446:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
11447:     }
11448:     unless (defined($cached)) {
11449:         my $chome=&homeserver($cnum,$cdom);
11450:         unless ($chome eq 'no_host') {
11451:             ($suppcount,my $errors) = (0,0);
11452:             my $suppmap = 'supplemental.sequence';
11453:             ($suppcount,$errors) =
11454:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
11455:         }
11456:         &do_cache_new('suppcount',$hashid,$suppcount,600);
11457:     }
11458:     return $suppcount;
11459: }
11460: 
11461: #
11462: # EXT resource caching routines
11463: #
11464: 
11465: sub clear_EXT_cache_status {
11466:     &delenv('cache.EXT.');
11467: }
11468: 
11469: sub EXT_cache_status {
11470:     my ($target_domain,$target_user) = @_;
11471:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
11472:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
11473:         # We know already the user has no data
11474:         return 1;
11475:     } else {
11476:         return 0;
11477:     }
11478: }
11479: 
11480: sub EXT_cache_set {
11481:     my ($target_domain,$target_user) = @_;
11482:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
11483:     #&appenv({$cachename => time});
11484: }
11485: 
11486: # --------------------------------------------------------- Value of a Variable
11487: sub EXT {
11488: 
11489:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
11490:     unless ($varname) { return ''; }
11491:     #get real user name/domain, courseid and symb
11492:     my $courseid;
11493:     my $publicuser;
11494:     if ($symbparm) {
11495: 	$symbparm=&get_symb_from_alias($symbparm);
11496:     }
11497:     if (!($uname && $udom)) {
11498:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
11499:       if (!$symbparm) {	$symbparm=$cursymb; }
11500:     } else {
11501: 	$courseid=$env{'request.course.id'};
11502:     }
11503:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
11504:     my $rest;
11505:     if (defined($therest[0])) {
11506:        $rest=join('.',@therest);
11507:     } else {
11508:        $rest='';
11509:     }
11510: 
11511:     my $qualifierrest=$qualifier;
11512:     if ($rest) { $qualifierrest.='.'.$rest; }
11513:     my $spacequalifierrest=$space;
11514:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
11515:     if ($realm eq 'user') {
11516: # --------------------------------------------------------------- user.resource
11517: 	if ($space eq 'resource') {
11518: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
11519: 		  || defined($Apache::lonhomework::parsing_a_task))
11520: 		 &&
11521: 		 ($symbparm eq &symbread()) ) {	
11522: 		# if we are in the middle of processing the resource the
11523: 		# get the value we are planning on committing
11524:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
11525:                     return $Apache::lonhomework::results{$qualifierrest};
11526:                 } else {
11527:                     return $Apache::lonhomework::history{$qualifierrest};
11528:                 }
11529: 	    } else {
11530: 		my %restored;
11531: 		if ($publicuser || $env{'request.state'} eq 'construct') {
11532: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
11533: 		} else {
11534: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
11535: 		}
11536: 		return $restored{$qualifierrest};
11537: 	    }
11538: # ----------------------------------------------------------------- user.access
11539:         } elsif ($space eq 'access') {
11540: 	    # FIXME - not supporting calls for a specific user
11541:             return &allowed($qualifier,$rest);
11542: # ------------------------------------------ user.preferences, user.environment
11543:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
11544: 	    if (($uname eq $env{'user.name'}) &&
11545: 		($udom eq $env{'user.domain'})) {
11546: 		return $env{join('.',('environment',$qualifierrest))};
11547: 	    } else {
11548: 		my %returnhash;
11549: 		if (!$publicuser) {
11550: 		    %returnhash=&userenvironment($udom,$uname,
11551: 						 $qualifierrest);
11552: 		}
11553: 		return $returnhash{$qualifierrest};
11554: 	    }
11555: # ----------------------------------------------------------------- user.course
11556:         } elsif ($space eq 'course') {
11557: 	    # FIXME - not supporting calls for a specific user
11558:             return $env{join('.',('request.course',$qualifier))};
11559: # ------------------------------------------------------------------- user.role
11560:         } elsif ($space eq 'role') {
11561: 	    # FIXME - not supporting calls for a specific user
11562:             my ($role,$where)=split(/\./,$env{'request.role'});
11563:             if ($qualifier eq 'value') {
11564: 		return $role;
11565:             } elsif ($qualifier eq 'extent') {
11566:                 return $where;
11567:             }
11568: # ----------------------------------------------------------------- user.domain
11569:         } elsif ($space eq 'domain') {
11570:             return $udom;
11571: # ------------------------------------------------------------------- user.name
11572:         } elsif ($space eq 'name') {
11573:             return $uname;
11574: # ---------------------------------------------------- Any other user namespace
11575:         } else {
11576: 	    my %reply;
11577: 	    if (!$publicuser) {
11578: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
11579: 	    }
11580: 	    return $reply{$qualifierrest};
11581:         }
11582:     } elsif ($realm eq 'query') {
11583: # ---------------------------------------------- pull stuff out of query string
11584:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
11585: 						[$spacequalifierrest]);
11586: 	return $env{'form.'.$spacequalifierrest}; 
11587:    } elsif ($realm eq 'request') {
11588: # ------------------------------------------------------------- request.browser
11589:         if ($space eq 'browser') {
11590:             return $env{'browser.'.$qualifier};
11591: # ------------------------------------------------------------ request.filename
11592:         } else {
11593:             return $env{'request.'.$spacequalifierrest};
11594:         }
11595:     } elsif ($realm eq 'course') {
11596: # ---------------------------------------------------------- course.description
11597:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
11598:     } elsif ($realm eq 'resource') {
11599: 
11600: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
11601: 	    if (!$symbparm) { $symbparm=&symbread(); }
11602: 	}
11603: 
11604:         if ($qualifier eq '') {
11605: 	    if ($space eq 'title') {
11606: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
11607: 	        return &gettitle($symbparm);
11608: 	    }
11609: 	
11610: 	    if ($space eq 'map') {
11611: 	        my ($map) = &decode_symb($symbparm);
11612: 	        return &symbread($map);
11613: 	    }
11614:             if ($space eq 'maptitle') {
11615:                 my ($map) = &decode_symb($symbparm);
11616:                 return &gettitle($map);
11617:             }
11618: 	    if ($space eq 'filename') {
11619: 	        if ($symbparm) {
11620: 		    return &clutter((&decode_symb($symbparm))[2]);
11621: 	        }
11622: 	        return &hreflocation('',$env{'request.filename'});
11623: 	    }
11624: 
11625:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
11626:                 if ($space eq 'visibleparts') {
11627:                     my $navmap = Apache::lonnavmaps::navmap->new();
11628:                     my $item;
11629:                     if (ref($navmap)) {
11630:                         my $res = $navmap->getBySymb($symbparm);
11631:                         my $parts = $res->parts();
11632:                         if (ref($parts) eq 'ARRAY') {
11633:                             $item = join(',',@{$parts});
11634:                         }
11635:                         undef($navmap);
11636:                     }
11637:                     return $item;
11638:                 }
11639:             }
11640:         }
11641: 
11642: 	my ($section, $group, @groups);
11643: 	my ($courselevelm,$courselevel);
11644:         if (($courseid eq '') && ($cid)) {
11645:             $courseid = $cid;
11646:         }
11647: 	if (($symbparm && $courseid) && 
11648: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
11649: 
11650: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
11651: 
11652: # ----------------------------------------------------- Cascading lookup scheme
11653: 	    my $symbp=$symbparm;
11654: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
11655: 
11656: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
11657: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
11658: 
11659: 	    if (($env{'user.name'} eq $uname) &&
11660: 		($env{'user.domain'} eq $udom)) {
11661: 		$section=$env{'request.course.sec'};
11662:                 @groups = split(/:/,$env{'request.course.groups'});  
11663:                 @groups=&sort_course_groups($courseid,@groups); 
11664: 	    } else {
11665: 		if (! defined($usection)) {
11666: 		    $section=&getsection($udom,$uname,$courseid);
11667: 		} else {
11668: 		    $section = $usection;
11669: 		}
11670:                 @groups = &get_users_groups($udom,$uname,$courseid);
11671: 	    }
11672: 
11673: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
11674: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
11675: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
11676: 
11677: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
11678: 	    my $courselevelr=$courseid.'.'.$symbparm;
11679: 	    $courselevelm=$courseid.'.'.$mapparm;
11680: 
11681: # ----------------------------------------------------------- first, check user
11682: 
11683: 	    my $userreply=&resdata($uname,$udom,'user',
11684: 				       ([$courselevelr,'resource'],
11685: 					[$courselevelm,'map'     ],
11686: 					[$courselevel, 'course'  ]));
11687: 	    if (defined($userreply)) { return &get_reply($userreply); }
11688: 
11689: # ------------------------------------------------ second, check some of course
11690:             my $coursereply;
11691:             if (@groups > 0) {
11692:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
11693:                                        $mapparm,$spacequalifierrest);
11694:                 if (defined($coursereply)) { return &get_reply($coursereply); }
11695:             }
11696: 
11697: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
11698: 				  $env{'course.'.$courseid.'.domain'},
11699: 				  'course',
11700: 				  ([$seclevelr,   'resource'],
11701: 				   [$seclevelm,   'map'     ],
11702: 				   [$seclevel,    'course'  ],
11703: 				   [$courselevelr,'resource']));
11704: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
11705: 
11706: # ------------------------------------------------------ third, check map parms
11707: 	    my %parmhash=();
11708: 	    my $thisparm='';
11709: 	    if (tie(%parmhash,'GDBM_File',
11710: 		    $env{'request.course.fn'}.'_parms.db',
11711: 		    &GDBM_READER(),0640)) {
11712: 		$thisparm=$parmhash{$symbparm};
11713: 		untie(%parmhash);
11714: 	    }
11715: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
11716: 	}
11717: # ------------------------------------------ fourth, look in resource metadata
11718: 
11719: 	$spacequalifierrest=~s/\./\_/;
11720: 	my $filename;
11721: 	if (!$symbparm) { $symbparm=&symbread(); }
11722: 	if ($symbparm) {
11723: 	    $filename=(&decode_symb($symbparm))[2];
11724: 	} else {
11725: 	    $filename=$env{'request.filename'};
11726: 	}
11727: 	my $metadata=&metadata($filename,$spacequalifierrest);
11728: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
11729: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
11730: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
11731: 
11732: # ---------------------------------------------- fourth, look in rest of course
11733: 	if ($symbparm && defined($courseid) && 
11734: 	    $courseid eq $env{'request.course.id'}) {
11735: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
11736: 				     $env{'course.'.$courseid.'.domain'},
11737: 				     'course',
11738: 				     ([$courselevelm,'map'   ],
11739: 				      [$courselevel, 'course']));
11740: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
11741: 	}
11742: # ------------------------------------------------------------------ Cascade up
11743: 	unless ($space eq '0') {
11744: 	    my @parts=split(/_/,$space);
11745: 	    my $id=pop(@parts);
11746: 	    my $part=join('_',@parts);
11747: 	    if ($part eq '') { $part='0'; }
11748: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
11749: 				 $symbparm,$udom,$uname,$section,1);
11750: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
11751: 	}
11752: 	if ($recurse) { return undef; }
11753: 	my $pack_def=&packages_tab_default($filename,$varname);
11754: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
11755: # ---------------------------------------------------- Any other user namespace
11756:     } elsif ($realm eq 'environment') {
11757: # ----------------------------------------------------------------- environment
11758: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
11759: 	    return $env{'environment.'.$spacequalifierrest};
11760: 	} else {
11761: 	    if ($uname eq 'anonymous' && $udom eq '') {
11762: 		return '';
11763: 	    }
11764: 	    my %returnhash=&userenvironment($udom,$uname,
11765: 					    $spacequalifierrest);
11766: 	    return $returnhash{$spacequalifierrest};
11767: 	}
11768:     } elsif ($realm eq 'system') {
11769: # ----------------------------------------------------------------- system.time
11770: 	if ($space eq 'time') {
11771: 	    return time;
11772:         }
11773:     } elsif ($realm eq 'server') {
11774: # ----------------------------------------------------------------- system.time
11775: 	if ($space eq 'name') {
11776: 	    return $ENV{'SERVER_NAME'};
11777:         }
11778:     }
11779:     return '';
11780: }
11781: 
11782: sub get_reply {
11783:     my ($reply_value) = @_;
11784:     if (ref($reply_value) eq 'ARRAY') {
11785:         if (wantarray) {
11786: 	    return @$reply_value;
11787:         }
11788:         return $reply_value->[0];
11789:     } else {
11790:         return $reply_value;
11791:     }
11792: }
11793: 
11794: sub check_group_parms {
11795:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
11796:     my @groupitems = ();
11797:     my $resultitem;
11798:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
11799:     foreach my $group (@{$groups}) {
11800:         foreach my $level (@levels) {
11801:              my $item = $courseid.'.['.$group.'].'.$level->[0];
11802:              push(@groupitems,[$item,$level->[1]]);
11803:         }
11804:     }
11805:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
11806:                             $env{'course.'.$courseid.'.domain'},
11807:                                      'course',@groupitems);
11808:     return $coursereply;
11809: }
11810: 
11811: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
11812:     my ($courseid,@groups) = @_;
11813:     @groups = sort(@groups);
11814:     return @groups;
11815: }
11816: 
11817: sub packages_tab_default {
11818:     my ($uri,$varname)=@_;
11819:     my (undef,$part,$name)=split(/\./,$varname);
11820: 
11821:     my (@extension,@specifics,$do_default);
11822:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
11823: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
11824: 	if ($pack_type eq 'default') {
11825: 	    $do_default=1;
11826: 	} elsif ($pack_type eq 'extension') {
11827: 	    push(@extension,[$package,$pack_type,$pack_part]);
11828: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
11829: 	    # only look at packages defaults for packages that this id is
11830: 	    push(@specifics,[$package,$pack_type,$pack_part]);
11831: 	}
11832:     }
11833:     # first look for a package that matches the requested part id
11834:     foreach my $package (@specifics) {
11835: 	my (undef,$pack_type,$pack_part)=@{$package};
11836: 	next if ($pack_part ne $part);
11837: 	if (defined($packagetab{"$pack_type&$name&default"})) {
11838: 	    return $packagetab{"$pack_type&$name&default"};
11839: 	}
11840:     }
11841:     # look for any possible matching non extension_ package
11842:     foreach my $package (@specifics) {
11843: 	my (undef,$pack_type,$pack_part)=@{$package};
11844: 	if (defined($packagetab{"$pack_type&$name&default"})) {
11845: 	    return $packagetab{"$pack_type&$name&default"};
11846: 	}
11847: 	if ($pack_type eq 'part') { $pack_part='0'; }
11848: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
11849: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
11850: 	}
11851:     }
11852:     # look for any posible extension_ match
11853:     foreach my $package (@extension) {
11854: 	my ($package,$pack_type)=@{$package};
11855: 	if (defined($packagetab{"$pack_type&$name&default"})) {
11856: 	    return $packagetab{"$pack_type&$name&default"};
11857: 	}
11858: 	if (defined($packagetab{$package."&$name&default"})) {
11859: 	    return $packagetab{$package."&$name&default"};
11860: 	}
11861:     }
11862:     # look for a global default setting
11863:     if ($do_default && defined($packagetab{"default&$name&default"})) {
11864: 	return $packagetab{"default&$name&default"};
11865:     }
11866:     return undef;
11867: }
11868: 
11869: sub add_prefix_and_part {
11870:     my ($prefix,$part)=@_;
11871:     my $keyroot;
11872:     if (defined($prefix) && $prefix !~ /^__/) {
11873: 	# prefix that has a part already
11874: 	$keyroot=$prefix;
11875:     } elsif (defined($prefix)) {
11876: 	# prefix that is missing a part
11877: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
11878:     } else {
11879: 	# no prefix at all
11880: 	if (defined($part)) { $keyroot='_'.$part; }
11881:     }
11882:     return $keyroot;
11883: }
11884: 
11885: # ---------------------------------------------------------------- Get metadata
11886: 
11887: my %metaentry;
11888: my %importedpartids;
11889: my %importedrespids;
11890: sub metadata {
11891:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
11892:     $uri=&declutter($uri);
11893:     # if it is a non metadata possible uri return quickly
11894:     if (($uri eq '') || 
11895: 	(($uri =~ m|^/*adm/|) && 
11896: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
11897:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
11898: 	return undef;
11899:     }
11900:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
11901: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
11902: 	return undef;
11903:     }
11904:     my $filename=$uri;
11905:     $uri=~s/\.meta$//;
11906: #
11907: # Is the metadata already cached?
11908: # Look at timestamp of caching
11909: # Everything is cached by the main uri, libraries are never directly cached
11910: #
11911:     if (!defined($liburi)) {
11912: 	my ($result,$cached)=&is_cached_new('meta',$uri);
11913: 	if (defined($cached)) { return $result->{':'.$what}; }
11914:     }
11915:     {
11916: # Imported parts would go here
11917:         my @origfiletagids=();
11918:         my $importedparts=0;
11919: 
11920: # Imported responseids would go here
11921:         my $importedresponses=0;
11922: #
11923: # Is this a recursive call for a library?
11924: #
11925: #	if (! exists($metacache{$uri})) {
11926: #	    $metacache{$uri}={};
11927: #	}
11928: 	my $cachetime = 60*60;
11929:         if ($liburi) {
11930: 	    $liburi=&declutter($liburi);
11931:             $filename=$liburi;
11932:         } else {
11933: 	    &devalidate_cache_new('meta',$uri);
11934: 	    undef(%metaentry);
11935: 	}
11936:         my %metathesekeys=();
11937:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
11938: 	my $metastring;
11939: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
11940: 	    my $which = &hreflocation('','/'.($liburi || $uri));
11941: 	    $metastring = 
11942: 		&Apache::lonnet::ssi_body($which,
11943: 					  ('grade_target' => 'meta'));
11944: 	    $cachetime = 1; # only want this cached in the child not long term
11945: 	} elsif (($uri !~ m -^(editupload)/-) && 
11946:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
11947: 	    my $file=&filelocation('',&clutter($filename));
11948: 	    #push(@{$metaentry{$uri.'.file'}},$file);
11949: 	    $metastring=&getfile($file);
11950: 	}
11951:         my $parser=HTML::LCParser->new(\$metastring);
11952:         my $token;
11953:         undef %metathesekeys;
11954:         while ($token=$parser->get_token) {
11955: 	    if ($token->[0] eq 'S') {
11956: 		if (defined($token->[2]->{'package'})) {
11957: #
11958: # This is a package - get package info
11959: #
11960: 		    my $package=$token->[2]->{'package'};
11961: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11962: 		    if (defined($token->[2]->{'id'})) { 
11963: 			$keyroot.='_'.$token->[2]->{'id'}; 
11964: 		    }
11965: 		    if ($metaentry{':packages'}) {
11966: 			$metaentry{':packages'}.=','.$package.$keyroot;
11967: 		    } else {
11968: 			$metaentry{':packages'}=$package.$keyroot;
11969: 		    }
11970: 		    foreach my $pack_entry (keys(%packagetab)) {
11971: 			my $part=$keyroot;
11972: 			$part=~s/^\_//;
11973: 			if ($pack_entry=~/^\Q$package\E\&/ || 
11974: 			    $pack_entry=~/^\Q$package\E_0\&/) {
11975: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
11976: 			    # ignore package.tab specified default values
11977:                             # here &package_tab_default() will fetch those
11978: 			    if ($subp eq 'default') { next; }
11979: 			    my $value=$packagetab{$pack_entry};
11980: 			    my $unikey;
11981: 			    if ($pack =~ /_0$/) {
11982: 				$unikey='parameter_0_'.$name;
11983: 				$part=0;
11984: 			    } else {
11985: 				$unikey='parameter'.$keyroot.'_'.$name;
11986: 			    }
11987: 			    if ($subp eq 'display') {
11988: 				$value.=' [Part: '.$part.']';
11989: 			    }
11990: 			    $metaentry{':'.$unikey.'.part'}=$part;
11991: 			    $metathesekeys{$unikey}=1;
11992: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
11993: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
11994: 			    }
11995: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
11996: 				$metaentry{':'.$unikey}=
11997: 				    $metaentry{':'.$unikey.'.default'};
11998: 			    }
11999: 			}
12000: 		    }
12001: 		} else {
12002: #
12003: # This is not a package - some other kind of start tag
12004: #
12005: 		    my $entry=$token->[1];
12006: 		    my $unikey='';
12007: 
12008: 		    if ($entry eq 'import') {
12009: #
12010: # Importing a library here
12011: #
12012:                         my $location=$parser->get_text('/import');
12013:                         my $dir=$filename;
12014:                         $dir=~s|[^/]*$||;
12015:                         $location=&filelocation($dir,$location);
12016: 
12017:                         my $importid=$token->[2]->{'id'};
12018:                         my $importmode=$token->[2]->{'importmode'};
12019: #
12020: # Check metadata for imported file to
12021: # see if it contained response items
12022: #
12023:                         my %currmetaentry = %metaentry;
12024:                         my $libresponseorder = &metadata($location,'responseorder');
12025:                         my $origfile;
12026:                         if ($libresponseorder ne '') {
12027:                             if ($#origfiletagids<0) {
12028:                                 undef(%importedrespids);
12029:                                 undef(%importedpartids);
12030:                             }
12031:                             @{$importedrespids{$importid}} = split(/\s*,\s*/,$libresponseorder);
12032:                             if (@{$importedrespids{$importid}} > 0) {
12033:                                 $importedresponses = 1;
12034: # We need to get the original file and the imported file to get the response order correct
12035: # Load and inspect original file
12036:                                 if ($#origfiletagids<0) {
12037:                                     my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
12038:                                     $origfile=&getfile($origfilelocation);
12039:                                     @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12040:                                 }
12041:                             }
12042:                         }
12043: # Do not overwrite contents of %metaentry hash for resource itself with 
12044: # hash populated for imported library file
12045:                         %metaentry = %currmetaentry;
12046:                         undef(%currmetaentry);
12047:                         if ($importmode eq 'problem') {
12048: # Import as problem/response
12049:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
12050:                         } elsif ($importmode eq 'part') {
12051: # Import as part(s)
12052:                            $importedparts=1;
12053: # We need to get the original file and the imported file to get the part order correct
12054: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
12055: # Load and inspect original file if we didn't do that already
12056:                            if ($#origfiletagids<0) {
12057:                                undef(%importedrespids);
12058:                                undef(%importedpartids);
12059:                                if ($origfile eq '') {
12060:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
12061:                                    $origfile=&getfile($origfilelocation);
12062:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12063:                                }
12064:                            }
12065: 
12066: # Load and inspect imported file
12067:                            my $impfile=&getfile($location);
12068:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12069:                            if ($#impfilepartids>=0) {
12070: # This problem had parts
12071:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
12072:                            } else {
12073: # Importing by turning a single problem into a problem part
12074: # It gets the import-tags ID as part-ID
12075:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
12076:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
12077:                            }
12078:                         } else {
12079: # Normal import
12080:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
12081:                            if (defined($token->[2]->{'id'})) {
12082:                               $unikey.='_'.$token->[2]->{'id'};
12083:                            }
12084:                         }
12085: 
12086: 			if ($depthcount<20) {
12087: 			    my $metadata = 
12088: 				&metadata($uri,'keys', $location,$unikey,
12089: 					  $depthcount+1);
12090: 			    foreach my $meta (split(',',$metadata)) {
12091: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
12092: 				$metathesekeys{$meta}=1;
12093: 			    }
12094: 			
12095:                         }
12096: 		    } else {
12097: #
12098: # Not importing, some other kind of non-package, non-library start tag
12099: # 
12100:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
12101:                         if (defined($token->[2]->{'id'})) {
12102:                             $unikey.='_'.$token->[2]->{'id'};
12103:                         }
12104: 			if (defined($token->[2]->{'name'})) { 
12105: 			    $unikey.='_'.$token->[2]->{'name'}; 
12106: 			}
12107: 			$metathesekeys{$unikey}=1;
12108: 			foreach my $param (@{$token->[3]}) {
12109: 			    $metaentry{':'.$unikey.'.'.$param} =
12110: 				$token->[2]->{$param};
12111: 			}
12112: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
12113: 			my $default=$metaentry{':'.$unikey.'.default'};
12114: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
12115: 		 # only ws inside the tag, and not in default, so use default
12116: 		 # as value
12117: 			    $metaentry{':'.$unikey}=$default;
12118: 			} elsif ( $internaltext =~ /\S/ ) {
12119: 		  # something interesting inside the tag
12120: 			    $metaentry{':'.$unikey}=$internaltext;
12121: 			} else {
12122: 		  # no interesting values, don't set a default
12123: 			}
12124: # end of not-a-package not-a-library import
12125: 		    }
12126: # end of not-a-package start tag
12127: 		}
12128: # the next is the end of "start tag"
12129: 	    }
12130: 	}
12131: 	my ($extension) = ($uri =~ /\.(\w+)$/);
12132: 	$extension = lc($extension);
12133: 	if ($extension eq 'htm') { $extension='html'; }
12134: 
12135: 	foreach my $key (keys(%packagetab)) {
12136: 	    #no specific packages #how's our extension
12137: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
12138: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
12139: 					 \%metathesekeys);
12140: 	}
12141: 
12142: 	if (!exists($metaentry{':packages'})
12143: 	    || $packagetab{"import_defaults&extension_$extension"}) {
12144: 	    foreach my $key (keys(%packagetab)) {
12145: 		#no specific packages well let's get default then
12146: 		if ($key!~/^default&/) { next; }
12147: 		&metadata_create_package_def($uri,$key,'default',
12148: 					     \%metathesekeys);
12149: 	    }
12150: 	}
12151: # are there custom rights to evaluate
12152: 	if ($metaentry{':copyright'} eq 'custom') {
12153: 
12154:     #
12155:     # Importing a rights file here
12156:     #
12157: 	    unless ($depthcount) {
12158: 		my $location=$metaentry{':customdistributionfile'};
12159: 		my $dir=$filename;
12160: 		$dir=~s|[^/]*$||;
12161: 		$location=&filelocation($dir,$location);
12162: 		my $rights_metadata =
12163: 		    &metadata($uri,'keys',$location,'_rights',
12164: 			      $depthcount+1);
12165: 		foreach my $rights (split(',',$rights_metadata)) {
12166: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
12167: 		    $metathesekeys{$rights}=1;
12168: 		}
12169: 	    }
12170: 	}
12171: 	# uniqifiy package listing
12172: 	my %seen;
12173: 	my @uniq_packages =
12174: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
12175: 	$metaentry{':packages'} = join(',',@uniq_packages);
12176: 
12177:         if (($importedresponses) || ($importedparts)) {
12178:             if ($importedparts) {
12179: # We had imported parts and need to rebuild partorder
12180:                 $metaentry{':partorder'}='';
12181:                 $metathesekeys{'partorder'}=1;
12182:             }
12183:             if ($importedresponses) {
12184: # We had imported responses and need to rebuild responseorder
12185:                 $metaentry{':responseorder'}='';
12186:                 $metathesekeys{'responseorder'}=1;
12187:             }
12188:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
12189:                 my $origid = $origfiletagids[$index+1];
12190:                 if ($origfiletagids[$index] eq 'part') {
12191: # Original part, part of the problem
12192:                     if ($importedparts) {
12193:                         $metaentry{':partorder'}.=','.$origid;
12194:                     }
12195:                 } elsif ($origfiletagids[$index] eq 'import') {
12196:                     if ($importedparts) {
12197: # We have imported parts at this position
12198:                         $metaentry{':partorder'}.=','.$importedpartids{$origid};
12199:                     }
12200:                     if ($importedresponses) {
12201: # We have imported responses at this position
12202:                         if (ref($importedrespids{$origid}) eq 'ARRAY') {
12203:                             $metaentry{':responseorder'}.=','.join(',',map { $origid.'_'.$_ } @{$importedrespids{$origid}});
12204:                         }
12205:                     }
12206:                 } else {
12207: # Original response item, part of the problem
12208:                     if ($importedresponses) {
12209:                         $metaentry{':responseorder'}.=','.$origid;
12210:                     }
12211:                 }
12212:             }
12213:             if ($importedparts) {
12214:                 $metaentry{':partorder'}=~s/^\,//;
12215:             }
12216:             if ($importedresponses) {
12217:                 $metaentry{':responseorder'}=~s/^\,//;
12218:             }
12219:         }
12220: 
12221: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
12222: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
12223: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
12224: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
12225: # this is the end of "was not already recently cached
12226:     }
12227:     return $metaentry{':'.$what};
12228: }
12229: 
12230: sub metadata_create_package_def {
12231:     my ($uri,$key,$package,$metathesekeys)=@_;
12232:     my ($pack,$name,$subp)=split(/\&/,$key);
12233:     if ($subp eq 'default') { next; }
12234:     
12235:     if (defined($metaentry{':packages'})) {
12236: 	$metaentry{':packages'}.=','.$package;
12237:     } else {
12238: 	$metaentry{':packages'}=$package;
12239:     }
12240:     my $value=$packagetab{$key};
12241:     my $unikey;
12242:     $unikey='parameter_0_'.$name;
12243:     $metaentry{':'.$unikey.'.part'}=0;
12244:     $$metathesekeys{$unikey}=1;
12245:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
12246: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
12247:     }
12248:     if (defined($metaentry{':'.$unikey.'.default'})) {
12249: 	$metaentry{':'.$unikey}=
12250: 	    $metaentry{':'.$unikey.'.default'};
12251:     }
12252: }
12253: 
12254: sub metadata_generate_part0 {
12255:     my ($metadata,$metacache,$uri) = @_;
12256:     my %allnames;
12257:     foreach my $metakey (keys(%$metadata)) {
12258: 	if ($metakey=~/^parameter\_(.*)/) {
12259: 	  my $part=$$metacache{':'.$metakey.'.part'};
12260: 	  my $name=$$metacache{':'.$metakey.'.name'};
12261: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
12262: 	    $allnames{$name}=$part;
12263: 	  }
12264: 	}
12265:     }
12266:     foreach my $name (keys(%allnames)) {
12267:       $$metadata{"parameter_0_$name"}=1;
12268:       my $key=":parameter_0_$name";
12269:       $$metacache{"$key.part"}='0';
12270:       $$metacache{"$key.name"}=$name;
12271:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
12272: 					   $allnames{$name}.'_'.$name.
12273: 					   '.type'};
12274:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
12275: 			     '.display'};
12276:       my $expr='[Part: '.$allnames{$name}.']';
12277:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
12278:       $$metacache{"$key.display"}=$olddis;
12279:     }
12280: }
12281: 
12282: # ------------------------------------------------------ Devalidate title cache
12283: 
12284: sub devalidate_title_cache {
12285:     my ($url)=@_;
12286:     if (!$env{'request.course.id'}) { return; }
12287:     my $symb=&symbread($url);
12288:     if (!$symb) { return; }
12289:     my $key=$env{'request.course.id'}."\0".$symb;
12290:     &devalidate_cache_new('title',$key);
12291: }
12292: 
12293: # ------------------------------------------------- Get the title of a course
12294: 
12295: sub current_course_title {
12296:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
12297: }
12298: # ------------------------------------------------- Get the title of a resource
12299: 
12300: sub gettitle {
12301:     my $urlsymb=shift;
12302:     my $symb=&symbread($urlsymb);
12303:     if ($symb) {
12304: 	my $key=$env{'request.course.id'}."\0".$symb;
12305: 	my ($result,$cached)=&is_cached_new('title',$key);
12306: 	if (defined($cached)) { 
12307: 	    return $result;
12308: 	}
12309: 	my ($map,$resid,$url)=&decode_symb($symb);
12310: 	my $title='';
12311: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
12312: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
12313: 	} else {
12314: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12315: 		    &GDBM_READER(),0640)) {
12316: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
12317: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
12318: 		untie(%bighash);
12319: 	    }
12320: 	}
12321: 	$title=~s/\&colon\;/\:/gs;
12322: 	if ($title) {
12323: # Remember both $symb and $title for dynamic metadata
12324:             $accesshash{$symb.'___crstitle'}=$title;
12325:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
12326: # Cache this title and then return it
12327: 	    return &do_cache_new('title',$key,$title,600);
12328: 	}
12329: 	$urlsymb=$url;
12330:     }
12331:     my $title=&metadata($urlsymb,'title');
12332:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
12333:     return $title;
12334: }
12335: 
12336: sub get_slot {
12337:     my ($which,$cnum,$cdom)=@_;
12338:     if (!$cnum || !$cdom) {
12339: 	(undef,my $courseid)=&whichuser();
12340: 	$cdom=$env{'course.'.$courseid.'.domain'};
12341: 	$cnum=$env{'course.'.$courseid.'.num'};
12342:     }
12343:     my $key=join("\0",'slots',$cdom,$cnum,$which);
12344:     my %slotinfo;
12345:     if (exists($remembered{$key})) {
12346: 	$slotinfo{$which} = $remembered{$key};
12347:     } else {
12348: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
12349: 	&Apache::lonhomework::showhash(%slotinfo);
12350: 	my ($tmp)=keys(%slotinfo);
12351: 	if ($tmp=~/^error:/) { return (); }
12352: 	$remembered{$key} = $slotinfo{$which};
12353:     }
12354:     if (ref($slotinfo{$which}) eq 'HASH') {
12355: 	return %{$slotinfo{$which}};
12356:     }
12357:     return $slotinfo{$which};
12358: }
12359: 
12360: sub get_reservable_slots {
12361:     my ($cnum,$cdom,$uname,$udom) = @_;
12362:     my $now = time;
12363:     my $reservable_info;
12364:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
12365:     if (exists($remembered{$key})) {
12366:         $reservable_info = $remembered{$key};
12367:     } else {
12368:         my %resv;
12369:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
12370:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
12371:         $reservable_info = \%resv;
12372:         $remembered{$key} = $reservable_info;
12373:     }
12374:     return $reservable_info;
12375: }
12376: 
12377: sub get_course_slots {
12378:     my ($cnum,$cdom) = @_;
12379:     my $hashid=$cnum.':'.$cdom;
12380:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
12381:     if (defined($cached)) {
12382:         if (ref($result) eq 'HASH') {
12383:             return %{$result};
12384:         }
12385:     } else {
12386:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
12387:         my ($tmp) = keys(%slots);
12388:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
12389:             &do_cache_new('allslots',$hashid,\%slots,600);
12390:             return %slots;
12391:         }
12392:     }
12393:     return;
12394: }
12395: 
12396: sub devalidate_slots_cache {
12397:     my ($cnum,$cdom)=@_;
12398:     my $hashid=$cnum.':'.$cdom;
12399:     &devalidate_cache_new('allslots',$hashid);
12400: }
12401: 
12402: sub get_coursechange {
12403:     my ($cdom,$cnum) = @_;
12404:     if ($cdom eq '' || $cnum eq '') {
12405:         return unless ($env{'request.course.id'});
12406:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
12407:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
12408:     }
12409:     my $hashid=$cdom.'_'.$cnum;
12410:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
12411:     if ((defined($cached)) && ($change ne '')) {
12412:         return $change;
12413:     } else {
12414:         my %crshash;
12415:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
12416:         if ($crshash{'internal.contentchange'} eq '') {
12417:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
12418:             if ($change eq '') {
12419:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
12420:                 $change = $crshash{'internal.created'};
12421:             }
12422:         } else {
12423:             $change = $crshash{'internal.contentchange'};
12424:         }
12425:         my $cachetime = 600;
12426:         &do_cache_new('crschange',$hashid,$change,$cachetime);
12427:     }
12428:     return $change;
12429: }
12430: 
12431: sub devalidate_coursechange_cache {
12432:     my ($cnum,$cdom)=@_;
12433:     my $hashid=$cnum.':'.$cdom;
12434:     &devalidate_cache_new('crschange',$hashid);
12435: }
12436: 
12437: # ------------------------------------------------- Update symbolic store links
12438: 
12439: sub symblist {
12440:     my ($mapname,%newhash)=@_;
12441:     $mapname=&deversion(&declutter($mapname));
12442:     my %hash;
12443:     if (($env{'request.course.fn'}) && (%newhash)) {
12444:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
12445:                       &GDBM_WRCREAT(),0640)) {
12446: 	    foreach my $url (keys(%newhash)) {
12447: 		next if ($url eq 'last_known'
12448: 			 && $env{'form.no_update_last_known'});
12449: 		$hash{declutter($url)}=&encode_symb($mapname,
12450: 						    $newhash{$url}->[1],
12451: 						    $newhash{$url}->[0]);
12452:             }
12453:             if (untie(%hash)) {
12454: 		return 'ok';
12455:             }
12456:         }
12457:     }
12458:     return 'error';
12459: }
12460: 
12461: # --------------------------------------------------------------- Verify a symb
12462: 
12463: sub symbverify {
12464:     my ($symb,$thisurl,$encstate)=@_;
12465:     my $thisfn=$thisurl;
12466:     $thisfn=&declutter($thisfn);
12467: # direct jump to resource in page or to a sequence - will construct own symbs
12468:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
12469: # check URL part
12470:     my ($map,$resid,$url)=&decode_symb($symb);
12471: 
12472:     unless ($url eq $thisfn) { return 0; }
12473: 
12474:     $symb=&symbclean($symb);
12475:     $thisurl=&deversion($thisurl);
12476:     $thisfn=&deversion($thisfn);
12477: 
12478:     my %bighash;
12479:     my $okay=0;
12480: 
12481:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12482:                             &GDBM_READER(),0640)) {
12483:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
12484:             $thisurl =~ s/\?.+$//;
12485:             if ($map =~ m{^uploaded/.+\.page$}) {
12486:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
12487:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
12488:             }
12489:         }
12490:         my $ids;
12491:         if ($map =~ m{^uploaded/.+\.page$}) {
12492:             $ids=$bighash{'ids_'.&clutter_with_no_wrapper($thisurl)};
12493:         } else {
12494:             $ids=$bighash{'ids_'.&clutter($thisurl)};
12495:         }
12496:         unless ($ids) {
12497:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
12498:             $ids=$bighash{$idkey};
12499:         }
12500:         if ($ids) {
12501: # ------------------------------------------------------------------- Has ID(s)
12502:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
12503:                 $symb =~ s/\?.+$//;
12504:             }
12505: 	    foreach my $id (split(/\,/,$ids)) {
12506: 	       my ($mapid,$resid)=split(/\./,$id);
12507:                if (
12508:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
12509:    eq $symb) {
12510:                    if (ref($encstate)) {
12511:                        $$encstate = $bighash{'encrypted_'.$id};
12512:                    }
12513:                    if (($env{'request.role.adv'}) ||
12514:                        ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
12515:                        ($thisurl eq '/adm/navmaps')) {
12516:                        $okay=1;
12517:                        last;
12518:                    }
12519:                }
12520:            }
12521:         }
12522: 	untie(%bighash);
12523:     }
12524:     return $okay;
12525: }
12526: 
12527: # --------------------------------------------------------------- Clean-up symb
12528: 
12529: sub symbclean {
12530:     my $symb=shift;
12531:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
12532: # remove version from map
12533:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
12534: 
12535: # remove version from URL
12536:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
12537: 
12538: # remove wrapper
12539: 
12540:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
12541:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
12542:     return $symb;
12543: }
12544: 
12545: # ---------------------------------------------- Split symb to find map and url
12546: 
12547: sub encode_symb {
12548:     my ($map,$resid,$url)=@_;
12549:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
12550: }
12551: 
12552: sub decode_symb {
12553:     my $symb=shift;
12554:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
12555:     my ($map,$resid,$url)=split(/___/,$symb);
12556:     return (&fixversion($map),$resid,&fixversion($url));
12557: }
12558: 
12559: sub fixversion {
12560:     my $fn=shift;
12561:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
12562:     my %bighash;
12563:     my $uri=&clutter($fn);
12564:     my $key=$env{'request.course.id'}.'_'.$uri;
12565: # is this cached?
12566:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
12567:     if (defined($cached)) { return $result; }
12568: # unfortunately not cached, or expired
12569:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12570: 	    &GDBM_READER(),0640)) {
12571:  	if ($bighash{'version_'.$uri}) {
12572:  	    my $version=$bighash{'version_'.$uri};
12573:  	    unless (($version eq 'mostrecent') || 
12574: 		    ($version==&getversion($uri))) {
12575:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
12576:  	    }
12577:  	}
12578:  	untie %bighash;
12579:     }
12580:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
12581: }
12582: 
12583: sub deversion {
12584:     my $url=shift;
12585:     $url=~s/\.\d+\.(\w+)$/\.$1/;
12586:     return $url;
12587: }
12588: 
12589: # ------------------------------------------------------ Return symb list entry
12590: 
12591: sub symbread {
12592:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles,
12593:         $ignoresymbdb,$noenccheck)=@_;
12594:     my $cache_str='request.symbread.cached.'.$thisfn;
12595:     if (defined($env{$cache_str})) {
12596:         unless (ref($possibles) eq 'HASH') {
12597:             if ($ignorecachednull) {
12598:                 return $env{$cache_str} unless ($env{$cache_str} eq '');
12599:             } else {
12600:                 return $env{$cache_str};
12601:             }
12602:         }
12603:     }
12604: # no filename provided? try from environment
12605:     unless ($thisfn) {
12606:         if ($env{'request.symb'}) {
12607:             return $env{$cache_str}=&symbclean($env{'request.symb'});
12608:         }
12609:         $thisfn=$env{'request.filename'};
12610:     }
12611:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
12612: # is that filename actually a symb? Verify, clean, and return
12613:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
12614: 	if (&symbverify($thisfn,$1)) {
12615: 	    return $env{$cache_str}=&symbclean($thisfn);
12616: 	}
12617:     }
12618:     $thisfn=declutter($thisfn);
12619:     my %hash;
12620:     my %bighash;
12621:     my $syval='';
12622:     if (($env{'request.course.fn'}) && ($thisfn)) {
12623:         my $targetfn = $thisfn;
12624:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
12625:             $targetfn = 'adm/wrapper/'.$thisfn;
12626:         }
12627: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
12628: 	    $targetfn=$1;
12629: 	}
12630:         unless ($ignoresymbdb) {
12631:             if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
12632:                           &GDBM_READER(),0640)) {
12633: 	        $syval=$hash{$targetfn};
12634:                 untie(%hash);
12635:             }
12636:             if ($syval && $checkforblock) {
12637:                 my @blockers = &has_comm_blocking('bre',$syval,$thisfn,$ignoresymbdb,$noenccheck);
12638:                 if (@blockers) {
12639:                     $syval='';
12640:                 }
12641:             }
12642:         }
12643: # ---------------------------------------------------------- There was an entry
12644:         if ($syval) {
12645: 	    #unless ($syval=~/\_\d+$/) {
12646: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
12647: 		    #&appenv({'request.ambiguous' => $thisfn});
12648: 		    #return $env{$cache_str}='';
12649: 		#}    
12650: 		#$syval.=$1;
12651: 	    #}
12652:         } else {
12653: # ------------------------------------------------------- Was not in symb table
12654:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12655:                             &GDBM_READER(),0640)) {
12656: # ---------------------------------------------- Get ID(s) for current resource
12657:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
12658:               unless ($ids) { 
12659:                  $ids=$bighash{'ids_/'.$thisfn};
12660:               }
12661:               unless ($ids) {
12662: # alias?
12663: 		  $ids=$bighash{'mapalias_'.$thisfn};
12664:               }
12665:               if ($ids) {
12666: # ------------------------------------------------------------------- Has ID(s)
12667:                  my @possibilities=split(/\,/,$ids);
12668:                  if ($#possibilities==0) {
12669: # ----------------------------------------------- There is only one possibility
12670: 		     my ($mapid,$resid)=split(/\./,$ids);
12671: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
12672: 						    $resid,$thisfn);
12673:                      if (ref($possibles) eq 'HASH') {
12674:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
12675:                              $possibles->{$syval} = 1;
12676:                          }
12677:                      }
12678:                      if ($checkforblock) {
12679:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
12680:                              my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids},'',$noenccheck);
12681:                              if (@blockers) {
12682:                                  $syval = '';
12683:                                  untie(%bighash);
12684:                                  return $env{$cache_str}='';
12685:                              }
12686:                          }
12687:                      }
12688:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
12689: # ------------------------------------------ There is more than one possibility
12690:                      my $realpossible=0;
12691:                      foreach my $id (@possibilities) {
12692: 			 my $file=$bighash{'src_'.$id};
12693:                          my $canaccess;
12694:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
12695:                              $canaccess = 1;
12696:                          } else {
12697:                              $canaccess = &allowed('bre',$file);
12698:                          }
12699:                          if ($canaccess) {
12700:          		     my ($mapid,$resid)=split(/\./,$id);
12701:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
12702:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
12703:                                                              $resid,$thisfn);
12704:                                  next if ($bighash{'randomout_'.$id} && !$env{'request.role.adv'});
12705:                                  next unless (($noenccheck) || ($bighash{'encrypted_'.$id} eq $env{'request.enc'}));
12706:                                  if ($checkforblock) {
12707:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file,'',$noenccheck);
12708:                                      if (@blockers > 0) {
12709:                                          $syval = '';
12710:                                      } else {
12711:                                          $syval = $poss_syval;
12712:                                          $realpossible++;
12713:                                      }
12714:                                  } else {
12715:                                      $syval = $poss_syval;
12716:                                      $realpossible++;
12717:                                  }
12718:                                  if ($syval) {
12719:                                      if (ref($possibles) eq 'HASH') {
12720:                                          $possibles->{$syval} = 1;
12721:                                      }
12722:                                  }
12723:                              }
12724: 			 }
12725:                      }
12726: 		     if ($realpossible!=1) { $syval=''; }
12727:                  } else {
12728:                      $syval='';
12729:                  }
12730: 	      }
12731:               untie(%bighash);
12732:            }
12733:         }
12734:         if ($syval) {
12735: 	    return $env{$cache_str}=$syval;
12736:         }
12737:     }
12738:     &appenv({'request.ambiguous' => $thisfn});
12739:     return $env{$cache_str}='';
12740: }
12741: 
12742: # ---------------------------------------------------------- Return random seed
12743: 
12744: sub numval {
12745:     my $txt=shift;
12746:     $txt=~tr/A-J/0-9/;
12747:     $txt=~tr/a-j/0-9/;
12748:     $txt=~tr/K-T/0-9/;
12749:     $txt=~tr/k-t/0-9/;
12750:     $txt=~tr/U-Z/0-5/;
12751:     $txt=~tr/u-z/0-5/;
12752:     $txt=~s/\D//g;
12753:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
12754:     return int($txt);
12755: }
12756: 
12757: sub numval2 {
12758:     my $txt=shift;
12759:     $txt=~tr/A-J/0-9/;
12760:     $txt=~tr/a-j/0-9/;
12761:     $txt=~tr/K-T/0-9/;
12762:     $txt=~tr/k-t/0-9/;
12763:     $txt=~tr/U-Z/0-5/;
12764:     $txt=~tr/u-z/0-5/;
12765:     $txt=~s/\D//g;
12766:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
12767:     my $total;
12768:     foreach my $val (@txts) { $total+=$val; }
12769:     if ($_64bit) { if ($total > 2**32) { return -1; } }
12770:     return int($total);
12771: }
12772: 
12773: sub numval3 {
12774:     use integer;
12775:     my $txt=shift;
12776:     $txt=~tr/A-J/0-9/;
12777:     $txt=~tr/a-j/0-9/;
12778:     $txt=~tr/K-T/0-9/;
12779:     $txt=~tr/k-t/0-9/;
12780:     $txt=~tr/U-Z/0-5/;
12781:     $txt=~tr/u-z/0-5/;
12782:     $txt=~s/\D//g;
12783:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
12784:     my $total;
12785:     foreach my $val (@txts) { $total+=$val; }
12786:     if ($_64bit) { $total=(($total<<32)>>32); }
12787:     return $total;
12788: }
12789: 
12790: sub digest {
12791:     my ($data)=@_;
12792:     my $digest=&Digest::MD5::md5($data);
12793:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
12794:     my ($e,$f);
12795:     {
12796:         use integer;
12797:         $e=($a+$b);
12798:         $f=($c+$d);
12799:         if ($_64bit) {
12800:             $e=(($e<<32)>>32);
12801:             $f=(($f<<32)>>32);
12802:         }
12803:     }
12804:     if (wantarray) {
12805: 	return ($e,$f);
12806:     } else {
12807: 	my $g;
12808: 	{
12809: 	    use integer;
12810: 	    $g=($e+$f);
12811: 	    if ($_64bit) {
12812: 		$g=(($g<<32)>>32);
12813: 	    }
12814: 	}
12815: 	return $g;
12816:     }
12817: }
12818: 
12819: sub latest_rnd_algorithm_id {
12820:     return '64bit5';
12821: }
12822: 
12823: sub get_rand_alg {
12824:     my ($courseid)=@_;
12825:     if (!$courseid) { $courseid=(&whichuser())[1]; }
12826:     if ($courseid) {
12827: 	return $env{"course.$courseid.rndseed"};
12828:     }
12829:     return &latest_rnd_algorithm_id();
12830: }
12831: 
12832: sub validCODE {
12833:     my ($CODE)=@_;
12834:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
12835:     return 0;
12836: }
12837: 
12838: sub getCODE {
12839:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
12840:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
12841: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
12842: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
12843: 	return $Apache::lonhomework::history{'resource.CODE'};
12844:     }
12845:     return undef;
12846: }
12847: #
12848: #  Determines the random seed for a specific context:
12849: #
12850: # parameters:
12851: #   symb      - in course context the symb for the seed.
12852: #   course_id - The course id of the form domain_coursenum.
12853: #   domain    - Domain for the user.
12854: #   course    - Course for the user.
12855: #   cenv      - environment of the course.
12856: #
12857: # NOTE:
12858: #   All parameters are picked out of the environment if missing
12859: #   or not defined.
12860: #   If a symb cannot be determined the current time is used instead.
12861: #
12862: #  For a given well defined symb, courside, domain, username,
12863: #  and course environment, the seed is reproducible.
12864: #
12865: sub rndseed {
12866:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
12867:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
12868:     if (!defined($symb)) {
12869: 	unless ($symb=$wsymb) { return time; }
12870:     }
12871:     if (!defined $courseid) { 
12872: 	$courseid=$wcourseid; 
12873:     }
12874:     if (!defined $domain) { $domain=$wdomain; }
12875:     if (!defined $username) { $username=$wusername }
12876: 
12877:     my $which;
12878:     if (defined($cenv->{'rndseed'})) {
12879: 	$which = $cenv->{'rndseed'};
12880:     } else {
12881: 	$which =&get_rand_alg($courseid);
12882:     }
12883:     if (defined(&getCODE())) {
12884: 	if ($which eq '64bit5') {
12885: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
12886: 	} elsif ($which eq '64bit4') {
12887: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
12888: 	} else {
12889: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
12890: 	}
12891:     } elsif ($which eq '64bit5') {
12892: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
12893:     } elsif ($which eq '64bit4') {
12894: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
12895:     } elsif ($which eq '64bit3') {
12896: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
12897:     } elsif ($which eq '64bit2') {
12898: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
12899:     } elsif ($which eq '64bit') {
12900: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
12901:     }
12902:     return &rndseed_32bit($symb,$courseid,$domain,$username);
12903: }
12904: 
12905: sub rndseed_32bit {
12906:     my ($symb,$courseid,$domain,$username)=@_;
12907:     {
12908: 	use integer;
12909: 	my $symbchck=unpack("%32C*",$symb) << 27;
12910: 	my $symbseed=numval($symb) << 22;
12911: 	my $namechck=unpack("%32C*",$username) << 17;
12912: 	my $nameseed=numval($username) << 12;
12913: 	my $domainseed=unpack("%32C*",$domain) << 7;
12914: 	my $courseseed=unpack("%32C*",$courseid);
12915: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
12916: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12917: 	#&logthis("rndseed :$num:$symb");
12918: 	if ($_64bit) { $num=(($num<<32)>>32); }
12919: 	return $num;
12920:     }
12921: }
12922: 
12923: sub rndseed_64bit {
12924:     my ($symb,$courseid,$domain,$username)=@_;
12925:     {
12926: 	use integer;
12927: 	my $symbchck=unpack("%32S*",$symb) << 21;
12928: 	my $symbseed=numval($symb) << 10;
12929: 	my $namechck=unpack("%32S*",$username);
12930: 	
12931: 	my $nameseed=numval($username) << 21;
12932: 	my $domainseed=unpack("%32S*",$domain) << 10;
12933: 	my $courseseed=unpack("%32S*",$courseid);
12934: 	
12935: 	my $num1=$symbchck+$symbseed+$namechck;
12936: 	my $num2=$nameseed+$domainseed+$courseseed;
12937: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12938: 	#&logthis("rndseed :$num:$symb");
12939: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
12940: 	return "$num1,$num2";
12941:     }
12942: }
12943: 
12944: sub rndseed_64bit2 {
12945:     my ($symb,$courseid,$domain,$username)=@_;
12946:     {
12947: 	use integer;
12948: 	# strings need to be an even # of cahracters long, it it is odd the
12949:         # last characters gets thrown away
12950: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
12951: 	my $symbseed=numval($symb) << 10;
12952: 	my $namechck=unpack("%32S*",$username.' ');
12953: 	
12954: 	my $nameseed=numval($username) << 21;
12955: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
12956: 	my $courseseed=unpack("%32S*",$courseid.' ');
12957: 	
12958: 	my $num1=$symbchck+$symbseed+$namechck;
12959: 	my $num2=$nameseed+$domainseed+$courseseed;
12960: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12961: 	#&logthis("rndseed :$num:$symb");
12962: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
12963: 	return "$num1,$num2";
12964:     }
12965: }
12966: 
12967: sub rndseed_64bit3 {
12968:     my ($symb,$courseid,$domain,$username)=@_;
12969:     {
12970: 	use integer;
12971: 	# strings need to be an even # of cahracters long, it it is odd the
12972:         # last characters gets thrown away
12973: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
12974: 	my $symbseed=numval2($symb) << 10;
12975: 	my $namechck=unpack("%32S*",$username.' ');
12976: 	
12977: 	my $nameseed=numval2($username) << 21;
12978: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
12979: 	my $courseseed=unpack("%32S*",$courseid.' ');
12980: 	
12981: 	my $num1=$symbchck+$symbseed+$namechck;
12982: 	my $num2=$nameseed+$domainseed+$courseseed;
12983: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12984: 	#&logthis("rndseed :$num1:$num2:$_64bit");
12985: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
12986: 	
12987: 	return "$num1:$num2";
12988:     }
12989: }
12990: 
12991: sub rndseed_64bit4 {
12992:     my ($symb,$courseid,$domain,$username)=@_;
12993:     {
12994: 	use integer;
12995: 	# strings need to be an even # of cahracters long, it it is odd the
12996:         # last characters gets thrown away
12997: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
12998: 	my $symbseed=numval3($symb) << 10;
12999: 	my $namechck=unpack("%32S*",$username.' ');
13000: 	
13001: 	my $nameseed=numval3($username) << 21;
13002: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
13003: 	my $courseseed=unpack("%32S*",$courseid.' ');
13004: 	
13005: 	my $num1=$symbchck+$symbseed+$namechck;
13006: 	my $num2=$nameseed+$domainseed+$courseseed;
13007: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13008: 	#&logthis("rndseed :$num1:$num2:$_64bit");
13009: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
13010: 	
13011: 	return "$num1:$num2";
13012:     }
13013: }
13014: 
13015: sub rndseed_64bit5 {
13016:     my ($symb,$courseid,$domain,$username)=@_;
13017:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
13018:     return "$num1:$num2";
13019: }
13020: 
13021: sub rndseed_CODE_64bit {
13022:     my ($symb,$courseid,$domain,$username)=@_;
13023:     {
13024: 	use integer;
13025: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
13026: 	my $symbseed=numval2($symb);
13027: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
13028: 	my $CODEseed=numval(&getCODE());
13029: 	my $courseseed=unpack("%32S*",$courseid.' ');
13030: 	my $num1=$symbseed+$CODEchck;
13031: 	my $num2=$CODEseed+$courseseed+$symbchck;
13032: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
13033: 	#&logthis("rndseed :$num1:$num2:$symb");
13034: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
13035: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
13036: 	return "$num1:$num2";
13037:     }
13038: }
13039: 
13040: sub rndseed_CODE_64bit4 {
13041:     my ($symb,$courseid,$domain,$username)=@_;
13042:     {
13043: 	use integer;
13044: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
13045: 	my $symbseed=numval3($symb);
13046: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
13047: 	my $CODEseed=numval3(&getCODE());
13048: 	my $courseseed=unpack("%32S*",$courseid.' ');
13049: 	my $num1=$symbseed+$CODEchck;
13050: 	my $num2=$CODEseed+$courseseed+$symbchck;
13051: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
13052: 	#&logthis("rndseed :$num1:$num2:$symb");
13053: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
13054: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
13055: 	return "$num1:$num2";
13056:     }
13057: }
13058: 
13059: sub rndseed_CODE_64bit5 {
13060:     my ($symb,$courseid,$domain,$username)=@_;
13061:     my $code = &getCODE();
13062:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
13063:     return "$num1:$num2";
13064: }
13065: 
13066: sub setup_random_from_rndseed {
13067:     my ($rndseed)=@_;
13068:     if ($rndseed =~/([,:])/) {
13069: 	my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
13070:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
13071:             &Math::Random::random_set_seed_from_phrase($rndseed);
13072:         } else {
13073:             &Math::Random::random_set_seed($num1,$num2);
13074:         }
13075:     } else {
13076: 	&Math::Random::random_set_seed_from_phrase($rndseed);
13077:     }
13078: }
13079: 
13080: sub latest_receipt_algorithm_id {
13081:     return 'receipt3';
13082: }
13083: 
13084: sub recunique {
13085:     my $fucourseid=shift;
13086:     my $unique;
13087:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
13088: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
13089: 	$unique=$env{"course.$fucourseid.internal.encseed"};
13090:     } else {
13091: 	$unique=$perlvar{'lonReceipt'};
13092:     }
13093:     return unpack("%32C*",$unique);
13094: }
13095: 
13096: sub recprefix {
13097:     my $fucourseid=shift;
13098:     my $prefix;
13099:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
13100: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
13101: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
13102:     } else {
13103: 	$prefix=$perlvar{'lonHostID'};
13104:     }
13105:     return unpack("%32C*",$prefix);
13106: }
13107: 
13108: sub ireceipt {
13109:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
13110: 
13111:     my $return =&recprefix($fucourseid).'-';
13112: 
13113:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
13114: 	$env{'request.state'} eq 'construct') {
13115: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
13116: 	return $return;
13117:     }
13118: 
13119:     my $cuname=unpack("%32C*",$funame);
13120:     my $cudom=unpack("%32C*",$fudom);
13121:     my $cucourseid=unpack("%32C*",$fucourseid);
13122:     my $cusymb=unpack("%32C*",$fusymb);
13123:     my $cunique=&recunique($fucourseid);
13124:     my $cpart=unpack("%32S*",$part);
13125:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
13126: 
13127: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
13128: 			       
13129: 	$return.= ($cunique%$cuname+
13130: 		   $cunique%$cudom+
13131: 		   $cusymb%$cuname+
13132: 		   $cusymb%$cudom+
13133: 		   $cucourseid%$cuname+
13134: 		   $cucourseid%$cudom+
13135: 		   $cpart%$cuname+
13136: 		   $cpart%$cudom);
13137:     } else {
13138: 	$return.= ($cunique%$cuname+
13139: 		   $cunique%$cudom+
13140: 		   $cusymb%$cuname+
13141: 		   $cusymb%$cudom+
13142: 		   $cucourseid%$cuname+
13143: 		   $cucourseid%$cudom);
13144:     }
13145:     return $return;
13146: }
13147: 
13148: sub receipt {
13149:     my ($part)=@_;
13150:     my ($symb,$courseid,$domain,$name) = &whichuser();
13151:     return &ireceipt($name,$domain,$courseid,$symb,$part);
13152: }
13153: 
13154: sub whichuser {
13155:     my ($passedsymb)=@_;
13156:     my ($symb,$courseid,$domain,$name,$publicuser);
13157:     if (defined($env{'form.grade_symb'})) {
13158: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
13159: 	my $allowed=&allowed('vgr',$tmp_courseid);
13160: 	if (!$allowed &&
13161: 	    exists($env{'request.course.sec'}) &&
13162: 	    $env{'request.course.sec'} !~ /^\s*$/) {
13163: 	    $allowed=&allowed('vgr',$tmp_courseid.
13164: 			      '/'.$env{'request.course.sec'});
13165: 	}
13166: 	if ($allowed) {
13167: 	    ($symb)=&get_env_multiple('form.grade_symb');
13168: 	    $courseid=$tmp_courseid;
13169: 	    ($domain)=&get_env_multiple('form.grade_domain');
13170: 	    ($name)=&get_env_multiple('form.grade_username');
13171: 	    return ($symb,$courseid,$domain,$name,$publicuser);
13172: 	}
13173:     }
13174:     if (!$passedsymb) {
13175: 	$symb=&symbread();
13176:     } else {
13177: 	$symb=$passedsymb;
13178:     }
13179:     $courseid=$env{'request.course.id'};
13180:     $domain=$env{'user.domain'};
13181:     $name=$env{'user.name'};
13182:     if ($name eq 'public' && $domain eq 'public') {
13183: 	if (!defined($env{'form.username'})) {
13184: 	    $env{'form.username'}.=time.rand(10000000);
13185: 	}
13186: 	$name.=$env{'form.username'};
13187:     }
13188:     return ($symb,$courseid,$domain,$name,$publicuser);
13189: 
13190: }
13191: 
13192: # ------------------------------------------------------------ Serves up a file
13193: # returns either the contents of the file or 
13194: # -1 if the file doesn't exist
13195: #
13196: # if the target is a file that was uploaded via DOCS, 
13197: # a check will be made to see if a current copy exists on the local server,
13198: # if it does this will be served, otherwise a copy will be retrieved from
13199: # the home server for the course and stored in /home/httpd/html/userfiles on
13200: # the local server.   
13201: 
13202: sub getfile {
13203:     my ($file) = @_;
13204:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
13205:     &repcopy($file);
13206:     return &readfile($file);
13207: }
13208: 
13209: sub repcopy_userfile {
13210:     my ($file)=@_;
13211:     my $londocroot = $perlvar{'lonDocRoot'};
13212:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
13213:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
13214:     my ($cdom,$cnum,$filename) = 
13215: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
13216:     my $uri="/uploaded/$cdom/$cnum/$filename";
13217:     if (-e "$file") {
13218: # we already have a local copy, check it out
13219: 	my @fileinfo = stat($file);
13220: 	my $rtncode;
13221: 	my $info;
13222: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
13223: 	if ($lwpresp ne 'ok') {
13224: # there is no such file anymore, even though we had a local copy
13225: 	    if ($rtncode eq '404') {
13226: 		unlink($file);
13227: 	    }
13228: 	    return -1;
13229: 	}
13230: 	if ($info < $fileinfo[9]) {
13231: # nice, the file we have is up-to-date, just say okay
13232: 	    return 'ok';
13233: 	} else {
13234: # the file is outdated, get rid of it
13235: 	    unlink($file);
13236: 	}
13237:     }
13238: # one way or the other, at this point, we don't have the file
13239: # construct the correct path for the file
13240:     my @parts = ($cdom,$cnum); 
13241:     if ($filename =~ m|^(.+)/[^/]+$|) {
13242: 	push @parts, split(/\//,$1);
13243:     }
13244:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
13245:     foreach my $part (@parts) {
13246: 	$path .= '/'.$part;
13247: 	if (!-e $path) {
13248: 	    mkdir($path,0770);
13249: 	}
13250:     }
13251: # now the path exists for sure
13252: # get a user agent
13253:     my $ua=new LWP::UserAgent;
13254:     my $transferfile=$file.'.in.transfer';
13255: # FIXME: this should flock
13256:     if (-e $transferfile) { return 'ok'; }
13257:     my $request;
13258:     $uri=~s/^\///;
13259:     my $homeserver = &homeserver($cnum,$cdom);
13260:     my $hostname = &hostname($homeserver);
13261:     my $protocol = $protocol{$homeserver};
13262:     $protocol = 'http' if ($protocol ne 'https');
13263:     $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
13264:     my $response=$ua->request($request,$transferfile);
13265: # did it work?
13266:     if ($response->is_error()) {
13267: 	unlink($transferfile);
13268: 	&logthis("Userfile repcopy failed for $uri");
13269: 	return -1;
13270:     }
13271: # worked, rename the transfer file
13272:     rename($transferfile,$file);
13273:     return 'ok';
13274: }
13275: 
13276: sub tokenwrapper {
13277:     my $uri=shift;
13278:     $uri=~s|^https?\://([^/]+)||;
13279:     $uri=~s|^/||;
13280:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
13281:     my $token=$1;
13282:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
13283:     if ($udom && $uname && $file) {
13284: 	$file=~s|(\?\.*)*$||;
13285:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
13286:         my $homeserver = &homeserver($uname,$udom);
13287:         my $hostname = &hostname($homeserver);
13288:         my $protocol = $protocol{$homeserver};
13289:         $protocol = 'http' if ($protocol ne 'https');
13290:         return $protocol.'://'.$hostname.'/'.$uri.
13291:                (($uri=~/\?/)?'&':'?').'token='.$token.
13292:                                '&tokenissued='.$perlvar{'lonHostID'};
13293:     } else {
13294:         return '/adm/notfound.html';
13295:     }
13296: }
13297: 
13298: # call with reqtype HEAD: get last modification time
13299: # call with reqtype GET: get the file contents
13300: # Do not call this with reqtype GET for large files! It loads everything into memory
13301: #
13302: sub getuploaded {
13303:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
13304:     $uri=~s/^\///;
13305:     my $homeserver = &homeserver($cnum,$cdom);
13306:     my $hostname = &hostname($homeserver);
13307:     my $protocol = $protocol{$homeserver};
13308:     $protocol = 'http' if ($protocol ne 'https');
13309:     $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
13310:     my $ua=new LWP::UserAgent;
13311:     my $request=new HTTP::Request($reqtype,$uri);
13312:     my $response=$ua->request($request);
13313:     $$rtncode = $response->code;
13314:     if (! $response->is_success()) {
13315: 	return 'failed';
13316:     }      
13317:     if ($reqtype eq 'HEAD') {
13318: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
13319:     } elsif ($reqtype eq 'GET') {
13320: 	$$info = $response->content;
13321:     }
13322:     return 'ok';
13323: }
13324: 
13325: sub readfile {
13326:     my $file = shift;
13327:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
13328:     my $fh;
13329:     open($fh,"<",$file);
13330:     my $a='';
13331:     while (my $line = <$fh>) { $a .= $line; }
13332:     return $a;
13333: }
13334: 
13335: sub filelocation {
13336:     my ($dir,$file) = @_;
13337:     my $location;
13338:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
13339: 
13340:     if ($file =~ m-^/adm/-) {
13341: 	$file=~s-^/adm/wrapper/-/-;
13342: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
13343:     }
13344: 
13345:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
13346:         $location = $file;
13347:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
13348:         my ($udom,$uname,$filename)=
13349:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
13350:         my $home=&homeserver($uname,$udom);
13351:         my $is_me=0;
13352:         my @ids=&current_machine_ids();
13353:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
13354:         if ($is_me) {
13355:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
13356:         } else {
13357:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
13358:   	      $udom.'/'.$uname.'/'.$filename;
13359:         }
13360:     } elsif ($file =~ m-^/adm/-) {
13361: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
13362:     } else {
13363:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
13364:         $file=~s:^/(res|priv)/:/:;
13365:         my $space=$1;
13366:         if ( !( $file =~ m:^/:) ) {
13367:             $location = $dir. '/'.$file;
13368:         } else {
13369:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
13370:         }
13371:     }
13372:     $location=~s://+:/:g; # remove duplicate /
13373:     while ($location=~m{/\.\./}) {
13374: 	if ($location =~ m{/[^/]+/\.\./}) {
13375: 	    $location=~ s{/[^/]+/\.\./}{/}g;
13376: 	} else {
13377: 	    $location=~ s{/\.\./}{/}g;
13378: 	}
13379:     } #remove dir/..
13380:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
13381:     return $location;
13382: }
13383: 
13384: sub hreflocation {
13385:     my ($dir,$file)=@_;
13386:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
13387: 	$file=filelocation($dir,$file);
13388:     } elsif ($file=~m-^/adm/-) {
13389: 	$file=~s-^/adm/wrapper/-/-;
13390: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
13391:     }
13392:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
13393: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
13394:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
13395: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
13396: 	        {/uploaded/$1/$2/}x;
13397:     }
13398:     if ($file=~ m{^/userfiles/}) {
13399: 	$file =~ s{^/userfiles/}{/uploaded/};
13400:     }
13401:     return $file;
13402: }
13403: 
13404: 
13405: 
13406: 
13407: 
13408: sub current_machine_domains {
13409:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
13410: }
13411: 
13412: sub machine_domains {
13413:     my ($hostname) = @_;
13414:     my @domains;
13415:     my %hostname = &all_hostnames();
13416:     while( my($id, $name) = each(%hostname)) {
13417: #	&logthis("-$id-$name-$hostname-");
13418: 	if ($hostname eq $name) {
13419: 	    push(@domains,&host_domain($id));
13420: 	}
13421:     }
13422:     return @domains;
13423: }
13424: 
13425: sub current_machine_ids {
13426:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
13427: }
13428: 
13429: sub machine_ids {
13430:     my ($hostname) = @_;
13431:     $hostname ||= &hostname($perlvar{'lonHostID'});
13432:     my @ids;
13433:     my %name_to_host = &all_names();
13434:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
13435: 	return @{ $name_to_host{$hostname} };
13436:     }
13437:     return;
13438: }
13439: 
13440: sub additional_machine_domains {
13441:     my @domains;
13442:     open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab");
13443:     while( my $line = <$fh>) {
13444:         $line =~ s/\s//g;
13445:         push(@domains,$line);
13446:     }
13447:     return @domains;
13448: }
13449: 
13450: sub default_login_domain {
13451:     my $domain = $perlvar{'lonDefDomain'};
13452:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
13453:     foreach my $posdom (&current_machine_domains(),
13454:                         &additional_machine_domains()) {
13455:         if (lc($posdom) eq lc($testdomain)) {
13456:             $domain=$posdom;
13457:             last;
13458:         }
13459:     }
13460:     return $domain;
13461: }
13462: 
13463: sub shared_institution {
13464:     my ($dom,$lonhost) = @_;
13465:     if ($lonhost eq '') {
13466:         $lonhost = $perlvar{'lonHostID'};
13467:     }
13468:     my $same_intdom;
13469:     my $hostintdom = &internet_dom($lonhost);
13470:     if ($hostintdom ne '') {
13471:         my %iphost = &get_iphost();
13472:         my $primary_id = &domain($dom,'primary');
13473:         my $primary_ip = &get_host_ip($primary_id);
13474:         if (ref($iphost{$primary_ip}) eq 'ARRAY') {
13475:             foreach my $id (@{$iphost{$primary_ip}}) {
13476:                 my $intdom = &internet_dom($id);
13477:                 if ($intdom eq $hostintdom) {
13478:                     $same_intdom = 1;
13479:                     last;
13480:                 }
13481:             }
13482:         }
13483:     }
13484:     return $same_intdom;
13485: }
13486: 
13487: sub uses_sts {
13488:     my ($ignore_cache) = @_;
13489:     my $lonhost = $perlvar{'lonHostID'};
13490:     my $hostname = &hostname($lonhost);
13491:     my $sts_on;
13492:     if ($protocol{$lonhost} eq 'https') {
13493:         my $cachetime = 12*3600;
13494:         if (!$ignore_cache) {
13495:             ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
13496:             if (defined($cached)) {
13497:                 return $sts_on;
13498:             }
13499:         }
13500:         my $ua=new LWP::UserAgent;
13501:         my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
13502:         my $request=new HTTP::Request('HEAD',$url);
13503:         my $response=$ua->request($request);
13504:         if ($response->is_success) {
13505:             my $has_sts = $response->header('Strict-Transport-Security');
13506:             if ($has_sts eq '') {
13507:                 $sts_on = 0;
13508:             } else {
13509:                 if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
13510:                     my $maxage = $1;
13511:                     if ($maxage) {
13512:                         $sts_on = 1;
13513:                     } else {
13514:                         $sts_on = 0;
13515:                     }
13516:                 } else {
13517:                     $sts_on = 0;
13518:                 }
13519:             }
13520:             return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
13521:         }
13522:     }
13523:     return;
13524: }
13525: 
13526: sub get_requestor_ip {
13527:     my ($r,$nolookup,$noproxy) = @_;
13528:     my $from_ip;
13529:     if (ref($r)) {
13530:         $from_ip = $r->get_remote_host($nolookup);
13531:     } else {
13532:         $from_ip = $ENV{'REMOTE_ADDR'};
13533:     }
13534:     return $from_ip;
13535: }
13536: 
13537: # ------------------------------------------------------------- Declutters URLs
13538: 
13539: sub declutter {
13540:     my $thisfn=shift;
13541:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
13542:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
13543:         $thisfn=~s{^/home/httpd/html}{};
13544:     }
13545:     $thisfn=~s/^\///;
13546:     $thisfn=~s|^adm/wrapper/||;
13547:     $thisfn=~s|^adm/coursedocs/showdoc/||;
13548:     $thisfn=~s/^res\///;
13549:     $thisfn=~s/^priv\///;
13550:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
13551:         $thisfn=~s/\?.+$//;
13552:     }
13553:     return $thisfn;
13554: }
13555: 
13556: # ------------------------------------------------------------- Clutter up URLs
13557: 
13558: sub clutter {
13559:     my $thisfn='/'.&declutter(shift);
13560:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
13561: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
13562:        $thisfn='/res'.$thisfn; 
13563:     }
13564:     if ($thisfn !~m|^/adm|) {
13565: 	if ($thisfn =~ m|^/ext/|) {
13566: 	    $thisfn='/adm/wrapper'.$thisfn;
13567: 	} else {
13568: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
13569: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
13570: 	    if ($embstyle eq 'ssi'
13571: 		|| ($embstyle eq 'hdn')
13572: 		|| ($embstyle eq 'rat')
13573: 		|| ($embstyle eq 'prv')
13574: 		|| ($embstyle eq 'ign')) {
13575: 		#do nothing with these
13576: 	    } elsif (($embstyle eq 'img') 
13577: 		|| ($embstyle eq 'emb')
13578: 		|| ($embstyle eq 'wrp')) {
13579: 		$thisfn='/adm/wrapper'.$thisfn;
13580: 	    } elsif ($embstyle eq 'unk'
13581: 		     && $thisfn!~/\.(sequence|page)$/) {
13582: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
13583: 	    } else {
13584: #		&logthis("Got a blank emb style");
13585: 	    }
13586: 	}
13587:     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
13588:         $thisfn='/adm/wrapper'.$thisfn;
13589:     }
13590:     return $thisfn;
13591: }
13592: 
13593: sub clutter_with_no_wrapper {
13594:     my $uri = &clutter(shift);
13595:     if ($uri =~ m-^/adm/-) {
13596: 	$uri =~ s-^/adm/wrapper/-/-;
13597: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
13598:     }
13599:     return $uri;
13600: }
13601: 
13602: sub freeze_escape {
13603:     my ($value)=@_;
13604:     if (ref($value)) {
13605: 	$value=&nfreeze($value);
13606: 	return '__FROZEN__'.&escape($value);
13607:     }
13608:     return &escape($value);
13609: }
13610: 
13611: 
13612: sub thaw_unescape {
13613:     my ($value)=@_;
13614:     if ($value =~ /^__FROZEN__/) {
13615: 	substr($value,0,10,undef);
13616: 	$value=&unescape($value);
13617: 	return &thaw($value);
13618:     }
13619:     return &unescape($value);
13620: }
13621: 
13622: sub correct_line_ends {
13623:     my ($result)=@_;
13624:     $$result =~s/\r\n/\n/mg;
13625:     $$result =~s/\r/\n/mg;
13626: }
13627: # ================================================================ Main Program
13628: 
13629: sub goodbye {
13630:    &logthis("Starting Shut down");
13631: #not converted to using infrastruture and probably shouldn't be
13632:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
13633: #converted
13634: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
13635:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
13636: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
13637: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
13638: #1.1 only
13639: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
13640: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
13641: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
13642: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
13643:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
13644:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
13645:    &logthis(sprintf("%-20s is %s",'hits',$hits));
13646:    &flushcourselogs();
13647:    &logthis("Shutting down");
13648: }
13649: 
13650: sub get_dns {
13651:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
13652:     if (!$ignore_cache) {
13653: 	my ($content,$cached)=
13654: 	    &Apache::lonnet::is_cached_new('dns',$url);
13655: 	if ($cached) {
13656: 	    &$func($content,$hashref);
13657: 	    return;
13658: 	}
13659:     }
13660: 
13661:     my %alldns;
13662:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
13663:         foreach my $dns (<$config>) {
13664: 	    next if ($dns !~ /^\^(\S*)/x);
13665:             my $line = $1;
13666:             my ($host,$protocol) = split(/:/,$line);
13667:             if ($protocol ne 'https') {
13668:                 $protocol = 'http';
13669:             }
13670: 	    $alldns{$host} = $protocol;
13671:         }
13672:         close($config);
13673:     }
13674:     while (%alldns) {
13675: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
13676: 	my $ua=new LWP::UserAgent;
13677:         $ua->timeout(30);
13678: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
13679: 	my $response=$ua->request($request);
13680:         delete($alldns{$dns});
13681: 	next if ($response->is_error());
13682: 	my @content = split("\n",$response->content);
13683:         unless ($nocache) {
13684: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
13685:         }
13686: 	&$func(\@content,$hashref);
13687: 	return;
13688:     }
13689:     my $which = (split('/',$url))[3];
13690:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
13691:     if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
13692:         my @content = <$config>;
13693:         &$func(\@content,$hashref);
13694:     }
13695:     return;
13696: }
13697: 
13698: # ------------------------------------------------------Get DNS checksums file
13699: sub parse_dns_checksums_tab {
13700:     my ($lines,$hashref) = @_;
13701:     my $lonhost = $perlvar{'lonHostID'};
13702:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
13703:     my $loncaparev = &get_server_loncaparev($machine_dom);
13704:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
13705:     my $webconfdir = '/etc/httpd/conf';
13706:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
13707:         $webconfdir = '/etc/apache2';
13708:     } elsif ($distro =~ /^sles(\d+)$/) {
13709:         if ($1 >= 10) {
13710:             $webconfdir = '/etc/apache2';
13711:         }
13712:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
13713:         if ($1 >= 10.0) {
13714:             $webconfdir = '/etc/apache2';
13715:         }
13716:     }
13717:     my ($release,$timestamp) = split(/\-/,$loncaparev);
13718:     my (%chksum,%revnum);
13719:     if (ref($lines) eq 'ARRAY') {
13720:         chomp(@{$lines});
13721:         my $version = shift(@{$lines});
13722:         if ($version eq $release) {
13723:             foreach my $line (@{$lines}) {
13724:                 my ($file,$version,$shasum) = split(/,/,$line);
13725:                 if ($file =~ m{^/etc/httpd/conf}) {
13726:                     if ($webconfdir eq '/etc/apache2') {
13727:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
13728:                     }
13729:                 }
13730:                 $chksum{$file} = $shasum;
13731:                 $revnum{$file} = $version;
13732:             }
13733:             if (ref($hashref) eq 'HASH') {
13734:                 %{$hashref} = (
13735:                                 sums     => \%chksum,
13736:                                 versions => \%revnum,
13737:                               );
13738:             }
13739:         }
13740:     }
13741:     return;
13742: }
13743: 
13744: sub fetch_dns_checksums {
13745:     my %checksums;
13746:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
13747:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
13748:     my ($release,$timestamp) = split(/\-/,$loncaparev);
13749:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
13750:              \%checksums);
13751:     return \%checksums;
13752: }
13753: 
13754: # ------------------------------------------------------------ Read domain file
13755: {
13756:     my $loaded;
13757:     my %domain;
13758: 
13759:     sub parse_domain_tab {
13760: 	my ($lines) = @_;
13761: 	foreach my $line (@$lines) {
13762: 	    next if ($line =~ /^(\#|\s*$ )/x);
13763: 
13764: 	    chomp($line);
13765: 	    my ($name,@elements) = split(/:/,$line,9);
13766: 	    my %this_domain;
13767: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
13768: 			       'lang_def', 'city', 'longi', 'lati',
13769: 			       'primary') {
13770: 		$this_domain{$field} = shift(@elements);
13771: 	    }
13772: 	    $domain{$name} = \%this_domain;
13773: 	}
13774:     }
13775: 
13776:     sub reset_domain_info {
13777: 	undef($loaded);
13778: 	undef(%domain);
13779:     }
13780: 
13781:     sub load_domain_tab {
13782: 	my ($ignore_cache,$nocache) = @_;
13783: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
13784: 	my $fh;
13785: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
13786: 	    my @lines = <$fh>;
13787: 	    &parse_domain_tab(\@lines);
13788: 	}
13789: 	close($fh);
13790: 	$loaded = 1;
13791:     }
13792: 
13793:     sub domain {
13794: 	&load_domain_tab() if (!$loaded);
13795: 
13796: 	my ($name,$what) = @_;
13797: 	return if ( !exists($domain{$name}) );
13798: 
13799: 	if (!$what) {
13800: 	    return $domain{$name}{'description'};
13801: 	}
13802: 	return $domain{$name}{$what};
13803:     }
13804: 
13805:     sub domain_info {
13806:         &load_domain_tab() if (!$loaded);
13807:         return %domain;
13808:     }
13809: 
13810: }
13811: 
13812: 
13813: # ------------------------------------------------------------- Read hosts file
13814: {
13815:     my %hostname;
13816:     my %hostdom;
13817:     my %libserv;
13818:     my $loaded;
13819:     my %name_to_host;
13820:     my %internetdom;
13821:     my %LC_dns_serv;
13822: 
13823:     sub parse_hosts_tab {
13824: 	my ($file) = @_;
13825: 	foreach my $configline (@$file) {
13826: 	    next if ($configline =~ /^(\#|\s*$ )/x);
13827:             chomp($configline);
13828: 	    if ($configline =~ /^\^/) {
13829:                 if ($configline =~ /^\^([\w.\-]+)/) {
13830:                     $LC_dns_serv{$1} = 1;
13831:                 }
13832:                 next;
13833:             }
13834: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
13835: 	    $name=~s/\s//g;
13836: 	    if ($id && $domain && $role && $name) {
13837:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
13838:                     my $curr = $hostname{$id};
13839:                     my $skip;
13840:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
13841:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
13842:                             $skip = 1;
13843:                         } else {
13844:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
13845:                         }
13846:                     }
13847:                     unless ($skip) {
13848:                         push(@{$name_to_host{$name}},$id);
13849:                     }
13850:                 } else {
13851:                     push(@{$name_to_host{$name}},$id);
13852:                 }
13853: 		$hostname{$id}=$name;
13854: 		$hostdom{$id}=$domain;
13855: 		if ($role eq 'library') { $libserv{$id}=$name; }
13856:                 if (defined($protocol)) {
13857:                     if ($protocol eq 'https') {
13858:                         $protocol{$id} = $protocol;
13859:                     } else {
13860:                         $protocol{$id} = 'http'; 
13861:                     }
13862:                 } else {
13863:                     $protocol{$id} = 'http';
13864:                 }
13865:                 if (defined($intdom)) {
13866:                     $internetdom{$id} = $intdom;
13867:                 }
13868: 	    }
13869: 	}
13870:     }
13871:     
13872:     sub reset_hosts_info {
13873: 	&purge_remembered();
13874: 	&reset_domain_info();
13875: 	&reset_hosts_ip_info();
13876: 	undef(%name_to_host);
13877: 	undef(%hostname);
13878: 	undef(%hostdom);
13879: 	undef(%libserv);
13880: 	undef($loaded);
13881:     }
13882: 
13883:     sub load_hosts_tab {
13884: 	my ($ignore_cache,$nocache) = @_;
13885: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
13886: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
13887: 	my @config = <$config>;
13888: 	&parse_hosts_tab(\@config);
13889: 	close($config);
13890: 	$loaded=1;
13891:     }
13892: 
13893:     sub hostname {
13894: 	&load_hosts_tab() if (!$loaded);
13895: 
13896: 	my ($lonid) = @_;
13897: 	return $hostname{$lonid};
13898:     }
13899: 
13900:     sub all_hostnames {
13901: 	&load_hosts_tab() if (!$loaded);
13902: 
13903: 	return %hostname;
13904:     }
13905: 
13906:     sub all_names {
13907:         my ($ignore_cache,$nocache) = @_;
13908: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
13909: 
13910: 	return %name_to_host;
13911:     }
13912: 
13913:     sub all_host_domain {
13914:         &load_hosts_tab() if (!$loaded);
13915:         return %hostdom;
13916:     }
13917: 
13918:     sub is_library {
13919: 	&load_hosts_tab() if (!$loaded);
13920: 
13921: 	return exists($libserv{$_[0]});
13922:     }
13923: 
13924:     sub all_library {
13925: 	&load_hosts_tab() if (!$loaded);
13926: 
13927: 	return %libserv;
13928:     }
13929: 
13930:     sub unique_library {
13931: 	#2x reverse removes all hostnames that appear more than once
13932:         my %unique = reverse &all_library();
13933:         return reverse %unique;
13934:     }
13935: 
13936:     sub get_servers {
13937: 	&load_hosts_tab() if (!$loaded);
13938: 
13939: 	my ($domain,$type) = @_;
13940: 	my %possible_hosts = ($type eq 'library') ? %libserv
13941: 	                                          : %hostname;
13942: 	my %result;
13943: 	if (ref($domain) eq 'ARRAY') {
13944: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
13945: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
13946: 		    $result{$host} = $hostname;
13947: 		}
13948: 	    }
13949: 	} else {
13950: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
13951: 		if ($hostdom{$host} eq $domain) {
13952: 		    $result{$host} = $hostname;
13953: 		}
13954: 	    }
13955: 	}
13956: 	return %result;
13957:     }
13958: 
13959:     sub get_unique_servers {
13960:         my %unique = reverse &get_servers(@_);
13961: 	return reverse %unique;
13962:     }
13963: 
13964:     sub host_domain {
13965: 	&load_hosts_tab() if (!$loaded);
13966: 
13967: 	my ($lonid) = @_;
13968: 	return $hostdom{$lonid};
13969:     }
13970: 
13971:     sub all_domains {
13972: 	&load_hosts_tab() if (!$loaded);
13973: 
13974: 	my %seen;
13975: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
13976: 	return @uniq;
13977:     }
13978: 
13979:     sub internet_dom {
13980:         &load_hosts_tab() if (!$loaded);
13981: 
13982:         my ($lonid) = @_;
13983:         return $internetdom{$lonid};
13984:     }
13985: 
13986:     sub is_LC_dns {
13987:         &load_hosts_tab() if (!$loaded);
13988: 
13989:         my ($hostname) = @_;
13990:         return exists($LC_dns_serv{$hostname});
13991:     }
13992: 
13993: }
13994: 
13995: { 
13996:     my %iphost;
13997:     my %name_to_ip;
13998:     my %lonid_to_ip;
13999: 
14000:     sub get_hosts_from_ip {
14001: 	my ($ip) = @_;
14002: 	my %iphosts = &get_iphost();
14003: 	if (ref($iphosts{$ip})) {
14004: 	    return @{$iphosts{$ip}};
14005: 	}
14006: 	return;
14007:     }
14008:     
14009:     sub reset_hosts_ip_info {
14010: 	undef(%iphost);
14011: 	undef(%name_to_ip);
14012: 	undef(%lonid_to_ip);
14013:     }
14014: 
14015:     sub get_host_ip {
14016: 	my ($lonid) = @_;
14017: 	if (exists($lonid_to_ip{$lonid})) {
14018: 	    return $lonid_to_ip{$lonid};
14019: 	}
14020: 	my $name=&hostname($lonid);
14021:    	my $ip = gethostbyname($name);
14022: 	return if (!$ip || length($ip) ne 4);
14023: 	$ip=inet_ntoa($ip);
14024: 	$name_to_ip{$name}   = $ip;
14025: 	$lonid_to_ip{$lonid} = $ip;
14026: 	return $ip;
14027:     }
14028:     
14029:     sub get_iphost {
14030: 	my ($ignore_cache,$nocache) = @_;
14031: 
14032: 	if (!$ignore_cache) {
14033: 	    if (%iphost) {
14034: 		return %iphost;
14035: 	    }
14036: 	    my ($ip_info,$cached)=
14037: 		&Apache::lonnet::is_cached_new('iphost','iphost');
14038: 	    if ($cached) {
14039: 		%iphost      = %{$ip_info->[0]};
14040: 		%name_to_ip  = %{$ip_info->[1]};
14041: 		%lonid_to_ip = %{$ip_info->[2]};
14042: 		return %iphost;
14043: 	    }
14044: 	}
14045: 
14046: 	# get yesterday's info for fallback
14047: 	my %old_name_to_ip;
14048: 	my ($ip_info,$cached)=
14049: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
14050: 	if ($cached) {
14051: 	    %old_name_to_ip = %{$ip_info->[1]};
14052: 	}
14053: 
14054: 	my %name_to_host = &all_names($ignore_cache,$nocache);
14055: 	foreach my $name (keys(%name_to_host)) {
14056: 	    my $ip;
14057: 	    if (!exists($name_to_ip{$name})) {
14058: 		$ip = gethostbyname($name);
14059: 		if (!$ip || length($ip) ne 4) {
14060: 		    if (defined($old_name_to_ip{$name})) {
14061: 			$ip = $old_name_to_ip{$name};
14062: 			&logthis("Can't find $name defaulting to old $ip");
14063: 		    } else {
14064: 			&logthis("Name $name no IP found");
14065: 			next;
14066: 		    }
14067: 		} else {
14068: 		    $ip=inet_ntoa($ip);
14069: 		}
14070: 		$name_to_ip{$name} = $ip;
14071: 	    } else {
14072: 		$ip = $name_to_ip{$name};
14073: 	    }
14074: 	    foreach my $id (@{ $name_to_host{$name} }) {
14075: 		$lonid_to_ip{$id} = $ip;
14076: 	    }
14077: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
14078: 	}
14079:         unless ($nocache) {
14080: 	    &do_cache_new('iphost','iphost',
14081: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
14082: 		          48*60*60);
14083:         }
14084: 
14085: 	return %iphost;
14086:     }
14087: 
14088:     #
14089:     #  Given a DNS returns the loncapa host name for that DNS 
14090:     # 
14091:     sub host_from_dns {
14092:         my ($dns) = @_;
14093:         my @hosts;
14094:         my $ip;
14095: 
14096:         if (exists($name_to_ip{$dns})) {
14097:             $ip = $name_to_ip{$dns};
14098:         }
14099:         if (!$ip) {
14100:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
14101:             if (length($ip) == 4) { 
14102: 	        $ip   = &IO::Socket::inet_ntoa($ip);
14103:             }
14104:         }
14105:         if ($ip) {
14106: 	    @hosts = get_hosts_from_ip($ip);
14107: 	    return $hosts[0];
14108:         }
14109:         return undef;
14110:     }
14111: 
14112:     sub get_internet_names {
14113:         my ($lonid) = @_;
14114:         return if ($lonid eq '');
14115:         my ($idnref,$cached)=
14116:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
14117:         if ($cached) {
14118:             return $idnref;
14119:         }
14120:         my $ip = &get_host_ip($lonid);
14121:         my @hosts = &get_hosts_from_ip($ip);
14122:         my %iphost = &get_iphost();
14123:         my (@idns,%seen);
14124:         foreach my $id (@hosts) {
14125:             my $dom = &host_domain($id);
14126:             my $prim_id = &domain($dom,'primary');
14127:             my $prim_ip = &get_host_ip($prim_id);
14128:             next if ($seen{$prim_ip});
14129:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
14130:                 foreach my $id (@{$iphost{$prim_ip}}) {
14131:                     my $intdom = &internet_dom($id);
14132:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
14133:                         push(@idns,$intdom);
14134:                     }
14135:                 }
14136:             }
14137:             $seen{$prim_ip} = 1;
14138:         }
14139:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
14140:     }
14141: 
14142: }
14143: 
14144: sub all_loncaparevs {
14145:     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);
14146: }
14147: 
14148: # ------------------------------------------------------- Read loncaparev table
14149: {
14150:     sub load_loncaparevs {
14151:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
14152:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
14153:                 while (my $configline=<$config>) {
14154:                     chomp($configline);
14155:                     my ($hostid,$loncaparev)=split(/:/,$configline);
14156:                     $loncaparevs{$hostid}=$loncaparev;
14157:                 }
14158:                 close($config);
14159:             }
14160:         }
14161:     }
14162: }
14163: 
14164: # ----------------------------------------------------- Read serverhostID table
14165: {
14166:     sub load_serverhomeIDs {
14167:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
14168:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
14169:                 while (my $configline=<$config>) {
14170:                     chomp($configline);
14171:                     my ($name,$id)=split(/:/,$configline);
14172:                     $serverhomeIDs{$name}=$id;
14173:                 }
14174:                 close($config);
14175:             }
14176:         }
14177:     }
14178: }
14179: 
14180: 
14181: BEGIN {
14182: 
14183: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
14184:     unless ($readit) {
14185: {
14186:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
14187:     %perlvar = (%perlvar,%{$configvars});
14188: }
14189: 
14190: 
14191: # ------------------------------------------------------ Read spare server file
14192: {
14193:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
14194: 
14195:     while (my $configline=<$config>) {
14196:        chomp($configline);
14197:        if ($configline) {
14198: 	   my ($host,$type) = split(':',$configline,2);
14199: 	   if (!defined($type) || $type eq '') { $type = 'default' };
14200: 	   push(@{ $spareid{$type} }, $host);
14201:        }
14202:     }
14203:     close($config);
14204: }
14205: # ------------------------------------------------------------ Read permissions
14206: {
14207:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
14208: 
14209:     while (my $configline=<$config>) {
14210: 	chomp($configline);
14211: 	if ($configline) {
14212: 	    my ($role,$perm)=split(/ /,$configline);
14213: 	    if ($perm ne '') { $pr{$role}=$perm; }
14214: 	}
14215:     }
14216:     close($config);
14217: }
14218: 
14219: # -------------------------------------------- Read plain texts for permissions
14220: {
14221:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
14222: 
14223:     while (my $configline=<$config>) {
14224: 	chomp($configline);
14225: 	if ($configline) {
14226: 	    my ($short,@plain)=split(/:/,$configline);
14227:             %{$prp{$short}} = ();
14228: 	    if (@plain > 0) {
14229:                 $prp{$short}{'std'} = $plain[0];
14230:                 for (my $i=1; $i<@plain; $i++) {
14231:                     $prp{$short}{'alt'.$i} = $plain[$i];  
14232:                 }
14233:             }
14234: 	}
14235:     }
14236:     close($config);
14237: }
14238: 
14239: # ---------------------------------------------------------- Read package table
14240: {
14241:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
14242: 
14243:     while (my $configline=<$config>) {
14244: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
14245: 	chomp($configline);
14246: 	my ($short,$plain)=split(/:/,$configline);
14247: 	my ($pack,$name)=split(/\&/,$short);
14248: 	if ($plain ne '') {
14249: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
14250: 	    $packagetab{$short}=$plain; 
14251: 	}
14252:     }
14253:     close($config);
14254: }
14255: 
14256: # --------------------------------------------------------- Read loncaparev table
14257: 
14258: &load_loncaparevs();
14259: 
14260: # ------------------------------------------------------- Read serverhostID table
14261: 
14262: &load_serverhomeIDs();
14263: 
14264: # ---------------------------------------------------------- Read releaseslist XML
14265: {
14266:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
14267:     if (-e $file) {
14268:         my $parser = HTML::LCParser->new($file);
14269:         while (my $token = $parser->get_token()) {
14270:             if ($token->[0] eq 'S') {
14271:                 my $item = $token->[1];
14272:                 my $name = $token->[2]{'name'};
14273:                 my $value = $token->[2]{'value'};
14274:                 if ($item ne '' && $name ne '' && $value ne '') {
14275:                     my $release = $parser->get_text();
14276:                     $release =~ s/(^\s*|\s*$ )//gx;
14277:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
14278:                 }
14279:             }
14280:         }
14281:     }
14282: }
14283: 
14284: # ---------------------------------------------------------- Read managers table
14285: {
14286:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
14287:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
14288:             while (my $configline=<$config>) {
14289:                 chomp($configline);
14290:                 next if ($configline =~ /^\#/);
14291:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
14292:                     $managerstab{$configline} = 1;
14293:                 }
14294:             }
14295:             close($config);
14296:         }
14297:     }
14298: }
14299: 
14300: # ------------- set up temporary directory
14301: {
14302:     $tmpdir = LONCAPA::tempdir();
14303: 
14304: }
14305: 
14306: # ------------- set default texengine (domain default overrides this)
14307: {
14308:     $deftex = LONCAPA::texengine();
14309: }
14310: 
14311: # ------------- set default minimum length for passwords for internal auth users
14312: {
14313:     $passwdmin = LONCAPA::passwd_min();
14314: }
14315: 
14316: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
14317: 				'compress_threshold'=> 20_000,
14318:  			        });
14319: 
14320: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
14321: $dumpcount=0;
14322: $locknum=0;
14323: 
14324: &logtouch();
14325: &logthis('<font color="yellow">INFO: Read configuration</font>');
14326: $readit=1;
14327:     {
14328: 	use integer;
14329: 	my $test=(2**32)+1;
14330: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
14331: 	&logthis(" Detected 64bit platform ($_64bit)");
14332:     }
14333: }
14334: }
14335: 
14336: 1;
14337: __END__
14338: 
14339: =pod
14340: 
14341: =head1 NAME
14342: 
14343: Apache::lonnet - Subroutines to ask questions about things in the network.
14344: 
14345: =head1 SYNOPSIS
14346: 
14347: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
14348: 
14349:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
14350: 
14351: Common parameters:
14352: 
14353: =over 4
14354: 
14355: =item *
14356: 
14357: $uname : an internal username (if $cname expecting a course Id specifically)
14358: 
14359: =item *
14360: 
14361: $udom : a domain (if $cdom expecting a course's domain specifically)
14362: 
14363: =item *
14364: 
14365: $symb : a resource instance identifier
14366: 
14367: =item *
14368: 
14369: $namespace : the name of a .db file that contains the data needed or
14370: being set.
14371: 
14372: =back
14373: 
14374: =head1 OVERVIEW
14375: 
14376: lonnet provides subroutines which interact with the
14377: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
14378: about classes, users, and resources.
14379: 
14380: For many of these objects you can also use this to store data about
14381: them or modify them in various ways.
14382: 
14383: =head2 Symbs
14384: 
14385: To identify a specific instance of a resource, LON-CAPA uses symbols
14386: or "symbs"X<symb>. These identifiers are built from the URL of the
14387: map, the resource number of the resource in the map, and the URL of
14388: the resource itself. The latter is somewhat redundant, but might help
14389: if maps change.
14390: 
14391: An example is
14392: 
14393:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
14394: 
14395: The respective map entry is
14396: 
14397:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
14398:   title="Problem 2">
14399:  </resource>
14400: 
14401: Symbs are used by the random number generator, as well as to store and
14402: restore data specific to a certain instance of for example a problem.
14403: 
14404: =head2 Storing And Retrieving Data
14405: 
14406: X<store()>X<cstore()>X<restore()>Three of the most important functions
14407: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
14408: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
14409: is is the non-critical message twin of cstore. These functions are for
14410: handlers to store a perl hash to a user's permanent data space in an
14411: easy manner, and to retrieve it again on another call. It is expected
14412: that a handler would use this once at the beginning to retrieve data,
14413: and then again once at the end to send only the new data back.
14414: 
14415: The data is stored in the user's data directory on the user's
14416: homeserver under the ID of the course.
14417: 
14418: The hash that is returned by restore will have all of the previous
14419: value for all of the elements of the hash.
14420: 
14421: Example:
14422: 
14423:  #creating a hash
14424:  my %hash;
14425:  $hash{'foo'}='bar';
14426: 
14427:  #storing it
14428:  &Apache::lonnet::cstore(\%hash);
14429: 
14430:  #changing a value
14431:  $hash{'foo'}='notbar';
14432: 
14433:  #adding a new value
14434:  $hash{'bar'}='foo';
14435:  &Apache::lonnet::cstore(\%hash);
14436: 
14437:  #retrieving the hash
14438:  my %history=&Apache::lonnet::restore();
14439: 
14440:  #print the hash
14441:  foreach my $key (sort(keys(%history))) {
14442:    print("\%history{$key} = $history{$key}");
14443:  }
14444: 
14445: Will print out:
14446: 
14447:  %history{1:foo} = bar
14448:  %history{1:keys} = foo:timestamp
14449:  %history{1:timestamp} = 990455579
14450:  %history{2:bar} = foo
14451:  %history{2:foo} = notbar
14452:  %history{2:keys} = foo:bar:timestamp
14453:  %history{2:timestamp} = 990455580
14454:  %history{bar} = foo
14455:  %history{foo} = notbar
14456:  %history{timestamp} = 990455580
14457:  %history{version} = 2
14458: 
14459: Note that the special hash entries C<keys>, C<version> and
14460: C<timestamp> were added to the hash. C<version> will be equal to the
14461: total number of versions of the data that have been stored. The
14462: C<timestamp> attribute will be the UNIX time the hash was
14463: stored. C<keys> is available in every historical section to list which
14464: keys were added or changed at a specific historical revision of a
14465: hash.
14466: 
14467: B<Warning>: do not store the hash that restore returns directly. This
14468: will cause a mess since it will restore the historical keys as if the
14469: were new keys. I.E. 1:foo will become 1:1:foo etc.
14470: 
14471: Calling convention:
14472: 
14473:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
14474:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
14475: 
14476: For more detailed information, see lonnet specific documentation.
14477: 
14478: =head1 RETURN MESSAGES
14479: 
14480: =over 4
14481: 
14482: =item * B<con_lost>: unable to contact remote host
14483: 
14484: =item * B<con_delayed>: unable to contact remote host, message will be delivered
14485: when the connection is brought back up
14486: 
14487: =item * B<con_failed>: unable to contact remote host and unable to save message
14488: for later delivery
14489: 
14490: =item * B<error:>: an error a occurred, a description of the error follows the :
14491: 
14492: =item * B<no_such_host>: unable to fund a host associated with the user/domain
14493: that was requested
14494: 
14495: =back
14496: 
14497: =head1 PUBLIC SUBROUTINES
14498: 
14499: =head2 Session Environment Functions
14500: 
14501: =over 4
14502: 
14503: =item * 
14504: X<appenv()>
14505: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
14506: the user envirnoment file, and will be restored for each access this
14507: user makes during this session, also modifies the %env for the current
14508: process. Optional rolesarrayref - if defined contains a reference to an array
14509: of roles which are exempt from the restriction on modifying user.role entries 
14510: in the user's environment.db and in %env.    
14511: 
14512: =item *
14513: X<delenv()>
14514: B<delenv($delthis,$regexp)>: removes all items from the session
14515: environment file that begin with $delthis. If the 
14516: optional second arg - $regexp - is true, $delthis is treated as a 
14517: regular expression, otherwise \Q$delthis\E is used. 
14518: The values are also deleted from the current processes %env.
14519: 
14520: =item * get_env_multiple($name) 
14521: 
14522: gets $name from the %env hash, it seemlessly handles the cases where multiple
14523: values may be defined and end up as an array ref.
14524: 
14525: returns an array of values
14526: 
14527: =back
14528: 
14529: =head2 User Information
14530: 
14531: =over 4
14532: 
14533: =item *
14534: X<queryauthenticate()>
14535: B<queryauthenticate($uname,$udom)>: try to determine user's current 
14536: authentication scheme
14537: 
14538: =item *
14539: X<authenticate()>
14540: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
14541: authenticate user from domain's lib servers (first use the current
14542: one). C<$upass> should be the users password.
14543: $checkdefauth is optional (value is 1 if a check should be made to
14544:    authenticate user using default authentication method, and allow
14545:    account creation if username does not have account in the domain).
14546: $clientcancheckhost is optional (value is 1 if checking whether the
14547:    server can host will occur on the client side in lonauth.pm).   
14548: 
14549: =item *
14550: X<homeserver()>
14551: B<homeserver($uname,$udom)>: find the server which has
14552: the user's directory and files (there must be only one), this caches
14553: the answer, and also caches if there is a borken connection.
14554: 
14555: =item *
14556: X<idget()>
14557: B<idget($udom,@ids)>: find the usernames behind a list of IDs
14558: (IDs are a unique resource in a domain, there must be only 1 ID per
14559: username, and only 1 username per ID in a specific domain) (returns
14560: hash: id=>name,id=>name)
14561: 
14562: =item *
14563: X<idrget()>
14564: B<idrget($udom,@unames)>: find the IDs behind a list of
14565: usernames (returns hash: name=>id,name=>id)
14566: 
14567: =item *
14568: X<idput()>
14569: B<idput($udom,%ids)>: store away a list of names and associated IDs
14570: 
14571: =item *
14572: X<rolesinit()>
14573: B<rolesinit($udom,$username)>: get user privileges.
14574: returns user role, first access and timer interval hashes
14575: 
14576: =item *
14577: X<privileged()>
14578: B<privileged($username,$domain)>: returns a true if user has a
14579: privileged and active role (i.e. su or dc), false otherwise.
14580: 
14581: =item *
14582: X<getsection()>
14583: B<getsection($udom,$uname,$cname)>: finds the section of student in the
14584: course $cname, return section name/number or '' for "not in course"
14585: and '-1' for "no section"
14586: 
14587: =item *
14588: X<userenvironment()>
14589: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
14590: passed in @what from the requested user's environment, returns a hash
14591: 
14592: =item * 
14593: X<userlog_query()>
14594: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
14595: activity.log file. %filters defines filters applied when parsing the
14596: log file. These can be start or end timestamps, or the type of action
14597: - log to look for Login or Logout events, check for Checkin or
14598: Checkout, role for role selection. The response is in the form
14599: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
14600: escaped strings of the action recorded in the activity.log file.
14601: 
14602: =back
14603: 
14604: =head2 User Roles
14605: 
14606: =over 4
14607: 
14608: =item *
14609: 
14610: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
14611: returns codes for allowed actions.
14612: 
14613: The first argument is required, all others are optional.
14614: 
14615: $priv is the privilege being checked.
14616: $uri contains additional information about what is being checked for access (e.g.,
14617: URL, course ID etc.).
14618: $symb is the unique resource instance identifier in a course; if needed,
14619: but not provided, it will be retrieved via a call to &symbread().
14620: $role is the role for which a priv is being checked (only used if priv is evb).
14621: $clientip is the user's IP address (only used when checking for access to portfolio
14622: files).
14623: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
14624: prevents recursive calls to &allowed.
14625: 
14626:  F: full access
14627:  U,I,K: authentication modes (cxx only)
14628:  '': forbidden
14629:  1: user needs to choose course
14630:  2: browse allowed
14631:  A: passphrase authentication needed
14632:  B: access temporarily blocked because of a blocking event in a course.
14633: 
14634: =item *
14635: 
14636: constructaccess($url,$setpriv) : check for access to construction space URL
14637: 
14638: See if the owner domain and name in the URL match those in the
14639: expected environment.  If so, return three element list
14640: ($ownername,$ownerdomain,$ownerhome).
14641: 
14642: Otherwise return the null string.
14643: 
14644: If second argument 'setpriv' is true, it assigns the privileges,
14645: and returns the same three element list, unless the owner has
14646: blocked "ad hoc" Domain Coordinator access to the Author Space,
14647: in which case the null string is returned.
14648: 
14649: =item *
14650: 
14651: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
14652: define a custom role rolename set privileges in format of lonTabs/roles.tab
14653: for system, domain, and course level. $uname and $udom are optional (current
14654: user's username and domain will be used when either of $uname or $udom are absent.
14655: 
14656: =item *
14657: 
14658: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
14659: (rolesplain.tab); plain text explanation of a user role term.
14660: $type is Course (default) or Community.
14661: If $forcedefault evaluates to true, text returned will be default 
14662: text for $type. Otherwise, if this is a course, the text returned 
14663: will be a custom name for the role (if defined in the course's 
14664: environment).  If no custom name is defined the default is returned.
14665:    
14666: =item *
14667: 
14668: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
14669: All arguments are optional. Returns a hash of a roles, either for
14670: co-author/assistant author roles for a user's Construction Space
14671: (default), or if $context is 'userroles', roles for the user himself,
14672: In the hash, keys are set to colon-separated $uname,$udom,$role, and
14673: (optionally) if $withsec is true, a fourth colon-separated item - $section.
14674: For each key, value is set to colon-separated start and end times for
14675: the role.  If no username and domain are specified, will default to
14676: current user/domain. Types, roles, and roledoms are references to arrays
14677: of role statuses (active, future or previous), roles 
14678: (e.g., cc,in, st etc.) and domains of the roles which can be used
14679: to restrict the list of roles reported. If no array ref is 
14680: provided for types, will default to return only active roles.
14681: 
14682: =item *
14683: 
14684: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
14685: user: $uname:$udom has a role in the course: $cdom_$cnum.
14686: 
14687: Additional optional arguments are: $type (if role checking is to be restricted
14688: to certain user status types -- previous (expired roles), active (currently
14689: available roles) or future (roles available in the future), and
14690: $hideprivileged -- if true will not report course roles for users who
14691: have active Domain Coordinator role in course's domain or in additional
14692: domains (specified in 'Domains to check for privileged users' in course
14693: environment -- set via:  Course Settings -> Classlists and staff listing).
14694: 
14695: =item *
14696: 
14697: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
14698: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
14699: $possdomains and $possroles are optional array refs -- to domains to check and
14700: roles to check.  If $possdomains is not specified, a dump will be done of the
14701: users' roles.db to check for a dc or su role in any domain. This can be
14702: time consuming if &privileged is called repeatedly (e.g., when displaying a
14703: classlist), so in such cases, supplying a $possdomains array is preferred, as
14704: this then allows &privileged_by_domain() to be used, which caches the identity
14705: of privileged users, eliminating the need for repeated calls to &dump().
14706: 
14707: =item *
14708: 
14709: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
14710: where the outer hash keys are domains specified in the $possdomains array ref,
14711: next inner hash keys are privileged roles specified in the $roles array ref,
14712: and the innermost hash contains key = value pairs for username:domain = end:start
14713: for active or future "privileged" users with that role in that domain. To avoid
14714: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
14715: innerhash are cached using priv_$role and $dom as the identifiers.
14716: 
14717: =back
14718: 
14719: =head2 User Modification
14720: 
14721: =over 4
14722: 
14723: =item *
14724: 
14725: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
14726: user for the level given by URL.  Optional start and end dates (leave empty
14727: string or zero for "no date")
14728: 
14729: =item *
14730: 
14731: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
14732: change a users, password, possible return values are: ok,
14733: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
14734: refused
14735: 
14736: =item *
14737: 
14738: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
14739: 
14740: =item *
14741: 
14742: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
14743:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
14744: 
14745: will update user information (firstname,middlename,lastname,generation,
14746: permanentemail), and if forceid is true, student/employee ID also.
14747: A user's institutional affiliation(s) can also be updated.
14748: User information fields will not be overwritten with empty entries 
14749: unless the field is included in the $candelete array reference.
14750: This array is included when a single user is modified via "Manage Users",
14751: or when Autoupdate.pl is run by cron in a domain.
14752: 
14753: =item *
14754: 
14755: modifystudent
14756: 
14757: modify a student's enrollment and identification information.
14758: The course id is resolved based on the current user's environment.  
14759: This means the invoking user must be a course coordinator or otherwise
14760: associated with a course.
14761: 
14762: This call is essentially a wrapper for lonnet::modifyuser and
14763: lonnet::modify_student_enrollment
14764: 
14765: Inputs: 
14766: 
14767: =over 4
14768: 
14769: =item B<$udom> Student's loncapa domain
14770: 
14771: =item B<$uname> Student's loncapa login name
14772: 
14773: =item B<$uid> Student/Employee ID
14774: 
14775: =item B<$umode> Student's authentication mode
14776: 
14777: =item B<$upass> Student's password
14778: 
14779: =item B<$first> Student's first name
14780: 
14781: =item B<$middle> Student's middle name
14782: 
14783: =item B<$last> Student's last name
14784: 
14785: =item B<$gene> Student's generation
14786: 
14787: =item B<$usec> Student's section in course
14788: 
14789: =item B<$end> Unix time of the roles expiration
14790: 
14791: =item B<$start> Unix time of the roles start date
14792: 
14793: =item B<$forceid> If defined, allow $uid to be changed
14794: 
14795: =item B<$desiredhome> server to use as home server for student
14796: 
14797: =item B<$email> Student's permanent e-mail address
14798: 
14799: =item B<$type> Type of enrollment (auto or manual)
14800: 
14801: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
14802: 
14803: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
14804: 
14805: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
14806: 
14807: =item B<$context> role change context (shown in User Management Logs display in a course)
14808: 
14809: =item B<$inststatus> institutional status of user - : separated string of escaped status types
14810: 
14811: =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.
14812: 
14813: =back
14814: 
14815: =item *
14816: 
14817: modify_student_enrollment
14818: 
14819: Change a student's enrollment status in a class.  The environment variable
14820: 'role.request.course' must be defined for this function to proceed.
14821: 
14822: Inputs:
14823: 
14824: =over 4
14825: 
14826: =item $udom, student's domain
14827: 
14828: =item $uname, student's name
14829: 
14830: =item $uid, student's user id
14831: 
14832: =item $first, student's first name
14833: 
14834: =item $middle
14835: 
14836: =item $last
14837: 
14838: =item $gene
14839: 
14840: =item $usec
14841: 
14842: =item $end
14843: 
14844: =item $start
14845: 
14846: =item $type
14847: 
14848: =item $locktype
14849: 
14850: =item $cid
14851: 
14852: =item $selfenroll
14853: 
14854: =item $context
14855: 
14856: =item $credits, number of credits student will earn from this class
14857: 
14858: =item $instsec, institutional course section code for student
14859: 
14860: =back
14861: 
14862: 
14863: =item *
14864: 
14865: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
14866: custom role; give a custom role to a user for the level given by URL.  Specify
14867: name and domain of role author, and role name
14868: 
14869: =item *
14870: 
14871: revokerole($udom,$uname,$url,$role) : revoke a role for url
14872: 
14873: =item *
14874: 
14875: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
14876: 
14877: =back
14878: 
14879: =head2 Course Infomation
14880: 
14881: =over 4
14882: 
14883: =item *
14884: 
14885: coursedescription($courseid,$options) : returns a hash of information about the
14886: specified course id, including all environment settings for the
14887: course, the description of the course will be in the hash under the
14888: key 'description'
14889: 
14890: $options is an optional parameter that if supplied is a hash reference that controls
14891: what how this function works.  It has the following key/values:
14892: 
14893: =over 4
14894: 
14895: =item freshen_cache
14896: 
14897: If defined, and the environment cache for the course is valid, it is 
14898: returned in the returned hash.
14899: 
14900: =item one_time
14901: 
14902: If defined, the last cache time is set to _now_
14903: 
14904: =item user
14905: 
14906: If defined, the supplied username is used instead of the current user.
14907: 
14908: 
14909: =back
14910: 
14911: =item *
14912: 
14913: resdata($name,$domain,$type,@which) : request for current parameter
14914: setting for a specific $type, where $type is either 'course' or 'user',
14915: @what should be a list of parameters to ask about. This routine caches
14916: answers for 10 minutes.
14917: 
14918: =item *
14919: 
14920: get_courseresdata($courseid, $domain) : dump the entire course resource
14921: data base, returning a hash that is keyed by the resource name and has
14922: values that are the resource value.  I believe that the timestamps and
14923: versions are also returned.
14924: 
14925: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
14926: supplemental content area. This routine caches the number of files for
14927: 10 minutes.
14928: 
14929: =back
14930: 
14931: =head2 Course Modification
14932: 
14933: =over 4
14934: 
14935: =item *
14936: 
14937: writecoursepref($courseid,%prefs) : write preferences (environment
14938: database) for a course
14939: 
14940: =item *
14941: 
14942: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
14943: 
14944: =item *
14945: 
14946: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
14947: 
14948: =item *
14949: 
14950: is_course($courseid), is_course($cdom, $cnum)
14951: 
14952: Accepts either a combined $courseid (in the form of domain_courseid) or the
14953: two component version $cdom, $cnum. It checks if the specified course exists.
14954: 
14955: Returns:
14956:     undef if the course doesn't exist, otherwise
14957:     in scalar context the combined courseid.
14958:     in list context the two components of the course identifier, domain and 
14959:     courseid.    
14960: 
14961: =back
14962: 
14963: =head2 Bubblesheet Configuration
14964: 
14965: =over 4
14966: 
14967: =item *
14968: 
14969: get_scantron_config($which)
14970: 
14971: $which - the name of the configuration to parse from the file.
14972: 
14973: Parses and returns the bubblesheet configuration line selected as a
14974: hash of configuration file fields.
14975: 
14976: 
14977: Returns:
14978:     If the named configuration is not in the file, an empty
14979:     hash is returned.
14980: 
14981:     a hash with the fields
14982:       name         - internal name for the this configuration setup
14983:       description  - text to display to operator that describes this config
14984:       CODElocation - if 0 or the string 'none'
14985:                           - no CODE exists for this config
14986:                      if -1 || the string 'letter'
14987:                           - a CODE exists for this config and is
14988:                             a string of letters
14989:                      Unsupported value (but planned for future support)
14990:                           if a positive integer
14991:                                - The CODE exists as the first n items from
14992:                                  the question section of the form
14993:                           if the string 'number'
14994:                                - The CODE exists for this config and is
14995:                                  a string of numbers
14996:       CODEstart   - (only matter if a CODE exists) column in the line where
14997:                      the CODE starts
14998:       CODElength  - length of the CODE
14999:       IDstart     - column where the student/employee ID starts
15000:       IDlength    - length of the student/employee ID info
15001:       Qstart      - column where the information from the bubbled
15002:                     'questions' start
15003:       Qlength     - number of columns comprising a single bubble line from
15004:                     the sheet. (usually either 1 or 10)
15005:       Qon         - either a single character representing the character used
15006:                     to signal a bubble was chosen in the positional setup, or
15007:                     the string 'letter' if the letter of the chosen bubble is
15008:                     in the final, or 'number' if a number representing the
15009:                     chosen bubble is in the file (1->A 0->J)
15010:       Qoff        - the character used to represent that a bubble was
15011:                     left blank
15012:       PaperID     - if the scanning process generates a unique number for each
15013:                     sheet scanned the column that this ID number starts in
15014:       PaperIDlength - number of columns that comprise the unique ID number
15015:                       for the sheet of paper
15016:       FirstName   - column that the first name starts in
15017:       FirstNameLength - number of columns that the first name spans
15018:       LastName    - column that the last name starts in
15019:       LastNameLength - number of columns that the last name spans
15020:       BubblesPerRow - number of bubbles available in each row used to
15021:                       bubble an answer. (If not specified, 10 assumed).
15022: 
15023: 
15024: =item *
15025: 
15026: get_scantronformat_file($cdom)
15027: 
15028: $cdom - the course's domain (optional); if not supplied, uses
15029: domain for current $env{'request.course.id'}.
15030: 
15031: Returns an array containing lines from the scantron format file for
15032: the domain of the course.
15033: 
15034: If a url for a custom.tab file is listed in domain's configuration.db,
15035: lines are from this file.
15036: 
15037: Otherwise, if a default.tab has been published in RES space by the
15038: domainconfig user, lines are from this file.
15039: 
15040: Otherwise, fall back to getting lines from the legacy file on the
15041: local server:  /home/httpd/lonTabs/default_scantronformat.tab
15042: 
15043: =back
15044: 
15045: =head2 Resource Subroutines
15046: 
15047: =over 4
15048: 
15049: =item *
15050: 
15051: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
15052: 
15053: =item *
15054: 
15055: repcopy($filename) : subscribes to the requested file, and attempts to
15056: replicate from the owning library server, Might return
15057: 'unavailable', 'not_found', 'forbidden', 'ok', or
15058: 'bad_request', also attempts to grab the metadata for the
15059: resource. Expects the local filesystem pathname
15060: (/home/httpd/html/res/....)
15061: 
15062: =back
15063: 
15064: =head2 Resource Information
15065: 
15066: =over 4
15067: 
15068: =item *
15069: 
15070: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
15071: and returns the value of a variety of different possible values,
15072: $varname should be a request string, and the other parameters can be
15073: used to specify who and what one is asking about. Ordinarily, $cid 
15074: does not need to be specified, as it is retrived from 
15075: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
15076: within lonuserstate::loadmap() when initializing a course, before
15077: $env{'request.course.id'} has been set, so it needs to be provided
15078: in that one case.
15079: 
15080: Possible values for $varname are environment.lastname (or other item
15081: from the envirnment hash), user.name (or someother aspect about the
15082: user), resource.0.maxtries (or some other part and parameter of a
15083: resource)
15084: 
15085: =item *
15086: 
15087: directcondval($number) : get current value of a condition; reads from a state
15088: string
15089: 
15090: =item *
15091: 
15092: condval($condidx) : value of condition index based on state
15093: 
15094: =item *
15095: 
15096: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
15097: resource's metadata, $what should be either a specific key, or either
15098: 'keys' (to get a list of possible keys) or 'packages' to get a list of
15099: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
15100: 
15101: this function automatically caches all requests
15102: 
15103: =item *
15104: 
15105: metadata_query($query,$custom,$customshow) : make a metadata query against the
15106: network of library servers; returns file handle of where SQL and regex results
15107: will be stored for query
15108: 
15109: =item *
15110: 
15111: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
15112: return symbolic list entry (all arguments optional).
15113: 
15114: Args: filename is the filename (including path) for the file for which a symb
15115: is required; donotrecurse, if true will prevent calls to allowed() being made
15116: to check access status if more than one resource was found in the bighash
15117: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
15118: a randompick); ignorecachednull, if true will prevent a symb of '' being
15119: returned if $env{$cache_str} is defined as ''; checkforblock if true will
15120: cause possible symbs to be checked to determine if they are subject to content
15121: blocking, if so they will not be included as possible symbs; possibles is a
15122: ref to a hash, which, as a side effect, will be populated with all possible
15123: symbs (content blocking not tested).
15124: 
15125: returns the data handle
15126: 
15127: =item *
15128: 
15129: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
15130: and is a possible symb for the URL in $thisfn, and if is an encrypted
15131: resource that the user accessed using /enc/ returns a 1 on success, 0
15132: on failure, user must be in a course, as it assumes the existence of
15133: the course initial hash, and uses $env('request.course.id'}.  The third
15134: arg is an optional reference to a scalar.  If this arg is passed in the
15135: call to symbverify, it will be set to 1 if the symb has been set to be 
15136: encrypted; otherwise it will be null.
15137: 
15138: =item *
15139: 
15140: symbclean($symb) : removes versions numbers from a symb, returns the
15141: cleaned symb
15142: 
15143: =item *
15144: 
15145: is_on_map($uri) : checks if the $uri is somewhere on the current
15146: course map, user must be in a course for it to work.
15147: 
15148: =item *
15149: 
15150: numval($salt) : return random seed value (addend for rndseed)
15151: 
15152: =item *
15153: 
15154: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
15155: a random seed, all arguments are optional, if they aren't sent it uses the
15156: environment to derive them. Note: if symb isn't sent and it can't get one
15157: from &symbread it will use the current time as its return value
15158: 
15159: =item *
15160: 
15161: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
15162: unfakeable, receipt
15163: 
15164: =item *
15165: 
15166: receipt() : API to ireceipt working off of env values; given out to users
15167: 
15168: =item *
15169: 
15170: countacc($url) : count the number of accesses to a given URL
15171: 
15172: =item *
15173: 
15174: 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
15175: 
15176: =item *
15177: 
15178: 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)
15179: 
15180: =item *
15181: 
15182: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
15183: 
15184: =item *
15185: 
15186: devalidate($symb) : devalidate temporary spreadsheet calculations,
15187: forcing spreadsheet to reevaluate the resource scores next time.
15188: 
15189: =item *
15190: 
15191: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
15192: when viewing in course context.
15193: 
15194:  input: six args -- filename (decluttered), course number, course domain,
15195:                     url, symb (if registered) and group (if this is a
15196:                     group item -- e.g., bulletin board, group page etc.).
15197: 
15198:  output: array of five scalars --
15199:          $cfile -- url for file editing if editable on current server
15200:          $home -- homeserver of resource (i.e., for author if published,
15201:                                           or course if uploaded.).
15202:          $switchserver --  1 if server switch will be needed.
15203:          $forceedit -- 1 if icon/link should be to go to edit mode
15204:          $forceview -- 1 if icon/link should be to go to view mode
15205: 
15206: =item *
15207: 
15208: is_course_upload($file,$cnum,$cdom)
15209: 
15210: Used in course context to determine if current file was uploaded to
15211: the course (i.e., would be found in /userfiles/docs on the course's
15212: homeserver.
15213: 
15214:   input: 3 args -- filename (decluttered), course number and course domain.
15215:   output: boolean -- 1 if file was uploaded.
15216: 
15217: =back
15218: 
15219: =head2 Storing/Retreiving Data
15220: 
15221: =over 4
15222: 
15223: =item *
15224: 
15225: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash 
15226: permanently for this url; hashref needs to be given and should be a \%hashname;
15227: the remaining args aren't required and if they aren't passed or are '' they will
15228: be derived from the env (with the exception of $laststore, which is an
15229: optional arg used when a user's submission is stored in grading).
15230: $laststore is $version=$timestamp, where $version is the most recent version
15231: number retrieved for the corresponding $symb in the $namespace db file, and
15232: $timestamp is the timestamp for that transaction (UNIX time).
15233: $laststore is currently only passed when cstore() is called by
15234: structuretags::finalize_storage().
15235: 
15236: =item *
15237: 
15238: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store 
15239: but uses critical subroutine
15240: 
15241: =item *
15242: 
15243: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
15244: all args are optional
15245: 
15246: =item *
15247: 
15248: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
15249: dumps the complete (or key matching regexp) namespace into a hash
15250: ($udom, $uname, $regexp, $range are optional) for a namespace that is
15251: normally &store()ed into
15252: 
15253: $range should be either an integer '100' (give me the first 100
15254:                                            matching records)
15255:               or be  two integers sperated by a - with no spaces
15256:                  '30-50' (give me the 30th through the 50th matching
15257:                           records)
15258: 
15259: 
15260: =item *
15261: 
15262: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
15263: replaces a &store() version of data with a replacement set of data
15264: for a particular resource in a namespace passed in the $storehash hash 
15265: reference. If $tolog is true, the transaction is logged in the courselog
15266: with an action=PUTSTORE.
15267: 
15268: =item *
15269: 
15270: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
15271: works very similar to store/cstore, but all data is stored in a
15272: temporary location and can be reset using tmpreset, $storehash should
15273: be a hash reference, returns nothing on success
15274: 
15275: =item *
15276: 
15277: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
15278: similar to restore, but all data is stored in a temporary location and
15279: can be reset using tmpreset. Returns a hash of values on success,
15280: error string otherwise.
15281: 
15282: =item *
15283: 
15284: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
15285: deltes all keys for $symb form the temporary storage hash.
15286: 
15287: =item *
15288: 
15289: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
15290: reference filled in from namesp ($udom and $uname are optional)
15291: 
15292: =item *
15293: 
15294: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
15295: namesp ($udom and $uname are optional)
15296: 
15297: =item *
15298: 
15299: dump($namespace,$udom,$uname,$regexp,$range) : 
15300: dumps the complete (or key matching regexp) namespace into a hash
15301: ($udom, $uname, $regexp, $range are optional)
15302: 
15303: $range should be either an integer '100' (give me the first 100
15304:                                            matching records)
15305:               or be  two integers sperated by a - with no spaces
15306:                  '30-50' (give me the 30th through the 50th matching
15307:                           records)
15308: =item *
15309: 
15310: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
15311: $store can be a scalar, an array reference, or if the amount to be 
15312: incremented is > 1, a hash reference.
15313: 
15314: ($udom and $uname are optional)
15315: 
15316: =item *
15317: 
15318: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
15319: ($udom and $uname are optional)
15320: 
15321: =item *
15322: 
15323: cput($namespace,$storehash,$udom,$uname) : critical put
15324: ($udom and $uname are optional)
15325: 
15326: =item *
15327: 
15328: newput($namespace,$storehash,$udom,$uname) :
15329: 
15330: Attempts to store the items in the $storehash, but only if they don't
15331: currently exist, if this succeeds you can be certain that you have 
15332: successfully created a new key value pair in the $namespace db.
15333: 
15334: 
15335: Args:
15336:  $namespace: name of database to store values to
15337:  $storehash: hashref to store to the db
15338:  $udom: (optional) domain of user containing the db
15339:  $uname: (optional) name of user caontaining the db
15340: 
15341: Returns:
15342:  'ok' -> succeeded in storing all keys of $storehash
15343:  'key_exists: <key>' -> failed to anything out of $storehash, as at
15344:                         least <key> already existed in the db (other
15345:                         requested keys may also already exist)
15346:  'error: <msg>' -> unable to tie the DB or other error occurred
15347:  'con_lost' -> unable to contact request server
15348:  'refused' -> action was not allowed by remote machine
15349: 
15350: 
15351: =item *
15352: 
15353: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
15354: reference filled in from namesp (encrypts the return communication)
15355: ($udom and $uname are optional)
15356: 
15357: =item *
15358: 
15359: log($udom,$name,$home,$message) : write to permanent log for user; use
15360: critical subroutine
15361: 
15362: =item *
15363: 
15364: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
15365: array reference filled in from namespace found in domain level on either
15366: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
15367: 
15368: =item *
15369: 
15370: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
15371: domain level either on specified domain server ($uhome) or primary domain 
15372: server ($udom and $uhome are optional)
15373: 
15374: =item * 
15375: 
15376: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
15377: for: authentication, language, quotas, timezone, date locale, and portal URL in
15378: the target domain.
15379: 
15380: May also include additional key => value pairs for the following groups:
15381: 
15382: =over
15383: 
15384: =item
15385: disk quotas (MB allocated by default to portfolios and authoring spaces).
15386: 
15387: =over
15388: 
15389: =item defaultquota, authorquota
15390: 
15391: =back
15392: 
15393: =item
15394: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
15395: portfolio for users).
15396: 
15397: =over
15398: 
15399: =item
15400: aboutme, blog, webdav, portfolio
15401: 
15402: =back
15403: 
15404: =item
15405: requestcourses: ability to request courses, and how requests are processed.
15406: 
15407: =over
15408: 
15409: =item
15410: official, unofficial, community, textbook
15411: 
15412: =back
15413: 
15414: =item
15415: inststatus: types of institutional affiliation, and order in which they are displayed.
15416: 
15417: =over
15418: 
15419: =item
15420: inststatustypes, inststatusorder, inststatusguest
15421: 
15422: =back
15423: 
15424: =item
15425: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
15426: for course's uploaded content.
15427: 
15428: =over
15429: 
15430: =item
15431: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
15432: communityquota, textbookquota
15433: 
15434: =back
15435: 
15436: =item
15437: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
15438: on your servers.
15439: 
15440: =over
15441: 
15442: =item
15443: remotesessions, hostedsessions
15444: 
15445: =back
15446: 
15447: =back
15448: 
15449: In cases where a domain coordinator has never used the "Set Domain Configuration"
15450: utility to create a configuration.db file on a domain's primary library server
15451: only the following domain defaults: auth_def, auth_arg_def, lang_def
15452: -- corresponding values are authentication type (internal, krb4, krb5,
15453: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
15454: will be available. Values are retrieved from cache (if current), unless the
15455: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
15456: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
15457: 
15458: Typical usage:
15459: 
15460: %domdefaults = &get_domain_defaults($target_domain);
15461: 
15462: =back
15463: 
15464: =head2 Network Status Functions
15465: 
15466: =over 4
15467: 
15468: =item *
15469: 
15470: dirlist() : return directory list based on URI (first arg).
15471: 
15472: Inputs: 1 required, 5 optional.
15473: 
15474: =over
15475: 
15476: =item 
15477: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
15478: 
15479: =item
15480: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
15481: 
15482: =item
15483: $username -  username of user/course to be listed. Extracted from $uri if absent. 
15484: 
15485: =item
15486: $getpropath - boolean: 1 if prepend path using &propath(). 
15487: 
15488: =item
15489: $getuserdir - boolean: 1 if prepend path for "userfiles".
15490: 
15491: =item 
15492: $alternateRoot - path to prepend in place of path from $uri.
15493: 
15494: =back
15495: 
15496: Returns: Array of up to two items.
15497: 
15498: =over
15499: 
15500: a reference to an array of files/subdirectories
15501: 
15502: =over
15503: 
15504: Each element in the array of files/subdirectories is a & separated list of
15505: item name and the result of running stat on the item.  If dirlist was requested
15506: for a file instead of a directory, the item name will be ''. For a directory 
15507: listing, if the item is a metadata file, the element will end &N&M 
15508: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
15509: default copyright set (1).  
15510: 
15511: =back
15512: 
15513: a scalar containing error condition (if encountered).
15514: 
15515: =over
15516: 
15517: =item 
15518: no_host (no homeserver identified for $username:$domain).
15519: 
15520: =item 
15521: no_such_host (server contacted for listing not identified as valid host).
15522: 
15523: =item 
15524: con_lost (connection to remote server failed).
15525: 
15526: =item 
15527: refused (invalid $username:$domain received on lond side).
15528: 
15529: =item 
15530: no_such_dir (directory at specified path on lond side does not exist). 
15531: 
15532: =item 
15533: empty (directory at specified path on lond side is empty).
15534: 
15535: =over
15536: 
15537: This is currently not encountered because the &ls3, &ls2, 
15538: &ls (_handler) routines on the lond side do not filter out
15539: . and .. from a directory listing. 
15540: 
15541: =back
15542: 
15543: =back
15544: 
15545: =back
15546: 
15547: =item *
15548: 
15549: spareserver() : find server with least workload from spare.tab
15550: 
15551: 
15552: =item *
15553: 
15554: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
15555: if there is no corresponding loncapa host.
15556: 
15557: =back
15558: 
15559: 
15560: =head2 Apache Request
15561: 
15562: =over 4
15563: 
15564: =item *
15565: 
15566: ssi($url,%hash) : server side include, does a complete request cycle on url to
15567: localhost, posts hash
15568: 
15569: =back
15570: 
15571: =head2 Data to String to Data
15572: 
15573: =over 4
15574: 
15575: =item *
15576: 
15577: hash2str(%hash) : convert a hash into a string complete with escaping and '='
15578: and '&' separators, supports elements that are arrayrefs and hashrefs
15579: 
15580: =item *
15581: 
15582: hashref2str($hashref) : convert a hashref into a string complete with
15583: escaping and '=' and '&' separators, supports elements that are
15584: arrayrefs and hashrefs
15585: 
15586: =item *
15587: 
15588: arrayref2str($arrayref) : convert an arrayref into a string complete
15589: with escaping and '&' separators, supports elements that are arrayrefs
15590: and hashrefs
15591: 
15592: =item *
15593: 
15594: str2hash($string) : convert string to hash using unescaping and
15595: splitting on '=' and '&', supports elements that are arrayrefs and
15596: hashrefs
15597: 
15598: =item *
15599: 
15600: str2array($string) : convert string to hash using unescaping and
15601: splitting on '&', supports elements that are arrayrefs and hashrefs
15602: 
15603: =back
15604: 
15605: =head2 Logging Routines
15606: 
15607: 
15608: These routines allow one to make log messages in the lonnet.log and
15609: lonnet.perm logfiles.
15610: 
15611: =over 4
15612: 
15613: =item *
15614: 
15615: logtouch() : make sure the logfile, lonnet.log, exists
15616: 
15617: =item *
15618: 
15619: logthis() : append message to the normal lonnet.log file, it gets
15620: preiodically rolled over and deleted.
15621: 
15622: =item *
15623: 
15624: logperm() : append a permanent message to lonnet.perm.log, this log
15625: file never gets deleted by any automated portion of the system, only
15626: messages of critical importance should go in here.
15627: 
15628: 
15629: =back
15630: 
15631: =head2 General File Helper Routines
15632: 
15633: =over 4
15634: 
15635: =item *
15636: 
15637: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
15638: (a) files in /uploaded
15639:   (i) If a local copy of the file exists - 
15640:       compares modification date of local copy with last-modified date for 
15641:       definitive version stored on home server for course. If local copy is 
15642:       stale, requests a new version from the home server and stores it. 
15643:       If the original has been removed from the home server, then local copy 
15644:       is unlinked.
15645:   (ii) If local copy does not exist -
15646:       requests the file from the home server and stores it. 
15647:   
15648:   If $caller is 'uploadrep':  
15649:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
15650:     for request for files originally uploaded via DOCS. 
15651:      - returns 'ok' if fresh local copy now available, -1 otherwise.
15652:   
15653:   Otherwise:
15654:      This indicates a call from the content generation phase of the request.
15655:      -  returns the entire contents of the file or -1.
15656:      
15657: (b) files in /res
15658:    - returns the entire contents of a file or -1; 
15659:    it properly subscribes to and replicates the file if neccessary.
15660: 
15661: 
15662: =item *
15663: 
15664: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
15665:                   reference
15666: 
15667: returns either a stat() list of data about the file or an empty list
15668: if the file doesn't exist or couldn't find out about it (connection
15669: problems or user unknown)
15670: 
15671: =item *
15672: 
15673: filelocation($dir,$file) : returns file system location of a file
15674: based on URI; meant to be "fairly clean" absolute reference, $dir is a
15675: directory that relative $file lookups are to looked in ($dir of /a/dir
15676: and a file of ../bob will become /a/bob)
15677: 
15678: =item *
15679: 
15680: hreflocation($dir,$file) : returns file system location or a URL; same as
15681: filelocation except for hrefs
15682: 
15683: =item *
15684: 
15685: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
15686: also removes beginning /home/httpd/html unless /priv/ follows it.
15687: 
15688: =back
15689: 
15690: =head2 Usererfile file routines (/uploaded*)
15691: 
15692: =over 4
15693: 
15694: =item *
15695: 
15696: userfileupload(): main rotine for putting a file in a user or course's
15697:                   filespace, arguments are,
15698: 
15699:  formname - required - this is the name of the element in $env where the
15700:            filename, and the contents of the file to create/modifed exist
15701:            the filename is in $env{'form.'.$formname.'.filename'} and the
15702:            contents of the file is located in $env{'form.'.$formname}
15703:  context - if coursedoc, store the file in the course of the active role
15704:              of the current user; 
15705:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
15706:            if 'canceloverwrite': delete file in tmp/overwrites directory
15707:  subdir - required - subdirectory to put the file in under ../userfiles/
15708:          if undefined, it will be placed in "unknown"
15709: 
15710:  (This routine calls clean_filename() to remove any dangerous
15711:  characters from the filename, and then calls finuserfileupload() to
15712:  complete the transaction)
15713: 
15714:  returns either the url of the uploaded file (/uploaded/....) if successful
15715:  and /adm/notfound.html if unsuccessful
15716: 
15717: =item *
15718: 
15719: clean_filename(): routine for cleaing a filename up for storage in
15720:                  userfile space, argument is:
15721: 
15722:  filename - proposed filename
15723: 
15724: returns: the new clean filename
15725: 
15726: =item *
15727: 
15728: finishuserfileupload(): routine that creates and sends the file to
15729: userspace, probably shouldn't be called directly
15730: 
15731:   docuname: username or courseid of destination for the file
15732:   docudom: domain of user/course of destination for the file
15733:   formname: same as for userfileupload()
15734:   fname: filename (including subdirectories) for the file
15735:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
15736:           if hashref, and context is scantron, will convert csv format to standard format
15737:   allfiles: reference to hash used to store objects found by parser
15738:   codebase: reference to hash used for codebases of java objects found by parser
15739:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
15740:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
15741:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
15742:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
15743:   context: if 'overwrite', will move the uploaded file from its temporary location to
15744:             userfiles to facilitate overwriting a previously uploaded file with same name.
15745:   mimetype: reference to scalar to accommodate mime type determined
15746:             from File::MMagic if $parser = parse.
15747: 
15748:  returns either the url of the uploaded file (/uploaded/....) if successful
15749:  and /adm/notfound.html if unsuccessful (or an error message if context 
15750:  was 'overwrite').
15751:  
15752: 
15753: =item *
15754: 
15755: renameuserfile(): renames an existing userfile to a new name
15756: 
15757:   Args:
15758:    docuname: username or courseid of destination for the file
15759:    docudom: domain of user/course of destination for the file
15760:    old: current file name (including any subdirs under userfiles)
15761:    new: desired file name (including any subdirs under userfiles)
15762: 
15763: =item *
15764: 
15765: mkdiruserfile(): creates a directory is a userfiles dir
15766: 
15767:   Args:
15768:    docuname: username or courseid of destination for the file
15769:    docudom: domain of user/course of destination for the file
15770:    dir: dir to create (including any subdirs under userfiles)
15771: 
15772: =item *
15773: 
15774: removeuserfile(): removes a file that exists in userfiles
15775: 
15776:   Args:
15777:    docuname: username or courseid of destination for the file
15778:    docudom: domain of user/course of destination for the file
15779:    fname: filname to delete (including any subdirs under userfiles)
15780: 
15781: =item *
15782: 
15783: removeuploadedurl(): convience function for removeuserfile()
15784: 
15785:   Args:
15786:    url:  a full /uploaded/... url to delete
15787: 
15788: =item * 
15789: 
15790: get_portfile_permissions():
15791:   Args:
15792:     domain: domain of user or course contain the portfolio files
15793:     user: name of user or num of course contain the portfolio files
15794:   Returns:
15795:     hashref of a dump of the proper file_permissions.db
15796:    
15797: 
15798: =item * 
15799: 
15800: get_access_controls():
15801: 
15802: Args:
15803:   current_permissions: the hash ref returned from get_portfile_permissions()
15804:   group: (optional) the group you want the files associated with
15805:   file: (optional) the file you want access info on
15806: 
15807: Returns:
15808:     a hash (keys are file names) of hashes containing
15809:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
15810:         values are XML containing access control settings (see below) 
15811: 
15812: Internal notes:
15813: 
15814:  access controls are stored in file_permissions.db as key=value pairs.
15815:     key -> path to file/file_name\0uniqueID:scope_end_start
15816:         where scope -> public,guest,course,group,domains or users.
15817:               end -> UNIX time for end of access (0 -> no end date)
15818:               start -> UNIX time for start of access
15819: 
15820:     value -> XML description of access control
15821:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
15822:             <start></start>
15823:             <end></end>
15824: 
15825:             <password></password>  for scope type = guest
15826: 
15827:             <domain></domain>     for scope type = course or group
15828:             <number></number>
15829:             <roles id="">
15830:              <role></role>
15831:              <access></access>
15832:              <section></section>
15833:              <group></group>
15834:             </roles>
15835: 
15836:             <dom></dom>         for scope type = domains
15837: 
15838:             <users>             for scope type = users
15839:              <user>
15840:               <uname></uname>
15841:               <udom></udom>
15842:              </user>
15843:             </users>
15844:            </scope> 
15845:               
15846:  Access data is also aggregated for each file in an additional key=value pair:
15847:  key -> path to file/file_name\0accesscontrol 
15848:  value -> reference to hash
15849:           hash contains key = value pairs
15850:           where key = uniqueID:scope_end_start
15851:                 value = UNIX time record was last updated
15852: 
15853:           Used to improve speed of look-ups of access controls for each file.  
15854:  
15855:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
15856: 
15857: =item *
15858: 
15859: modify_access_controls():
15860: 
15861: Modifies access controls for a portfolio file
15862: Args
15863: 1. file name
15864: 2. reference to hash of required changes,
15865: 3. domain
15866: 4. username
15867:   where domain,username are the domain of the portfolio owner 
15868:   (either a user or a course) 
15869: 
15870: Returns:
15871: 1. result of additions or updates ('ok' or 'error', with error message). 
15872: 2. result of deletions ('ok' or 'error', with error message).
15873: 3. reference to hash of any new or updated access controls.
15874: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
15875:    key = integer (inbound ID)
15876:    value = uniqueID
15877: 
15878: =item *
15879: 
15880: get_timebased_id():
15881: 
15882: Attempts to get a unique timestamp-based suffix for use with items added to a
15883: course via the Course Editor (e.g., folders, composite pages,
15884: group bulletin boards).
15885: 
15886: Args: (first three required; six others optional)
15887: 
15888: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
15889:    docssequence, or name of group
15890: 
15891: 2. keyid (alphanumeric): name of temporary locking key in hash,
15892:    e.g., num, boardids
15893: 
15894: 3. namespace: name of gdbm file used to store suffixes already assigned;
15895:    file will be named nohist_namespace.db
15896: 
15897: 4. cdom: domain of course; default is current course domain from %env
15898: 
15899: 5. cnum: course number; default is current course number from %env
15900: 
15901: 6. idtype: set to concat if an additional digit is to be appended to the
15902:    unix timestamp to form the suffix, if the plain timestamp is already
15903:    in use.  Default is to not do this, but simply increment the unix
15904:    timestamp by 1 until a unique key is obtained.
15905: 
15906: 7. who: holder of locking key; defaults to user:domain for user.
15907: 
15908: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
15909:    retrying); default is 3.
15910: 
15911: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
15912: 
15913: Returns:
15914: 
15915: 1. suffix obtained (numeric)
15916: 
15917: 2. result of deleting locking key (ok if deleted, or lock never obtained)
15918: 
15919: 3. error: contains (localized) error message if an error occurred.
15920: 
15921: 
15922: =back
15923: 
15924: =head2 HTTP Helper Routines
15925: 
15926: =over 4
15927: 
15928: =item *
15929: 
15930: escape() : unpack non-word characters into CGI-compatible hex codes
15931: 
15932: =item *
15933: 
15934: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
15935: 
15936: =back
15937: 
15938: =head1 PRIVATE SUBROUTINES
15939: 
15940: =head2 Underlying communication routines (Shouldn't call)
15941: 
15942: =over 4
15943: 
15944: =item *
15945: 
15946: subreply() : tries to pass a message to lonc, returns con_lost if incapable
15947: 
15948: =item *
15949: 
15950: reply() : uses subreply to send a message to remote machine, logs all failures
15951: 
15952: =item *
15953: 
15954: critical() : passes a critical message to another server; if cannot
15955: get through then place message in connection buffer directory and
15956: returns con_delayed, if incapable of saving message, returns
15957: con_failed
15958: 
15959: =item *
15960: 
15961: reconlonc() : tries to reconnect lonc client processes.
15962: 
15963: =back
15964: 
15965: =head2 Resource Access Logging
15966: 
15967: =over 4
15968: 
15969: =item *
15970: 
15971: flushcourselogs() : flush (save) buffer logs and access logs
15972: 
15973: =item *
15974: 
15975: courselog($what) : save message for course in hash
15976: 
15977: =item *
15978: 
15979: courseacclog($what) : save message for course using &courselog().  Perform
15980: special processing for specific resource types (problems, exams, quizzes, etc).
15981: 
15982: =item *
15983: 
15984: goodbye() : flush course logs and log shutting down; it is called in srm.conf
15985: as a PerlChildExitHandler
15986: 
15987: =back
15988: 
15989: =head2 Other
15990: 
15991: =over 4
15992: 
15993: =item *
15994: 
15995: symblist($mapname,%newhash) : update symbolic storage links
15996: 
15997: =back
15998: 
15999: =cut
16000: 

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