File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1172.2.140: download - view: text, annotated - select for diffs
Thu Feb 11 20:01:55 2021 UTC (3 years, 4 months ago) by raeburn
Branches: version_2_11_X
CVS tags: version_2_11_3_uiuc, version_2_11_3
- For 2.11
  Backport 1.1443

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1172.2.140 2021/02/11 20:01:55 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:             $rep = &LONCAPA::Lond::get_dom("getdom:$udom:$namespace:$items");
 1905:         } else {        
 1906:             $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
 1907:         }
 1908:         my %returnhash;
 1909:         if ($rep eq '' || $rep =~ /^error: 2 /) {
 1910:             return %returnhash;
 1911:         }
 1912:         my @pairs=split(/\&/,$rep);
 1913:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 1914:             return @pairs;
 1915:         }
 1916:         my $i=0;
 1917:         foreach my $item (@$storearr) {
 1918:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
 1919:             $i++;
 1920:         }
 1921:         return %returnhash;
 1922:     } else {
 1923:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
 1924:     }
 1925: }
 1926: 
 1927: # -------------------------------------------- put items in domain db files 
 1928: 
 1929: sub put_dom {
 1930:     my ($namespace,$storehash,$udom,$uhome)=@_;
 1931:     if (!$udom) {
 1932:         $udom=$env{'user.domain'};
 1933:         if (defined(&domain($udom,'primary'))) {
 1934:             $uhome=&domain($udom,'primary');
 1935:         } else {
 1936:             undef($uhome);
 1937:         }
 1938:     } else {
 1939:         if (!$uhome) {
 1940:             if (defined(&domain($udom,'primary'))) {
 1941:                 $uhome=&domain($udom,'primary');
 1942:             }
 1943:         }
 1944:     } 
 1945:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1946:         my $items='';
 1947:         foreach my $item (keys(%$storehash)) {
 1948:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 1949:         }
 1950:         $items=~s/\&$//;
 1951:         return &reply("putdom:$udom:$namespace:$items",$uhome);
 1952:     } else {
 1953:         &logthis("put_dom failed - no homeserver and/or domain");
 1954:     }
 1955: }
 1956: 
 1957: # --------------------- newput for items in db file owned by domainconfig user
 1958: sub newput_dom {
 1959:     my ($namespace,$storehash,$udom) = @_;
 1960:     my $result;
 1961:     if (!$udom) {
 1962:         $udom=$env{'user.domain'};
 1963:     }
 1964:     if ($udom) {
 1965:         my $uname = &get_domainconfiguser($udom);
 1966:         $result = &newput($namespace,$storehash,$udom,$uname);
 1967:     }
 1968:     return $result;
 1969: }
 1970: 
 1971: # --------------------- delete for items in db file owned by domainconfig user
 1972: sub del_dom {
 1973:     my ($namespace,$storearr,$udom)=@_;
 1974:     if (ref($storearr) eq 'ARRAY') {
 1975:         if (!$udom) {
 1976:             $udom=$env{'user.domain'};
 1977:         }
 1978:         if ($udom) {
 1979:             my $uname = &get_domainconfiguser($udom); 
 1980:             return &del($namespace,$storearr,$udom,$uname);
 1981:         }
 1982:     }
 1983: }
 1984: 
 1985: # ----------------------------------construct domainconfig user for a domain 
 1986: sub get_domainconfiguser {
 1987:     my ($udom) = @_;
 1988:     return $udom.'-domainconfig';
 1989: }
 1990: 
 1991: sub retrieve_inst_usertypes {
 1992:     my ($udom) = @_;
 1993:     my (%returnhash,@order);
 1994:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 1995:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
 1996:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
 1997:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
 1998:     } else {
 1999:         if (defined(&domain($udom,'primary'))) {
 2000:             my $uhome=&domain($udom,'primary');
 2001:             my $rep=&reply("inst_usertypes:$udom",$uhome);
 2002:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
 2003:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
 2004:                 return (\%returnhash,\@order);
 2005:             }
 2006:             my ($hashitems,$orderitems) = split(/:/,$rep); 
 2007:             my @pairs=split(/\&/,$hashitems);
 2008:             foreach my $item (@pairs) {
 2009:                 my ($key,$value)=split(/=/,$item,2);
 2010:                 $key = &unescape($key);
 2011:                 next if ($key =~ /^error: 2 /);
 2012:                 $returnhash{$key}=&thaw_unescape($value);
 2013:             }
 2014:             my @esc_order = split(/\&/,$orderitems);
 2015:             foreach my $item (@esc_order) {
 2016:                 push(@order,&unescape($item));
 2017:             }
 2018:         } else {
 2019:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
 2020:         }
 2021:         return (\%returnhash,\@order);
 2022:     }
 2023: }
 2024: 
 2025: sub is_domainimage {
 2026:     my ($url) = @_;
 2027:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
 2028:         if (&domain($1) ne '') {
 2029:             return '1';
 2030:         }
 2031:     }
 2032:     return;
 2033: }
 2034: 
 2035: sub inst_directory_query {
 2036:     my ($srch) = @_;
 2037:     my $udom = $srch->{'srchdomain'};
 2038:     my %results;
 2039:     my $homeserver = &domain($udom,'primary');
 2040:     my $outcome;
 2041:     if ($homeserver ne '') {
 2042:         unless ($homeserver eq $perlvar{'lonHostID'}) {
 2043:             if ($srch->{'srchby'} eq 'email') {
 2044:                 my $lcrev = &get_server_loncaparev($udom,$homeserver);
 2045:                 my ($major,$minor,$subver) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.(\d+)[\w.\-]+\'?$/);
 2046:                 if (($major eq '' && $minor eq '') || ($major < 2) ||
 2047:                     (($major == 2) && ($minor < 11)) ||
 2048:                     (($major == 2) && ($minor == 11) && ($subver < 3))) {
 2049:                     return;
 2050:                 }
 2051:             }
 2052:         }
 2053: 	my $queryid=&reply("querysend:instdirsearch:".
 2054: 			   &escape($srch->{'srchby'}).':'.
 2055: 			   &escape($srch->{'srchterm'}).':'.
 2056: 			   &escape($srch->{'srchtype'}),$homeserver);
 2057: 	my $host=&hostname($homeserver);
 2058: 	if ($queryid !~/^\Q$host\E\_/) {
 2059: 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
 2060: 	    return;
 2061: 	}
 2062: 	my $response = &get_query_reply($queryid);
 2063: 	my $maxtries = 5;
 2064: 	my $tries = 1;
 2065: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 2066: 	    $response = &get_query_reply($queryid);
 2067: 	    $tries ++;
 2068: 	}
 2069: 
 2070:         if (!&error($response) && $response ne 'refused') {
 2071:             if ($response eq 'unavailable') {
 2072:                 $outcome = $response;
 2073:             } else {
 2074:                 $outcome = 'ok';
 2075:                 my @matches = split(/\n/,$response);
 2076:                 foreach my $match (@matches) {
 2077:                     my ($key,$value) = split(/=/,$match);
 2078:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 2079:                 }
 2080:             }
 2081:         }
 2082:     }
 2083:     return ($outcome,%results);
 2084: }
 2085: 
 2086: sub usersearch {
 2087:     my ($srch) = @_;
 2088:     my $dom = $srch->{'srchdomain'};
 2089:     my %results;
 2090:     my %libserv = &all_library();
 2091:     my $query = 'usersearch';
 2092:     foreach my $tryserver (keys(%libserv)) {
 2093:         if (&host_domain($tryserver) eq $dom) {
 2094:             unless ($tryserver eq $perlvar{'lonHostID'}) {
 2095:                 if ($srch->{'srchby'} eq 'email') {
 2096:                     my $lcrev = &get_server_loncaparev($dom,$tryserver);
 2097:                     my ($major,$minor,$subver) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.(\d+)[\w.\-]+\'?$/);
 2098:                     next if (($major eq '' && $minor eq '') || ($major < 2) ||
 2099:                              (($major == 2) && ($minor < 11)) ||
 2100:                              (($major == 2) && ($minor == 11) && ($subver < 3)));
 2101:                 }
 2102:             }
 2103:             my $host=&hostname($tryserver);
 2104:             my $queryid=
 2105:                 &reply("querysend:".&escape($query).':'.
 2106:                        &escape($srch->{'srchby'}).':'.
 2107:                        &escape($srch->{'srchtype'}).':'.
 2108:                        &escape($srch->{'srchterm'}),$tryserver);
 2109:             if ($queryid !~/^\Q$host\E\_/) {
 2110:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 2111:                 next;
 2112:             }
 2113:             my $reply = &get_query_reply($queryid);
 2114:             my $maxtries = 1;
 2115:             my $tries = 1;
 2116:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 2117:                 $reply = &get_query_reply($queryid);
 2118:                 $tries ++;
 2119:             }
 2120:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 2121:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 2122:             } else {
 2123:                 my @matches;
 2124:                 if ($reply =~ /\n/) {
 2125:                     @matches = split(/\n/,$reply);
 2126:                 } else {
 2127:                     @matches = split(/\&/,$reply);
 2128:                 }
 2129:                 foreach my $match (@matches) {
 2130:                     my ($uname,$udom,%userhash);
 2131:                     foreach my $entry (split(/:/,$match)) {
 2132:                         my ($key,$value) =
 2133:                             map {&unescape($_);} split(/=/,$entry);
 2134:                         $userhash{$key} = $value;
 2135:                         if ($key eq 'username') {
 2136:                             $uname = $value;
 2137:                         } elsif ($key eq 'domain') {
 2138:                             $udom = $value;
 2139:                         }
 2140:                     }
 2141:                     $results{$uname.':'.$udom} = \%userhash;
 2142:                 }
 2143:             }
 2144:         }
 2145:     }
 2146:     return %results;
 2147: }
 2148: 
 2149: sub get_instuser {
 2150:     my ($udom,$uname,$id) = @_;
 2151:     my $homeserver = &domain($udom,'primary');
 2152:     my ($outcome,%results);
 2153:     if ($homeserver ne '') {
 2154:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 2155:                            &escape($id).':'.&escape($udom),$homeserver);
 2156:         my $host=&hostname($homeserver);
 2157:         if ($queryid !~/^\Q$host\E\_/) {
 2158:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 2159:             return;
 2160:         }
 2161:         my $response = &get_query_reply($queryid);
 2162:         my $maxtries = 5;
 2163:         my $tries = 1;
 2164:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 2165:             $response = &get_query_reply($queryid);
 2166:             $tries ++;
 2167:         }
 2168:         if (!&error($response) && $response ne 'refused') {
 2169:             if ($response eq 'unavailable') {
 2170:                 $outcome = $response;
 2171:             } else {
 2172:                 $outcome = 'ok';
 2173:                 my @matches = split(/\n/,$response);
 2174:                 foreach my $match (@matches) {
 2175:                     my ($key,$value) = split(/=/,$match);
 2176:                     $results{&unescape($key)} = &thaw_unescape($value);
 2177:                 }
 2178:             }
 2179:         }
 2180:     }
 2181:     my %userinfo;
 2182:     if (ref($results{$uname}) eq 'HASH') {
 2183:         %userinfo = %{$results{$uname}};
 2184:     } 
 2185:     return ($outcome,%userinfo);
 2186: }
 2187: 
 2188: sub get_multiple_instusers {
 2189:     my ($udom,$users,$caller) = @_;
 2190:     my ($outcome,$results);
 2191:     if (ref($users) eq 'HASH') {
 2192:         my $count = keys(%{$users});
 2193:         my $requested = &freeze_escape($users);
 2194:         my $homeserver = &domain($udom,'primary');
 2195:         if ($homeserver ne '') {
 2196:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
 2197:             my $host=&hostname($homeserver);
 2198:             if ($queryid !~/^\Q$host\E\_/) {
 2199:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
 2200:                          ' for host: '.$homeserver.'in domain '.$udom);
 2201:                 return ($outcome,$results);
 2202:             }
 2203:             my $response = &get_query_reply($queryid);
 2204:             my $maxtries = 5;
 2205:             if ($count > 100) {
 2206:                 $maxtries = 1+int($count/20);
 2207:             }
 2208:             my $tries = 1;
 2209:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
 2210:                 $response = &get_query_reply($queryid);
 2211:                 $tries ++;
 2212:             }
 2213:             if ($response eq '') {
 2214:                 $results = {};
 2215:                 foreach my $key (keys(%{$users})) {
 2216:                     my ($uname,$id);
 2217:                     if ($caller eq 'id') {
 2218:                         $id = $key;
 2219:                     } else {
 2220:                         $uname = $key;
 2221:                     }
 2222:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
 2223:                     $outcome = $resp;
 2224:                     if ($resp eq 'ok') {
 2225:                         %{$results} = (%{$results}, %info);
 2226:                     } else {
 2227:                         last;
 2228:                     }
 2229:                 }
 2230:             } elsif(!&error($response) && ($response ne 'refused')) {
 2231:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
 2232:                     $outcome = $response;
 2233:                 } else {
 2234:                     ($outcome,my $userdata) = split(/=/,$response,2);
 2235:                     if ($outcome eq 'ok') {
 2236:                         $results = &thaw_unescape($userdata);
 2237:                     }
 2238:                 }
 2239:             }
 2240:         }
 2241:     }
 2242:     return ($outcome,$results);
 2243: }
 2244: 
 2245: sub inst_rulecheck {
 2246:     my ($udom,$uname,$id,$item,$rules) = @_;
 2247:     my %returnhash;
 2248:     if ($udom ne '') {
 2249:         if (ref($rules) eq 'ARRAY') {
 2250:             @{$rules} = map {&escape($_);} (@{$rules});
 2251:             my $rulestr = join(':',@{$rules});
 2252:             my $homeserver=&domain($udom,'primary');
 2253:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 2254:                 my $response;
 2255:                 if ($item eq 'username') {                
 2256:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 2257:                                               ':'.&escape($uname).':'.$rulestr,
 2258:                                               $homeserver));
 2259:                 } elsif ($item eq 'id') {
 2260:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 2261:                                               ':'.&escape($id).':'.$rulestr,
 2262:                                               $homeserver));
 2263:                 } elsif ($item eq 'selfcreate') {
 2264:                     $response=&unescape(&reply('instselfcreatecheck:'.
 2265:                                                &escape($udom).':'.&escape($uname).
 2266:                                               ':'.$rulestr,$homeserver));
 2267:                 }
 2268:                 if ($response ne 'refused') {
 2269:                     my @pairs=split(/\&/,$response);
 2270:                     foreach my $item (@pairs) {
 2271:                         my ($key,$value)=split(/=/,$item,2);
 2272:                         $key = &unescape($key);
 2273:                         next if ($key =~ /^error: 2 /);
 2274:                         $returnhash{$key}=&thaw_unescape($value);
 2275:                     }
 2276:                 }
 2277:             }
 2278:         }
 2279:     }
 2280:     return %returnhash;
 2281: }
 2282: 
 2283: sub inst_userrules {
 2284:     my ($udom,$check) = @_;
 2285:     my (%ruleshash,@ruleorder);
 2286:     if ($udom ne '') {
 2287:         my $homeserver=&domain($udom,'primary');
 2288:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 2289:             my $response;
 2290:             if ($check eq 'id') {
 2291:                 $response=&reply('instidrules:'.&escape($udom),
 2292:                                  $homeserver);
 2293:             } elsif ($check eq 'email') {
 2294:                 $response=&reply('instemailrules:'.&escape($udom),
 2295:                                  $homeserver);
 2296:             } else {
 2297:                 $response=&reply('instuserrules:'.&escape($udom),
 2298:                                  $homeserver);
 2299:             }
 2300:             if (($response ne 'refused') && ($response ne 'error') && 
 2301:                 ($response ne 'unknown_cmd') && 
 2302:                 ($response ne 'no_such_host')) {
 2303:                 my ($hashitems,$orderitems) = split(/:/,$response);
 2304:                 my @pairs=split(/\&/,$hashitems);
 2305:                 foreach my $item (@pairs) {
 2306:                     my ($key,$value)=split(/=/,$item,2);
 2307:                     $key = &unescape($key);
 2308:                     next if ($key =~ /^error: 2 /);
 2309:                     $ruleshash{$key}=&thaw_unescape($value);
 2310:                 }
 2311:                 my @esc_order = split(/\&/,$orderitems);
 2312:                 foreach my $item (@esc_order) {
 2313:                     push(@ruleorder,&unescape($item));
 2314:                 }
 2315:             }
 2316:         }
 2317:     }
 2318:     return (\%ruleshash,\@ruleorder);
 2319: }
 2320: 
 2321: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 2322: 
 2323: sub get_domain_defaults {
 2324:     my ($domain,$ignore_cache) = @_;
 2325:     return if (($domain eq '') || ($domain eq 'public'));
 2326:     my $cachetime = 60*60*24;
 2327:     unless ($ignore_cache) {
 2328:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 2329:         if (defined($cached)) {
 2330:             if (ref($result) eq 'HASH') {
 2331:                 return %{$result};
 2332:             }
 2333:         }
 2334:     }
 2335:     my %domdefaults;
 2336:     my %domconfig =
 2337:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
 2338:                                   'requestcourses','inststatus',
 2339:                                   'coursedefaults','usersessions',
 2340:                                   'requestauthor','selfenrollment',
 2341:                                   'coursecategories','autoenroll',
 2342:                                   'helpsettings'],$domain);
 2343:     my @coursetypes = ('official','unofficial','community','textbook');
 2344:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 2345:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 2346:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 2347:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 2348:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 2349:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
 2350:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
 2351:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
 2352:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
 2353:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
 2354:     } else {
 2355:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 2356:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 2357:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 2358:     }
 2359:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 2360:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 2361:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 2362:         } else {
 2363:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 2364:         }
 2365:         my @usertools = ('aboutme','blog','webdav','portfolio');
 2366:         foreach my $item (@usertools) {
 2367:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 2368:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 2369:             }
 2370:         }
 2371:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
 2372:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
 2373:         }
 2374:     }
 2375:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 2376:         foreach my $item ('official','unofficial','community','textbook') {
 2377:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
 2378:         }
 2379:     }
 2380:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
 2381:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
 2382:     }
 2383:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
 2384:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
 2385:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
 2386:         }
 2387:     }
 2388:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
 2389:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
 2390:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
 2391:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
 2392:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
 2393:         }
 2394:         foreach my $type (@coursetypes) {
 2395:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
 2396:                 unless ($type eq 'community') {
 2397:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
 2398:                 }
 2399:             }
 2400:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
 2401:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
 2402:             }
 2403:             if ($domdefaults{'postsubmit'} eq 'on') {
 2404:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
 2405:                     $domdefaults{$type.'postsubtimeout'} =
 2406:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
 2407:                 }
 2408:             }
 2409:         }
 2410:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
 2411:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
 2412:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
 2413:                 if (@clonecodes) {
 2414:                     $domdefaults{'canclone'} = join('+',@clonecodes);
 2415:                 }
 2416:             }
 2417:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
 2418:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
 2419:         }
 2420:         if ($domconfig{'coursedefaults'}{'texengine'}) {
 2421:             $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
 2422:         }
 2423:     }
 2424:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
 2425:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
 2426:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
 2427:         }
 2428:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
 2429:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
 2430:         }
 2431:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
 2432:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
 2433:         }
 2434:         if (ref($domconfig{'usersessions'}{'offloadoth'}) eq 'HASH') {
 2435:             $domdefaults{'offloadoth'} = $domconfig{'usersessions'}{'offloadoth'};
 2436:         }
 2437:     }
 2438:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
 2439:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
 2440:             my @settings = ('types','registered','enroll_dates','access_dates','section',
 2441:                             'approval','limit');
 2442:             foreach my $type (@coursetypes) {
 2443:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
 2444:                     my @mgrdc = ();
 2445:                     foreach my $item (@settings) {
 2446:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
 2447:                             push(@mgrdc,$item);
 2448:                         }
 2449:                     }
 2450:                     if (@mgrdc) {
 2451:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
 2452:                     }
 2453:                 }
 2454:             }
 2455:         }
 2456:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
 2457:             foreach my $type (@coursetypes) {
 2458:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
 2459:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
 2460:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
 2461:                     }
 2462:                 }
 2463:             }
 2464:         }
 2465:     }
 2466:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 2467:         $domdefaults{'catauth'} = 'std';
 2468:         $domdefaults{'catunauth'} = 'std';
 2469:         if ($domconfig{'coursecategories'}{'auth'}) {
 2470:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
 2471:         }
 2472:         if ($domconfig{'coursecategories'}{'unauth'}) {
 2473:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
 2474:         }
 2475:     }
 2476:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 2477:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
 2478:     }
 2479:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
 2480:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
 2481:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
 2482:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
 2483:         }
 2484:     }
 2485:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
 2486:     return %domdefaults;
 2487: }
 2488: 
 2489: sub get_dom_cats {
 2490:     my ($dom) = @_;
 2491:     return unless (&domain($dom));
 2492:     my ($cats,$cached)=&is_cached_new('cats',$dom);
 2493:     unless (defined($cached)) {
 2494:         my %domconfig = &get_dom('configuration',['coursecategories'],$dom);
 2495:         if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 2496:             if (ref($domconfig{'coursecategories'}{'cats'}) eq 'HASH') {
 2497:                 %{$cats} = %{$domconfig{'coursecategories'}{'cats'}};
 2498:             } else {
 2499:                 $cats = {};
 2500:             }
 2501:         } else {
 2502:             $cats = {};
 2503:         }
 2504:         &Apache::lonnet::do_cache_new('cats',$dom,$cats,3600);
 2505:     }
 2506:     return $cats;
 2507: }
 2508: 
 2509: sub get_dom_instcats {
 2510:     my ($dom) = @_;
 2511:     return unless (&domain($dom));
 2512:     my ($instcats,$cached)=&is_cached_new('instcats',$dom);
 2513:     unless (defined($cached)) {
 2514:         my (%coursecodes,%codes,@codetitles,%cat_titles,%cat_order);
 2515:         my $totcodes = &retrieve_instcodes(\%coursecodes,$dom);
 2516:         if ($totcodes > 0) {
 2517:             my $caller = 'global';
 2518:             if (&auto_instcode_format($caller,$dom,\%coursecodes,\%codes,
 2519:                                       \@codetitles,\%cat_titles,\%cat_order) eq 'ok') {
 2520:                 $instcats = {
 2521:                                 codes => \%codes,
 2522:                                 codetitles => \@codetitles,
 2523:                                 cat_titles => \%cat_titles,
 2524:                                 cat_order => \%cat_order,
 2525:                             };
 2526:                 &do_cache_new('instcats',$dom,$instcats,3600);
 2527:             }
 2528:         }
 2529:     }
 2530:     return $instcats;
 2531: }
 2532: 
 2533: sub retrieve_instcodes {
 2534:     my ($coursecodes,$dom) = @_;
 2535:     my $totcodes;
 2536:     my %courses = &courseiddump($dom,'.',1,'.','.','.',undef,undef,'Course');
 2537:     foreach my $course (keys(%courses)) {
 2538:         if (ref($courses{$course}) eq 'HASH') {
 2539:             if ($courses{$course}{'inst_code'} ne '') {
 2540:                 $$coursecodes{$course} = $courses{$course}{'inst_code'};
 2541:                 $totcodes ++;
 2542:             }
 2543:         }
 2544:     }
 2545:     return $totcodes;
 2546: }
 2547: 
 2548: # --------------------------------------------- Get domain config for passwords
 2549: 
 2550: sub get_passwdconf {
 2551:     my ($dom) = @_;
 2552:     my (%passwdconf,$gotconf,$lookup);
 2553:     my ($result,$cached)=&is_cached_new('passwdconf',$dom);
 2554:     if (defined($cached)) {
 2555:         if (ref($result) eq 'HASH') {
 2556:             %passwdconf = %{$result};
 2557:             $gotconf = 1;
 2558:         }
 2559:     }
 2560:     unless ($gotconf) {
 2561:         my %domconfig = &get_dom('configuration',['passwords'],$dom);
 2562:         if (ref($domconfig{'passwords'}) eq 'HASH') {
 2563:             %passwdconf = %{$domconfig{'passwords'}};
 2564:         }
 2565:         my $cachetime = 24*60*60;
 2566:         &do_cache_new('passwdconf',$dom,\%passwdconf,$cachetime);
 2567:     }
 2568:     return %passwdconf;
 2569: }
 2570: 
 2571: # --------------------------------------------------- Assign a key to a student
 2572: 
 2573: sub assign_access_key {
 2574: #
 2575: # a valid key looks like uname:udom#comments
 2576: # comments are being appended
 2577: #
 2578:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 2579:     $kdom=
 2580:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 2581:     $knum=
 2582:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 2583:     $cdom=
 2584:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2585:     $cnum=
 2586:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2587:     $udom=$env{'user.name'} unless (defined($udom));
 2588:     $uname=$env{'user.domain'} unless (defined($uname));
 2589:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 2590:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 2591:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 2592:                                                   # assigned to this person
 2593:                                                   # - this should not happen,
 2594:                                                   # unless something went wrong
 2595:                                                   # the first time around
 2596: # ready to assign
 2597:         $logentry=$1.'; '.$logentry;
 2598:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 2599:                                                  $kdom,$knum) eq 'ok') {
 2600: # key now belongs to user
 2601: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 2602:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 2603:                 &appenv({'environment.'.$envkey => $ckey});
 2604:                 return 'ok';
 2605:             } else {
 2606:                 return 
 2607:   'error: Count not permanently assign key, will need to be re-entered later.';
 2608: 	    }
 2609:         } else {
 2610:             return 'error: Could not assign key, try again later.';
 2611:         }
 2612:     } elsif (!$existing{$ckey}) {
 2613: # the key does not exist
 2614: 	return 'error: The key does not exist';
 2615:     } else {
 2616: # the key is somebody else's
 2617: 	return 'error: The key is already in use';
 2618:     }
 2619: }
 2620: 
 2621: # ------------------------------------------ put an additional comment on a key
 2622: 
 2623: sub comment_access_key {
 2624: #
 2625: # a valid key looks like uname:udom#comments
 2626: # comments are being appended
 2627: #
 2628:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 2629:     $cdom=
 2630:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2631:     $cnum=
 2632:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2633:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2634:     if ($existing{$ckey}) {
 2635:         $existing{$ckey}.='; '.$logentry;
 2636: # ready to assign
 2637:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 2638:                                                  $cdom,$cnum) eq 'ok') {
 2639: 	    return 'ok';
 2640:         } else {
 2641: 	    return 'error: Count not store comment.';
 2642:         }
 2643:     } else {
 2644: # the key does not exist
 2645: 	return 'error: The key does not exist';
 2646:     }
 2647: }
 2648: 
 2649: # ------------------------------------------------------ Generate a set of keys
 2650: 
 2651: sub generate_access_keys {
 2652:     my ($number,$cdom,$cnum,$logentry)=@_;
 2653:     $cdom=
 2654:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2655:     $cnum=
 2656:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2657:     unless (&allowed('mky',$cdom)) { return 0; }
 2658:     unless (($cdom) && ($cnum)) { return 0; }
 2659:     if ($number>10000) { return 0; }
 2660:     sleep(2); # make sure don't get same seed twice
 2661:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 2662:     my $total=0;
 2663:     for (my $i=1;$i<=$number;$i++) {
 2664:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 2665:                   sprintf("%lx",int(100000*rand)).'-'.
 2666:                   sprintf("%lx",int(100000*rand));
 2667:        $newkey=~s/1/g/g; # folks mix up 1 and l
 2668:        $newkey=~s/0/h/g; # and also 0 and O
 2669:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 2670:        if ($existing{$newkey}) {
 2671:            $i--;
 2672:        } else {
 2673: 	  if (&put('accesskeys',
 2674:               { $newkey => '# generated '.localtime().
 2675:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 2676:                            '; '.$logentry },
 2677: 		   $cdom,$cnum) eq 'ok') {
 2678:               $total++;
 2679: 	  }
 2680:        }
 2681:     }
 2682:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 2683:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 2684:     return $total;
 2685: }
 2686: 
 2687: # ------------------------------------------------------- Validate an accesskey
 2688: 
 2689: sub validate_access_key {
 2690:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 2691:     $cdom=
 2692:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2693:     $cnum=
 2694:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2695:     $udom=$env{'user.domain'} unless (defined($udom));
 2696:     $uname=$env{'user.name'} unless (defined($uname));
 2697:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2698:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 2699: }
 2700: 
 2701: # ------------------------------------- Find the section of student in a course
 2702: sub devalidate_getsection_cache {
 2703:     my ($udom,$unam,$courseid)=@_;
 2704:     my $hashid="$udom:$unam:$courseid";
 2705:     &devalidate_cache_new('getsection',$hashid);
 2706: }
 2707: 
 2708: sub courseid_to_courseurl {
 2709:     my ($courseid) = @_;
 2710:     #already url style courseid
 2711:     return $courseid if ($courseid =~ m{^/});
 2712: 
 2713:     if (exists($env{'course.'.$courseid.'.num'})) {
 2714: 	my $cnum = $env{'course.'.$courseid.'.num'};
 2715: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 2716: 	return "/$cdom/$cnum";
 2717:     }
 2718: 
 2719:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 2720:     if (exists($courseinfo{'num'})) {
 2721: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 2722:     }
 2723: 
 2724:     return undef;
 2725: }
 2726: 
 2727: sub getsection {
 2728:     my ($udom,$unam,$courseid)=@_;
 2729:     my $cachetime=1800;
 2730: 
 2731:     my $hashid="$udom:$unam:$courseid";
 2732:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 2733:     if (defined($cached)) { return $result; }
 2734: 
 2735:     my %Pending; 
 2736:     my %Expired;
 2737:     #
 2738:     # Each role can either have not started yet (pending), be active, 
 2739:     #    or have expired.
 2740:     #
 2741:     # If there is an active role, we are done.
 2742:     #
 2743:     # If there is more than one role which has not started yet, 
 2744:     #     choose the one which will start sooner
 2745:     # If there is one role which has not started yet, return it.
 2746:     #
 2747:     # If there is more than one expired role, choose the one which ended last.
 2748:     # If there is a role which has expired, return it.
 2749:     #
 2750:     $courseid = &courseid_to_courseurl($courseid);
 2751:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 2752:     foreach my $key (keys(%roleshash)) {
 2753:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 2754:         my $section=$1;
 2755:         if ($key eq $courseid.'_st') { $section=''; }
 2756:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 2757:         my $now=time;
 2758:         if (defined($end) && $end && ($now > $end)) {
 2759:             $Expired{$end}=$section;
 2760:             next;
 2761:         }
 2762:         if (defined($start) && $start && ($now < $start)) {
 2763:             $Pending{$start}=$section;
 2764:             next;
 2765:         }
 2766:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 2767:     }
 2768:     #
 2769:     # Presumedly there will be few matching roles from the above
 2770:     # loop and the sorting time will be negligible.
 2771:     if (scalar(keys(%Pending))) {
 2772:         my ($time) = sort {$a <=> $b} keys(%Pending);
 2773:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 2774:     } 
 2775:     if (scalar(keys(%Expired))) {
 2776:         my @sorted = sort {$a <=> $b} keys(%Expired);
 2777:         my $time = pop(@sorted);
 2778:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 2779:     }
 2780:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 2781: }
 2782: 
 2783: sub save_cache {
 2784:     &purge_remembered();
 2785:     #&Apache::loncommon::validate_page();
 2786:     undef(%env);
 2787:     undef($env_loaded);
 2788: }
 2789: 
 2790: my $to_remember=-1;
 2791: my %remembered;
 2792: my %accessed;
 2793: my $kicks=0;
 2794: my $hits=0;
 2795: sub make_key {
 2796:     my ($name,$id) = @_;
 2797:     if (length($id) > 65 
 2798: 	&& length(&escape($id)) > 200) {
 2799: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 2800:     }
 2801:     return &escape($name.':'.$id);
 2802: }
 2803: 
 2804: sub devalidate_cache_new {
 2805:     my ($name,$id,$debug) = @_;
 2806:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 2807:     my $remembered_id=$name.':'.$id;
 2808:     $id=&make_key($name,$id);
 2809:     $memcache->delete($id);
 2810:     delete($remembered{$remembered_id});
 2811:     delete($accessed{$remembered_id});
 2812: }
 2813: 
 2814: sub is_cached_new {
 2815:     my ($name,$id,$debug) = @_;
 2816:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) for 
 2817:                                      # keys in %remembered hash, which persists for
 2818:                                      # duration of request (no restriction on key length).
 2819:     if (exists($remembered{$remembered_id})) {
 2820: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
 2821: 	$accessed{$remembered_id}=[&gettimeofday()];
 2822: 	$hits++;
 2823: 	return ($remembered{$remembered_id},1);
 2824:     }
 2825:     $id=&make_key($name,$id);
 2826:     my $value = $memcache->get($id);
 2827:     if (!(defined($value))) {
 2828: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 2829: 	return (undef,undef);
 2830:     }
 2831:     if ($value eq '__undef__') {
 2832: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 2833: 	$value=undef;
 2834:     }
 2835:     &make_room($remembered_id,$value,$debug);
 2836:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 2837:     return ($value,1);
 2838: }
 2839: 
 2840: sub do_cache_new {
 2841:     my ($name,$id,$value,$time,$debug) = @_;
 2842:     my $remembered_id=$name.':'.$id;
 2843:     $id=&make_key($name,$id);
 2844:     my $setvalue=$value;
 2845:     if (!defined($setvalue)) {
 2846: 	$setvalue='__undef__';
 2847:     }
 2848:     if (!defined($time) ) {
 2849: 	$time=600;
 2850:     }
 2851:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 2852:     my $result = $memcache->set($id,$setvalue,$time);
 2853:     if (! $result) {
 2854: 	&logthis("caching of id -> $id  failed");
 2855: 	$memcache->disconnect_all();
 2856:     }
 2857:     # need to make a copy of $value
 2858:     &make_room($remembered_id,$value,$debug);
 2859:     return $value;
 2860: }
 2861: 
 2862: sub make_room {
 2863:     my ($remembered_id,$value,$debug)=@_;
 2864: 
 2865:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
 2866:                                     : $value;
 2867:     if ($to_remember<0) { return; }
 2868:     $accessed{$remembered_id}=[&gettimeofday()];
 2869:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 2870:     my $to_kick;
 2871:     my $max_time=0;
 2872:     foreach my $other (keys(%accessed)) {
 2873: 	if (&tv_interval($accessed{$other}) > $max_time) {
 2874: 	    $to_kick=$other;
 2875: 	    $max_time=&tv_interval($accessed{$other});
 2876: 	}
 2877:     }
 2878:     delete($remembered{$to_kick});
 2879:     delete($accessed{$to_kick});
 2880:     $kicks++;
 2881:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 2882:     return;
 2883: }
 2884: 
 2885: sub purge_remembered {
 2886:     #&logthis("Tossing ".scalar(keys(%remembered)));
 2887:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 2888:     undef(%remembered);
 2889:     undef(%accessed);
 2890: }
 2891: # ------------------------------------- Read an entry from a user's environment
 2892: 
 2893: sub userenvironment {
 2894:     my ($udom,$unam,@what)=@_;
 2895:     my $items;
 2896:     foreach my $item (@what) {
 2897:         $items.=&escape($item).'&';
 2898:     }
 2899:     $items=~s/\&$//;
 2900:     my %returnhash=();
 2901:     my $uhome = &homeserver($unam,$udom);
 2902:     unless ($uhome eq 'no_host') {
 2903:         my @answer=split(/\&/, 
 2904:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
 2905:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
 2906:             return %returnhash;
 2907:         }
 2908:         my $i;
 2909:         for ($i=0;$i<=$#what;$i++) {
 2910: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
 2911:         }
 2912:     }
 2913:     return %returnhash;
 2914: }
 2915: 
 2916: # ---------------------------------------------------------- Get a studentphoto
 2917: sub studentphoto {
 2918:     my ($udom,$unam,$ext) = @_;
 2919:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 2920:     if (defined($env{'request.course.id'})) {
 2921:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 2922:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 2923:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 2924:             } else {
 2925:                 my ($result,$perm_reqd)=
 2926: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 2927:                 if ($result eq 'ok') {
 2928:                     if (!($perm_reqd eq 'yes')) {
 2929:                         return(&retrievestudentphoto($udom,$unam,$ext));
 2930:                     }
 2931:                 }
 2932:             }
 2933:         }
 2934:     } else {
 2935:         my ($result,$perm_reqd) = 
 2936: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 2937:         if ($result eq 'ok') {
 2938:             if (!($perm_reqd eq 'yes')) {
 2939:                 return(&retrievestudentphoto($udom,$unam,$ext));
 2940:             }
 2941:         }
 2942:     }
 2943:     return '/adm/lonKaputt/lonlogo_broken.gif';
 2944: }
 2945: 
 2946: sub retrievestudentphoto {
 2947:     my ($udom,$unam,$ext,$type) = @_;
 2948:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 2949:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 2950:     if ($ret eq 'ok') {
 2951:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 2952:         if ($type eq 'thumbnail') {
 2953:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 2954:         }
 2955:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 2956:         return $tokenurl;
 2957:     } else {
 2958:         if ($type eq 'thumbnail') {
 2959:             return '/adm/lonKaputt/genericstudent_tn.gif';
 2960:         } else { 
 2961:             return '/adm/lonKaputt/lonlogo_broken.gif';
 2962:         }
 2963:     }
 2964: }
 2965: 
 2966: # -------------------------------------------------------------------- New chat
 2967: 
 2968: sub chatsend {
 2969:     my ($newentry,$anon,$group)=@_;
 2970:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 2971:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2972:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 2973:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 2974: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 2975: 		   &escape($newentry)).':'.$group,$chome);
 2976: }
 2977: 
 2978: # ------------------------------------------ Find current version of a resource
 2979: 
 2980: sub getversion {
 2981:     my $fname=&clutter(shift);
 2982:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
 2983:     return &currentversion(&filelocation('',$fname));
 2984: }
 2985: 
 2986: sub currentversion {
 2987:     my $fname=shift;
 2988:     my $author=$fname;
 2989:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2990:     my ($udom,$uname)=split(/\//,$author);
 2991:     my $home=&homeserver($uname,$udom);
 2992:     if ($home eq 'no_host') { 
 2993:         return -1; 
 2994:     }
 2995:     my $answer=&reply("currentversion:$fname",$home);
 2996:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 2997: 	return -1;
 2998:     }
 2999:     return $answer;
 3000: }
 3001: 
 3002: #
 3003: # Return special version number of resource if set by override, empty otherwise
 3004: #
 3005: sub usedversion {
 3006:     my $fname=shift;
 3007:     unless ($fname) { $fname=$env{'request.uri'}; }
 3008:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
 3009:     if ($urlversion) { return $urlversion; }
 3010:     return '';
 3011: }
 3012: 
 3013: # ----------------------------- Subscribe to a resource, return URL if possible
 3014: 
 3015: sub subscribe {
 3016:     my $fname=shift;
 3017:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 3018:     $fname=~s/[\n\r]//g;
 3019:     my $author=$fname;
 3020:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3021:     my ($udom,$uname)=split(/\//,$author);
 3022:     my $home=homeserver($uname,$udom);
 3023:     if ($home eq 'no_host') {
 3024:         return 'not_found';
 3025:     }
 3026:     my $answer=reply("sub:$fname",$home);
 3027:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 3028: 	$answer.=' by '.$home;
 3029:     }
 3030:     return $answer;
 3031: }
 3032:     
 3033: # -------------------------------------------------------------- Replicate file
 3034: 
 3035: sub repcopy {
 3036:     my $filename=shift;
 3037:     $filename=~s/\/+/\//g;
 3038:     my $londocroot = $perlvar{'lonDocRoot'};
 3039:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
 3040:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
 3041:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
 3042: 	$filename=~m{^/*(uploaded|editupload)/}) {
 3043: 	return &repcopy_userfile($filename);
 3044:     }
 3045:     $filename=~s/[\n\r]//g;
 3046:     my $transname="$filename.in.transfer";
 3047: # FIXME: this should flock
 3048:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 3049:     my $remoteurl=subscribe($filename);
 3050:     if ($remoteurl =~ /^con_lost by/) {
 3051: 	   &logthis("Subscribe returned $remoteurl: $filename");
 3052:            return 'unavailable';
 3053:     } elsif ($remoteurl eq 'not_found') {
 3054: 	   #&logthis("Subscribe returned not_found: $filename");
 3055: 	   return 'not_found';
 3056:     } elsif ($remoteurl =~ /^rejected by/) {
 3057: 	   &logthis("Subscribe returned $remoteurl: $filename");
 3058:            return 'forbidden';
 3059:     } elsif ($remoteurl eq 'directory') {
 3060:            return 'ok';
 3061:     } else {
 3062:         my $author=$filename;
 3063:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3064:         my ($udom,$uname)=split(/\//,$author);
 3065:         my $home=homeserver($uname,$udom);
 3066:         unless ($home eq $perlvar{'lonHostID'}) {
 3067:            my @parts=split(/\//,$filename);
 3068:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 3069:            if ($path ne "$londocroot/res") {
 3070:                &logthis("Malconfiguration for replication: $filename");
 3071: 	       return 'bad_request';
 3072:            }
 3073:            my $count;
 3074:            for ($count=5;$count<$#parts;$count++) {
 3075:                $path.="/$parts[$count]";
 3076:                if ((-e $path)!=1) {
 3077: 		   mkdir($path,0777);
 3078:                }
 3079:            }
 3080:            my $ua=new LWP::UserAgent;
 3081:            my $request=new HTTP::Request('GET',"$remoteurl");
 3082:            my $response=$ua->request($request,$transname);
 3083:            if ($response->is_error()) {
 3084: 	       unlink($transname);
 3085:                my $message=$response->status_line;
 3086:                &logthis("<font color=\"blue\">WARNING:"
 3087:                        ." LWP get: $message: $filename</font>");
 3088:                return 'unavailable';
 3089:            } else {
 3090: 	       if ($remoteurl!~/\.meta$/) {
 3091:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 3092:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
 3093:                   if ($mresponse->is_error()) {
 3094: 		      unlink($filename.'.meta');
 3095:                       &logthis(
 3096:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 3097:                   }
 3098: 	       }
 3099:                rename($transname,$filename);
 3100:                return 'ok';
 3101:            }
 3102:        }
 3103:     }
 3104: }
 3105: 
 3106: # ------------------------------------------------- Unsubscribe from a resource
 3107: 
 3108: sub unsubscribe {
 3109:     my ($fname) = @_;
 3110:     my $answer;
 3111:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return $answer; }
 3112:     $fname=~s/[\n\r]//g;
 3113:     my $author=$fname;
 3114:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3115:     my ($udom,$uname)=split(/\//,$author);
 3116:     my $home=homeserver($uname,$udom);
 3117:     if ($home eq 'no_host') {
 3118:         $answer = 'no_host';
 3119:     } elsif (grep { $_ eq $home } &current_machine_ids()) {
 3120:         $answer = 'home';
 3121:     } else {
 3122:         $answer = reply("unsub:$fname",$home);
 3123:     }
 3124:     return $answer;
 3125: }
 3126: 
 3127: # ------------------------------------------------ Get server side include body
 3128: sub ssi_body {
 3129:     my ($filelink,%form)=@_;
 3130:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 3131:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 3132:     }
 3133:     my $output='';
 3134:     my $response;
 3135:     if ($filelink=~/^https?\:/) {
 3136:        ($output,$response)=&externalssi($filelink);
 3137:     } else {
 3138:        $filelink .= $filelink=~/\?/ ? '&' : '?';
 3139:        $filelink .= 'inhibitmenu=yes';
 3140:        ($output,$response)=&ssi($filelink,%form);
 3141:     }
 3142:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 3143:     $output=~s/^.*?\<body[^\>]*\>//si;
 3144:     $output=~s/\<\/body\s*\>.*?$//si;
 3145:     if (wantarray) {
 3146:         return ($output, $response);
 3147:     } else {
 3148:         return $output;
 3149:     }
 3150: }
 3151: 
 3152: # --------------------------------------------------------- Server Side Include
 3153: 
 3154: sub absolute_url {
 3155:     my ($host_name) = @_;
 3156:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 3157:     if ($host_name eq '') {
 3158: 	$host_name = $ENV{'SERVER_NAME'};
 3159:     }
 3160:     return $protocol.$host_name;
 3161: }
 3162: 
 3163: #
 3164: #   Server side include.
 3165: # Parameters:
 3166: #  fn     Possibly encrypted resource name/id.
 3167: #  form   Hash that describes how the rendering should be done
 3168: #         and other things.
 3169: # Returns:
 3170: #   Scalar context: The content of the response.
 3171: #   Array context:  2 element list of the content and the full response object.
 3172: #     
 3173: sub ssi {
 3174: 
 3175:     my ($fn,%form)=@_;
 3176:     my ($request,$response);
 3177: 
 3178:     $form{'no_update_last_known'}=1;
 3179:     &Apache::lonenc::check_encrypt(\$fn);
 3180:     if (%form) {
 3181:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 3182:       $request->content(join('&',map {
 3183:             my $name = escape($_);
 3184:             "$name=" . ( ref($form{$_}) eq 'ARRAY'
 3185:             ? join("&$name=", map {escape($_) } @{$form{$_}})
 3186:             : &escape($form{$_}) );
 3187:         } keys(%form)));
 3188:     } else {
 3189:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 3190:     }
 3191: 
 3192:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 3193: 
 3194:     if (($env{'request.course.id'}) &&
 3195:         ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
 3196:         ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
 3197:         ($form{'grade_symb'} ne '') &&
 3198:         (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
 3199:                                  ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
 3200:         if (LWP::UserAgent->VERSION >= 5.834) {
 3201:             my $ua=new LWP::UserAgent;
 3202:             $ua->local_address('127.0.0.1');
 3203:             $response = $ua->request($request);
 3204:         } else {
 3205:             {
 3206:                 require LWP::Protocol::http;
 3207:                 local @LWP::Protocol::http::EXTRA_SOCK_OPTS = (LocalAddr => '127.0.0.1');
 3208:                 my $ua=new LWP::UserAgent;
 3209:                 $response = $ua->request($request);
 3210:                 @LWP::Protocol::http::EXTRA_SOCK_OPTS = ();
 3211:             }
 3212:         }
 3213:     } else {
 3214:         my $ua=new LWP::UserAgent;
 3215:         $response = $ua->request($request);
 3216:     }
 3217:     if (wantarray) {
 3218: 	return ($response->content, $response);
 3219:     } else {
 3220: 	return $response->content;
 3221:     }
 3222: }
 3223: 
 3224: sub externalssi {
 3225:     my ($url)=@_;
 3226:     my $ua=new LWP::UserAgent;
 3227:     my $request=new HTTP::Request('GET',$url);
 3228:     my $response=$ua->request($request);
 3229:     if (wantarray) {
 3230:         return ($response->content, $response);
 3231:     } else {
 3232:         return $response->content;
 3233:     }
 3234: }
 3235: 
 3236: # If the local copy of a replicated resource is outdated, trigger a
 3237: # connection from the homeserver to flush the delayed queue. If no update
 3238: # happens, remove local copies of outdated resource (and corresponding
 3239: # metadata file).
 3240: 
 3241: sub remove_stale_resfile {
 3242:     my ($url) = @_;
 3243:     my $removed;
 3244:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
 3245:         my $audom = $1;
 3246:         my $auname = $2;
 3247:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
 3248:             my $homeserver = &homeserver($auname,$audom);
 3249:             unless (($homeserver eq 'no_host') ||
 3250:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
 3251:                 my $fname = &filelocation('',$url);
 3252:                 if (-e $fname) {
 3253:                     my $hostname = &hostname($homeserver);
 3254:                     if ($hostname) {
 3255:                         my $protocol = $protocol{$homeserver};
 3256:                         $protocol = 'http' if ($protocol ne 'https');
 3257:                         my $uri = $protocol.'://'.$hostname.'/raw/'.&declutter($url);
 3258:                         my $ua=new LWP::UserAgent;
 3259:                         $ua->timeout(5);
 3260:                         my $request=new HTTP::Request('HEAD',$uri);
 3261:                         my $response=$ua->request($request);
 3262:                         if ($response->is_success()) {
 3263:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
 3264:                             my $locmodtime = (stat($fname))[9];
 3265:                             if ($locmodtime < $remmodtime) {
 3266:                                 my $stale;
 3267:                                 my $answer = &reply('pong',$homeserver);
 3268:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
 3269:                                     sleep(0.2);
 3270:                                     $locmodtime = (stat($fname))[9];
 3271:                                     if ($locmodtime < $remmodtime) {
 3272:                                         my $posstransfer = $fname.'.in.transfer';
 3273:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
 3274:                                             $removed = 1;
 3275:                                         } else {
 3276:                                             $stale = 1;
 3277:                                         }
 3278:                                     } else {
 3279:                                         $removed = 1;
 3280:                                     }
 3281:                                 } else {
 3282:                                     $stale = 1;
 3283:                                 }
 3284:                                 if ($stale) {
 3285:                                     if (unlink($fname)) {
 3286:                                         if ($uri!~/\.meta$/) {
 3287:                                             if (-e $fname.'.meta') {
 3288:                                                 unlink($fname.'.meta');
 3289:                                             }
 3290:                                         }
 3291:                                         my $unsubresult = &unsubscribe($fname);
 3292:                                         unless ($unsubresult eq 'ok') {
 3293:                                             &logthis("no unsub of $fname from $homeserver, reason: $unsubresult");
 3294:                                         }
 3295:                                         $removed = 1;
 3296:                                     }
 3297:                                 }
 3298:                             }
 3299:                         }
 3300:                     }
 3301:                 }
 3302:             }
 3303:         }
 3304:     }
 3305:     return $removed;
 3306: }
 3307: 
 3308: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 3309: 
 3310: sub allowuploaded {
 3311:     my ($srcurl,$url)=@_;
 3312:     $url=&clutter(&declutter($url));
 3313:     my $dir=$url;
 3314:     $dir=~s/\/[^\/]+$//;
 3315:     my %httpref=();
 3316:     my $httpurl=&hreflocation('',$url);
 3317:     $httpref{'httpref.'.$httpurl}=$srcurl;
 3318:     &Apache::lonnet::appenv(\%httpref);
 3319: }
 3320: 
 3321: #
 3322: # Determine if the current user should be able to edit a particular resource,
 3323: # when viewing in course context.
 3324: # (a) When viewing resource used to determine if "Edit" item is included in
 3325: #     Functions.
 3326: # (b) When displaying folder contents in course editor, used to determine if
 3327: #     "Edit" link will be displayed alongside resource.
 3328: #
 3329: #  input: six args -- filename (decluttered), course number, course domain,
 3330: #                   url, symb (if registered) and group (if this is a group
 3331: #                   item -- e.g., bulletin board, group page etc.).
 3332: #  output: array of five scalars --
 3333: #          $cfile -- url for file editing if editable on current server
 3334: #          $home -- homeserver of resource (i.e., for author if published,
 3335: #                                           or course if uploaded.).
 3336: #          $switchserver --  1 if server switch will be needed.
 3337: #          $forceedit -- 1 if icon/link should be to go to edit mode
 3338: #          $forceview -- 1 if icon/link should be to go to view mode
 3339: #
 3340: 
 3341: sub can_edit_resource {
 3342:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
 3343:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
 3344: #
 3345: # For aboutme pages user can only edit his/her own.
 3346: #
 3347:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
 3348:         my ($sdom,$sname) = ($1,$2);
 3349:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
 3350:             $home = $env{'user.home'};
 3351:             $cfile = $resurl;
 3352:             if ($env{'form.forceedit'}) {
 3353:                 $forceview = 1;
 3354:             } else {
 3355:                 $forceedit = 1;
 3356:             }
 3357:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
 3358:         } else {
 3359:             return;
 3360:         }
 3361:     }
 3362: 
 3363:     if ($env{'request.course.id'}) {
 3364:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
 3365:         if ($group ne '') {
 3366: # if this is a group homepage or group bulletin board, check group privs
 3367:             my $allowed = 0;
 3368:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
 3369:                 if ((&allowed('mdg',$env{'request.course.id'}.
 3370:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 3371:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 3372:                     $allowed = 1;
 3373:                 }
 3374:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
 3375:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 3376:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 3377:                     $allowed = 1;
 3378:                 }
 3379:             }
 3380:             if ($allowed) {
 3381:                 $home=&homeserver($cnum,$cdom);
 3382:                 if ($env{'form.forceedit'}) {
 3383:                     $forceview = 1;
 3384:                 } else {
 3385:                     $forceedit = 1;
 3386:                 }
 3387:                 $cfile = $resurl;
 3388:             } else {
 3389:                 return;
 3390:             }
 3391:         } else {
 3392:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
 3393:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
 3394:                     return;
 3395:                 }
 3396:             } elsif (!$crsedit) {
 3397: #
 3398: # No edit allowed where CC has switched to student role.
 3399: #
 3400:                 return;
 3401:             }
 3402:         }
 3403:     }
 3404: 
 3405:     if ($file ne '') {
 3406:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
 3407:             if (&is_course_upload($file,$cnum,$cdom)) {
 3408:                 $uploaded = 1;
 3409:                 $incourse = 1;
 3410:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
 3411:                     $cfile = &hreflocation('',$file);
 3412:                     if ($env{'form.forceedit'}) {
 3413:                         $forceview = 1;
 3414:                     } else {
 3415:                         $forceedit = 1;
 3416:                     }
 3417:                 }
 3418:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
 3419:                 $incourse = 1;
 3420:                 if ($env{'form.forceedit'}) {
 3421:                     $forceview = 1;
 3422:                 } else {
 3423:                     $forceedit = 1;
 3424:                 }
 3425:                 $cfile = $resurl;
 3426:             } elsif (($resurl ne '') && (&is_on_map($resurl))) {
 3427:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
 3428:                     $incourse = 1;
 3429:                     if ($env{'form.forceedit'}) {
 3430:                         $forceview = 1;
 3431:                     } else {
 3432:                         $forceedit = 1;
 3433:                     }
 3434:                     $cfile = $resurl;
 3435:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
 3436:                     $incourse = 1;
 3437:                     $cfile = $resurl.'/smpedit';
 3438:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
 3439:                     $incourse = 1;
 3440:                     if ($env{'form.forceedit'}) {
 3441:                         $forceview = 1;
 3442:                     } else {
 3443:                         $forceedit = 1;
 3444:                     }
 3445:                     $cfile = $resurl;
 3446:                 } elsif (($resurl =~ m{^/ext/}) && ($symb ne '')) {
 3447:                     my ($map,$id,$res) = &decode_symb($symb);
 3448:                     if ($map =~ /\.page$/) {
 3449:                         $incourse = 1;
 3450:                         if ($env{'form.forceedit'}) {
 3451:                             $forceview = 1;
 3452:                             $cfile = $map;
 3453:                         } else {
 3454:                             $forceedit = 1;
 3455:                             $cfile =  '/adm/wrapper'.$resurl;
 3456:                         }
 3457:                     }
 3458:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 3459:                     $incourse = 1;
 3460:                     if ($env{'form.forceedit'}) {
 3461:                         $forceview = 1;
 3462:                     } else {
 3463:                         $forceedit = 1;
 3464:                     }
 3465:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 3466:                 }
 3467:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
 3468:                 my $template = '/res/lib/templates/simpleproblem.problem';
 3469:                 if (&is_on_map($template)) {
 3470:                     $incourse = 1;
 3471:                     $forceview = 1;
 3472:                     $cfile = $template;
 3473:                 }
 3474:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 3475:                 $incourse = 1;
 3476:                 if ($env{'form.forceedit'}) {
 3477:                     $forceview = 1;
 3478:                 } else {
 3479:                     $forceedit = 1;
 3480:                 }
 3481:                 $cfile = $resurl;
 3482:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
 3483:                 $incourse = 1;
 3484:                 $forceview = 1;
 3485:                 if ($symb) {
 3486:                     my ($map,$id,$res)=&decode_symb($symb);
 3487:                     $env{'request.symb'} = $symb;
 3488:                     $cfile = &clutter($res);
 3489:                 } else {
 3490:                     $cfile = $env{'form.suppurl'};
 3491:                     $cfile =~ s{^http://}{};
 3492:                     $cfile = '/adm/wrapper/ext/'.$cfile;
 3493:                 }
 3494:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 3495:                 if ($env{'form.forceedit'}) {
 3496:                     $forceview = 1;
 3497:                 } else {
 3498:                     $forceedit = 1;
 3499:                 }
 3500:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 3501:             }
 3502:         }
 3503:         if ($uploaded || $incourse) {
 3504:             $home=&homeserver($cnum,$cdom);
 3505:         } elsif ($file !~ m{/$}) {
 3506:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
 3507:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
 3508:             # Check that the user has permission to edit this resource
 3509:             my $setpriv = 1;
 3510:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
 3511:             if (defined($cfudom)) {
 3512:                 $home=&homeserver($cfuname,$cfudom);
 3513:                 $cfile=$file;
 3514:             }
 3515:         }
 3516:         if (($cfile ne '') && (!$incourse || $uploaded) &&
 3517:             (($home ne '') && ($home ne 'no_host'))) {
 3518:             my @ids=&current_machine_ids();
 3519:             unless (grep(/^\Q$home\E$/,@ids)) {
 3520:                 $switchserver=1;
 3521:             }
 3522:         }
 3523:     }
 3524:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
 3525: }
 3526: 
 3527: sub is_course_upload {
 3528:     my ($file,$cnum,$cdom) = @_;
 3529:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
 3530:     $uploadpath =~ s{^\/}{};
 3531:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
 3532:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
 3533:         return 1;
 3534:     }
 3535:     return;
 3536: }
 3537: 
 3538: sub in_course {
 3539:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
 3540:     if ($hideprivileged) {
 3541:         my $skipuser;
 3542:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
 3543:         my @possdoms = ($cdom);
 3544:         if ($coursehash{'checkforpriv'}) {
 3545:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
 3546:         }
 3547:         if (&privileged($uname,$udom,\@possdoms)) {
 3548:             $skipuser = 1;
 3549:             if ($coursehash{'nothideprivileged'}) {
 3550:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3551:                     my $user;
 3552:                     if ($item =~ /:/) {
 3553:                         $user = $item;
 3554:                     } else {
 3555:                         $user = join(':',split(/[\@]/,$item));
 3556:                     }
 3557:                     if ($user eq $uname.':'.$udom) {
 3558:                         undef($skipuser);
 3559:                         last;
 3560:                     }
 3561:                 }
 3562:             }
 3563:             if ($skipuser) {
 3564:                 return 0;
 3565:             }
 3566:         }
 3567:     }
 3568:     $type ||= 'any';
 3569:     if (!defined($cdom) || !defined($cnum)) {
 3570:         my $cid  = $env{'request.course.id'};
 3571:         $cdom = $env{'course.'.$cid.'.domain'};
 3572:         $cnum = $env{'course.'.$cid.'.num'};
 3573:     }
 3574:     my $typesref;
 3575:     if (($type eq 'any') || ($type eq 'all')) {
 3576:         $typesref = ['active','previous','future'];
 3577:     } elsif ($type eq 'previous' || $type eq 'future') {
 3578:         $typesref = [$type];
 3579:     }
 3580:     my %roles = &get_my_roles($uname,$udom,'userroles',
 3581:                               $typesref,undef,[$cdom]);
 3582:     my ($tmp) = keys(%roles);
 3583:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
 3584:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
 3585:     if (@course_roles > 0) {
 3586:         return 1;
 3587:     }
 3588:     return 0;
 3589: }
 3590: 
 3591: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 3592: # input: action, courseID, current domain, intended
 3593: #        path to file, source of file, instruction to parse file for objects,
 3594: #        ref to hash for embedded objects,
 3595: #        ref to hash for codebase of java objects.
 3596: #        reference to scalar to accommodate mime type determined
 3597: #          from File::MMagic if $parser = parse.
 3598: #
 3599: # output: url to file (if action was uploaddoc), 
 3600: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 3601: #
 3602: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 3603: # course.
 3604: #
 3605: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3606: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 3607: #          course's home server.
 3608: #
 3609: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 3610: #          be copied from $source (current location) to 
 3611: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3612: #         and will then be copied to
 3613: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 3614: #         course's home server.
 3615: #
 3616: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3617: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 3618: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3619: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 3620: #         in course's home server.
 3621: #
 3622: 
 3623: sub process_coursefile {
 3624:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
 3625:         $mimetype)=@_;
 3626:     my $fetchresult;
 3627:     my $home=&homeserver($docuname,$docudom);
 3628:     if ($action eq 'propagate') {
 3629:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3630: 			     $home);
 3631:     } else {
 3632:         my $fpath = '';
 3633:         my $fname = $file;
 3634:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3635:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3636:         my $filepath = &build_filepath($fpath);
 3637:         if ($action eq 'copy') {
 3638:             if ($source eq '') {
 3639:                 $fetchresult = 'no source file';
 3640:                 return $fetchresult;
 3641:             } else {
 3642:                 my $destination = $filepath.'/'.$fname;
 3643:                 rename($source,$destination);
 3644:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3645:                                  $home);
 3646:             }
 3647:         } elsif ($action eq 'uploaddoc') {
 3648:             open(my $fh,'>',$filepath.'/'.$fname);
 3649:             print $fh $env{'form.'.$source};
 3650:             close($fh);
 3651:             if ($parser eq 'parse') {
 3652:                 my $mm = new File::MMagic;
 3653:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
 3654:                 if ($type eq 'text/html') {
 3655:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 3656:                     unless ($parse_result eq 'ok') {
 3657:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 3658:                     }
 3659:                 }
 3660:                 if (ref($mimetype)) {
 3661:                     $$mimetype = $type;
 3662:                 } 
 3663:             }
 3664:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3665:                                  $home);
 3666:             if ($fetchresult eq 'ok') {
 3667:                 return '/uploaded/'.$fpath.'/'.$fname;
 3668:             } else {
 3669:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3670:                         ' to host '.$home.': '.$fetchresult);
 3671:                 return '/adm/notfound.html';
 3672:             }
 3673:         }
 3674:     }
 3675:     unless ( $fetchresult eq 'ok') {
 3676:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3677:              ' to host '.$home.': '.$fetchresult);
 3678:     }
 3679:     return $fetchresult;
 3680: }
 3681: 
 3682: sub build_filepath {
 3683:     my ($fpath) = @_;
 3684:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 3685:     unless ($fpath eq '') {
 3686:         my @parts=split('/',$fpath);
 3687:         foreach my $part (@parts) {
 3688:             $filepath.= '/'.$part;
 3689:             if ((-e $filepath)!=1) {
 3690:                 mkdir($filepath,0777);
 3691:             }
 3692:         }
 3693:     }
 3694:     return $filepath;
 3695: }
 3696: 
 3697: sub store_edited_file {
 3698:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 3699:     my $file = $primary_url;
 3700:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 3701:     my $fpath = '';
 3702:     my $fname = $file;
 3703:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3704:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3705:     my $filepath = &build_filepath($fpath);
 3706:     open(my $fh,'>',$filepath.'/'.$fname);
 3707:     print $fh $content;
 3708:     close($fh);
 3709:     my $home=&homeserver($docuname,$docudom);
 3710:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3711: 			  $home);
 3712:     if ($$fetchresult eq 'ok') {
 3713:         return '/uploaded/'.$fpath.'/'.$fname;
 3714:     } else {
 3715:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3716: 		 ' to host '.$home.': '.$$fetchresult);
 3717:         return '/adm/notfound.html';
 3718:     }
 3719: }
 3720: 
 3721: sub clean_filename {
 3722:     my ($fname,$args)=@_;
 3723: # Replace Windows backslashes by forward slashes
 3724:     $fname=~s/\\/\//g;
 3725:     if (!$args->{'keep_path'}) {
 3726:         # Get rid of everything but the actual filename
 3727: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 3728:     }
 3729: # Replace spaces by underscores
 3730:     $fname=~s/\s+/\_/g;
 3731: # Transliterate non-ascii text to ascii
 3732:     my $lang = &Apache::lonlocal::current_language();
 3733:     $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
 3734: # Replace all other weird characters by nothing
 3735:     $fname=~s{[^/\w\.\-]}{}g;
 3736: # Replace all .\d. sequences with _\d. so they no longer look like version
 3737: # numbers
 3738:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 3739: # Replace three or more adjacent underscores with one for consistency
 3740: # with loncfile::filename_check() so complete url can be extracted by
 3741: # lonnet::decode_symb()
 3742:     $fname=~s/_{3,}/_/g;
 3743:     return $fname;
 3744: }
 3745: 
 3746: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
 3747: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
 3748: # image with the same aspect ratio as the original, but with dimensions which do 
 3749: # not exceed $resizewidth and $resizeheight.
 3750:  
 3751: sub resizeImage {
 3752:     my ($img_path,$resizewidth,$resizeheight) = @_;
 3753:     my $ima = Image::Magick->new;
 3754:     my $resized;
 3755:     if (-e $img_path) {
 3756:         $ima->Read($img_path);
 3757:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
 3758:             my $width = $ima->Get('width');
 3759:             my $height = $ima->Get('height');
 3760:             if ($width > $resizewidth) {
 3761: 	        my $factor = $width/$resizewidth;
 3762:                 my $newheight = $height/$factor;
 3763:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
 3764:                 $resized = 1;
 3765:             }
 3766:         }
 3767:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
 3768:             my $width = $ima->Get('width');
 3769:             my $height = $ima->Get('height');
 3770:             if ($height > $resizeheight) {
 3771:                 my $factor = $height/$resizeheight;
 3772:                 my $newwidth = $width/$factor;
 3773:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
 3774:                 $resized = 1;
 3775:             }
 3776:         }
 3777:         if ($resized) {
 3778:             $ima->Write($img_path);
 3779:         }
 3780:     }
 3781:     return;
 3782: }
 3783: 
 3784: # --------------- Take an uploaded file and put it into the userfiles directory
 3785: # input: $formname - the contents of the file are in $env{"form.$formname"}
 3786: #                    the desired filename is in $env{"form.$formname.filename"}
 3787: #        $context - possible values: coursedoc, existingfile, overwrite, 
 3788: #                                    canceloverwrite, scantron or ''. 
 3789: #                   if 'coursedoc': upload to the current course
 3790: #                   if 'existingfile': write file to tmp/overwrites directory 
 3791: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
 3792: #                   $context is passed as argument to &finishuserfileupload
 3793: #        $subdir - directory in userfile to store the file into
 3794: #        $parser - instruction to parse file for objects ($parser = parse) or
 3795: #                  if context is 'scantron', $parser is hashref of csv column mapping
 3796: #                  (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3,
 3797: #                          Section => 4, CODE => 5, FirstQuestion => 9 }).
 3798: #        $allfiles - reference to hash for embedded objects
 3799: #        $codebase - reference to hash for codebase of java objects
 3800: #        $desuname - username for permanent storage of uploaded file
 3801: #        $dsetudom - domain for permanaent storage of uploaded file
 3802: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 3803: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 3804: #        $resizewidth - width (pixels) to which to resize uploaded image
 3805: #        $resizeheight - height (pixels) to which to resize uploaded image
 3806: #        $mimetype - reference to scalar to accommodate mime type determined
 3807: #                    from File::MMagic.
 3808: # 
 3809: # output: url of file in userspace, or error: <message> 
 3810: #             or /adm/notfound.html if failure to upload occurse
 3811: 
 3812: sub userfileupload {
 3813:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
 3814:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
 3815:     if (!defined($subdir)) { $subdir='unknown'; }
 3816:     my $fname=$env{'form.'.$formname.'.filename'};
 3817:     $fname=&clean_filename($fname);
 3818:     # See if there is anything left
 3819:     unless ($fname) { return 'error: no uploaded file'; }
 3820:     # If filename now begins with a . prepend unix timestamp _ milliseconds
 3821:     if ($fname =~ /^\./) {
 3822:         my ($s,$usec) = &gettimeofday();
 3823:         while (length($usec) < 6) {
 3824:             $usec = '0'.$usec;
 3825:         }
 3826:         $fname = $s.'_'.substr($usec,0,3).$fname;
 3827:     }
 3828:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
 3829:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
 3830:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
 3831:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3832:         my $now = time;
 3833:         my $filepath;
 3834:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
 3835:              $filepath = 'tmp/helprequests/'.$now;
 3836:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
 3837:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 3838:                          '_'.$env{'user.domain'}.'/pending';
 3839:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3840:             my ($docuname,$docudom);
 3841:             if ($destudom =~ /^$match_domain$/) {
 3842:                 $docudom = $destudom;
 3843:             } else {
 3844:                 $docudom = $env{'user.domain'};
 3845:             }
 3846:             if ($destuname =~ /^$match_username$/) { 
 3847:                 $docuname = $destuname;
 3848:             } else {
 3849:                 $docuname = $env{'user.name'};
 3850:             }
 3851:             if (exists($env{'form.group'})) {
 3852:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3853:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3854:             }
 3855:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
 3856:             if ($context eq 'canceloverwrite') {
 3857:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
 3858:                 if (-e  $tempfile) {
 3859:                     my @info = stat($tempfile);
 3860:                     if ($info[9] eq $env{'form.timestamp'}) {
 3861:                         unlink($tempfile);
 3862:                     }
 3863:                 }
 3864:                 return;
 3865:             }
 3866:         }
 3867:         # Create the directory if not present
 3868:         my @parts=split(/\//,$filepath);
 3869:         my $fullpath = $perlvar{'lonDaemons'};
 3870:         for (my $i=0;$i<@parts;$i++) {
 3871:             $fullpath .= '/'.$parts[$i];
 3872:             if ((-e $fullpath)!=1) {
 3873:                 mkdir($fullpath,0777);
 3874:             }
 3875:         }
 3876:         open(my $fh,'>',$fullpath.'/'.$fname);
 3877:         print $fh $env{'form.'.$formname};
 3878:         close($fh);
 3879:         if ($context eq 'existingfile') {
 3880:             my @info = stat($fullpath.'/'.$fname);
 3881:             return ($fullpath.'/'.$fname,$info[9]);
 3882:         } else {
 3883:             return $fullpath.'/'.$fname;
 3884:         }
 3885:     }
 3886:     if ($subdir eq 'scantron') {
 3887:         $fname = 'scantron_orig_'.$fname;
 3888:     } else {
 3889:         $fname="$subdir/$fname";
 3890:     }
 3891:     if ($context eq 'coursedoc') {
 3892: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3893: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3894:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 3895:             return &finishuserfileupload($docuname,$docudom,
 3896: 					 $formname,$fname,$parser,$allfiles,
 3897: 					 $codebase,$thumbwidth,$thumbheight,
 3898:                                          $resizewidth,$resizeheight,$context,$mimetype);
 3899:         } else {
 3900:             if ($env{'form.folder'}) {
 3901:                 $fname=$env{'form.folder'}.'/'.$fname;
 3902:             }
 3903:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 3904: 				       $fname,$formname,$parser,
 3905: 				       $allfiles,$codebase,$mimetype);
 3906:         }
 3907:     } elsif (defined($destuname)) {
 3908:         my $docuname=$destuname;
 3909:         my $docudom=$destudom;
 3910: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 3911: 				     $parser,$allfiles,$codebase,
 3912:                                      $thumbwidth,$thumbheight,
 3913:                                      $resizewidth,$resizeheight,$context,$mimetype);
 3914:     } else {
 3915:         my $docuname=$env{'user.name'};
 3916:         my $docudom=$env{'user.domain'};
 3917:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
 3918:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3919:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3920:         }
 3921: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 3922: 				     $parser,$allfiles,$codebase,
 3923:                                      $thumbwidth,$thumbheight,
 3924:                                      $resizewidth,$resizeheight,$context,$mimetype);
 3925:     }
 3926: }
 3927: 
 3928: sub finishuserfileupload {
 3929:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 3930:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
 3931:     my $path=$docudom.'/'.$docuname.'/';
 3932:     my $filepath=$perlvar{'lonDocRoot'};
 3933:   
 3934:     my ($fnamepath,$file,$fetchthumb);
 3935:     $file=$fname;
 3936:     if ($fname=~m|/|) {
 3937:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 3938: 	$path.=$fnamepath.'/';
 3939:     }
 3940:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 3941:     my $count;
 3942:     for ($count=4;$count<=$#parts;$count++) {
 3943:         $filepath.="/$parts[$count]";
 3944:         if ((-e $filepath)!=1) {
 3945: 	    mkdir($filepath,0777);
 3946:         }
 3947:     }
 3948: 
 3949: # Save the file
 3950:     {
 3951: 	if (!open(FH,'>',$filepath.'/'.$file)) {
 3952: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 3953: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 3954: 	    return '/adm/notfound.html';
 3955: 	}
 3956:         if ($context eq 'overwrite') {
 3957:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
 3958:             my $target = $filepath.'/'.$file;
 3959:             if (-e $source) {
 3960:                 my @info = stat($source);
 3961:                 if ($info[9] eq $env{'form.timestamp'}) {   
 3962:                     unless (&File::Copy::move($source,$target)) {
 3963:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
 3964:                         return "Moving from $source failed";
 3965:                     }
 3966:                 } else {
 3967:                     return "Temporary file: $source had unexpected date/time for last modification";
 3968:                 }
 3969:             } else {
 3970:                 return "Temporary file: $source missing";
 3971:             }
 3972:         } elsif (!print FH ($env{'form.'.$formname})) {
 3973: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 3974: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 3975: 	    return '/adm/notfound.html';
 3976: 	}
 3977: 	close(FH);
 3978:         if ($resizewidth && $resizeheight) {
 3979:             my $mm = new File::MMagic;
 3980:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
 3981:             if ($mime_type =~ m{^image/}) {
 3982: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
 3983:             }  
 3984: 	}
 3985:     }
 3986:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
 3987:         if (ref($mimetype)) {
 3988:             if ($$mimetype eq '') {
 3989:                 my $mm = new File::MMagic;
 3990:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
 3991:                 $$mimetype = $type;
 3992:             }
 3993:         }
 3994:     }
 3995:     if (($context ne 'scantron') && ($parser eq 'parse')) {
 3996:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
 3997:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
 3998:                                                        $allfiles,$codebase);
 3999:             unless ($parse_result eq 'ok') {
 4000:                 &logthis('Failed to parse '.$filepath.$file.
 4001: 	   	         ' for embedded media: '.$parse_result); 
 4002:             }
 4003:         }
 4004:     } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
 4005:         my $format = $env{'form.scantron_format'};
 4006:         &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
 4007:     }
 4008:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 4009:         my $input = $filepath.'/'.$file;
 4010:         my $output = $filepath.'/'.'tn-'.$file;
 4011:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 4012:         my @args = ('convert','-sample',$thumbsize,$input,$output);
 4013:         system({$args[0]} @args);
 4014:         if (-e $filepath.'/'.'tn-'.$file) {
 4015:             $fetchthumb  = 1; 
 4016:         }
 4017:     }
 4018:  
 4019: # Notify homeserver to grep it
 4020: #
 4021:     my $docuhome=&homeserver($docuname,$docudom);	
 4022:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 4023:     if ($fetchresult eq 'ok') {
 4024:         if ($fetchthumb) {
 4025:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 4026:             if ($thumbresult ne 'ok') {
 4027:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 4028:                          $docuhome.': '.$thumbresult);
 4029:             }
 4030:         }
 4031: #
 4032: # Return the URL to it
 4033:         return '/uploaded/'.$path.$file;
 4034:     } else {
 4035:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 4036: 		 ': '.$fetchresult);
 4037:         return '/adm/notfound.html';
 4038:     }
 4039: }
 4040: 
 4041: sub extract_embedded_items {
 4042:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 4043:     my @state = ();
 4044:     my (%lastids,%related,%shockwave,%flashvars);
 4045:     my %javafiles = (
 4046:                       codebase => '',
 4047:                       code => '',
 4048:                       archive => ''
 4049:                     );
 4050:     my %mediafiles = (
 4051:                       src => '',
 4052:                       movie => '',
 4053:                      );
 4054:     my $p;
 4055:     if ($content) {
 4056:         $p = HTML::LCParser->new($content);
 4057:     } else {
 4058:         $p = HTML::LCParser->new($fullpath);
 4059:     }
 4060:     while (my $t=$p->get_token()) {
 4061: 	if ($t->[0] eq 'S') {
 4062: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 4063: 	    push(@state, $tagname);
 4064:             if (lc($tagname) eq 'allow') {
 4065:                 &add_filetype($allfiles,$attr->{'src'},'src');
 4066:             }
 4067: 	    if (lc($tagname) eq 'img') {
 4068: 		&add_filetype($allfiles,$attr->{'src'},'src');
 4069: 	    }
 4070: 	    if (lc($tagname) eq 'a') {
 4071:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
 4072: 		    &add_filetype($allfiles,$attr->{'href'},'href');
 4073:                 }
 4074: 	    }
 4075:             if (lc($tagname) eq 'script') {
 4076:                 my $src;
 4077:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 4078:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 4079:                 } else {
 4080:                     if ($attr->{'src'} ne '') {
 4081:                         $src = $attr->{'src'};
 4082:                         &add_filetype($allfiles,$src,'src');
 4083:                     }
 4084:                 }
 4085:                 my $text = $p->get_trimmed_text();
 4086:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
 4087:                     my @swfargs = split(/,/,$1);
 4088:                     foreach my $item (@swfargs) {
 4089:                         $item =~ s/["']//g;
 4090:                         $item =~ s/^\s+//;
 4091:                         $item =~ s/\s+$//;
 4092:                     }
 4093:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
 4094:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
 4095:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
 4096:                         } else {
 4097:                             $related{$swfargs[0]} = [$swfargs[2]];
 4098:                         }
 4099:                     }
 4100:                 }
 4101:             }
 4102:             if (lc($tagname) eq 'link') {
 4103:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 4104:                     &add_filetype($allfiles,$attr->{'href'},'href');
 4105:                 }
 4106:             }
 4107: 	    if (lc($tagname) eq 'object' ||
 4108: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 4109: 		foreach my $item (keys(%javafiles)) {
 4110: 		    $javafiles{$item} = '';
 4111: 		}
 4112:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
 4113:                     $lastids{lc($tagname)} = $attr->{'id'};
 4114:                 }
 4115: 	    }
 4116: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 4117: 		my $name = lc($attr->{'name'});
 4118: 		foreach my $item (keys(%javafiles)) {
 4119: 		    if ($name eq $item) {
 4120: 			$javafiles{$item} = $attr->{'value'};
 4121: 			last;
 4122: 		    }
 4123: 		}
 4124:                 my $pathfrom;
 4125: 		foreach my $item (keys(%mediafiles)) {
 4126: 		    if ($name eq $item) {
 4127:                         $pathfrom = $attr->{'value'};
 4128:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
 4129: 			&add_filetype($allfiles,$pathfrom,$name);
 4130: 			last;
 4131: 		    }
 4132: 		}
 4133:                 if ($name eq 'flashvars') {
 4134:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
 4135:                 }
 4136:                 if ($pathfrom ne '') {
 4137:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
 4138:                                          $pathfrom);
 4139:                 }
 4140: 	    }
 4141: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 4142: 		foreach my $item (keys(%javafiles)) {
 4143: 		    if ($attr->{$item}) {
 4144: 			$javafiles{$item} = $attr->{$item};
 4145: 			last;
 4146: 		    }
 4147: 		}
 4148: 		foreach my $item (keys(%mediafiles)) {
 4149: 		    if ($attr->{$item}) {
 4150: 			&add_filetype($allfiles,$attr->{$item},$item);
 4151: 			last;
 4152: 		    }
 4153: 		}
 4154:                 if (lc($tagname) eq 'embed') {
 4155:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
 4156:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
 4157:                                              $attr->{'src'});
 4158:                     }
 4159:                 }
 4160: 	    }
 4161:             if (lc($tagname) eq 'iframe') {
 4162:                 my $src = $attr->{'src'} ;
 4163:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
 4164:                     &add_filetype($allfiles,$src,'src');
 4165:                 } elsif ($src =~ m{^/}) {
 4166:                     if ($env{'request.course.id'}) {
 4167:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4168:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4169:                         my $url = &hreflocation('',$fullpath);
 4170:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
 4171:                             my $relpath = $1;
 4172:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
 4173:                                 &add_filetype($allfiles,$1,'src');
 4174:                             }
 4175:                         }
 4176:                     }
 4177:                 }
 4178:             }
 4179:             if ($t->[4] =~ m{/>$}) {
 4180:                 pop(@state);
 4181:             }
 4182: 	} elsif ($t->[0] eq 'E') {
 4183: 	    my ($tagname) = ($t->[1]);
 4184: 	    if ($javafiles{'codebase'} ne '') {
 4185: 		$javafiles{'codebase'} .= '/';
 4186: 	    }  
 4187: 	    if (lc($tagname) eq 'applet' ||
 4188: 		lc($tagname) eq 'object' ||
 4189: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 4190: 		) {
 4191: 		foreach my $item (keys(%javafiles)) {
 4192: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 4193: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 4194: 			&add_filetype($allfiles,$file,$item);
 4195: 		    }
 4196: 		}
 4197: 	    } 
 4198: 	    pop @state;
 4199: 	}
 4200:     }
 4201:     foreach my $id (sort(keys(%flashvars))) {
 4202:         if ($shockwave{$id} ne '') {
 4203:             my @pairs = split(/\&/,$flashvars{$id});
 4204:             foreach my $pair (@pairs) {
 4205:                 my ($key,$value) = split(/\=/,$pair);
 4206:                 if ($key eq 'thumb') {
 4207:                     &add_filetype($allfiles,$value,$key);
 4208:                 } elsif ($key eq 'content') {
 4209:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
 4210:                     my ($ext) = ($value =~ /\.([^.]+)$/);
 4211:                     if ($ext ne '') {
 4212:                         &add_filetype($allfiles,$path.$value,$ext);
 4213:                     }
 4214:                 }
 4215:             }
 4216:         }
 4217:     }
 4218:     return 'ok';
 4219: }
 4220: 
 4221: sub add_filetype {
 4222:     my ($allfiles,$file,$type)=@_;
 4223:     if (exists($allfiles->{$file})) {
 4224: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 4225: 	    push(@{$allfiles->{$file}}, &escape($type));
 4226: 	}
 4227:     } else {
 4228: 	@{$allfiles->{$file}} = (&escape($type));
 4229:     }
 4230: }
 4231: 
 4232: sub embedded_dependency {
 4233:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
 4234:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
 4235:         if (($identifier ne '') &&
 4236:             (ref($related->{$identifier}) eq 'ARRAY') &&
 4237:             ($pathfrom ne '')) {
 4238:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
 4239:             foreach my $dep (@{$related->{$identifier}}) {
 4240:                 &add_filetype($allfiles,$path.$dep,'object');
 4241:             }
 4242:         }
 4243:     }
 4244:     return;
 4245: }
 4246: 
 4247: sub bubblesheet_converter {
 4248:     my ($cdom,$fullpath,$config,$format) = @_;
 4249:     if ((&domain($cdom) ne '') &&
 4250:         ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
 4251:         (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
 4252:         my (%csvcols,%csvoptions);
 4253:         if (ref($config->{'fields'}) eq 'HASH') {
 4254:             %csvcols = %{$config->{'fields'}};
 4255:         }
 4256:         if (ref($config->{'options'}) eq 'HASH') {
 4257:             %csvoptions = %{$config->{'options'}};
 4258:         }
 4259:         my %csvbynum = reverse(%csvcols);
 4260:         my %scantronconf = &get_scantron_config($format,$cdom);
 4261:         if (keys(%scantronconf)) {
 4262:             my %bynum = (
 4263:                           $scantronconf{CODEstart} => 'CODEstart',
 4264:                           $scantronconf{IDstart}   => 'IDstart',
 4265:                           $scantronconf{PaperID}   => 'PaperID',
 4266:                           $scantronconf{FirstName} => 'FirstName',
 4267:                           $scantronconf{LastName}  => 'LastName',
 4268:                           $scantronconf{Qstart}    => 'Qstart',
 4269:                         );
 4270:             my @ordered;
 4271:             foreach my $item (sort { $a <=> $b } keys(%bynum)) {
 4272:                 push(@ordered,$bynum{$item});
 4273:             }
 4274:             my %mapstart = (
 4275:                               CODEstart => 'CODE',
 4276:                               IDstart   => 'ID',
 4277:                               PaperID   => 'PaperID',
 4278:                               FirstName => 'FirstName',
 4279:                               LastName  => 'LastName',
 4280:                               Qstart    => 'FirstQuestion',
 4281:                            );
 4282:             my %maplength = (
 4283:                               CODEstart => 'CODElength',
 4284:                               IDstart   => 'IDlength',
 4285:                               PaperID   => 'PaperIDlength',
 4286:                               FirstName => 'FirstNamelength',
 4287:                               LastName  => 'LastNamelength',
 4288:             );
 4289:             if (open(my $fh,'<',$fullpath)) {
 4290:                 my $output;
 4291:                 my %lettdig = &letter_to_digits();
 4292:                 my %diglett = reverse(%lettdig);
 4293:                 my $numletts = scalar(keys(%lettdig));
 4294:                 my $num = 0;
 4295:                 while (my $line=<$fh>) {
 4296:                     $num ++;
 4297:                     next if (($num == 1) && ($csvoptions{'hdr'} == 1));
 4298:                     $line =~ s{[\r\n]+$}{};
 4299:                     my %found;
 4300:                     my @values = split(/,/,$line);
 4301:                     my ($qstart,$record);
 4302:                     for (my $i=0; $i<@values; $i++) {
 4303:                         if ((($qstart ne '') && ($i > $qstart)) ||
 4304:                             ($csvbynum{$i} eq 'FirstQuestion')) {
 4305:                             if ($values[$i] eq '') {
 4306:                                 $values[$i] = $scantronconf{'Qoff'};
 4307:                             } elsif ($scantronconf{'Qon'} eq 'number') {
 4308:                                 if ($values[$i] =~ /^[A-Ja-j]$/) {
 4309:                                     $values[$i] = $lettdig{uc($values[$i])};
 4310:                                 }
 4311:                             } elsif ($scantronconf{'Qon'} eq 'letter') {
 4312:                                 if ($values[$i] =~ /^[0-9]$/) {
 4313:                                     $values[$i] = $diglett{$values[$i]};
 4314:                                 }
 4315:                             } else {
 4316:                                 if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
 4317:                                     my $digit;
 4318:                                     if ($values[$i] =~ /^[A-Ja-j]$/) {
 4319:                                         $digit = $lettdig{uc($values[$i])}-1;
 4320:                                         if ($values[$i] eq 'J') {
 4321:                                             $digit += $numletts;
 4322:                                         }
 4323:                                     } elsif ($values[$i] =~ /^[0-9]$/) {
 4324:                                         $digit = $values[$i]-1;
 4325:                                         if ($values[$i] eq '0') {
 4326:                                             $digit += $numletts;
 4327:                                         }
 4328:                                     }
 4329:                                     my $qval='';
 4330:                                     for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
 4331:                                         if ($j == $digit) {
 4332:                                             $qval .= $scantronconf{'Qon'};
 4333:                                         } else {
 4334:                                             $qval .= $scantronconf{'Qoff'};
 4335:                                         }
 4336:                                     }
 4337:                                     $values[$i] = $qval;
 4338:                                 }
 4339:                             }
 4340:                             if (length($values[$i]) > $scantronconf{'Qlength'}) {
 4341:                                 $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
 4342:                             }
 4343:                             my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
 4344:                             if ($numblank > 0) {
 4345:                                  $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
 4346:                             }
 4347:                             if ($csvbynum{$i} eq 'FirstQuestion') {
 4348:                                 $qstart = $i;
 4349:                                 $found{$csvbynum{$i}} = $values[$i];
 4350:                             } else {
 4351:                                 $found{'FirstQuestion'} .= $values[$i];
 4352:                             }
 4353:                         } elsif (exists($csvbynum{$i})) {
 4354:                             if ($csvoptions{'rem'}) {
 4355:                                 $values[$i] =~ s/^\s+//;
 4356:                             }
 4357:                             if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
 4358:                                 while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
 4359:                                     $values[$i] = '0'.$values[$i];
 4360:                                 }
 4361:                             }
 4362:                             $found{$csvbynum{$i}} = $values[$i];
 4363:                         }
 4364:                     }
 4365:                     foreach my $item (@ordered) {
 4366:                         my $currlength = 1+length($record);
 4367:                         my $numspaces = $scantronconf{$item} - $currlength;
 4368:                         if ($numspaces > 0) {
 4369:                             $record .= (' ' x $numspaces);
 4370:                         }
 4371:                         if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
 4372:                             unless ($item eq 'Qstart') {
 4373:                                 if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
 4374:                                     $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
 4375:                                 }
 4376:                             }
 4377:                             $record .= $found{$mapstart{$item}};
 4378:                         }
 4379:                     }
 4380:                     $output .= "$record\n";
 4381:                 }
 4382:                 close($fh);
 4383:                 if ($output) {
 4384:                     if (open(my $fh,'>',$fullpath)) {
 4385:                         print $fh $output;
 4386:                         close($fh);
 4387:                     }
 4388:                 }
 4389:             }
 4390:         }
 4391:         return;
 4392:     }
 4393: }
 4394: 
 4395: sub letter_to_digits {
 4396:     my %lettdig = (
 4397:                     A => 1,
 4398:                     B => 2,
 4399:                     C => 3,
 4400:                     D => 4,
 4401:                     E => 5,
 4402:                     F => 6,
 4403:                     G => 7,
 4404:                     H => 8,
 4405:                     I => 9,
 4406:                     J => 0,
 4407:                   );
 4408:     return %lettdig;
 4409: }
 4410: 
 4411: sub get_scantron_config {
 4412:     my ($which,$cdom) = @_;
 4413:     my @lines = &get_scantronformat_file($cdom);
 4414:     my %config;
 4415:     #FIXME probably should move to XML it has already gotten a bit much now
 4416:     foreach my $line (@lines) {
 4417:         my ($name,$descrip)=split(/:/,$line);
 4418:         if ($name ne $which ) { next; }
 4419:         chomp($line);
 4420:         my @config=split(/:/,$line);
 4421:         $config{'name'}=$config[0];
 4422:         $config{'description'}=$config[1];
 4423:         $config{'CODElocation'}=$config[2];
 4424:         $config{'CODEstart'}=$config[3];
 4425:         $config{'CODElength'}=$config[4];
 4426:         $config{'IDstart'}=$config[5];
 4427:         $config{'IDlength'}=$config[6];
 4428:         $config{'Qstart'}=$config[7];
 4429:         $config{'Qlength'}=$config[8];
 4430:         $config{'Qoff'}=$config[9];
 4431:         $config{'Qon'}=$config[10];
 4432:         $config{'PaperID'}=$config[11];
 4433:         $config{'PaperIDlength'}=$config[12];
 4434:         $config{'FirstName'}=$config[13];
 4435:         $config{'FirstNamelength'}=$config[14];
 4436:         $config{'LastName'}=$config[15];
 4437:         $config{'LastNamelength'}=$config[16];
 4438:         $config{'BubblesPerRow'}=$config[17];
 4439:         last;
 4440:     }
 4441:     return %config;
 4442: }
 4443: 
 4444: sub get_scantronformat_file {
 4445:     my ($cdom) = @_;
 4446:     if ($cdom eq '') {
 4447:         $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 4448:     }
 4449:     my %domconfig = &get_dom('configuration',['scantron'],$cdom);
 4450:     my $gottab = 0;
 4451:     my @lines;
 4452:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 4453:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
 4454:             my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
 4455:             if ($formatfile ne '-1') {
 4456:                 @lines = split("\n",$formatfile,-1);
 4457:                 $gottab = 1;
 4458:             }
 4459:         }
 4460:     }
 4461:     if (!$gottab) {
 4462:         my $confname = $cdom.'-domainconfig';
 4463:         my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
 4464:         my $formatfile = &getfile($default);
 4465:         if ($formatfile ne '-1') {
 4466:             @lines = split("\n",$formatfile,-1);
 4467:             $gottab = 1;
 4468:         }
 4469:     }
 4470:     if (!$gottab) {
 4471:         my @domains = &current_machine_domains();
 4472:         if (grep(/^\Q$cdom\E$/,@domains)) {
 4473:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
 4474:                 @lines = <$fh>;
 4475:                 close($fh);
 4476:             }
 4477:         } else {
 4478:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
 4479:                 @lines = <$fh>;
 4480:                 close($fh);
 4481:             }
 4482:         }
 4483:     }
 4484:     return @lines;
 4485: }
 4486: 
 4487: sub removeuploadedurl {
 4488:     my ($url)=@_;	
 4489:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 4490:     return &removeuserfile($uname,$udom,$fname);
 4491: }
 4492: 
 4493: sub removeuserfile {
 4494:     my ($docuname,$docudom,$fname)=@_;
 4495:     my $home=&homeserver($docuname,$docudom);    
 4496:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 4497:     if ($result eq 'ok') {	
 4498:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 4499:             my $metafile = $fname.'.meta';
 4500:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 4501: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 4502:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 4503:             my $sqlresult = 
 4504:                 &update_portfolio_table($docuname,$docudom,$file,
 4505:                                         'portfolio_metadata',$group,
 4506:                                         'delete');
 4507:         }
 4508:     }
 4509:     return $result;
 4510: }
 4511: 
 4512: sub mkdiruserfile {
 4513:     my ($docuname,$docudom,$dir)=@_;
 4514:     my $home=&homeserver($docuname,$docudom);
 4515:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 4516: }
 4517: 
 4518: sub renameuserfile {
 4519:     my ($docuname,$docudom,$old,$new)=@_;
 4520:     my $home=&homeserver($docuname,$docudom);
 4521:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 4522:                         &escape("$old").':'.&escape("$new"),$home);
 4523:     if ($result eq 'ok') {
 4524:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 4525:             my $oldmeta = $old.'.meta';
 4526:             my $newmeta = $new.'.meta';
 4527:             my $metaresult = 
 4528:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 4529: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 4530:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 4531:             my $sqlresult = 
 4532:                 &update_portfolio_table($docuname,$docudom,$file,
 4533:                                         'portfolio_metadata',$group,
 4534:                                         'delete');
 4535:         }
 4536:     }
 4537:     return $result;
 4538: }
 4539: 
 4540: # ------------------------------------------------------------------------- Log
 4541: 
 4542: sub log {
 4543:     my ($dom,$nam,$hom,$what)=@_;
 4544:     return critical("log:$dom:$nam:$what",$hom);
 4545: }
 4546: 
 4547: # ------------------------------------------------------------------ Course Log
 4548: #
 4549: # This routine flushes several buffers of non-mission-critical nature
 4550: #
 4551: 
 4552: sub flushcourselogs {
 4553:     &logthis('Flushing log buffers');
 4554: #
 4555: # course logs
 4556: # This is a log of all transactions in a course, which can be used
 4557: # for data mining purposes
 4558: #
 4559: # It also collects the courseid database, which lists last transaction
 4560: # times and course titles for all courseids
 4561: #
 4562:     my %courseidbuffer=();
 4563:     foreach my $crsid (keys(%courselogs)) {
 4564:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 4565: 		          &escape($courselogs{$crsid}),
 4566: 		          $coursehombuf{$crsid}) eq 'ok') {
 4567: 	    delete $courselogs{$crsid};
 4568:         } else {
 4569:             &logthis('Failed to flush log buffer for '.$crsid);
 4570:             if (length($courselogs{$crsid})>40000) {
 4571:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 4572:                         " exceeded maximum size, deleting.</font>");
 4573:                delete $courselogs{$crsid};
 4574:             }
 4575:         }
 4576:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 4577:             'description' => $coursedescrbuf{$crsid},
 4578:             'inst_code'    => $courseinstcodebuf{$crsid},
 4579:             'type'        => $coursetypebuf{$crsid},
 4580:             'owner'       => $courseownerbuf{$crsid},
 4581:         };
 4582:     }
 4583: #
 4584: # Write course id database (reverse lookup) to homeserver of courses 
 4585: # Is used in pickcourse
 4586: #
 4587:     foreach my $crs_home (keys(%courseidbuffer)) {
 4588:         my $response = &courseidput(&host_domain($crs_home),
 4589:                                     $courseidbuffer{$crs_home},
 4590:                                     $crs_home,'timeonly');
 4591:     }
 4592: #
 4593: # File accesses
 4594: # Writes to the dynamic metadata of resources to get hit counts, etc.
 4595: #
 4596:     foreach my $entry (keys(%accesshash)) {
 4597:         if ($entry =~ /___count$/) {
 4598:             my ($dom,$name);
 4599:             ($dom,$name,undef)=
 4600: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 4601:             if (! defined($dom) || $dom eq '' || 
 4602:                 ! defined($name) || $name eq '') {
 4603:                 my $cid = $env{'request.course.id'};
 4604:                 $dom  = $env{'request.'.$cid.'.domain'};
 4605:                 $name = $env{'request.'.$cid.'.num'};
 4606:             }
 4607:             my $value = $accesshash{$entry};
 4608:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 4609:             my %temphash=($url => $value);
 4610:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 4611:             if ($result eq 'ok') {
 4612:                 delete $accesshash{$entry};
 4613:             }
 4614:         } else {
 4615:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 4616:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
 4617:             my %temphash=($entry => $accesshash{$entry});
 4618:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 4619:                 delete $accesshash{$entry};
 4620:             }
 4621:         }
 4622:     }
 4623: #
 4624: # Roles
 4625: # Reverse lookup of user roles for course faculty/staff and co-authorship
 4626: #
 4627:     foreach my $entry (keys(%userrolehash)) {
 4628:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 4629: 	    split(/\:/,$entry);
 4630:         if (&Apache::lonnet::put('nohist_userroles',
 4631:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 4632:                 $rudom,$runame) eq 'ok') {
 4633: 	    delete $userrolehash{$entry};
 4634:         }
 4635:     }
 4636: #
 4637: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
 4638: #
 4639:     my %domrolebuffer = ();
 4640:     foreach my $entry (keys(%domainrolehash)) {
 4641:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 4642:         if ($domrolebuffer{$rudom}) {
 4643:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 4644:                       '='.&escape($domainrolehash{$entry});
 4645:         } else {
 4646:             $domrolebuffer{$rudom}.=&escape($entry).
 4647:                       '='.&escape($domainrolehash{$entry});
 4648:         }
 4649:         delete $domainrolehash{$entry};
 4650:     }
 4651:     foreach my $dom (keys(%domrolebuffer)) {
 4652:         my %servers;
 4653:         if (defined(&domain($dom,'primary'))) {
 4654:             my $primary=&domain($dom,'primary');
 4655:             my $hostname=&hostname($primary);
 4656:             $servers{$primary} = $hostname;
 4657:         } else {
 4658:             %servers = &get_servers($dom,'library');
 4659:         }
 4660: 	foreach my $tryserver (keys(%servers)) {
 4661: 	    if (&reply('domroleput:'.$dom.':'.
 4662: 	               $domrolebuffer{$dom},$tryserver) eq 'ok') {
 4663: 	        last;
 4664: 	    } else {
 4665: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 4666: 	    }
 4667:         }
 4668:     }
 4669:     $dumpcount++;
 4670: }
 4671: 
 4672: sub courselog {
 4673:     my $what=shift;
 4674:     $what=time.':'.$what;
 4675:     unless ($env{'request.course.id'}) { return ''; }
 4676:     $coursedombuf{$env{'request.course.id'}}=
 4677:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 4678:     $coursenumbuf{$env{'request.course.id'}}=
 4679:        $env{'course.'.$env{'request.course.id'}.'.num'};
 4680:     $coursehombuf{$env{'request.course.id'}}=
 4681:        $env{'course.'.$env{'request.course.id'}.'.home'};
 4682:     $coursedescrbuf{$env{'request.course.id'}}=
 4683:        $env{'course.'.$env{'request.course.id'}.'.description'};
 4684:     $courseinstcodebuf{$env{'request.course.id'}}=
 4685:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 4686:     $courseownerbuf{$env{'request.course.id'}}=
 4687:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 4688:     $coursetypebuf{$env{'request.course.id'}}=
 4689:        $env{'course.'.$env{'request.course.id'}.'.type'};
 4690:     if (defined $courselogs{$env{'request.course.id'}}) {
 4691: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 4692:     } else {
 4693: 	$courselogs{$env{'request.course.id'}}.=$what;
 4694:     }
 4695:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 4696: 	&flushcourselogs();
 4697:     }
 4698: }
 4699: 
 4700: sub courseacclog {
 4701:     my $fnsymb=shift;
 4702:     unless ($env{'request.course.id'}) { return ''; }
 4703:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 4704:     if ($fnsymb=~/$LONCAPA::assess_re/) {
 4705:         $what.=':POST';
 4706:         # FIXME: Probably ought to escape things....
 4707: 	foreach my $key (keys(%env)) {
 4708:             if ($key=~/^form\.(.*)/) {
 4709:                 my $formitem = $1;
 4710:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 4711:                     $what.=':'.$formitem.'='.$env{$key};
 4712:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 4713:                     if ($formitem eq 'proctorpassword') {
 4714:                         $what.=':'.$formitem.'=' . '*' x length($env{$key});
 4715:                     } else {
 4716:                         $what.=':'.$formitem.'='.$env{$key};
 4717:                     }
 4718:                 }
 4719:             }
 4720:         }
 4721:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 4722:         # FIXME: We should not be depending on a form parameter that someone
 4723:         # editing lonsearchcat.pm might change in the future.
 4724:         if ($env{'form.phase'} eq 'course_search') {
 4725:             $what.= ':POST';
 4726:             # FIXME: Probably ought to escape things....
 4727:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 4728:                                  'crsdiscuss') {
 4729:                 $what.=':'.$element.'='.$env{'form.'.$element};
 4730:             }
 4731:         }
 4732:     }
 4733:     &courselog($what);
 4734: }
 4735: 
 4736: sub countacc {
 4737:     my $url=&declutter(shift);
 4738:     return if (! defined($url) || $url eq '');
 4739:     unless ($env{'request.course.id'}) { return ''; }
 4740: #
 4741: # Mark that this url was used in this course
 4742: #
 4743:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 4744: #
 4745: # Increase the access count for this resource in this child process
 4746: #
 4747:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 4748:     $accesshash{$key}++;
 4749: }
 4750: 
 4751: sub linklog {
 4752:     my ($from,$to)=@_;
 4753:     $from=&declutter($from);
 4754:     $to=&declutter($to);
 4755:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 4756:     $accesshash{$to.'___'.$from.'___goto'}=1;
 4757: }
 4758: 
 4759: sub statslog {
 4760:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
 4761:     if ($users<2) { return; }
 4762:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
 4763:             'course'       => $env{'request.course.id'},
 4764:             'sections'     => '"all"',
 4765:             'num_students' => $users,
 4766:             'part'         => $part,
 4767:             'symb'         => $symb,
 4768:             'mean_tries'   => $av_attempts,
 4769:             'deg_of_diff'  => $degdiff});
 4770:     foreach my $key (keys(%dynstore)) {
 4771:         $accesshash{$key}=$dynstore{$key};
 4772:     }
 4773: }
 4774:   
 4775: sub userrolelog {
 4776:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 4777:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
 4778:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 4779:        $userrolehash
 4780:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 4781:                     =$tend.':'.$tstart;
 4782:     }
 4783:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
 4784:        $userrolehash
 4785:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 4786:                     =$tend.':'.$tstart;
 4787:     }
 4788:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
 4789:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 4790:        $domainrolehash
 4791:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 4792:                     = $tend.':'.$tstart;
 4793:     }
 4794: }
 4795: 
 4796: sub courserolelog {
 4797:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 4798:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 4799:         my $cdom = $1;
 4800:         my $cnum = $2;
 4801:         my $sec = $3;
 4802:         my $namespace = 'rolelog';
 4803:         my %storehash = (
 4804:                            role    => $trole,
 4805:                            start   => $tstart,
 4806:                            end     => $tend,
 4807:                            selfenroll => $selfenroll,
 4808:                            context    => $context,
 4809:                         );
 4810:         if ($trole eq 'gr') {
 4811:             $namespace = 'groupslog';
 4812:             $storehash{'group'} = $sec;
 4813:         } else {
 4814:             $storehash{'section'} = $sec;
 4815:         }
 4816:         &write_log('course',$namespace,\%storehash,$delflag,$username,
 4817:                    $domain,$cnum,$cdom);
 4818:         if (($trole ne 'st') || ($sec ne '')) {
 4819:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 4820:         }
 4821:     }
 4822:     return;
 4823: }
 4824: 
 4825: sub domainrolelog {
 4826:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 4827:     if ($area =~ m{^/($match_domain)/$}) {
 4828:         my $cdom = $1;
 4829:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
 4830:         my $namespace = 'rolelog';
 4831:         my %storehash = (
 4832:                            role    => $trole,
 4833:                            start   => $tstart,
 4834:                            end     => $tend,
 4835:                            context => $context,
 4836:                         );
 4837:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
 4838:                    $domain,$domconfiguser,$cdom);
 4839:     }
 4840:     return;
 4841: 
 4842: }
 4843: 
 4844: sub coauthorrolelog {
 4845:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 4846:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
 4847:         my $audom = $1;
 4848:         my $auname = $2;
 4849:         my $namespace = 'rolelog';
 4850:         my %storehash = (
 4851:                            role    => $trole,
 4852:                            start   => $tstart,
 4853:                            end     => $tend,
 4854:                            context => $context,
 4855:                         );
 4856:         &write_log('author',$namespace,\%storehash,$delflag,$username,
 4857:                    $domain,$auname,$audom);
 4858:     }
 4859:     return;
 4860: }
 4861: 
 4862: sub get_course_adv_roles {
 4863:     my ($cid,$codes) = @_;
 4864:     $cid=$env{'request.course.id'} unless (defined($cid));
 4865:     my %coursehash=&coursedescription($cid);
 4866:     my $crstype = &Apache::loncommon::course_type($cid);
 4867:     my %nothide=();
 4868:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 4869:         if ($user !~ /:/) {
 4870: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 4871:         } else {
 4872:             $nothide{$user}=1;
 4873:         }
 4874:     }
 4875:     my @possdoms = ($coursehash{'domain'});
 4876:     if ($coursehash{'checkforpriv'}) {
 4877:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
 4878:     }
 4879:     my %returnhash=();
 4880:     my %dumphash=
 4881:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 4882:     my $now=time;
 4883:     my %privileged;
 4884:     foreach my $entry (keys(%dumphash)) {
 4885: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 4886:         if (($tstart) && ($tstart<0)) { next; }
 4887:         if (($tend) && ($tend<$now)) { next; }
 4888:         if (($tstart) && ($now<$tstart)) { next; }
 4889:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 4890: 	if ($username eq '' || $domain eq '') { next; }
 4891:         if ((&privileged($username,$domain,\@possdoms)) &&
 4892:             (!$nothide{$username.':'.$domain})) { next; }
 4893: 	if ($role eq 'cr') { next; }
 4894:         if ($codes) {
 4895:             if ($section) { $role .= ':'.$section; }
 4896:             if ($returnhash{$role}) {
 4897:                 $returnhash{$role}.=','.$username.':'.$domain;
 4898:             } else {
 4899:                 $returnhash{$role}=$username.':'.$domain;
 4900:             }
 4901:         } else {
 4902:             my $key=&plaintext($role,$crstype);
 4903:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 4904:             if ($returnhash{$key}) {
 4905: 	        $returnhash{$key}.=','.$username.':'.$domain;
 4906:             } else {
 4907:                 $returnhash{$key}=$username.':'.$domain;
 4908:             }
 4909:         }
 4910:     }
 4911:     return %returnhash;
 4912: }
 4913: 
 4914: sub get_my_roles {
 4915:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 4916:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 4917:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 4918:     my (%dumphash,%nothide);
 4919:     if ($context eq 'userroles') {
 4920:         %dumphash = &dump('roles',$udom,$uname);
 4921:     } else {
 4922:         %dumphash = &dump('nohist_userroles',$udom,$uname);
 4923:         if ($hidepriv) {
 4924:             my %coursehash=&coursedescription($udom.'_'.$uname);
 4925:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 4926:                 if ($user !~ /:/) {
 4927:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 4928:                 } else {
 4929:                     $nothide{$user} = 1;
 4930:                 }
 4931:             }
 4932:         }
 4933:     }
 4934:     my %returnhash=();
 4935:     my $now=time;
 4936:     my %privileged;
 4937:     foreach my $entry (keys(%dumphash)) {
 4938:         my ($role,$tend,$tstart);
 4939:         if ($context eq 'userroles') {
 4940:             next if ($entry =~ /^rolesdef/);
 4941: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 4942:         } else {
 4943:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 4944:         }
 4945:         if (($tstart) && ($tstart<0)) { next; }
 4946:         my $status = 'active';
 4947:         if (($tend) && ($tend<=$now)) {
 4948:             $status = 'previous';
 4949:         } 
 4950:         if (($tstart) && ($now<$tstart)) {
 4951:             $status = 'future';
 4952:         }
 4953:         if (ref($types) eq 'ARRAY') {
 4954:             if (!grep(/^\Q$status\E$/,@{$types})) {
 4955:                 next;
 4956:             } 
 4957:         } else {
 4958:             if ($status ne 'active') {
 4959:                 next;
 4960:             }
 4961:         }
 4962:         my ($rolecode,$username,$domain,$section,$area);
 4963:         if ($context eq 'userroles') {
 4964:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
 4965:             (undef,$domain,$username,$section) = split(/\//,$area);
 4966:         } else {
 4967:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 4968:         }
 4969:         if (ref($roledoms) eq 'ARRAY') {
 4970:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 4971:                 next;
 4972:             }
 4973:         }
 4974:         if (ref($roles) eq 'ARRAY') {
 4975:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 4976:                 if ($role =~ /^cr\//) {
 4977:                     if (!grep(/^cr$/,@{$roles})) {
 4978:                         next;
 4979:                     }
 4980:                 } elsif ($role =~ /^gr\//) {
 4981:                     if (!grep(/^gr$/,@{$roles})) {
 4982:                         next;
 4983:                     }
 4984:                 } else {
 4985:                     next;
 4986:                 }
 4987:             }
 4988:         }
 4989:         if ($hidepriv) {
 4990:             my @privroles = ('dc','su');
 4991:             if ($context eq 'userroles') {
 4992:                 next if (grep(/^\Q$role\E$/,@privroles));
 4993:             } else {
 4994:                 my $possdoms = [$domain];
 4995:                 if (ref($roledoms) eq 'ARRAY') {
 4996:                    push(@{$possdoms},@{$roledoms});
 4997:                 }
 4998:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
 4999:                     if (!$nothide{$username.':'.$domain}) {
 5000:                         next;
 5001:                     }
 5002:                 }
 5003:             }
 5004:         }
 5005:         if ($withsec) {
 5006:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 5007:                 $tstart.':'.$tend;
 5008:         } else {
 5009:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 5010:         }
 5011:     }
 5012:     return %returnhash;
 5013: }
 5014: 
 5015: sub get_all_adhocroles {
 5016:     my ($dom) = @_;
 5017:     my @roles_by_num = ();
 5018:     my %domdefaults = &get_domain_defaults($dom);
 5019:     my (%description,%access_in_dom,%access_info);
 5020:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
 5021:         my $count = 0;
 5022:         my %domcurrent = %{$domdefaults{'adhocroles'}};
 5023:         my %ordered;
 5024:         foreach my $role (sort(keys(%domcurrent))) {
 5025:             my ($order,$desc,$access_in_dom);
 5026:             if (ref($domcurrent{$role}) eq 'HASH') {
 5027:                 $order = $domcurrent{$role}{'order'};
 5028:                 $desc = $domcurrent{$role}{'desc'};
 5029:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
 5030:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
 5031:             }
 5032:             if ($order eq '') {
 5033:                 $order = $count;
 5034:             }
 5035:             $ordered{$order} = $role;
 5036:             if ($desc ne '') {
 5037:                 $description{$role} = $desc;
 5038:             } else {
 5039:                 $description{$role}= $role;
 5040:             }
 5041:             $count++;
 5042:         }
 5043:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 5044:             push(@roles_by_num,$ordered{$item});
 5045:         }
 5046:     }
 5047:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
 5048: }
 5049: 
 5050: sub get_my_adhocroles {
 5051:     my ($cid,$checkreg) = @_;
 5052:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
 5053:     if ($env{'request.course.id'} eq $cid) {
 5054:         $cdom = $env{'course.'.$cid.'.domain'};
 5055:         $cnum = $env{'course.'.$cid.'.num'};
 5056:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
 5057:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
 5058:         $cdom = $1;
 5059:         $cnum = $2;
 5060:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
 5061:                                      $cdom,$cnum);
 5062:     }
 5063:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
 5064:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
 5065:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
 5066:         if ($rosterhash{$user} ne '') {
 5067:             my $type = (split(/:/,$rosterhash{$user}))[5];
 5068:             return ([],{}) if ($type eq 'auto');
 5069:         }
 5070:     }
 5071:     if (($cdom ne '') && ($cnum ne ''))  {
 5072:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
 5073:             my $then=$env{'user.login.time'};
 5074:             my $update=$env{'user.update.time'};
 5075:             if (!$update) {
 5076:                 $update = $then;
 5077:             }
 5078:             my @liveroles;
 5079:             foreach my $role ('dh','da') {
 5080:                 if ($env{"user.role.$role./$cdom/"}) {
 5081:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
 5082:                     my $limit = $update;
 5083:                     if ($env{'request.role'} eq "$role./$cdom/") {
 5084:                         $limit = $then;
 5085:                     }
 5086:                     my $activerole = 1;
 5087:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
 5088:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
 5089:                     if ($activerole) {
 5090:                         push(@liveroles,$role);
 5091:                     }
 5092:                 }
 5093:             }
 5094:             if (@liveroles) {
 5095:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
 5096:                     my ($accessref,$accessinfo,%access_in_dom);
 5097:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
 5098:                     if (ref($roles_by_num) eq 'ARRAY') {
 5099:                         if (@{$roles_by_num}) {
 5100:                             my %settings;
 5101:                             if ($env{'request.course.id'} eq $cid) {
 5102:                                 foreach my $envkey (keys(%env)) {
 5103:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
 5104:                                         $settings{$1} = $env{$envkey};
 5105:                                     }
 5106:                                 }
 5107:                             } else {
 5108:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
 5109:                             }
 5110:                             my %setincrs;
 5111:                             if ($settings{'internal.adhocaccess'}) {
 5112:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
 5113:                             }
 5114:                             my @statuses;
 5115:                             if ($env{'environment.inststatus'}) {
 5116:                                 @statuses = split(/,/,$env{'environment.inststatus'});
 5117:                             }
 5118:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
 5119:                             if (ref($accessref) eq 'HASH') {
 5120:                                 %access_in_dom = %{$accessref};
 5121:                             }
 5122:                             foreach my $role (@{$roles_by_num}) {
 5123:                                 my ($curraccess,@okstatus,@personnel);
 5124:                                 if ($setincrs{$role}) {
 5125:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
 5126:                                     if ($curraccess eq 'status') {
 5127:                                         @okstatus = split(/\&/,$rest);
 5128:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5129:                                         @personnel = split(/\&/,$rest);
 5130:                                     }
 5131:                                 } else {
 5132:                                     $curraccess = $access_in_dom{$role};
 5133:                                     if (ref($accessinfo) eq 'HASH') {
 5134:                                         if ($curraccess eq 'status') {
 5135:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
 5136:                                                 @okstatus = @{$accessinfo->{$role}};
 5137:                                             }
 5138:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5139:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
 5140:                                                 @personnel = @{$accessinfo->{$role}};
 5141:                                             }
 5142:                                         }
 5143:                                     }
 5144:                                 }
 5145:                                 if ($curraccess eq 'none') {
 5146:                                     next;
 5147:                                 } elsif ($curraccess eq 'all') {
 5148:                                     push(@possroles,$role);
 5149:                                 } elsif ($curraccess eq 'dh') {
 5150:                                     if (grep(/^dh$/,@liveroles)) {
 5151:                                         push(@possroles,$role);
 5152:                                     } else {
 5153:                                         next;
 5154:                                     }
 5155:                                 } elsif ($curraccess eq 'da') {
 5156:                                     if (grep(/^da$/,@liveroles)) {
 5157:                                         push(@possroles,$role);
 5158:                                     } else {
 5159:                                         next;
 5160:                                     }
 5161:                                 } elsif ($curraccess eq 'status') {
 5162:                                     if (@okstatus) {
 5163:                                         if (!@statuses) {
 5164:                                             if (grep(/^default$/,@okstatus)) {
 5165:                                                 push(@possroles,$role);
 5166:                                             }
 5167:                                         } else {
 5168:                                             foreach my $status (@okstatus) {
 5169:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
 5170:                                                     push(@possroles,$role);
 5171:                                                     last;
 5172:                                                 }
 5173:                                             }
 5174:                                         }
 5175:                                     }
 5176:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5177:                                     if (grep(/^\Q$user\E$/,@personnel)) {
 5178:                                         if ($curraccess eq 'exc') {
 5179:                                             push(@possroles,$role);
 5180:                                         }
 5181:                                     } elsif ($curraccess eq 'inc') {
 5182:                                         push(@possroles,$role);
 5183:                                     }
 5184:                                 }
 5185:                             }
 5186:                         }
 5187:                     }
 5188:                 }
 5189:             }
 5190:         }
 5191:     }
 5192:     unless (ref($description) eq 'HASH') {
 5193:         if (ref($roles_by_num) eq 'ARRAY') {
 5194:             my %desc;
 5195:             map { $desc{$_} = $_; } (@{$roles_by_num});
 5196:             $description = \%desc;
 5197:         } else {
 5198:             $description = {};
 5199:         }
 5200:     }
 5201:     return (\@possroles,$description);
 5202: }
 5203: 
 5204: # ----------------------------------------------------- Frontpage Announcements
 5205: #
 5206: #
 5207: 
 5208: sub postannounce {
 5209:     my ($server,$text)=@_;
 5210:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 5211:     unless ($text=~/\w/) { $text=''; }
 5212:     return &reply('setannounce:'.&escape($text),$server);
 5213: }
 5214: 
 5215: sub getannounce {
 5216: 
 5217:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 5218: 	my $announcement='';
 5219: 	while (my $line = <$fh>) { $announcement .= $line; }
 5220: 	close($fh);
 5221: 	if ($announcement=~/\w/) { 
 5222: 	    return 
 5223:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 5224:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 5225: 	} else {
 5226: 	    return '';
 5227: 	}
 5228:     } else {
 5229: 	return '';
 5230:     }
 5231: }
 5232: 
 5233: # ---------------------------------------------------------- Course ID routines
 5234: # Deal with domain's nohist_courseid.db files
 5235: #
 5236: 
 5237: sub courseidput {
 5238:     my ($domain,$storehash,$coursehome,$caller) = @_;
 5239:     return unless (ref($storehash) eq 'HASH');
 5240:     my $outcome;
 5241:     if ($caller eq 'timeonly') {
 5242:         my $cids = '';
 5243:         foreach my $item (keys(%$storehash)) {
 5244:             $cids.=&escape($item).'&';
 5245:         }
 5246:         $cids=~s/\&$//;
 5247:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 5248:                           $coursehome);       
 5249:     } else {
 5250:         my $items = '';
 5251:         foreach my $item (keys(%$storehash)) {
 5252:             $items.= &escape($item).'='.
 5253:                      &freeze_escape($$storehash{$item}).'&';
 5254:         }
 5255:         $items=~s/\&$//;
 5256:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 5257:                           $coursehome);
 5258:     }
 5259:     if ($outcome eq 'unknown_cmd') {
 5260:         my $what;
 5261:         foreach my $cid (keys(%$storehash)) {
 5262:             $what .= &escape($cid).'=';
 5263:             foreach my $item ('description','inst_code','owner','type') {
 5264:                 $what .= &escape($storehash->{$cid}{$item}).':';
 5265:             }
 5266:             $what =~ s/\:$/&/;
 5267:         }
 5268:         $what =~ s/\&$//;  
 5269:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 5270:     } else {
 5271:         return $outcome;
 5272:     }
 5273: }
 5274: 
 5275: sub courseiddump {
 5276:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 5277:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 5278:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
 5279:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
 5280:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
 5281:     my $as_hash = 1;
 5282:     my %returnhash;
 5283:     if (!$domfilter) { $domfilter=''; }
 5284:     my %libserv = &all_library();
 5285:     foreach my $tryserver (keys(%libserv)) {
 5286:         if ( (  $hostidflag == 1 
 5287: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 5288: 	     || (!defined($hostidflag)) ) {
 5289: 
 5290: 	    if (($domfilter eq '') ||
 5291: 		(&host_domain($tryserver) eq $domfilter)) {
 5292:                 my $rep;
 5293:                 if (grep { $_ eq $tryserver } &current_machine_ids()) {
 5294:                     $rep = &LONCAPA::Lond::dump_course_id_handler(
 5295:                         join(":", (&host_domain($tryserver), $sincefilter,
 5296:                                 &escape($descfilter), &escape($instcodefilter),
 5297:                                 &escape($ownerfilter), &escape($coursefilter),
 5298:                                 &escape($typefilter), &escape($regexp_ok),
 5299:                                 $as_hash, &escape($selfenrollonly),
 5300:                                 &escape($catfilter), $showhidden, $caller,
 5301:                                 &escape($cloner), &escape($cc_clone), $cloneonly,
 5302:                                 &escape($createdbefore), &escape($createdafter),
 5303:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
 5304:                                 $reqcrsdom,&escape($reqinstcode))));
 5305:                 } else {
 5306:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
 5307:                              $sincefilter.':'.&escape($descfilter).':'.
 5308:                              &escape($instcodefilter).':'.&escape($ownerfilter).
 5309:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
 5310:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
 5311:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
 5312:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
 5313:                              &escape($cc_clone).':'.$cloneonly.':'.
 5314:                              &escape($createdbefore).':'.&escape($createdafter).':'.
 5315:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
 5316:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
 5317:                 }
 5318: 
 5319:                 my @pairs=split(/\&/,$rep);
 5320:                 foreach my $item (@pairs) {
 5321:                     my ($key,$value)=split(/\=/,$item,2);
 5322:                     $key = &unescape($key);
 5323:                     next if ($key =~ /^error: 2 /);
 5324:                     my $result = &thaw_unescape($value);
 5325:                     if (ref($result) eq 'HASH') {
 5326:                         $returnhash{$key}=$result;
 5327:                     } else {
 5328:                         my @responses = split(/:/,$value);
 5329:                         my @items = ('description','inst_code','owner','type');
 5330:                         for (my $i=0; $i<@responses; $i++) {
 5331:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 5332:                         }
 5333:                     }
 5334:                 }
 5335:             }
 5336:         }
 5337:     }
 5338:     return %returnhash;
 5339: }
 5340: 
 5341: sub courselastaccess {
 5342:     my ($cdom,$cnum,$hostidref) = @_;
 5343:     my %returnhash;
 5344:     if ($cdom && $cnum) {
 5345:         my $chome = &homeserver($cnum,$cdom);
 5346:         if ($chome ne 'no_host') {
 5347:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
 5348:             &extract_lastaccess(\%returnhash,$rep);
 5349:         }
 5350:     } else {
 5351:         if (!$cdom) { $cdom=''; }
 5352:         my %libserv = &all_library();
 5353:         foreach my $tryserver (keys(%libserv)) {
 5354:             if (ref($hostidref) eq 'ARRAY') {
 5355:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
 5356:             } 
 5357:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
 5358:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
 5359:                 &extract_lastaccess(\%returnhash,$rep);
 5360:             }
 5361:         }
 5362:     }
 5363:     return %returnhash;
 5364: }
 5365: 
 5366: sub extract_lastaccess {
 5367:     my ($returnhash,$rep) = @_;
 5368:     if (ref($returnhash) eq 'HASH') {
 5369:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
 5370:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
 5371:                  $rep eq '') {
 5372:             my @pairs=split(/\&/,$rep);
 5373:             foreach my $item (@pairs) {
 5374:                 my ($key,$value)=split(/\=/,$item,2);
 5375:                 $key = &unescape($key);
 5376:                 next if ($key =~ /^error: 2 /);
 5377:                 $returnhash->{$key} = &thaw_unescape($value);
 5378:             }
 5379:         }
 5380:     }
 5381:     return;
 5382: }
 5383: 
 5384: # ---------------------------------------------------------- DC e-mail
 5385: 
 5386: sub dcmailput {
 5387:     my ($domain,$msgid,$message,$server)=@_;
 5388:     my $status = &Apache::lonnet::critical(
 5389:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 5390:        &escape($message),$server);
 5391:     return $status;
 5392: }
 5393: 
 5394: sub dcmaildump {
 5395:     my ($dom,$startdate,$enddate,$senders) = @_;
 5396:     my %returnhash=();
 5397: 
 5398:     if (defined(&domain($dom,'primary'))) {
 5399:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 5400:                                                          &escape($enddate).':';
 5401: 	my @esc_senders=map { &escape($_)} @$senders;
 5402: 	$cmd.=&escape(join('&',@esc_senders));
 5403: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 5404:             my ($key,$value) = split(/\=/,$line,2);
 5405:             if (($key) && ($value)) {
 5406:                 $returnhash{&unescape($key)} = &unescape($value);
 5407:             }
 5408:         }
 5409:     }
 5410:     return %returnhash;
 5411: }
 5412: # ---------------------------------------------------------- Domain roles
 5413: 
 5414: sub get_domain_roles {
 5415:     my ($dom,$roles,$startdate,$enddate)=@_;
 5416:     if ((!defined($startdate)) || ($startdate eq '')) {
 5417:         $startdate = '.';
 5418:     }
 5419:     if ((!defined($enddate)) || ($enddate eq '')) {
 5420:         $enddate = '.';
 5421:     }
 5422:     my $rolelist;
 5423:     if (ref($roles) eq 'ARRAY') {
 5424:         $rolelist = join('&',@{$roles});
 5425:     }
 5426:     my %personnel = ();
 5427: 
 5428:     my %servers = &get_servers($dom,'library');
 5429:     foreach my $tryserver (keys(%servers)) {
 5430: 	%{$personnel{$tryserver}}=();
 5431: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 5432: 					    &escape($startdate).':'.
 5433: 					    &escape($enddate).':'.
 5434: 					    &escape($rolelist), $tryserver))) {
 5435: 	    my ($key,$value) = split(/\=/,$line,2);
 5436: 	    if (($key) && ($value)) {
 5437: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 5438: 	    }
 5439: 	}
 5440:     }
 5441:     return %personnel;
 5442: }
 5443: 
 5444: sub get_active_domroles {
 5445:     my ($dom,$roles) = @_;
 5446:     return () unless (ref($roles) eq 'ARRAY');
 5447:     my $now = time;
 5448:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
 5449:     my %domroles;
 5450:     foreach my $server (keys(%dompersonnel)) {
 5451:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
 5452:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
 5453:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
 5454:         }
 5455:     }
 5456:     return %domroles;
 5457: }
 5458: 
 5459: # ----------------------------------------------------------- Interval timing 
 5460: 
 5461: {
 5462: # Caches needed for speedup of navmaps
 5463: # We don't want to cache this for very long at all (5 seconds at most)
 5464: # 
 5465: # The user for whom we cache
 5466: my $cachedkey='';
 5467: # The cached times for this user
 5468: my %cachedtimes=();
 5469: # When this was last done
 5470: my $cachedtime='';
 5471: 
 5472: sub load_all_first_access {
 5473:     my ($uname,$udom)=@_;
 5474:     if (($cachedkey eq $uname.':'.$udom) &&
 5475:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
 5476:         return;
 5477:     }
 5478:     $cachedtime=time;
 5479:     $cachedkey=$uname.':'.$udom;
 5480:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
 5481: }
 5482: 
 5483: sub get_first_access {
 5484:     my ($type,$argsymb,$argmap)=@_;
 5485:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 5486:     if ($argsymb) { $symb=$argsymb; }
 5487:     my ($map,$id,$res)=&decode_symb($symb);
 5488:     if ($argmap) { $map = $argmap; }
 5489:     if ($type eq 'course') {
 5490: 	$res='course';
 5491:     } elsif ($type eq 'map') {
 5492: 	$res=&symbread($map);
 5493:     } else {
 5494: 	$res=$symb;
 5495:     }
 5496:     &load_all_first_access($uname,$udom);
 5497:     return $cachedtimes{"$courseid\0$res"};
 5498: }
 5499: 
 5500: sub set_first_access {
 5501:     my ($type,$interval)=@_;
 5502:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 5503:     my ($map,$id,$res)=&decode_symb($symb);
 5504:     if ($type eq 'course') {
 5505: 	$res='course';
 5506:     } elsif ($type eq 'map') {
 5507: 	$res=&symbread($map);
 5508:     } else {
 5509: 	$res=$symb;
 5510:     }
 5511:     $cachedkey='';
 5512:     my $firstaccess=&get_first_access($type,$symb,$map);
 5513:     if ($firstaccess) {
 5514:         &logthis("First access time already set ($firstaccess) when attempting ".
 5515:                  "to set new value (type: $type, extent: $res) for $uname:$udom ".
 5516:                  "in $courseid");
 5517:         return 'already_set';
 5518:     } else {
 5519:         my $start = time;
 5520: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
 5521:                           $udom,$uname);
 5522:         if ($putres eq 'ok') {
 5523:             &put('timerinterval',{"$courseid\0$res"=>$interval},
 5524:                  $udom,$uname); 
 5525:             &appenv(
 5526:                      {
 5527:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
 5528:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
 5529:                      }
 5530:                   );
 5531:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
 5532:                 $cachedtimes{"$courseid\0$res"} = $start;
 5533:             }
 5534:         } elsif ($putres ne 'refused') {
 5535:             &logthis("Result: $putres when attempting to set first access time ".
 5536:                      "(type: $type, extent: $res) for $uname:$udom in $courseid");
 5537:         }
 5538:         return $putres;
 5539:     }
 5540:     return 'already_set';
 5541: }
 5542: }
 5543: 
 5544: sub checkout {
 5545:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
 5546:     my $now=time;
 5547:     my $lonhost=$perlvar{'lonHostID'};
 5548:     my $ip = &get_requestor_ip();
 5549:     my $infostr=&escape(
 5550:                  'CHECKOUTTOKEN&'.
 5551:                  $tuname.'&'.
 5552:                  $tudom.'&'.
 5553:                  $tcrsid.'&'.
 5554:                  $symb.'&'.
 5555:                  $now.'&'.$ip);
 5556:     my $token=&reply('tmpput:'.$infostr,$lonhost);
 5557:     if ($token=~/^error\:/) {
 5558:         &logthis("<font color=\"blue\">WARNING: ".
 5559:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
 5560:                  "</font>");
 5561:         return '';
 5562:     }
 5563: 
 5564:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
 5565:     $token=~tr/a-z/A-Z/;
 5566: 
 5567:     my %infohash=('resource.0.outtoken' => $token,
 5568:                   'resource.0.checkouttime' => $now,
 5569:                   'resource.0.outremote' => $ip);
 5570: 
 5571:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 5572:        return '';
 5573:     } else {
 5574:         &logthis("<font color=\"blue\">WARNING: ".
 5575:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
 5576:                  "</font>");
 5577:     }
 5578: 
 5579:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 5580:                          &escape('Checkout '.$infostr.' - '.
 5581:                                                  $token)) ne 'ok') {
 5582:         return '';
 5583:     } else {
 5584:         &logthis("<font color=\"blue\">WARNING: ".
 5585:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
 5586:                  "</font>");
 5587:     }
 5588:     return $token;
 5589: }
 5590: 
 5591: # ------------------------------------------------------------ Check in an item
 5592: 
 5593: sub checkin {
 5594:     my $token=shift;
 5595:     my $now=time;
 5596:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
 5597:     $lonhost=~tr/A-Z/a-z/;
 5598:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
 5599:     $dtoken=~s/\W/\_/g;
 5600:     my $ip = &get_requestor_ip();
 5601:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
 5602:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
 5603: 
 5604:     unless (($tuname) && ($tudom)) {
 5605:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
 5606:         return '';
 5607:     }
 5608: 
 5609:     unless (&allowed('mgr',$tcrsid)) {
 5610:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
 5611:                  $env{'user.name'}.' - '.$env{'user.domain'});
 5612:         return '';
 5613:     }
 5614: 
 5615:     my %infohash=('resource.0.intoken' => $token,
 5616:                   'resource.0.checkintime' => $now,
 5617:                   'resource.0.inremote' => $ip);
 5618: 
 5619:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 5620:        return '';
 5621:     }
 5622: 
 5623:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 5624:                          &escape('Checkin - '.$token)) ne 'ok') {
 5625:         return '';
 5626:     }
 5627: 
 5628:     return ($symb,$tuname,$tudom,$tcrsid);
 5629: }
 5630: 
 5631: # --------------------------------------------- Set Expire Date for Spreadsheet
 5632: 
 5633: sub expirespread {
 5634:     my ($uname,$udom,$stype,$usymb)=@_;
 5635:     my $cid=$env{'request.course.id'}; 
 5636:     if ($cid) {
 5637:        my $now=time;
 5638:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 5639:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 5640:                             $env{'course.'.$cid.'.num'}.
 5641: 	        	    ':nohist_expirationdates:'.
 5642:                             &escape($key).'='.$now,
 5643:                             $env{'course.'.$cid.'.home'})
 5644:     }
 5645:     return 'ok';
 5646: }
 5647: 
 5648: # ----------------------------------------------------- Devalidate Spreadsheets
 5649: 
 5650: sub devalidate {
 5651:     my ($symb,$uname,$udom)=@_;
 5652:     my $cid=$env{'request.course.id'}; 
 5653:     if ($cid) {
 5654:         # delete the stored spreadsheets for
 5655:         # - the student level sheet of this user in course's homespace
 5656:         # - the assessment level sheet for this resource 
 5657:         #   for this user in user's homespace
 5658: 	# - current conditional state info
 5659: 	my $key=$uname.':'.$udom.':';
 5660:         my $status=
 5661: 	    &del('nohist_calculatedsheets',
 5662: 		 [$key.'studentcalc:'],
 5663: 		 $env{'course.'.$cid.'.domain'},
 5664: 		 $env{'course.'.$cid.'.num'})
 5665: 		.' '.
 5666: 	    &del('nohist_calculatedsheets_'.$cid,
 5667: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 5668:         unless ($status eq 'ok ok') {
 5669:            &logthis('Could not devalidate spreadsheet '.
 5670:                     $uname.' at '.$udom.' for '.
 5671: 		    $symb.': '.$status);
 5672:         }
 5673: 	&delenv('user.state.'.$cid);
 5674:     }
 5675: }
 5676: 
 5677: sub get_scalar {
 5678:     my ($string,$end) = @_;
 5679:     my $value;
 5680:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 5681: 	$value = $1;
 5682:     } elsif ($$string =~ s/^([^&]*?)&//) {
 5683: 	$value = $1;
 5684:     }
 5685:     return &unescape($value);
 5686: }
 5687: 
 5688: sub array2str {
 5689:   my (@array) = @_;
 5690:   my $result=&arrayref2str(\@array);
 5691:   $result=~s/^__ARRAY_REF__//;
 5692:   $result=~s/__END_ARRAY_REF__$//;
 5693:   return $result;
 5694: }
 5695: 
 5696: sub arrayref2str {
 5697:   my ($arrayref) = @_;
 5698:   my $result='__ARRAY_REF__';
 5699:   foreach my $elem (@$arrayref) {
 5700:     if(ref($elem) eq 'ARRAY') {
 5701:       $result.=&arrayref2str($elem).'&';
 5702:     } elsif(ref($elem) eq 'HASH') {
 5703:       $result.=&hashref2str($elem).'&';
 5704:     } elsif(ref($elem)) {
 5705:       #print("Got a ref of ".(ref($elem))." skipping.");
 5706:     } else {
 5707:       $result.=&escape($elem).'&';
 5708:     }
 5709:   }
 5710:   $result=~s/\&$//;
 5711:   $result .= '__END_ARRAY_REF__';
 5712:   return $result;
 5713: }
 5714: 
 5715: sub hash2str {
 5716:   my (%hash) = @_;
 5717:   my $result=&hashref2str(\%hash);
 5718:   $result=~s/^__HASH_REF__//;
 5719:   $result=~s/__END_HASH_REF__$//;
 5720:   return $result;
 5721: }
 5722: 
 5723: sub hashref2str {
 5724:   my ($hashref)=@_;
 5725:   my $result='__HASH_REF__';
 5726:   foreach my $key (sort(keys(%$hashref))) {
 5727:     if (ref($key) eq 'ARRAY') {
 5728:       $result.=&arrayref2str($key).'=';
 5729:     } elsif (ref($key) eq 'HASH') {
 5730:       $result.=&hashref2str($key).'=';
 5731:     } elsif (ref($key)) {
 5732:       $result.='=';
 5733:       #print("Got a ref of ".(ref($key))." skipping.");
 5734:     } else {
 5735: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
 5736:     }
 5737: 
 5738:     if(ref($hashref->{$key}) eq 'ARRAY') {
 5739:       $result.=&arrayref2str($hashref->{$key}).'&';
 5740:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 5741:       $result.=&hashref2str($hashref->{$key}).'&';
 5742:     } elsif(ref($hashref->{$key})) {
 5743:        $result.='&';
 5744:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 5745:     } else {
 5746:       $result.=&escape($hashref->{$key}).'&';
 5747:     }
 5748:   }
 5749:   $result=~s/\&$//;
 5750:   $result .= '__END_HASH_REF__';
 5751:   return $result;
 5752: }
 5753: 
 5754: sub str2hash {
 5755:     my ($string)=@_;
 5756:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 5757:     return %$hash;
 5758: }
 5759: 
 5760: sub str2hashref {
 5761:   my ($string) = @_;
 5762: 
 5763:   my %hash;
 5764: 
 5765:   if($string !~ /^__HASH_REF__/) {
 5766:       if (! ($string eq '' || !defined($string))) {
 5767: 	  $hash{'error'}='Not hash reference';
 5768:       }
 5769:       return (\%hash, $string);
 5770:   }
 5771: 
 5772:   $string =~ s/^__HASH_REF__//;
 5773: 
 5774:   while($string !~ /^__END_HASH_REF__/) {
 5775:       #key
 5776:       my $key='';
 5777:       if($string =~ /^__HASH_REF__/) {
 5778:           ($key, $string)=&str2hashref($string);
 5779:           if(defined($key->{'error'})) {
 5780:               $hash{'error'}='Bad data';
 5781:               return (\%hash, $string);
 5782:           }
 5783:       } elsif($string =~ /^__ARRAY_REF__/) {
 5784:           ($key, $string)=&str2arrayref($string);
 5785:           if($key->[0] eq 'Array reference error') {
 5786:               $hash{'error'}='Bad data';
 5787:               return (\%hash, $string);
 5788:           }
 5789:       } else {
 5790:           $string =~ s/^(.*?)=//;
 5791: 	  $key=&unescape($1);
 5792:       }
 5793:       $string =~ s/^=//;
 5794: 
 5795:       #value
 5796:       my $value='';
 5797:       if($string =~ /^__HASH_REF__/) {
 5798:           ($value, $string)=&str2hashref($string);
 5799:           if(defined($value->{'error'})) {
 5800:               $hash{'error'}='Bad data';
 5801:               return (\%hash, $string);
 5802:           }
 5803:       } elsif($string =~ /^__ARRAY_REF__/) {
 5804:           ($value, $string)=&str2arrayref($string);
 5805:           if($value->[0] eq 'Array reference error') {
 5806:               $hash{'error'}='Bad data';
 5807:               return (\%hash, $string);
 5808:           }
 5809:       } else {
 5810: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 5811:       }
 5812:       $string =~ s/^&//;
 5813: 
 5814:       $hash{$key}=$value;
 5815:   }
 5816: 
 5817:   $string =~ s/^__END_HASH_REF__//;
 5818: 
 5819:   return (\%hash, $string);
 5820: }
 5821: 
 5822: sub str2array {
 5823:     my ($string)=@_;
 5824:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 5825:     return @$array;
 5826: }
 5827: 
 5828: sub str2arrayref {
 5829:   my ($string) = @_;
 5830:   my @array;
 5831: 
 5832:   if($string !~ /^__ARRAY_REF__/) {
 5833:       if (! ($string eq '' || !defined($string))) {
 5834: 	  $array[0]='Array reference error';
 5835:       }
 5836:       return (\@array, $string);
 5837:   }
 5838: 
 5839:   $string =~ s/^__ARRAY_REF__//;
 5840: 
 5841:   while($string !~ /^__END_ARRAY_REF__/) {
 5842:       my $value='';
 5843:       if($string =~ /^__HASH_REF__/) {
 5844:           ($value, $string)=&str2hashref($string);
 5845:           if(defined($value->{'error'})) {
 5846:               $array[0] ='Array reference error';
 5847:               return (\@array, $string);
 5848:           }
 5849:       } elsif($string =~ /^__ARRAY_REF__/) {
 5850:           ($value, $string)=&str2arrayref($string);
 5851:           if($value->[0] eq 'Array reference error') {
 5852:               $array[0] ='Array reference error';
 5853:               return (\@array, $string);
 5854:           }
 5855:       } else {
 5856: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 5857:       }
 5858:       $string =~ s/^&//;
 5859: 
 5860:       push(@array, $value);
 5861:   }
 5862: 
 5863:   $string =~ s/^__END_ARRAY_REF__//;
 5864: 
 5865:   return (\@array, $string);
 5866: }
 5867: 
 5868: # -------------------------------------------------------------------Temp Store
 5869: 
 5870: sub tmpreset {
 5871:   my ($symb,$namespace,$domain,$stuname) = @_;
 5872:   if (!$symb) {
 5873:     $symb=&symbread();
 5874:     if (!$symb) { $symb= $env{'request.url'}; }
 5875:   }
 5876:   $symb=escape($symb);
 5877: 
 5878:   if (!$namespace) { $namespace=$env{'request.state'}; }
 5879:   $namespace=~s/\//\_/g;
 5880:   $namespace=~s/\W//g;
 5881: 
 5882:   if (!$domain) { $domain=$env{'user.domain'}; }
 5883:   if (!$stuname) { $stuname=$env{'user.name'}; }
 5884:   if ($domain eq 'public' && $stuname eq 'public') {
 5885:       $stuname=&get_requestor_ip();
 5886:   }
 5887:   my $path=LONCAPA::tempdir();
 5888:   my %hash;
 5889:   if (tie(%hash,'GDBM_File',
 5890: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 5891: 	  &GDBM_WRCREAT(),0640)) {
 5892:     foreach my $key (keys(%hash)) {
 5893:       if ($key=~ /:$symb/) {
 5894: 	delete($hash{$key});
 5895:       }
 5896:     }
 5897:   }
 5898: }
 5899: 
 5900: sub tmpstore {
 5901:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 5902: 
 5903:   if (!$symb) {
 5904:     $symb=&symbread();
 5905:     if (!$symb) { $symb= $env{'request.url'}; }
 5906:   }
 5907:   $symb=escape($symb);
 5908: 
 5909:   if (!$namespace) {
 5910:     # I don't think we would ever want to store this for a course.
 5911:     # it seems this will only be used if we don't have a course.
 5912:     #$namespace=$env{'request.course.id'};
 5913:     #if (!$namespace) {
 5914:       $namespace=$env{'request.state'};
 5915:     #}
 5916:   }
 5917:   $namespace=~s/\//\_/g;
 5918:   $namespace=~s/\W//g;
 5919:   if (!$domain) { $domain=$env{'user.domain'}; }
 5920:   if (!$stuname) { $stuname=$env{'user.name'}; }
 5921:   if ($domain eq 'public' && $stuname eq 'public') {
 5922:       $stuname=&get_requestor_ip();
 5923:   }
 5924:   my $now=time;
 5925:   my %hash;
 5926:   my $path=LONCAPA::tempdir();
 5927:   if (tie(%hash,'GDBM_File',
 5928: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 5929: 	  &GDBM_WRCREAT(),0640)) {
 5930:     $hash{"version:$symb"}++;
 5931:     my $version=$hash{"version:$symb"};
 5932:     my $allkeys=''; 
 5933:     foreach my $key (keys(%$storehash)) {
 5934:       $allkeys.=$key.':';
 5935:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 5936:     }
 5937:     $hash{"$version:$symb:timestamp"}=$now;
 5938:     $allkeys.='timestamp';
 5939:     $hash{"$version:keys:$symb"}=$allkeys;
 5940:     if (untie(%hash)) {
 5941:       return 'ok';
 5942:     } else {
 5943:       return "error:$!";
 5944:     }
 5945:   } else {
 5946:     return "error:$!";
 5947:   }
 5948: }
 5949: 
 5950: # -----------------------------------------------------------------Temp Restore
 5951: 
 5952: sub tmprestore {
 5953:   my ($symb,$namespace,$domain,$stuname) = @_;
 5954: 
 5955:   if (!$symb) {
 5956:     $symb=&symbread();
 5957:     if (!$symb) { $symb= $env{'request.url'}; }
 5958:   }
 5959:   $symb=escape($symb);
 5960: 
 5961:   if (!$namespace) { $namespace=$env{'request.state'}; }
 5962: 
 5963:   if (!$domain) { $domain=$env{'user.domain'}; }
 5964:   if (!$stuname) { $stuname=$env{'user.name'}; }
 5965:   if ($domain eq 'public' && $stuname eq 'public') {
 5966:       $stuname=&get_requestor_ip();
 5967:   }
 5968:   my %returnhash;
 5969:   $namespace=~s/\//\_/g;
 5970:   $namespace=~s/\W//g;
 5971:   my %hash;
 5972:   my $path=LONCAPA::tempdir();
 5973:   if (tie(%hash,'GDBM_File',
 5974: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 5975: 	  &GDBM_READER(),0640)) {
 5976:     my $version=$hash{"version:$symb"};
 5977:     $returnhash{'version'}=$version;
 5978:     my $scope;
 5979:     for ($scope=1;$scope<=$version;$scope++) {
 5980:       my $vkeys=$hash{"$scope:keys:$symb"};
 5981:       my @keys=split(/:/,$vkeys);
 5982:       my $key;
 5983:       $returnhash{"$scope:keys"}=$vkeys;
 5984:       foreach $key (@keys) {
 5985: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 5986: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 5987:       }
 5988:     }
 5989:     if (!(untie(%hash))) {
 5990:       return "error:$!";
 5991:     }
 5992:   } else {
 5993:     return "error:$!";
 5994:   }
 5995:   return %returnhash;
 5996: }
 5997: 
 5998: # ----------------------------------------------------------------------- Store
 5999: 
 6000: sub store {
 6001:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 6002:     my $home='';
 6003: 
 6004:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 6005: 
 6006:     $symb=&symbclean($symb);
 6007:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 6008: 
 6009:     if (!$domain) { $domain=$env{'user.domain'}; }
 6010:     if (!$stuname) { $stuname=$env{'user.name'}; }
 6011: 
 6012:     &devalidate($symb,$stuname,$domain);
 6013: 
 6014:     $symb=escape($symb);
 6015:     if (!$namespace) { 
 6016:        unless ($namespace=$env{'request.course.id'}) { 
 6017:           return ''; 
 6018:        } 
 6019:     }
 6020:     if (!$home) { $home=$env{'user.home'}; }
 6021: 
 6022:     $$storehash{'ip'}=&get_requestor_ip();
 6023:     $$storehash{'host'}=$perlvar{'lonHostID'};
 6024: 
 6025:     my $namevalue='';
 6026:     foreach my $key (keys(%$storehash)) {
 6027:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 6028:     }
 6029:     $namevalue=~s/\&$//;
 6030:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 6031:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 6032: }
 6033: 
 6034: # -------------------------------------------------------------- Critical Store
 6035: 
 6036: sub cstore {
 6037:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 6038:     my $home='';
 6039: 
 6040:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 6041: 
 6042:     $symb=&symbclean($symb);
 6043:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 6044: 
 6045:     if (!$domain) { $domain=$env{'user.domain'}; }
 6046:     if (!$stuname) { $stuname=$env{'user.name'}; }
 6047: 
 6048:     &devalidate($symb,$stuname,$domain);
 6049: 
 6050:     $symb=escape($symb);
 6051:     if (!$namespace) { 
 6052:        unless ($namespace=$env{'request.course.id'}) { 
 6053:           return ''; 
 6054:        } 
 6055:     }
 6056:     if (!$home) { $home=$env{'user.home'}; }
 6057: 
 6058:     $$storehash{'ip'}=&get_requestor_ip();
 6059:     $$storehash{'host'}=$perlvar{'lonHostID'};
 6060: 
 6061:     my $namevalue='';
 6062:     foreach my $key (keys(%$storehash)) {
 6063:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 6064:     }
 6065:     $namevalue=~s/\&$//;
 6066:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 6067:     return critical
 6068:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 6069: }
 6070: 
 6071: # --------------------------------------------------------------------- Restore
 6072: 
 6073: sub restore {
 6074:     my ($symb,$namespace,$domain,$stuname) = @_;
 6075:     my $home='';
 6076: 
 6077:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 6078: 
 6079:     if (!$symb) {
 6080:         return if ($namespace eq 'courserequests');
 6081:         unless ($symb=escape(&symbread())) { return ''; }
 6082:     } else {
 6083:         unless ($namespace eq 'courserequests') {
 6084:             $symb=&escape(&symbclean($symb));
 6085:         }
 6086:     }
 6087:     if (!$namespace) { 
 6088:        unless ($namespace=$env{'request.course.id'}) { 
 6089:           return ''; 
 6090:        } 
 6091:     }
 6092:     if (!$domain) { $domain=$env{'user.domain'}; }
 6093:     if (!$stuname) { $stuname=$env{'user.name'}; }
 6094:     if (!$home) { $home=$env{'user.home'}; }
 6095:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 6096: 
 6097:     my %returnhash=();
 6098:     foreach my $line (split(/\&/,$answer)) {
 6099: 	my ($name,$value)=split(/\=/,$line);
 6100:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 6101:     }
 6102:     my $version;
 6103:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 6104:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 6105:           $returnhash{$item}=$returnhash{$version.':'.$item};
 6106:        }
 6107:     }
 6108:     return %returnhash;
 6109: }
 6110: 
 6111: # ---------------------------------------------------------- Course Description
 6112: #
 6113: #  
 6114: 
 6115: sub coursedescription {
 6116:     my ($courseid,$args)=@_;
 6117:     $courseid=~s/^\///;
 6118:     $courseid=~s/\_/\//g;
 6119:     my ($cdomain,$cnum)=split(/\//,$courseid);
 6120:     my $chome=&homeserver($cnum,$cdomain);
 6121:     my $normalid=$cdomain.'_'.$cnum;
 6122:     # need to always cache even if we get errors otherwise we keep 
 6123:     # trying and trying and trying to get the course description.
 6124:     my %envhash=();
 6125:     my %returnhash=();
 6126:     
 6127:     my $expiretime=600;
 6128:     if ($env{'request.course.id'} eq $normalid) {
 6129: 	$expiretime=120;
 6130:     }
 6131: 
 6132:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 6133:     if (!$args->{'freshen_cache'}
 6134: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 6135: 	foreach my $key (keys(%env)) {
 6136: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 6137: 	    my ($setting) = $1;
 6138: 	    $returnhash{$setting} = $env{$key};
 6139: 	}
 6140: 	return %returnhash;
 6141:     }
 6142: 
 6143:     # get the data again
 6144: 
 6145:     if (!$args->{'one_time'}) {
 6146: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 6147:     }
 6148: 
 6149:     if ($chome ne 'no_host') {
 6150:        %returnhash=&dump('environment',$cdomain,$cnum);
 6151:        if (!exists($returnhash{'con_lost'})) {
 6152: 	   my $username = $env{'user.name'}; # Defult username
 6153: 	   if(defined $args->{'user'}) {
 6154: 	       $username = $args->{'user'};
 6155: 	   }
 6156:            $returnhash{'home'}= $chome;
 6157: 	   $returnhash{'domain'} = $cdomain;
 6158: 	   $returnhash{'num'} = $cnum;
 6159:            if (!defined($returnhash{'type'})) {
 6160:                $returnhash{'type'} = 'Course';
 6161:            }
 6162:            while (my ($name,$value) = each %returnhash) {
 6163:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 6164:            }
 6165:            $returnhash{'url'}=&clutter($returnhash{'url'});
 6166:            $returnhash{'fn'}=LONCAPA::tempdir() .
 6167: 	       $username.'_'.$cdomain.'_'.$cnum;
 6168:            $envhash{'course.'.$normalid.'.home'}=$chome;
 6169:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 6170:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 6171:        }
 6172:     }
 6173:     if (!$args->{'one_time'}) {
 6174: 	&appenv(\%envhash);
 6175:     }
 6176:     return %returnhash;
 6177: }
 6178: 
 6179: sub update_released_required {
 6180:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
 6181:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
 6182:         $cid = $env{'request.course.id'};
 6183:         $cdom = $env{'course.'.$cid.'.domain'};
 6184:         $cnum = $env{'course.'.$cid.'.num'};
 6185:         $chome = $env{'course.'.$cid.'.home'};
 6186:     }
 6187:     if ($needsrelease) {
 6188:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
 6189:         my $needsupdate;
 6190:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
 6191:             $needsupdate = 1;
 6192:         } else {
 6193:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
 6194:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
 6195:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
 6196:                 $needsupdate = 1;
 6197:             }
 6198:         }
 6199:         if ($needsupdate) {
 6200:             my %needshash = (
 6201:                              'internal.releaserequired' => $needsrelease,
 6202:                             );
 6203:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
 6204:             if ($putresult eq 'ok') {
 6205:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
 6206:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 6207:                 if (ref($crsinfo{$cid}) eq 'HASH') {
 6208:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
 6209:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
 6210:                 }
 6211:             }
 6212:         }
 6213:     }
 6214:     return;
 6215: }
 6216: 
 6217: # -------------------------------------------------See if a user is privileged
 6218: 
 6219: sub privileged {
 6220:     my ($username,$domain,$possdomains,$possroles)=@_;
 6221:     my $now = time;
 6222:     my $roles;
 6223:     if (ref($possroles) eq 'ARRAY') {
 6224:         $roles = $possroles;
 6225:     } else {
 6226:         $roles = ['dc','su'];
 6227:     }
 6228:     if (ref($possdomains) eq 'ARRAY') {
 6229:         my %privileged = &privileged_by_domain($possdomains,$roles);
 6230:         foreach my $dom (@{$possdomains}) {
 6231:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
 6232:                 (ref($privileged{$dom}) eq 'HASH')) {
 6233:                 foreach my $role (@{$roles}) {
 6234:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 6235:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
 6236:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
 6237:                             return 1 unless (($end && $end < $now) ||
 6238:                                              ($start && $start > $now));
 6239:                         }
 6240:                     }
 6241:                 }
 6242:             }
 6243:         }
 6244:     } else {
 6245:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
 6246:         my $now = time;
 6247: 
 6248:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
 6249:             my ($trole, $tend, $tstart) = split(/_/, $role);
 6250:             if (grep(/^\Q$trole\E$/,@{$roles})) {
 6251:                 return 1 unless ($tend && $tend < $now)
 6252:                         or ($tstart && $tstart > $now);
 6253:             }
 6254:         }
 6255:     }
 6256:     return 0;
 6257: }
 6258: 
 6259: sub privileged_by_domain {
 6260:     my ($domains,$roles) = @_;
 6261:     my %privileged = ();
 6262:     my $cachetime = 60*60*24;
 6263:     my $now = time;
 6264:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
 6265:         return %privileged;
 6266:     }
 6267:     foreach my $dom (@{$domains}) {
 6268:         next if (ref($privileged{$dom}) eq 'HASH');
 6269:         my $needroles;
 6270:         foreach my $role (@{$roles}) {
 6271:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
 6272:             if (defined($cached)) {
 6273:                 if (ref($result) eq 'HASH') {
 6274:                     $privileged{$dom}{$role} = $result;
 6275:                 }
 6276:             } else {
 6277:                 $needroles = 1;
 6278:             }
 6279:         }
 6280:         if ($needroles) {
 6281:             my %dompersonnel = &get_domain_roles($dom,$roles);
 6282:             $privileged{$dom} = {};
 6283:             foreach my $server (keys(%dompersonnel)) {
 6284:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 6285:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
 6286:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
 6287:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
 6288:                         next if ($end && $end < $now);
 6289:                         $privileged{$dom}{$trole}{$uname.':'.$udom} =
 6290:                             $dompersonnel{$server}{$item};
 6291:                     }
 6292:                 }
 6293:             }
 6294:             if (ref($privileged{$dom}) eq 'HASH') {
 6295:                 foreach my $role (@{$roles}) {
 6296:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 6297:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
 6298:                     } else {
 6299:                         my %hash = ();
 6300:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
 6301:                     }
 6302:                 }
 6303:             }
 6304:         }
 6305:     }
 6306:     return %privileged;
 6307: }
 6308: 
 6309: # -------------------------------------------------------- Get user privileges
 6310: 
 6311: sub rolesinit {
 6312:     my ($domain, $username) = @_;
 6313:     my %userroles = ('user.login.time' => time);
 6314:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
 6315: 
 6316:     # firstaccess and timerinterval are related to timed maps/resources. 
 6317:     # also, blocking can be triggered by an activating timer
 6318:     # it's saved in the user's %env.
 6319:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
 6320:     my %timerinterval = &dump('timerinterval', $domain, $username);
 6321:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
 6322:         %timerintchk, %timerintenv);
 6323: 
 6324:     foreach my $key (keys(%firstaccess)) {
 6325:         my ($cid, $rest) = split(/\0/, $key);
 6326:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
 6327:     }
 6328: 
 6329:     foreach my $key (keys(%timerinterval)) {
 6330:         my ($cid,$rest) = split(/\0/,$key);
 6331:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
 6332:     }
 6333: 
 6334:     my %allroles=();
 6335:     my %allgroups=();
 6336: 
 6337:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
 6338:         my $role = $rolesdump{$area};
 6339:         $area =~ s/\_\w\w$//;
 6340: 
 6341:         my ($trole, $tend, $tstart, $group_privs);
 6342: 
 6343:         if ($role =~ /^cr/) {
 6344:         # Custom role, defined by a user 
 6345:         # e.g., user.role.cr/msu/smith/mynewrole
 6346:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 6347:                 $trole = $1;
 6348:                 ($tend, $tstart) = split('_', $2);
 6349:             } else {
 6350:                 $trole = $role;
 6351:             }
 6352:         } elsif ($role =~ m|^gr/|) {
 6353:         # Role of member in a group, defined within a course/community
 6354:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
 6355:             ($trole, $tend, $tstart) = split(/_/, $role);
 6356:             next if $tstart eq '-1';
 6357:             ($trole, $group_privs) = split(/\//, $trole);
 6358:             $group_privs = &unescape($group_privs);
 6359:         } else {
 6360:         # Just a normal role, defined in roles.tab
 6361:             ($trole, $tend, $tstart) = split(/_/,$role);
 6362:         }
 6363: 
 6364:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 6365:                  $username);
 6366:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 6367: 
 6368:         # role expired or not available yet?
 6369:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
 6370:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
 6371: 
 6372:         next if $area eq '' or $trole eq '';
 6373: 
 6374:         my $spec = "$trole.$area";
 6375:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
 6376: 
 6377:         if ($trole =~ /^cr\//) {
 6378:         # Custom role, defined by a user
 6379:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 6380:         } elsif ($trole eq 'gr') {
 6381:         # Role of a member in a group, defined within a course/community
 6382:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 6383:             next;
 6384:         } else {
 6385:         # Normal role, defined in roles.tab
 6386:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 6387:         }
 6388: 
 6389:         my $cid = $tdomain.'_'.$trest;
 6390:         unless ($firstaccchk{$cid}) {
 6391:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
 6392:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
 6393:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
 6394:                         $coursetimerstarts{$cid}{$item}; 
 6395:                 }
 6396:             }
 6397:             $firstaccchk{$cid} = 1;
 6398:         }
 6399:         unless ($timerintchk{$cid}) {
 6400:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
 6401:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
 6402:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
 6403:                        $coursetimerintervals{$cid}{$item};
 6404:                 }
 6405:             }
 6406:             $timerintchk{$cid} = 1;
 6407:         }
 6408:     }
 6409: 
 6410:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
 6411:                                                           \%allroles, \%allgroups);
 6412:     $env{'user.adv'} = $userroles{'user.adv'};
 6413:     $env{'user.rar'} = $userroles{'user.rar'};
 6414: 
 6415:     return (\%userroles,\%firstaccenv,\%timerintenv);
 6416: }
 6417: 
 6418: sub set_arearole {
 6419:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
 6420:     unless ($nolog) {
 6421: # log the associated role with the area
 6422:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 6423:     }
 6424:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 6425: }
 6426: 
 6427: sub custom_roleprivs {
 6428:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 6429:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 6430:     my $homsvr = &homeserver($rauthor,$rdomain);
 6431:     if (&hostname($homsvr) ne '') {
 6432:         my ($rdummy,$roledef)=
 6433:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 6434:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 6435:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 6436:             if (defined($syspriv)) {
 6437:                 if ($trest =~ /^$match_community$/) {
 6438:                     $syspriv =~ s/bre\&S//; 
 6439:                 }
 6440:                 $$allroles{'cm./'}.=':'.$syspriv;
 6441:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 6442:             }
 6443:             if ($tdomain ne '') {
 6444:                 if (defined($dompriv)) {
 6445:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 6446:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 6447:                 }
 6448:                 if (($trest ne '') && (defined($coursepriv))) {
 6449:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
 6450:                         my $rolename = $1;
 6451:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
 6452:                     }
 6453:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 6454:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 6455:                 }
 6456:             }
 6457:         }
 6458:     }
 6459: }
 6460: 
 6461: sub course_adhocrole_privs {
 6462:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
 6463:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
 6464:     if ($overrides{"internal.adhocpriv.$rolename"}) {
 6465:         my (%currprivs,%storeprivs);
 6466:         foreach my $item (split(/:/,$coursepriv)) {
 6467:             my ($priv,$restrict) = split(/\&/,$item);
 6468:             $currprivs{$priv} = $restrict;
 6469:         }
 6470:         my (%possadd,%possremove,%full);
 6471:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
 6472:             my ($priv,$restrict)=split(/\&/,$item);
 6473:             $full{$priv} = $restrict;
 6474:         }
 6475:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
 6476:              next if ($item eq '');
 6477:              my ($rule,$rest) = split(/=/,$item);
 6478:              next unless (($rule eq 'off') || ($rule eq 'on'));
 6479:              foreach my $priv (split(/:/,$rest)) {
 6480:                  if ($priv ne '') {
 6481:                      if ($rule eq 'off') {
 6482:                          $possremove{$priv} = 1;
 6483:                      } else {
 6484:                          $possadd{$priv} = 1;
 6485:                      }
 6486:                  }
 6487:              }
 6488:          }
 6489:          foreach my $priv (sort(keys(%full))) {
 6490:              if (exists($currprivs{$priv})) {
 6491:                  unless (exists($possremove{$priv})) {
 6492:                      $storeprivs{$priv} = $currprivs{$priv};
 6493:                  }
 6494:              } elsif (exists($possadd{$priv})) {
 6495:                  $storeprivs{$priv} = $full{$priv};
 6496:              }
 6497:          }
 6498:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
 6499:      }
 6500:      return $coursepriv;
 6501: }
 6502: 
 6503: sub group_roleprivs {
 6504:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 6505:     my $access = 1;
 6506:     my $now = time;
 6507:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 6508:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 6509:     if ($access) {
 6510:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 6511:         $$allgroups{$course}{$group} .=':'.$group_privs;
 6512:     }
 6513: }
 6514: 
 6515: sub standard_roleprivs {
 6516:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 6517:     if (defined($pr{$trole.':s'})) {
 6518:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 6519:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 6520:     }
 6521:     if ($tdomain ne '') {
 6522:         if (defined($pr{$trole.':d'})) {
 6523:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 6524:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 6525:         }
 6526:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 6527:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 6528:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 6529:         }
 6530:     }
 6531: }
 6532: 
 6533: sub set_userprivs {
 6534:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
 6535:     my $author=0;
 6536:     my $adv=0;
 6537:     my $rar=0;
 6538:     my %grouproles = ();
 6539:     if (keys(%{$allgroups}) > 0) {
 6540:         my @groupkeys; 
 6541:         foreach my $role (keys(%{$allroles})) {
 6542:             push(@groupkeys,$role);
 6543:         }
 6544:         if (ref($groups_roles) eq 'HASH') {
 6545:             foreach my $key (keys(%{$groups_roles})) {
 6546:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
 6547:                     push(@groupkeys,$key);
 6548:                 }
 6549:             }
 6550:         }
 6551:         if (@groupkeys > 0) {
 6552:             foreach my $role (@groupkeys) {
 6553:                 my ($trole,$area,$sec,$extendedarea);
 6554:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 6555:                     $trole = $1;
 6556:                     $area = $2;
 6557:                     $sec = $3;
 6558:                     $extendedarea = $area.$sec;
 6559:                     if (exists($$allgroups{$area})) {
 6560:                         foreach my $group (keys(%{$$allgroups{$area}})) {
 6561:                             my $spec = $trole.'.'.$extendedarea;
 6562:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
 6563:                                                 $$allgroups{$area}{$group};
 6564:                         }
 6565:                     }
 6566:                 }
 6567:             }
 6568:         }
 6569:     }
 6570:     foreach my $group (keys(%grouproles)) {
 6571:         $$allroles{$group} = $grouproles{$group};
 6572:     }
 6573:     foreach my $role (keys(%{$allroles})) {
 6574:         my %thesepriv;
 6575:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 6576:         foreach my $item (split(/:/,$$allroles{$role})) {
 6577:             if ($item ne '') {
 6578:                 my ($privilege,$restrictions)=split(/&/,$item);
 6579:                 if ($restrictions eq '') {
 6580:                     $thesepriv{$privilege}='F';
 6581:                 } elsif ($thesepriv{$privilege} ne 'F') {
 6582:                     $thesepriv{$privilege}.=$restrictions;
 6583:                 }
 6584:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 6585:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
 6586:             }
 6587:         }
 6588:         my $thesestr='';
 6589:         foreach my $priv (sort(keys(%thesepriv))) {
 6590: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 6591: 	}
 6592:         $userroles->{'user.priv.'.$role} = $thesestr;
 6593:     }
 6594:     return ($author,$adv,$rar);
 6595: }
 6596: 
 6597: sub role_status {
 6598:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 6599:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 6600:         my ($one,$two) = split(m{\./},$rolekey,2);
 6601:         (undef,undef,$$role) = split(/\./,$one,3);
 6602:         unless (!defined($$role) || $$role eq '') {
 6603:             $$where = '/'.$two;
 6604:             $$trolecode=$$role.'.'.$$where;
 6605:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 6606:             $$tstatus='is';
 6607:             if ($$tstart && $$tstart>$update) {
 6608:                 $$tstatus='future';
 6609:                 if ($$tstart<$now) {
 6610:                     if ($$tstart && $$tstart>$refresh) {
 6611:                         if (($$where ne '') && ($$role ne '')) {
 6612:                             my (%allroles,%allgroups,$group_privs,
 6613:                                 %groups_roles,@rolecodes);
 6614:                             my %userroles = (
 6615:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 6616:                             );
 6617:                             @rolecodes = ('cm'); 
 6618:                             my $spec=$$role.'.'.$$where;
 6619:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 6620:                             if ($$role =~ /^cr\//) {
 6621:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 6622:                                 push(@rolecodes,'cr');
 6623:                             } elsif ($$role eq 'gr') {
 6624:                                 push(@rolecodes,$$role);
 6625:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 6626:                                                     $env{'user.name'});
 6627:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
 6628:                                 (undef,my $group_privs) = split(/\//,$trole);
 6629:                                 $group_privs = &unescape($group_privs);
 6630:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 6631:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
 6632:                                 &get_groups_roles($tdomain,$trest,
 6633:                                                   \%course_roles,\@rolecodes,
 6634:                                                   \%groups_roles);
 6635:                             } else {
 6636:                                 push(@rolecodes,$$role);
 6637:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 6638:                             }
 6639:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
 6640:                                                                    \%groups_roles);
 6641:                             &appenv(\%userroles,\@rolecodes);
 6642:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
 6643:                         }
 6644:                     }
 6645:                     $$tstatus = 'is';
 6646:                 }
 6647:             }
 6648:             if ($$tend) {
 6649:                 if ($$tend<$update) {
 6650:                     $$tstatus='expired';
 6651:                 } elsif ($$tend<$now) {
 6652:                     $$tstatus='will_not';
 6653:                 }
 6654:             }
 6655:         }
 6656:     }
 6657: }
 6658: 
 6659: sub get_groups_roles {
 6660:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
 6661:     return unless((ref($cdom_courseroles) eq 'HASH') && 
 6662:                   (ref($rolecodes) eq 'ARRAY') && 
 6663:                   (ref($groups_roles) eq 'HASH')); 
 6664:     if (keys(%{$cdom_courseroles}) > 0) {
 6665:         my ($cnum) = ($rest =~ /^($match_courseid)/);
 6666:         if ($cdom ne '' && $cnum ne '') {
 6667:             foreach my $key (keys(%{$cdom_courseroles})) {
 6668:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
 6669:                     my $crsrole = $1;
 6670:                     my $crssec = $2;
 6671:                     if ($crsrole =~ /^cr/) {
 6672:                         unless (grep(/^cr$/,@{$rolecodes})) {
 6673:                             push(@{$rolecodes},'cr');
 6674:                         }
 6675:                     } else {
 6676:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
 6677:                             push(@{$rolecodes},$crsrole);
 6678:                         }
 6679:                     }
 6680:                     my $rolekey = "$crsrole./$cdom/$cnum";
 6681:                     if ($crssec ne '') {
 6682:                         $rolekey .= "/$crssec";
 6683:                     }
 6684:                     $rolekey .= './';
 6685:                     $groups_roles->{$rolekey} = $rolecodes;
 6686:                 }
 6687:             }
 6688:         }
 6689:     }
 6690:     return;
 6691: }
 6692: 
 6693: sub delete_env_groupprivs {
 6694:     my ($where,$courseroles,$possroles) = @_;
 6695:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
 6696:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
 6697:     unless (ref($courseroles->{$udom}) eq 'HASH') {
 6698:         %{$courseroles->{$udom}} =
 6699:             &get_my_roles('','','userroles',['active'],
 6700:                           $possroles,[$udom],1);
 6701:     }
 6702:     if (ref($courseroles->{$udom}) eq 'HASH') {
 6703:         foreach my $item (keys(%{$courseroles->{$udom}})) {
 6704:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
 6705:             my $area = '/'.$cdom.'/'.$cnum;
 6706:             my $privkey = "user.priv.$crsrole.$area";
 6707:             if ($crssec ne '') {
 6708:                 $privkey .= '/'.$crssec;
 6709:             }
 6710:             $privkey .= ".$area/$group";
 6711:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
 6712:         }
 6713:     }
 6714:     return;
 6715: }
 6716: 
 6717: sub check_adhoc_privs {
 6718:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
 6719:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 6720:     if ($sec) {
 6721:         $cckey .= '/'.$sec;
 6722:     }
 6723:     my $setprivs;
 6724:     if ($env{$cckey}) {
 6725:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 6726:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 6727:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 6728:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
 6729:             $setprivs = 1;
 6730:         }
 6731:     } else {
 6732:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
 6733:         $setprivs = 1;
 6734:     }
 6735:     return $setprivs;
 6736: }
 6737: 
 6738: sub set_adhoc_privileges {
 6739: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
 6740:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
 6741:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 6742:     if ($sec ne '') {
 6743:         $area .= '/'.$sec;
 6744:     }
 6745:     my $spec = $role.'.'.$area;
 6746:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 6747:                                   $env{'user.name'},1);
 6748:     my %rolehash = ();
 6749:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
 6750:         my $rolename = $1;
 6751:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
 6752:         my %domdef = &get_domain_defaults($dcdom);
 6753:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
 6754:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
 6755:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
 6756:             }
 6757:         }
 6758:     } else {
 6759:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
 6760:     }
 6761:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
 6762:     &appenv(\%userroles,[$role,'cm']);
 6763:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
 6764:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
 6765:         &appenv( {'request.role'        => $spec,
 6766:                   'request.role.domain' => $dcdom,
 6767:                   'request.course.sec'  => $sec, 
 6768:                  }
 6769:                );
 6770:         my $tadv=0;
 6771:         if (&allowed('adv') eq 'F') { $tadv=1; }
 6772:         &appenv({'request.role.adv'    => $tadv});
 6773:     }
 6774: }
 6775: 
 6776: # --------------------------------------------------------------- get interface
 6777: 
 6778: sub get {
 6779:    my ($namespace,$storearr,$udomain,$uname)=@_;
 6780:    my $items='';
 6781:    foreach my $item (@$storearr) {
 6782:        $items.=&escape($item).'&';
 6783:    }
 6784:    $items=~s/\&$//;
 6785:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6786:    if (!$uname) { $uname=$env{'user.name'}; }
 6787:    my $uhome=&homeserver($uname,$udomain);
 6788: 
 6789:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 6790:    my @pairs=split(/\&/,$rep);
 6791:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 6792:      return @pairs;
 6793:    }
 6794:    my %returnhash=();
 6795:    my $i=0;
 6796:    foreach my $item (@$storearr) {
 6797:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 6798:       $i++;
 6799:    }
 6800:    return %returnhash;
 6801: }
 6802: 
 6803: # --------------------------------------------------------------- del interface
 6804: 
 6805: sub del {
 6806:    my ($namespace,$storearr,$udomain,$uname)=@_;
 6807:    my $items='';
 6808:    foreach my $item (@$storearr) {
 6809:        $items.=&escape($item).'&';
 6810:    }
 6811: 
 6812:    $items=~s/\&$//;
 6813:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6814:    if (!$uname) { $uname=$env{'user.name'}; }
 6815:    my $uhome=&homeserver($uname,$udomain);
 6816:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 6817: }
 6818: 
 6819: # -------------------------------------------------------------- dump interface
 6820: 
 6821: sub unserialize {
 6822:     my ($rep, $escapedkeys) = @_;
 6823: 
 6824:     return {} if $rep =~ /^error/;
 6825: 
 6826:     my %returnhash=();
 6827:     foreach my $item (split(/\&/,$rep)) {
 6828:         my ($key, $value) = split(/=/, $item, 2);
 6829:         $key = unescape($key) unless $escapedkeys;
 6830:         next if $key =~ /^error: 2 /;
 6831:         $returnhash{$key} = &thaw_unescape($value);
 6832:     }
 6833:     return \%returnhash;
 6834: }
 6835: 
 6836: # see Lond::dump_with_regexp
 6837: # if $escapedkeys hash keys won't get unescaped.
 6838: sub dump {
 6839:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
 6840:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 6841:     if (!$uname) { $uname=$env{'user.name'}; }
 6842:     my $uhome=&homeserver($uname,$udomain);
 6843: 
 6844:     if ($regexp) {
 6845:         $regexp=&escape($regexp);
 6846:     } else {
 6847:         $regexp='.';
 6848:     }
 6849:     if (grep { $_ eq $uhome } &current_machine_ids()) {
 6850:         # user is hosted on this machine
 6851:         my $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
 6852:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
 6853:         return %{&unserialize($reply, $escapedkeys)};
 6854:     }
 6855:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 6856:     my @pairs=split(/\&/,$rep);
 6857:     my %returnhash=();
 6858:     if (!($rep =~ /^error/ )) {
 6859: 	foreach my $item (@pairs) {
 6860: 	    my ($key,$value)=split(/=/,$item,2);
 6861:             $key = &unescape($key) unless ($escapedkeys);
 6862: 	    next if ($key =~ /^error: 2 /);
 6863: 	    $returnhash{$key}=&thaw_unescape($value);
 6864: 	}
 6865:     }
 6866:     return %returnhash;
 6867: }
 6868: 
 6869: 
 6870: # --------------------------------------------------------- dumpstore interface
 6871: 
 6872: sub dumpstore {
 6873:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 6874:    # same as dump but keys must be escaped. They may contain colon separated
 6875:    # lists of values that may themself contain colons (e.g. symbs).
 6876:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
 6877: }
 6878: 
 6879: # -------------------------------------------------------------- keys interface
 6880: 
 6881: sub getkeys {
 6882:    my ($namespace,$udomain,$uname)=@_;
 6883:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6884:    if (!$uname) { $uname=$env{'user.name'}; }
 6885:    my $uhome=&homeserver($uname,$udomain);
 6886:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 6887:    my @keyarray=();
 6888:    foreach my $key (split(/\&/,$rep)) {
 6889:       next if ($key =~ /^error: 2 /);
 6890:       push(@keyarray,&unescape($key));
 6891:    }
 6892:    return @keyarray;
 6893: }
 6894: 
 6895: # --------------------------------------------------------------- currentdump
 6896: sub currentdump {
 6897:    my ($courseid,$sdom,$sname)=@_;
 6898:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 6899:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 6900:    $sname    = $env{'user.name'}         if (! defined($sname));
 6901:    my $uhome = &homeserver($sname,$sdom);
 6902:    my $rep;
 6903: 
 6904:    if (grep { $_ eq $uhome } current_machine_ids()) {
 6905:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
 6906:                    $courseid)));
 6907:    } else {
 6908:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 6909:    }
 6910: 
 6911:    return if ($rep =~ /^(error:|no_such_host)/);
 6912:    #
 6913:    my %returnhash=();
 6914:    #
 6915:    if ($rep eq "unknown_cmd") { 
 6916:        # an old lond will not know currentdump
 6917:        # Do a dump and make it look like a currentdump
 6918:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 6919:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 6920:        my %hash = @tmp;
 6921:        @tmp=();
 6922:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 6923:    } else {
 6924:        my @pairs=split(/\&/,$rep);
 6925:        foreach my $pair (@pairs) {
 6926:            my ($key,$value)=split(/=/,$pair,2);
 6927:            my ($symb,$param) = split(/:/,$key);
 6928:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 6929:                                                         &thaw_unescape($value);
 6930:        }
 6931:    }
 6932:    return %returnhash;
 6933: }
 6934: 
 6935: sub convert_dump_to_currentdump{
 6936:     my %hash = %{shift()};
 6937:     my %returnhash;
 6938:     # Code ripped from lond, essentially.  The only difference
 6939:     # here is the unescaping done by lonnet::dump().  Conceivably
 6940:     # we might run in to problems with parameter names =~ /^v\./
 6941:     while (my ($key,$value) = each(%hash)) {
 6942:         my ($v,$symb,$param) = split(/:/,$key);
 6943: 	$symb  = &unescape($symb);
 6944: 	$param = &unescape($param);
 6945:         next if ($v eq 'version' || $symb eq 'keys');
 6946:         next if (exists($returnhash{$symb}) &&
 6947:                  exists($returnhash{$symb}->{$param}) &&
 6948:                  $returnhash{$symb}->{'v.'.$param} > $v);
 6949:         $returnhash{$symb}->{$param}=$value;
 6950:         $returnhash{$symb}->{'v.'.$param}=$v;
 6951:     }
 6952:     #
 6953:     # Remove all of the keys in the hashes which keep track of
 6954:     # the version of the parameter.
 6955:     while (my ($symb,$param_hash) = each(%returnhash)) {
 6956:         # use a foreach because we are going to delete from the hash.
 6957:         foreach my $key (keys(%$param_hash)) {
 6958:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 6959:         }
 6960:     }
 6961:     return \%returnhash;
 6962: }
 6963: 
 6964: # ------------------------------------------------------ critical inc interface
 6965: 
 6966: sub cinc {
 6967:     return &inc(@_,'critical');
 6968: }
 6969: 
 6970: # --------------------------------------------------------------- inc interface
 6971: 
 6972: sub inc {
 6973:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 6974:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 6975:     if (!$uname) { $uname=$env{'user.name'}; }
 6976:     my $uhome=&homeserver($uname,$udomain);
 6977:     my $items='';
 6978:     if (! ref($store)) {
 6979:         # got a single value, so use that instead
 6980:         $items = &escape($store).'=&';
 6981:     } elsif (ref($store) eq 'SCALAR') {
 6982:         $items = &escape($$store).'=&';        
 6983:     } elsif (ref($store) eq 'ARRAY') {
 6984:         $items = join('=&',map {&escape($_);} @{$store});
 6985:     } elsif (ref($store) eq 'HASH') {
 6986:         while (my($key,$value) = each(%{$store})) {
 6987:             $items.= &escape($key).'='.&escape($value).'&';
 6988:         }
 6989:     }
 6990:     $items=~s/\&$//;
 6991:     if ($critical) {
 6992: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 6993:     } else {
 6994: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 6995:     }
 6996: }
 6997: 
 6998: # --------------------------------------------------------------- put interface
 6999: 
 7000: sub put {
 7001:    my ($namespace,$storehash,$udomain,$uname)=@_;
 7002:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7003:    if (!$uname) { $uname=$env{'user.name'}; }
 7004:    my $uhome=&homeserver($uname,$udomain);
 7005:    my $items='';
 7006:    foreach my $item (keys(%$storehash)) {
 7007:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 7008:    }
 7009:    $items=~s/\&$//;
 7010:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 7011: }
 7012: 
 7013: # ------------------------------------------------------------ newput interface
 7014: 
 7015: sub newput {
 7016:    my ($namespace,$storehash,$udomain,$uname)=@_;
 7017:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7018:    if (!$uname) { $uname=$env{'user.name'}; }
 7019:    my $uhome=&homeserver($uname,$udomain);
 7020:    my $items='';
 7021:    foreach my $key (keys(%$storehash)) {
 7022:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 7023:    }
 7024:    $items=~s/\&$//;
 7025:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 7026: }
 7027: 
 7028: # ---------------------------------------------------------  putstore interface
 7029: 
 7030: sub putstore {
 7031:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
 7032:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7033:    if (!$uname) { $uname=$env{'user.name'}; }
 7034:    my $uhome=&homeserver($uname,$udomain);
 7035:    my $items='';
 7036:    foreach my $key (keys(%$storehash)) {
 7037:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 7038:    }
 7039:    $items=~s/\&$//;
 7040:    my $esc_symb=&escape($symb);
 7041:    my $esc_v=&escape($version);
 7042:    my $reply =
 7043:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 7044: 	      $uhome);
 7045:    if (($tolog) && ($reply eq 'ok')) {
 7046:        my $namevalue='';
 7047:        foreach my $key (keys(%{$storehash})) {
 7048:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 7049:        }
 7050:        my $ip = &get_requestor_ip();
 7051:        $namevalue .= 'ip='.&escape($ip).
 7052:                      '&host='.&escape($perlvar{'lonHostID'}).
 7053:                      '&version='.$esc_v.
 7054:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
 7055:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
 7056:    }
 7057:    if ($reply eq 'unknown_cmd') {
 7058:        # gfall back to way things use to be done
 7059:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 7060: 			    $uname);
 7061:    }
 7062:    return $reply;
 7063: }
 7064: 
 7065: sub old_putstore {
 7066:     my ($namespace,$symb,$version,$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 %newstorehash;
 7071:     foreach my $item (keys(%$storehash)) {
 7072: 	my $key = $version.':'.&escape($symb).':'.$item;
 7073: 	$newstorehash{$key} = $storehash->{$item};
 7074:     }
 7075:     my $items='';
 7076:     my %allitems = ();
 7077:     foreach my $item (keys(%newstorehash)) {
 7078: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 7079: 	    my $key = $1.':keys:'.$2;
 7080: 	    $allitems{$key} .= $3.':';
 7081: 	}
 7082: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 7083:     }
 7084:     foreach my $item (keys(%allitems)) {
 7085: 	$allitems{$item} =~ s/\:$//;
 7086: 	$items.= $item.'='.$allitems{$item}.'&';
 7087:     }
 7088:     $items=~s/\&$//;
 7089:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 7090: }
 7091: 
 7092: # ------------------------------------------------------ critical put interface
 7093: 
 7094: sub cput {
 7095:    my ($namespace,$storehash,$udomain,$uname)=@_;
 7096:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7097:    if (!$uname) { $uname=$env{'user.name'}; }
 7098:    my $uhome=&homeserver($uname,$udomain);
 7099:    my $items='';
 7100:    foreach my $item (keys(%$storehash)) {
 7101:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 7102:    }
 7103:    $items=~s/\&$//;
 7104:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 7105: }
 7106: 
 7107: # -------------------------------------------------------------- eget interface
 7108: 
 7109: sub eget {
 7110:    my ($namespace,$storearr,$udomain,$uname)=@_;
 7111:    my $items='';
 7112:    foreach my $item (@$storearr) {
 7113:        $items.=&escape($item).'&';
 7114:    }
 7115:    $items=~s/\&$//;
 7116:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7117:    if (!$uname) { $uname=$env{'user.name'}; }
 7118:    my $uhome=&homeserver($uname,$udomain);
 7119:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 7120:    my @pairs=split(/\&/,$rep);
 7121:    my %returnhash=();
 7122:    my $i=0;
 7123:    foreach my $item (@$storearr) {
 7124:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 7125:       $i++;
 7126:    }
 7127:    return %returnhash;
 7128: }
 7129: 
 7130: # ------------------------------------------------------------ tmpput interface
 7131: sub tmpput {
 7132:     my ($storehash,$server,$context)=@_;
 7133:     my $items='';
 7134:     foreach my $item (keys(%$storehash)) {
 7135: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 7136:     }
 7137:     $items=~s/\&$//;
 7138:     if (defined($context)) {
 7139:         $items .= ':'.&escape($context);
 7140:     }
 7141:     return &reply("tmpput:$items",$server);
 7142: }
 7143: 
 7144: # ------------------------------------------------------------ tmpget interface
 7145: sub tmpget {
 7146:     my ($token,$server)=@_;
 7147:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 7148:     my $rep=&reply("tmpget:$token",$server);
 7149:     my %returnhash;
 7150:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
 7151:         return %returnhash;
 7152:     }
 7153:     foreach my $item (split(/\&/,$rep)) {
 7154: 	my ($key,$value)=split(/=/,$item);
 7155: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 7156:     }
 7157:     return %returnhash;
 7158: }
 7159: 
 7160: # ------------------------------------------------------------ tmpdel interface
 7161: sub tmpdel {
 7162:     my ($token,$server)=@_;
 7163:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 7164:     return &reply("tmpdel:$token",$server);
 7165: }
 7166: 
 7167: # ------------------------------------------------------------ get_timebased_id
 7168: 
 7169: sub get_timebased_id {
 7170:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
 7171:         $maxtries) = @_;
 7172:     my ($newid,$error,$dellock);
 7173:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
 7174:         return ('','ok','invalid call to get suffix');
 7175:     }
 7176: 
 7177: # set defaults for any optional args for which values were not supplied
 7178:     if ($who eq '') {
 7179:         $who = $env{'user.name'}.':'.$env{'user.domain'};
 7180:     }
 7181:     if (!$locktries) {
 7182:         $locktries = 3;
 7183:     }
 7184:     if (!$maxtries) {
 7185:         $maxtries = 10;
 7186:     }
 7187: 
 7188:     if (($cdom eq '') || ($cnum eq '')) {
 7189:         if ($env{'request.course.id'}) {
 7190:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7191:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7192:         }
 7193:         if (($cdom eq '') || ($cnum eq '')) {
 7194:             return ('','ok','call to get suffix not in course context');
 7195:         }
 7196:     }
 7197: 
 7198: # construct locking item
 7199:     my $lockhash = {
 7200:                       $prefix."\0".'locked_'.$keyid => $who,
 7201:                    };
 7202:     my $tries = 0;
 7203: 
 7204: # attempt to get lock on nohist_$namespace file
 7205:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 7206:     while (($gotlock ne 'ok') && $tries <$locktries) {
 7207:         $tries ++;
 7208:         sleep 1;
 7209:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 7210:     }
 7211: 
 7212: # attempt to get unique identifier, based on current timestamp
 7213:     if ($gotlock eq 'ok') {
 7214:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
 7215:         my $id = time;
 7216:         $newid = $id;
 7217:         if ($idtype eq 'addcode') {
 7218:             $newid .= &sixnum_code();
 7219:         }
 7220:         my $idtries = 0;
 7221:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
 7222:             if ($idtype eq 'concat') {
 7223:                 $newid = $id.$idtries;
 7224:             } elsif ($idtype eq 'addcode') {
 7225:                 $newid = $newid.&sixnum_code();
 7226:             } else {
 7227:                 $newid ++;
 7228:             }
 7229:             $idtries ++;
 7230:         }
 7231:         if (!exists($inuse{$prefix."\0".$newid})) {
 7232:             my %new_item =  (
 7233:                               $prefix."\0".$newid => $who,
 7234:                             );
 7235:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
 7236:                                                  $cdom,$cnum);
 7237:             if ($putresult ne 'ok') {
 7238:                 undef($newid);
 7239:                 $error = 'error saving new item: '.$putresult;
 7240:             }
 7241:         } else {
 7242:              undef($newid);
 7243:              $error = ('error: no unique suffix available for the new item ');
 7244:         }
 7245: #  remove lock
 7246:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
 7247:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
 7248:     } else {
 7249:         $error = "error: could not obtain lockfile\n";
 7250:         $dellock = 'ok';
 7251:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
 7252:             $dellock = 'nolock';
 7253:         }
 7254:     }
 7255:     return ($newid,$dellock,$error);
 7256: }
 7257: 
 7258: sub sixnum_code {
 7259:     my $code;
 7260:     for (0..6) {
 7261:         $code .= int( rand(9) );
 7262:     }
 7263:     return $code;
 7264: }
 7265: 
 7266: # -------------------------------------------------- portfolio access checking
 7267: 
 7268: sub portfolio_access {
 7269:     my ($requrl,$clientip) = @_;
 7270:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 7271:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
 7272:     if ($result) {
 7273:         my %setters;
 7274:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 7275:             my ($startblock,$endblock) =
 7276:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 7277:             if ($startblock && $endblock) {
 7278:                 return 'B';
 7279:             }
 7280:         } else {
 7281:             my ($startblock,$endblock) =
 7282:                 &Apache::loncommon::blockcheck(\%setters,'port');
 7283:             if ($startblock && $endblock) {
 7284:                 return 'B';
 7285:             }
 7286:         }
 7287:     }
 7288:     if ($result eq 'ok') {
 7289:        return 'F';
 7290:     } elsif ($result =~ /^[^:]+:guest_/) {
 7291:        return 'A';
 7292:     }
 7293:     return '';
 7294: }
 7295: 
 7296: sub get_portfolio_access {
 7297:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
 7298: 
 7299:     if (!ref($access_hash)) {
 7300: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 7301: 	my %access_controls = &get_access_controls($current_perms,$group,
 7302: 						   $file_name);
 7303: 	$access_hash = $access_controls{$file_name};
 7304:     }
 7305: 
 7306:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
 7307:     my $now = time;
 7308:     if (ref($access_hash) eq 'HASH') {
 7309:         foreach my $key (keys(%{$access_hash})) {
 7310:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 7311:             if ($start > $now) {
 7312:                 next;
 7313:             }
 7314:             if ($end && $end<$now) {
 7315:                 next;
 7316:             }
 7317:             if ($scope eq 'public') {
 7318:                 $public = $key;
 7319:                 last;
 7320:             } elsif ($scope eq 'guest') {
 7321:                 $guest = $key;
 7322:             } elsif ($scope eq 'domains') {
 7323:                 push(@domains,$key);
 7324:             } elsif ($scope eq 'users') {
 7325:                 push(@users,$key);
 7326:             } elsif ($scope eq 'course') {
 7327:                 push(@courses,$key);
 7328:             } elsif ($scope eq 'group') {
 7329:                 push(@groups,$key);
 7330:             } elsif ($scope eq 'ip') {
 7331:                 push(@ips,$key);
 7332:             }
 7333:         }
 7334:         if ($public) {
 7335:             return 'ok';
 7336:         } elsif (@ips > 0) {
 7337:             my $allowed;
 7338:             foreach my $ipkey (@ips) {
 7339:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
 7340:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
 7341:                         $allowed = 1;
 7342:                         last;
 7343:                     }
 7344:                 }
 7345:             }
 7346:             if ($allowed) {
 7347:                 return 'ok';
 7348:             }
 7349:         }
 7350:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 7351:             if ($guest) {
 7352:                 return $guest;
 7353:             }
 7354:         } else {
 7355:             if (@domains > 0) {
 7356:                 foreach my $domkey (@domains) {
 7357:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 7358:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 7359:                             return 'ok';
 7360:                         }
 7361:                     }
 7362:                 }
 7363:             }
 7364:             if (@users > 0) {
 7365:                 foreach my $userkey (@users) {
 7366:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 7367:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 7368:                             if (ref($item) eq 'HASH') {
 7369:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 7370:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 7371:                                     return 'ok';
 7372:                                 }
 7373:                             }
 7374:                         }
 7375:                     } 
 7376:                 }
 7377:             }
 7378:             my %roleshash;
 7379:             my @courses_and_groups = @courses;
 7380:             push(@courses_and_groups,@groups); 
 7381:             if (@courses_and_groups > 0) {
 7382:                 my (%allgroups,%allroles); 
 7383:                 my ($start,$end,$role,$sec,$group);
 7384:                 foreach my $envkey (%env) {
 7385:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 7386:                         my $cid = $2.'_'.$3; 
 7387:                         if ($1 eq 'gr') {
 7388:                             $group = $4;
 7389:                             $allgroups{$cid}{$group} = $env{$envkey};
 7390:                         } else {
 7391:                             if ($4 eq '') {
 7392:                                 $sec = 'none';
 7393:                             } else {
 7394:                                 $sec = $4;
 7395:                             }
 7396:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 7397:                         }
 7398:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 7399:                         my $cid = $2.'_'.$3;
 7400:                         if ($4 eq '') {
 7401:                             $sec = 'none';
 7402:                         } else {
 7403:                             $sec = $4;
 7404:                         }
 7405:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 7406:                     }
 7407:                 }
 7408:                 if (keys(%allroles) == 0) {
 7409:                     return;
 7410:                 }
 7411:                 foreach my $key (@courses_and_groups) {
 7412:                     my %content = %{$$access_hash{$key}};
 7413:                     my $cnum = $content{'number'};
 7414:                     my $cdom = $content{'domain'};
 7415:                     my $cid = $cdom.'_'.$cnum;
 7416:                     if (!exists($allroles{$cid})) {
 7417:                         next;
 7418:                     }    
 7419:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 7420:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 7421:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 7422:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 7423:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 7424:                         foreach my $role (keys(%{$allroles{$cid}})) {
 7425:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 7426:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 7427:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 7428:                                         if (grep/^all$/,@sections) {
 7429:                                             return 'ok';
 7430:                                         } else {
 7431:                                             if (grep/^$sec$/,@sections) {
 7432:                                                 return 'ok';
 7433:                                             }
 7434:                                         }
 7435:                                     }
 7436:                                 }
 7437:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 7438:                                     if (grep/^none$/,@groups) {
 7439:                                         return 'ok';
 7440:                                     }
 7441:                                 } else {
 7442:                                     if (grep/^all$/,@groups) {
 7443:                                         return 'ok';
 7444:                                     } 
 7445:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 7446:                                         if (grep/^$group$/,@groups) {
 7447:                                             return 'ok';
 7448:                                         }
 7449:                                     }
 7450:                                 } 
 7451:                             }
 7452:                         }
 7453:                     }
 7454:                 }
 7455:             }
 7456:             if ($guest) {
 7457:                 return $guest;
 7458:             }
 7459:         }
 7460:     }
 7461:     return;
 7462: }
 7463: 
 7464: sub course_group_datechecker {
 7465:     my ($dates,$now,$status) = @_;
 7466:     my ($start,$end) = split(/\./,$dates);
 7467:     if (!$start && !$end) {
 7468:         return 'ok';
 7469:     }
 7470:     if (grep/^active$/,@{$status}) {
 7471:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 7472:             return 'ok';
 7473:         }
 7474:     }
 7475:     if (grep/^previous$/,@{$status}) {
 7476:         if ($end > $now ) {
 7477:             return 'ok';
 7478:         }
 7479:     }
 7480:     if (grep/^future$/,@{$status}) {
 7481:         if ($start > $now) {
 7482:             return 'ok';
 7483:         }
 7484:     }
 7485:     return; 
 7486: }
 7487: 
 7488: sub parse_portfolio_url {
 7489:     my ($url) = @_;
 7490: 
 7491:     my ($type,$udom,$unum,$group,$file_name);
 7492:     
 7493:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 7494: 	$type = 1;
 7495:         $udom = $1;
 7496:         $unum = $2;
 7497:         $file_name = $3;
 7498:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 7499: 	$type = 2;
 7500:         $udom = $1;
 7501:         $unum = $2;
 7502:         $group = $3;
 7503:         $file_name = $3.'/'.$4;
 7504:     }
 7505:     if (wantarray) {
 7506: 	return ($type,$udom,$unum,$file_name,$group);
 7507:     }
 7508:     return $type;
 7509: }
 7510: 
 7511: sub is_portfolio_url {
 7512:     my ($url) = @_;
 7513:     return scalar(&parse_portfolio_url($url));
 7514: }
 7515: 
 7516: sub is_portfolio_file {
 7517:     my ($file) = @_;
 7518:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 7519:         return 1;
 7520:     }
 7521:     return;
 7522: }
 7523: 
 7524: sub usertools_access {
 7525:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
 7526:     my ($access,%tools);
 7527:     if ($context eq '') {
 7528:         $context = 'tools';
 7529:     }
 7530:     if ($context eq 'requestcourses') {
 7531:         %tools = (
 7532:                       official   => 1,
 7533:                       unofficial => 1,
 7534:                       community  => 1,
 7535:                       textbook   => 1,
 7536:                  );
 7537:     } elsif ($context eq 'requestauthor') {
 7538:         %tools = (
 7539:                       requestauthor => 1,
 7540:                  );
 7541:     } else {
 7542:         %tools = (
 7543:                       aboutme   => 1,
 7544:                       blog      => 1,
 7545:                       webdav    => 1,
 7546:                       portfolio => 1,
 7547:                  );
 7548:     }
 7549:     return if (!defined($tools{$tool}));
 7550: 
 7551:     if (($udom eq '') || ($uname eq '')) {
 7552:         $udom = $env{'user.domain'};
 7553:         $uname = $env{'user.name'};
 7554:     }
 7555: 
 7556:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 7557:         if ($action ne 'reload') {
 7558:             if ($context eq 'requestcourses') {
 7559:                 return $env{'environment.canrequest.'.$tool};
 7560:             } elsif ($context eq 'requestauthor') {
 7561:                 return $env{'environment.canrequest.author'};
 7562:             } else {
 7563:                 return $env{'environment.availabletools.'.$tool};
 7564:             }
 7565:         }
 7566:     }
 7567: 
 7568:     my ($toolstatus,$inststatus,$envkey);
 7569:     if ($context eq 'requestauthor') {
 7570:         $envkey = $context;
 7571:     } else {
 7572:         $envkey = $context.'.'.$tool;
 7573:     }
 7574: 
 7575:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 7576:          ($action ne 'reload')) {
 7577:         $toolstatus = $env{'environment.'.$envkey};
 7578:         $inststatus = $env{'environment.inststatus'};
 7579:     } else {
 7580:         if (ref($userenvref) eq 'HASH') {
 7581:             $toolstatus = $userenvref->{$envkey};
 7582:             $inststatus = $userenvref->{'inststatus'};
 7583:         } else {
 7584:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
 7585:             $toolstatus = $userenv{$envkey};
 7586:             $inststatus = $userenv{'inststatus'};
 7587:         }
 7588:     }
 7589: 
 7590:     if ($toolstatus ne '') {
 7591:         if ($toolstatus) {
 7592:             $access = 1;
 7593:         } else {
 7594:             $access = 0;
 7595:         }
 7596:         return $access;
 7597:     }
 7598: 
 7599:     my ($is_adv,%domdef);
 7600:     if (ref($is_advref) eq 'HASH') {
 7601:         $is_adv = $is_advref->{'is_adv'};
 7602:     } else {
 7603:         $is_adv = &is_advanced_user($udom,$uname);
 7604:     }
 7605:     if (ref($domdefref) eq 'HASH') {
 7606:         %domdef = %{$domdefref};
 7607:     } else {
 7608:         %domdef = &get_domain_defaults($udom);
 7609:     }
 7610:     if (ref($domdef{$tool}) eq 'HASH') {
 7611:         if ($is_adv) {
 7612:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 7613:                 if ($domdef{$tool}{'_LC_adv'}) { 
 7614:                     $access = 1;
 7615:                 } else {
 7616:                     $access = 0;
 7617:                 }
 7618:                 return $access;
 7619:             }
 7620:         }
 7621:         if ($inststatus ne '') {
 7622:             my ($hasaccess,$hasnoaccess);
 7623:             foreach my $affiliation (split(/:/,$inststatus)) {
 7624:                 if ($domdef{$tool}{$affiliation} ne '') { 
 7625:                     if ($domdef{$tool}{$affiliation}) {
 7626:                         $hasaccess = 1;
 7627:                     } else {
 7628:                         $hasnoaccess = 1;
 7629:                     }
 7630:                 }
 7631:             }
 7632:             if ($hasaccess || $hasnoaccess) {
 7633:                 if ($hasaccess) {
 7634:                     $access = 1;
 7635:                 } elsif ($hasnoaccess) {
 7636:                     $access = 0; 
 7637:                 }
 7638:                 return $access;
 7639:             }
 7640:         } else {
 7641:             if ($domdef{$tool}{'default'} ne '') {
 7642:                 if ($domdef{$tool}{'default'}) {
 7643:                     $access = 1;
 7644:                 } elsif ($domdef{$tool}{'default'} == 0) {
 7645:                     $access = 0;
 7646:                 }
 7647:                 return $access;
 7648:             }
 7649:         }
 7650:     } else {
 7651:         if (($context eq 'tools') && ($tool ne 'webdav')) {
 7652:             $access = 1;
 7653:         } else {
 7654:             $access = 0;
 7655:         }
 7656:         return $access;
 7657:     }
 7658: }
 7659: 
 7660: sub is_course_owner {
 7661:     my ($cdom,$cnum,$udom,$uname) = @_;
 7662:     if (($udom eq '') || ($uname eq '')) {
 7663:         $udom = $env{'user.domain'};
 7664:         $uname = $env{'user.name'};
 7665:     }
 7666:     unless (($udom eq '') || ($uname eq '')) {
 7667:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
 7668:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
 7669:                 return 1;
 7670:             } else {
 7671:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
 7672:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
 7673:                     return 1;
 7674:                 }
 7675:             }
 7676:         }
 7677:     }
 7678:     return;
 7679: }
 7680: 
 7681: sub is_advanced_user {
 7682:     my ($udom,$uname) = @_;
 7683:     if ($udom ne '' && $uname ne '') {
 7684:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 7685:             if (wantarray) {
 7686:                 return ($env{'user.adv'},$env{'user.author'});
 7687:             } else {
 7688:                 return $env{'user.adv'};
 7689:             }
 7690:         }
 7691:     }
 7692:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 7693:     my %allroles;
 7694:     my ($is_adv,$is_author);
 7695:     foreach my $role (keys(%roleshash)) {
 7696:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 7697:         my $area = '/'.$tdomain.'/'.$trest;
 7698:         if ($sec ne '') {
 7699:             $area .= '/'.$sec;
 7700:         }
 7701:         if (($area ne '') && ($trole ne '')) {
 7702:             my $spec=$trole.'.'.$area;
 7703:             if ($trole =~ /^cr\//) {
 7704:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 7705:             } elsif ($trole ne 'gr') {
 7706:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 7707:             }
 7708:             if ($trole eq 'au') {
 7709:                 $is_author = 1;
 7710:             }
 7711:         }
 7712:     }
 7713:     foreach my $role (keys(%allroles)) {
 7714:         last if ($is_adv);
 7715:         foreach my $item (split(/:/,$allroles{$role})) {
 7716:             if ($item ne '') {
 7717:                 my ($privilege,$restrictions)=split(/&/,$item);
 7718:                 if ($privilege eq 'adv') {
 7719:                     $is_adv = 1;
 7720:                     last;
 7721:                 }
 7722:             }
 7723:         }
 7724:     }
 7725:     if (wantarray) {
 7726:         return ($is_adv,$is_author);
 7727:     }
 7728:     return $is_adv;
 7729: }
 7730: 
 7731: sub check_can_request {
 7732:     my ($dom,$can_request,$request_domains) = @_;
 7733:     my $canreq = 0;
 7734:     my ($types,$typename) = &Apache::loncommon::course_types();
 7735:     my @options = ('approval','validate','autolimit');
 7736:     my $optregex = join('|',@options);
 7737:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
 7738:         foreach my $type (@{$types}) {
 7739:             if (&usertools_access($env{'user.name'},
 7740:                                   $env{'user.domain'},
 7741:                                   $type,undef,'requestcourses')) {
 7742:                 $canreq ++;
 7743:                 if (ref($request_domains) eq 'HASH') {
 7744:                     push(@{$request_domains->{$type}},$env{'user.domain'});
 7745:                 }
 7746:                 if ($dom eq $env{'user.domain'}) {
 7747:                     $can_request->{$type} = 1;
 7748:                 }
 7749:             }
 7750:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
 7751:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
 7752:                 if (@curr > 0) {
 7753:                     foreach my $item (@curr) {
 7754:                         if (ref($request_domains) eq 'HASH') {
 7755:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
 7756:                             if ($otherdom ne '') {
 7757:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
 7758:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
 7759:                                         push(@{$request_domains->{$type}},$otherdom);
 7760:                                     }
 7761:                                 } else {
 7762:                                     push(@{$request_domains->{$type}},$otherdom);
 7763:                                 }
 7764:                             }
 7765:                         }
 7766:                     }
 7767:                     unless($dom eq $env{'user.domain'}) {
 7768:                         $canreq ++;
 7769:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
 7770:                             $can_request->{$type} = 1;
 7771:                         }
 7772:                     }
 7773:                 }
 7774:             }
 7775:         }
 7776:     }
 7777:     return $canreq;
 7778: }
 7779: 
 7780: # ---------------------------------------------- Custom access rule evaluation
 7781: 
 7782: sub customaccess {
 7783:     my ($priv,$uri)=@_;
 7784:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 7785:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 7786:     $udom = &LONCAPA::clean_domain($udom);
 7787:     $ucrs = &LONCAPA::clean_username($ucrs);
 7788:     my $access=0;
 7789:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 7790: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 7791: 	if ($type eq 'user') {
 7792: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 7793: 		my ($tdom,$tuname)=split(m{/},$scope);
 7794: 		if ($tdom) {
 7795: 		    if ($tdom ne $env{'user.domain'}) { next; }
 7796: 		}
 7797: 		if ($tuname) {
 7798: 		    if ($tuname ne $env{'user.name'}) { next; }
 7799: 		}
 7800: 		$access=($effect eq 'allow');
 7801: 		last;
 7802: 	    }
 7803: 	} else {
 7804: 	    if ($role) {
 7805: 		if ($role ne $urole) { next; }
 7806: 	    }
 7807: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 7808: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 7809: 		if ($tdom) {
 7810: 		    if ($tdom ne $udom) { next; }
 7811: 		}
 7812: 		if ($tcrs) {
 7813: 		    if ($tcrs ne $ucrs) { next; }
 7814: 		}
 7815: 		if ($tsec) {
 7816: 		    if ($tsec ne $usec) { next; }
 7817: 		}
 7818: 		$access=($effect eq 'allow');
 7819: 		last;
 7820: 	    }
 7821: 	    if ($realm eq '' && $role eq '') {
 7822: 		$access=($effect eq 'allow');
 7823: 	    }
 7824: 	}
 7825:     }
 7826:     return $access;
 7827: }
 7828: 
 7829: # ------------------------------------------------- Check for a user privilege
 7830: 
 7831: sub allowed {
 7832:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck,$ignorecache)=@_;
 7833:     my $ver_orguri=$uri;
 7834:     $uri=&deversion($uri);
 7835:     my $orguri=$uri;
 7836:     $uri=&declutter($uri);
 7837: 
 7838:     if ($priv eq 'evb') {
 7839: # Evade communication block restrictions for specified role in a course
 7840:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 7841:             return $1;
 7842:         } else {
 7843:             return;
 7844:         }
 7845:     }
 7846: 
 7847:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 7848: # Free bre access to adm and meta resources
 7849:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|viewclasslist|aboutme)$})) 
 7850: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 7851: 	&& ($priv eq 'bre')) {
 7852: 	return 'F';
 7853:     }
 7854: 
 7855: # Free bre access to user's own portfolio contents
 7856:     my ($space,$domain,$name,@dir)=split('/',$uri);
 7857:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 7858: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 7859:         my %setters;
 7860:         my ($startblock,$endblock) = 
 7861:             &Apache::loncommon::blockcheck(\%setters,'port');
 7862:         if ($startblock && $endblock) {
 7863:             return 'B';
 7864:         } else {
 7865:             return 'F';
 7866:         }
 7867:     }
 7868: 
 7869: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 7870:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 7871:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 7872:         if (exists($env{'request.course.id'})) {
 7873:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7874:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7875:             if (($domain eq $cdom) && ($name eq $cnum)) {
 7876:                 my $courseprivid=$env{'request.course.id'};
 7877:                 $courseprivid=~s/\_/\//;
 7878:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 7879:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 7880:                     return $1; 
 7881:                 } else {
 7882:                     if ($env{'request.course.sec'}) {
 7883:                         $courseprivid.='/'.$env{'request.course.sec'};
 7884:                     }
 7885:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 7886:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 7887:                         return $2;
 7888:                     }
 7889:                 }
 7890:             }
 7891:         }
 7892:     }
 7893: 
 7894: # Free bre to public access
 7895: 
 7896:     if ($priv eq 'bre') {
 7897:         my $copyright=&metadata($uri,'copyright');
 7898: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 7899:            return 'F'; 
 7900:         }
 7901:         if ($copyright eq 'priv') {
 7902:             $uri=~/([^\/]+)\/([^\/]+)\//;
 7903: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 7904: 		return '';
 7905:             }
 7906:         }
 7907:         if ($copyright eq 'domain') {
 7908:             $uri=~/([^\/]+)\/([^\/]+)\//;
 7909: 	    unless (($env{'user.domain'} eq $1) ||
 7910:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 7911: 		return '';
 7912:             }
 7913:         }
 7914:         if ($env{'request.role'}=~ /li\.\//) {
 7915:             # Library role, so allow browsing of resources in this domain.
 7916:             return 'F';
 7917:         }
 7918:         if ($copyright eq 'custom') {
 7919: 	    unless (&customaccess($priv,$uri)) { return ''; }
 7920:         }
 7921:     }
 7922:     # Domain coordinator is trying to create a course
 7923:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 7924:         # uri is the requested domain in this case.
 7925:         # comparison to 'request.role.domain' shows if the user has selected
 7926:         # a role of dc for the domain in question.
 7927:         return 'F' if ($uri eq $env{'request.role.domain'});
 7928:     }
 7929: 
 7930:     my $thisallowed='';
 7931:     my $statecond=0;
 7932:     my $courseprivid='';
 7933: 
 7934:     my $ownaccess;
 7935:     # Community Coordinator or Assistant Co-author browsing resource space.
 7936:     if (($priv eq 'bro') && ($env{'user.author'})) {
 7937:         if ($uri eq '') {
 7938:             $ownaccess = 1;
 7939:         } else {
 7940:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
 7941:                 my $udom = $env{'user.domain'};
 7942:                 my $uname = $env{'user.name'};
 7943:                 if ($uri =~ m{^\Q$udom\E/?$}) {
 7944:                     $ownaccess = 1;
 7945:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
 7946:                     unless ($uri =~ m{\.\./}) {
 7947:                         $ownaccess = 1;
 7948:                     }
 7949:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
 7950:                     my $now = time;
 7951:                     if ($uri =~ m{^([^/]+)/?$}) {
 7952:                         my $adom = $1;
 7953:                         foreach my $key (keys(%env)) {
 7954:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
 7955:                                 my ($start,$end) = split('.',$env{$key});
 7956:                                 if (($now >= $start) && (!$end || $end < $now)) {
 7957:                                     $ownaccess = 1;
 7958:                                     last;
 7959:                                 }
 7960:                             }
 7961:                         }
 7962:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
 7963:                         my $adom = $1;
 7964:                         my $aname = $2;
 7965:                         foreach my $role ('ca','aa') { 
 7966:                             if ($env{"user.role.$role./$adom/$aname"}) {
 7967:                                 my ($start,$end) =
 7968:                                     split('.',$env{"user.role.$role./$adom/$aname"});
 7969:                                 if (($now >= $start) && (!$end || $end < $now)) {
 7970:                                     $ownaccess = 1;
 7971:                                     last;
 7972:                                 }
 7973:                             }
 7974:                         }
 7975:                     }
 7976:                 }
 7977:             }
 7978:         }
 7979:     }
 7980: 
 7981: # Course
 7982: 
 7983:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 7984:         unless (($priv eq 'bro') && (!$ownaccess)) {
 7985:             $thisallowed.=$1;
 7986:         }
 7987:     }
 7988: 
 7989: # Domain
 7990: 
 7991:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 7992:        =~/\Q$priv\E\&([^\:]*)/) {
 7993:         unless (($priv eq 'bro') && (!$ownaccess)) {
 7994:             $thisallowed.=$1;
 7995:         }
 7996:     }
 7997: 
 7998: # User who is not author or co-author might still be able to edit
 7999: # resource of an author in the domain (e.g., if Domain Coordinator).
 8000:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
 8001:         (&allowed('mdc',$env{'request.course.id'}))) {
 8002:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
 8003:             $thisallowed.=$1;
 8004:         }
 8005:     }
 8006: 
 8007: # Course: uri itself is a course
 8008:     my $courseuri=$uri;
 8009:     $courseuri=~s/\_(\d)/\/$1/;
 8010:     $courseuri=~s/^([^\/])/\/$1/;
 8011: 
 8012:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 8013:        =~/\Q$priv\E\&([^\:]*)/) {
 8014:         if ($priv eq 'mip') {
 8015:             my $rem = $1;
 8016:             if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
 8017:                 ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
 8018:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8019:                 if ($cdom ne '') {
 8020:                     my %passwdconf = &get_passwdconf($cdom);
 8021:                     if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
 8022:                         if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
 8023:                             if (@{$passwdconf{'crsownerchg'}{'by'}}) {
 8024:                                 my @inststatuses = split(':',$env{'environment.inststatus'});
 8025:                                 unless (@inststatuses) {
 8026:                                     @inststatuses = ('default');
 8027:                                 }
 8028:                                 foreach my $status (@inststatuses) {
 8029:                                     if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
 8030:                                         $thisallowed.=$rem;
 8031:                                     }
 8032:                                 }
 8033:                             }
 8034:                         }
 8035:                     }
 8036:                 }
 8037:             }
 8038:         } else {
 8039:             unless (($priv eq 'bro') && (!$ownaccess)) {
 8040:                 $thisallowed.=$1;
 8041:             }
 8042:         }
 8043:     }
 8044: 
 8045: # URI is an uploaded document for this course, default permissions don't matter
 8046: # not allowing 'edit' access (editupload) to uploaded course docs
 8047:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 8048: 	$thisallowed='';
 8049:         my ($match)=&is_on_map($uri);
 8050:         if ($match) {
 8051:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 8052:                   =~/\Q$priv\E\&([^\:]*)/) {
 8053:                 my $value = $1;
 8054:                 if ($noblockcheck) {
 8055:                     $thisallowed.=$value;
 8056:                 } else {
 8057:                     my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
 8058:                     if (@blockers > 0) {
 8059:                         $thisallowed = 'B';
 8060:                     } else {
 8061:                         $thisallowed.=$value;
 8062:                     }
 8063:                 }
 8064:             }
 8065:         } else {
 8066:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 8067:             if ($refuri) {
 8068:                 if ($refuri =~ m|^/adm/|) {
 8069:                     $thisallowed='F';
 8070:                 } else {
 8071:                     $refuri=&declutter($refuri);
 8072:                     my ($match) = &is_on_map($refuri);
 8073:                     if ($match) {
 8074:                         if ($noblockcheck) {
 8075:                             $thisallowed='F';
 8076:                         } else {
 8077:                             my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
 8078:                             if (@blockers > 0) {
 8079:                                 $thisallowed = 'B';
 8080:                             } else {
 8081:                                 $thisallowed='F';
 8082:                             }
 8083:                         }
 8084:                     }
 8085:                 }
 8086:             }
 8087:         }
 8088:     }
 8089: 
 8090:     if ($priv eq 'bre'
 8091: 	&& $thisallowed ne 'F' 
 8092: 	&& $thisallowed ne '2'
 8093: 	&& &is_portfolio_url($uri)) {
 8094: 	$thisallowed = &portfolio_access($uri,$clientip);
 8095:     }
 8096:     
 8097: # Full access at system, domain or course-wide level? Exit.
 8098:     if ($thisallowed=~/F/) {
 8099: 	return 'F';
 8100:     }
 8101: 
 8102: # If this is generating or modifying users, exit with special codes
 8103: 
 8104:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 8105: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 8106: 	    my ($audom,$auname)=split('/',$uri);
 8107: # no author name given, so this just checks on the general right to make a co-author in this domain
 8108: 	    unless ($auname) { return $thisallowed; }
 8109: # an author name is given, so we are about to actually make a co-author for a certain account
 8110: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 8111: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 8112: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 8113: 	}
 8114: 	return $thisallowed;
 8115:     }
 8116: #
 8117: # Gathered so far: system, domain and course wide privileges
 8118: #
 8119: # Course: See if uri or referer is an individual resource that is part of 
 8120: # the course
 8121: 
 8122:     if ($env{'request.course.id'}) {
 8123: 
 8124: # If this is modifying password (internal auth) domains must match for user and user's role.
 8125: 
 8126:         if ($priv eq 'mip') {
 8127:             if ($env{'user.domain'} eq $env{'request.role.domain'}) {
 8128:                 return $thisallowed;
 8129:             } else {
 8130:                 return '';
 8131:             }
 8132:         }
 8133: 
 8134:        $courseprivid=$env{'request.course.id'};
 8135:        if ($env{'request.course.sec'}) {
 8136:           $courseprivid.='/'.$env{'request.course.sec'};
 8137:        }
 8138:        $courseprivid=~s/\_/\//;
 8139:        my $checkreferer=1;
 8140:        my ($match,$cond)=&is_on_map($uri);
 8141:        if ($match) {
 8142:            $statecond=$cond;
 8143:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 8144:                =~/\Q$priv\E\&([^\:]*)/) {
 8145:                my $value = $1;
 8146:                if ($priv eq 'bre') {
 8147:                    if ($noblockcheck) {
 8148:                        $thisallowed.=$value;
 8149:                    } else {
 8150:                        my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
 8151:                        if (@blockers > 0) {
 8152:                            $thisallowed = 'B';
 8153:                        } else {
 8154:                            $thisallowed.=$value;
 8155:                        }
 8156:                    }
 8157:                } else {
 8158:                    $thisallowed.=$value;
 8159:                }
 8160:                $checkreferer=0;
 8161:            }
 8162:        }
 8163: 
 8164:        if ($checkreferer) {
 8165: 	  my $refuri=$env{'httpref.'.$orguri};
 8166:             unless ($refuri) {
 8167:                 foreach my $key (keys(%env)) {
 8168: 		    if ($key=~/^httpref\..*\*/) {
 8169: 			my $pattern=$key;
 8170:                         $pattern=~s/^httpref\.\/res\///;
 8171:                         $pattern=~s/\*/\[\^\/\]\+/g;
 8172:                         $pattern=~s/\//\\\//g;
 8173:                         if ($orguri=~/$pattern/) {
 8174: 			    $refuri=$env{$key};
 8175:                         }
 8176:                     }
 8177:                 }
 8178:             }
 8179: 
 8180:          if ($refuri) { 
 8181: 	  $refuri=&declutter($refuri);
 8182:           my ($match,$cond)=&is_on_map($refuri);
 8183:             if ($match) {
 8184:               my $refstatecond=$cond;
 8185:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 8186:                   =~/\Q$priv\E\&([^\:]*)/) {
 8187:                   my $value = $1;
 8188:                   if ($priv eq 'bre') {
 8189:                       if ($noblockcheck) {
 8190:                           $thisallowed.=$value;
 8191:                       } else {
 8192:                           my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
 8193:                           if (@blockers > 0) {
 8194:                               $thisallowed = 'B';
 8195:                           } else {
 8196:                               $thisallowed.=$value;
 8197:                           }
 8198:                       }
 8199:                   } else {
 8200:                       $thisallowed.=$value;
 8201:                   }
 8202:                   $uri=$refuri;
 8203:                   $statecond=$refstatecond;
 8204:               }
 8205:           }
 8206:         }
 8207:        }
 8208:    }
 8209: 
 8210: #
 8211: # Gathered now: all privileges that could apply, and condition number
 8212: # 
 8213: #
 8214: # Full or no access?
 8215: #
 8216: 
 8217:     if ($thisallowed=~/F/) {
 8218: 	return 'F';
 8219:     }
 8220: 
 8221:     unless ($thisallowed) {
 8222:         return '';
 8223:     }
 8224: 
 8225: # Restrictions exist, deal with them
 8226: #
 8227: #   C:according to course preferences
 8228: #   R:according to resource settings
 8229: #   L:unless locked
 8230: #   X:according to user session state
 8231: #
 8232: 
 8233: # Possibly locked functionality, check all courses
 8234: # Locks might take effect only after 10 minutes cache expiration for other
 8235: # courses, and 2 minutes for current course
 8236: 
 8237:     my $envkey;
 8238:     if ($thisallowed=~/L/) {
 8239:         foreach $envkey (keys(%env)) {
 8240:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 8241:                my $courseid=$2;
 8242:                my $roleid=$1.'.'.$2;
 8243:                $courseid=~s/^\///;
 8244:                my $expiretime=600;
 8245:                if ($env{'request.role'} eq $roleid) {
 8246: 		  $expiretime=120;
 8247:                }
 8248: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 8249:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 8250:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 8251: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 8252:                }
 8253:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 8254:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 8255: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 8256:                        &log($env{'user.domain'},$env{'user.name'},
 8257:                             $env{'user.home'},
 8258:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 8259:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 8260:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 8261: 		       return '';
 8262:                    }
 8263:                }
 8264:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 8265:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 8266: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 8267:                        &log($env{'user.domain'},$env{'user.name'},
 8268:                             $env{'user.home'},
 8269:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 8270:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 8271:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 8272: 		       return '';
 8273:                    }
 8274:                }
 8275: 	   }
 8276:        }
 8277:     }
 8278: 
 8279: #
 8280: # Rest of the restrictions depend on selected course
 8281: #
 8282: 
 8283:     unless ($env{'request.course.id'}) {
 8284: 	if ($thisallowed eq 'A') {
 8285: 	    return 'A';
 8286:         } elsif ($thisallowed eq 'B') {
 8287:             return 'B';
 8288: 	} else {
 8289: 	    return '1';
 8290: 	}
 8291:     }
 8292: 
 8293: #
 8294: # Now user is definitely in a course
 8295: #
 8296: 
 8297: 
 8298: # Course preferences
 8299: 
 8300:    if ($thisallowed=~/C/) {
 8301:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 8302:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 8303:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 8304: 	   =~/\Q$rolecode\E/) {
 8305: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 8306: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 8307: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 8308: 			$env{'request.course.id'});
 8309: 	   }
 8310:            return '';
 8311:        }
 8312: 
 8313:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 8314: 	   =~/\Q$unamedom\E/) {
 8315: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 8316: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 8317: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 8318: 			$env{'request.course.id'});
 8319: 	   }
 8320:            return '';
 8321:        }
 8322:    }
 8323: 
 8324: # Resource preferences
 8325: 
 8326:    if ($thisallowed=~/R/) {
 8327:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 8328:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 8329: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 8330: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 8331: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 8332: 	   }
 8333: 	   return '';
 8334:        }
 8335:    }
 8336: 
 8337: # Restricted by state or randomout?
 8338: 
 8339:    if ($thisallowed=~/X/) {
 8340:       if ($env{'acc.randomout'}) {
 8341: 	 if (!$symb) { $symb=&symbread($uri,1); }
 8342:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 8343:             return ''; 
 8344:          }
 8345:       }
 8346:       if (&condval($statecond)) {
 8347: 	 return '2';
 8348:       } else {
 8349:          return '';
 8350:       }
 8351:    }
 8352: 
 8353:     if ($thisallowed eq 'A') {
 8354: 	return 'A';
 8355:     } elsif ($thisallowed eq 'B') {
 8356:         return 'B';
 8357:     }
 8358:    return 'F';
 8359: }
 8360: 
 8361: # ------------------------------------------- Check construction space access
 8362: 
 8363: sub constructaccess {
 8364:     my ($url,$setpriv)=@_;
 8365: 
 8366: # We do not allow editing of previous versions of files
 8367:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
 8368: 
 8369: # Get username and domain from URL
 8370:     my ($ownername,$ownerdomain,$ownerhome);
 8371: 
 8372:     ($ownerdomain,$ownername) =
 8373:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)(?:/|$)});
 8374: 
 8375: # The URL does not really point to any authorspace, forget it
 8376:     unless (($ownername) && ($ownerdomain)) { return ''; }
 8377: 
 8378: # Now we need to see if the user has access to the authorspace of
 8379: # $ownername at $ownerdomain
 8380: 
 8381:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
 8382: # Real author for this?
 8383:        $ownerhome = $env{'user.home'};
 8384:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
 8385:           return ($ownername,$ownerdomain,$ownerhome);
 8386:        }
 8387:     } else {
 8388: # Co-author for this?
 8389:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
 8390:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
 8391:             $ownerhome = &homeserver($ownername,$ownerdomain);
 8392:             return ($ownername,$ownerdomain,$ownerhome);
 8393:         }
 8394:     }
 8395: 
 8396: # We don't have any access right now. If we are not possibly going to do anything about this,
 8397: # we might as well leave
 8398:    unless ($setpriv) { return ''; }
 8399: 
 8400: # Backdoor access?
 8401:     my $allowed=&allowed('eco',$ownerdomain);
 8402: # Nope
 8403:     unless ($allowed) { return ''; }
 8404: # Looks like we may have access, but could be locked by the owner of the construction space
 8405:     if ($allowed eq 'U') {
 8406:         my %blocked=&get('environment',['domcoord.author'],
 8407:                          $ownerdomain,$ownername);
 8408: # Is blocked by owner
 8409:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
 8410:     }
 8411:     if (($allowed eq 'F') || ($allowed eq 'U')) {
 8412: # Grant temporary access
 8413:         my $then=$env{'user.login.time'};
 8414:         my $update=$env{'user.update.time'};
 8415:         if (!$update) { $update = $then; }
 8416:         my $refresh=$env{'user.refresh.time'};
 8417:         if (!$refresh) { $refresh = $update; }
 8418:         my $now = time;
 8419:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
 8420:                            $now,'ca','constructaccess');
 8421:         $ownerhome = &homeserver($ownername,$ownerdomain);
 8422:         return($ownername,$ownerdomain,$ownerhome);
 8423:     }
 8424: # No business here
 8425:     return '';
 8426: }
 8427: 
 8428: # ----------------------------------------------------------- Content Blocking
 8429: 
 8430: {
 8431: # Caches for faster Course Contents display where content blocking
 8432: # is in operation (i.e., interval param set) for timed quiz.
 8433: #
 8434: # User for whom data are being temporarily cached.
 8435: my $cacheduser='';
 8436: # Course for which data are being temporarily cached.
 8437: my $cachedcid='';
 8438: # Cached blockers for this user (a hash of blocking items).
 8439: my %cachedblockers=();
 8440: # When the data were last cached.
 8441: my $cachedlast='';
 8442: 
 8443: sub load_all_blockers {
 8444:     my ($uname,$udom)=@_;
 8445:     if (($uname ne '') && ($udom ne '')) {
 8446:         if (($cacheduser eq $uname.':'.$udom) &&
 8447:             ($cachedcid eq $env{'request.course.id'}) &&
 8448:             (abs($cachedlast-time)<5)) {
 8449:             return;
 8450:         }
 8451:     }
 8452:     $cachedlast=time;
 8453:     $cacheduser=$uname.':'.$udom;
 8454:     $cachedcid=$env{'request.course.id'};
 8455:     %cachedblockers = &get_commblock_resources();
 8456:     return;
 8457: }
 8458: 
 8459: sub get_comm_blocks {
 8460:     my ($cdom,$cnum) = @_;
 8461:     if ($cdom eq '' || $cnum eq '') {
 8462:         return unless ($env{'request.course.id'});
 8463:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8464:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8465:     }
 8466:     my %commblocks;
 8467:     my $hashid=$cdom.'_'.$cnum;
 8468:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
 8469:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
 8470:         %commblocks = %{$blocksref};
 8471:     } else {
 8472:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
 8473:         my $cachetime = 600;
 8474:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
 8475:     }
 8476:     return %commblocks;
 8477: }
 8478: 
 8479: sub get_commblock_resources {
 8480:     my ($blocks) = @_;
 8481:     my %blockers = ();
 8482:     return %blockers unless ($env{'request.course.id'});
 8483:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 8484:     my %commblocks;
 8485:     if (ref($blocks) eq 'HASH') {
 8486:         %commblocks = %{$blocks};
 8487:     } else {
 8488:         %commblocks = &get_comm_blocks();
 8489:     }
 8490:     return %blockers unless (keys(%commblocks) > 0);
 8491:     my $navmap = Apache::lonnavmaps::navmap->new();
 8492:     return %blockers unless (ref($navmap));
 8493:     my $now = time;
 8494:     foreach my $block (keys(%commblocks)) {
 8495:         if ($block =~ /^(\d+)____(\d+)$/) {
 8496:             my ($start,$end) = ($1,$2);
 8497:             if ($start <= $now && $end >= $now) {
 8498:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 8499:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 8500:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 8501:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 8502:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
 8503:                             }
 8504:                         }
 8505:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 8506:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 8507:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 8508:                             }
 8509:                         }
 8510:                     }
 8511:                 }
 8512:             }
 8513:         } elsif ($block =~ /^firstaccess____(.+)$/) {
 8514:             my $item = $1;
 8515:             my @to_test;
 8516:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 8517:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 8518:                     my @interval;
 8519:                     my $type = 'map';
 8520:                     if ($item eq 'course') {
 8521:                         $type = 'course';
 8522:                         @interval=&EXT("resource.0.interval");
 8523:                     } else {
 8524:                         if ($item =~ /___\d+___/) {
 8525:                             $type = 'resource';
 8526:                             @interval=&EXT("resource.0.interval",$item);
 8527:                             if (ref($navmap)) {
 8528:                                 my $res = $navmap->getBySymb($item);
 8529:                                 push(@to_test,$res);
 8530:                             }
 8531:                         } else {
 8532:                             my $mapsymb = &symbread($item,1);
 8533:                             if ($mapsymb) {
 8534:                                 if (ref($navmap)) {
 8535:                                     my $mapres = $navmap->getBySymb($mapsymb);
 8536:                                     if (ref($mapres)) {
 8537:                                         my $first = $mapres->map_start();
 8538:                                         my $finish = $mapres->map_finish();
 8539:                                         my $it = $navmap->getIterator($first,$finish,undef,0,0);
 8540:                                         if (ref($it)) {
 8541:                                             my $res;
 8542:                                             while ($res = $it->next(undef,1)) {
 8543:                                                 next unless (ref($res));
 8544:                                                 my $symb = $res->symb();
 8545:                                                 next if (($symb eq $mapsymb) || ($symb eq ''));
 8546:                                                 @interval=&EXT("resource.0.interval",$symb);
 8547:                                                 if ($interval[1] eq 'map') {
 8548:                                                     if ($res->answerable()) {
 8549:                                                         push(@to_test,$res);
 8550:                                                         last;
 8551:                                                     }
 8552:                                                 }
 8553:                                             }
 8554:                                         }
 8555:                                     }
 8556:                                 }
 8557:                             }
 8558:                         }
 8559:                     }
 8560:                     if ($interval[0] =~ /^\d+$/) {
 8561:                         my $first_access;
 8562:                         if ($type eq 'resource') {
 8563:                             $first_access=&get_first_access($interval[1],$item);
 8564:                         } elsif ($type eq 'map') {
 8565:                             $first_access=&get_first_access($interval[1],undef,$item);
 8566:                         } else {
 8567:                             $first_access=&get_first_access($interval[1]);
 8568:                         }
 8569:                         if ($first_access) {
 8570:                             my $timesup = $first_access+$interval[0];
 8571:                             if ($timesup > $now) {
 8572:                                 my $activeblock;
 8573:                                 foreach my $res (@to_test) {
 8574:                                     if ($res->answerable()) {
 8575:                                         $activeblock = 1;
 8576:                                         last;
 8577:                                     }
 8578:                                 }
 8579:                                 if ($activeblock) {
 8580:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 8581:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 8582:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
 8583:                                          }
 8584:                                     }
 8585:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 8586:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 8587:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 8588:                                         }
 8589:                                     }
 8590:                                 }
 8591:                             }
 8592:                         }
 8593:                     }
 8594:                 }
 8595:             }
 8596:         }
 8597:     }
 8598:     return %blockers;
 8599: }
 8600: 
 8601: sub has_comm_blocking {
 8602:     my ($priv,$symb,$uri,$ignoresymbdb,$noenccheck,$blocked,$blocks) = @_;
 8603:     my @blockers;
 8604:     return unless ($env{'request.course.id'});
 8605:     return unless ($priv eq 'bre');
 8606:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 8607:     return if ($env{'request.state'} eq 'construct');
 8608:     my %blockinfo;
 8609:     if (ref($blocks) eq 'HASH') {
 8610:         %blockinfo = &get_commblock_resources($blocks);
 8611:     } else {
 8612:         &load_all_blockers($env{'user.name'},$env{'user.domain'});
 8613:         %blockinfo = %cachedblockers;
 8614:     }
 8615:     return unless (keys(%blockinfo) > 0);
 8616:     my (%possibles,@symbs);
 8617:     if (!$symb) {
 8618:         $symb = &symbread($uri,1,1,1,\%possibles,$ignoresymbdb,$noenccheck);
 8619:     }
 8620:     if ($symb) {
 8621:         @symbs = ($symb);
 8622:     } elsif (keys(%possibles)) {
 8623:         @symbs = keys(%possibles);
 8624:     }
 8625:     my $noblock;
 8626:     foreach my $symb (@symbs) {
 8627:         last if ($noblock);
 8628:         my ($map,$resid,$resurl)=&decode_symb($symb);
 8629:         foreach my $block (keys(%blockinfo)) {
 8630:             if ($block =~ /^firstaccess____(.+)$/) {
 8631:                 my $item = $1;
 8632:                 unless ($blocked) {
 8633:                     if (($item eq $map) || ($item eq $symb)) {
 8634:                         $noblock = 1;
 8635:                         last;
 8636:                     }
 8637:                 }
 8638:             }
 8639:             if (ref($blockinfo{$block}) eq 'HASH') {
 8640:                 if (ref($blockinfo{$block}{'resources'}) eq 'HASH') {
 8641:                     if ($blockinfo{$block}{'resources'}{$symb}) {
 8642:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 8643:                             push(@blockers,$block);
 8644:                         }
 8645:                     }
 8646:                 }
 8647:                 if (ref($blockinfo{$block}{'maps'}) eq 'HASH') {
 8648:                     if ($blockinfo{$block}{'maps'}{$map}) {
 8649:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 8650:                             push(@blockers,$block);
 8651:                         }
 8652:                     }
 8653:                 }
 8654:             }
 8655:         }
 8656:     }
 8657:     unless ($noblock) {
 8658:         return @blockers;
 8659:     }
 8660:     return;
 8661: }
 8662: }
 8663: 
 8664: # -------------------------------- Deversion and split uri into path an filename
 8665: 
 8666: #
 8667: #   Removes the version from a URI and
 8668: #   splits it in to its filename and path to the filename.
 8669: #   Seems like File::Basename could have done this more clearly.
 8670: #   Parameters:
 8671: #      $uri   - input URI
 8672: #   Returns:
 8673: #     Two element list consisting of 
 8674: #     $pathname  - the URI up to and excluding the trailing /
 8675: #     $filename  - The part of the URI following the last /
 8676: #  NOTE:
 8677: #    Another realization of this is simply:
 8678: #    use File::Basename;
 8679: #    ...
 8680: #    $uri = shift;
 8681: #    $filename = basename($uri);
 8682: #    $path     = dirname($uri);
 8683: #    return ($filename, $path);
 8684: #
 8685: #     The implementation below is probably faster however.
 8686: #
 8687: sub split_uri_for_cond {
 8688:     my $uri=&deversion(&declutter(shift));
 8689:     my @uriparts=split(/\//,$uri);
 8690:     my $filename=pop(@uriparts);
 8691:     my $pathname=join('/',@uriparts);
 8692:     return ($pathname,$filename);
 8693: }
 8694: # --------------------------------------------------- Is a resource on the map?
 8695: 
 8696: sub is_on_map {
 8697:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 8698:     #Trying to find the conditional for the file
 8699:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 8700: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 8701:     if ($match) {
 8702: 	return (1,$1);
 8703:     } else {
 8704: 	return (0,0);
 8705:     }
 8706: }
 8707: 
 8708: # --------------------------------------------------------- Get symb from alias
 8709: 
 8710: sub get_symb_from_alias {
 8711:     my $symb=shift;
 8712:     my ($map,$resid,$url)=&decode_symb($symb);
 8713: # Already is a symb
 8714:     if ($url) { return $symb; }
 8715: # Must be an alias
 8716:     my $aliassymb='';
 8717:     my %bighash;
 8718:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 8719:                             &GDBM_READER(),0640)) {
 8720:         my $rid=$bighash{'mapalias_'.$symb};
 8721: 	if ($rid) {
 8722: 	    my ($mapid,$resid)=split(/\./,$rid);
 8723: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 8724: 				    $resid,$bighash{'src_'.$rid});
 8725: 	}
 8726:         untie %bighash;
 8727:     }
 8728:     return $aliassymb;
 8729: }
 8730: 
 8731: # ----------------------------------------------------------------- Define Role
 8732: 
 8733: sub definerole {
 8734:   if (allowed('mcr','/')) {
 8735:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
 8736:     foreach my $role (split(':',$sysrole)) {
 8737: 	my ($crole,$cqual)=split(/\&/,$role);
 8738:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 8739:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 8740: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 8741:                return "refused:s:$crole&$cqual"; 
 8742:             }
 8743:         }
 8744:     }
 8745:     foreach my $role (split(':',$domrole)) {
 8746: 	my ($crole,$cqual)=split(/\&/,$role);
 8747:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 8748:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 8749: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 8750:                return "refused:d:$crole&$cqual"; 
 8751:             }
 8752:         }
 8753:     }
 8754:     foreach my $role (split(':',$courole)) {
 8755: 	my ($crole,$cqual)=split(/\&/,$role);
 8756:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 8757:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 8758: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 8759:                return "refused:c:$crole&$cqual"; 
 8760:             }
 8761:         }
 8762:     }
 8763:     my $uhome;
 8764:     if (($uname ne '') && ($udom ne '')) {
 8765:         $uhome = &homeserver($uname,$udom);
 8766:         return $uhome if ($uhome eq 'no_host');
 8767:     } else {
 8768:         $uname = $env{'user.name'};
 8769:         $udom = $env{'user.domain'};
 8770:         $uhome = $env{'user.home'};
 8771:     }
 8772:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 8773:                 "$udom:$uname:rolesdef_$rolename=".
 8774:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 8775:     return reply($command,$uhome);
 8776:   } else {
 8777:     return 'refused';
 8778:   }
 8779: }
 8780: 
 8781: # ---------------- Make a metadata query against the network of library servers
 8782: 
 8783: sub metadata_query {
 8784:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
 8785:     my %rhash;
 8786:     my %libserv = &all_library();
 8787:     my @server_list = (defined($server_array) ? @$server_array
 8788:                                               : keys(%libserv) );
 8789:     for my $server (@server_list) {
 8790:         my $domains = '';
 8791:         if (ref($domains_hash) eq 'HASH') {
 8792:             $domains = $domains_hash->{$server};    
 8793:         }
 8794: 	unless ($custom or $customshow) {
 8795: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
 8796: 	    $rhash{$server}=$reply;
 8797: 	}
 8798: 	else {
 8799: 	    my $reply=&reply("querysend:".&escape($query).':'.
 8800: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
 8801: 			     $server);
 8802: 	    $rhash{$server}=$reply;
 8803: 	}
 8804:     }
 8805:     return \%rhash;
 8806: }
 8807: 
 8808: # ----------------------------------------- Send log queries and wait for reply
 8809: 
 8810: sub log_query {
 8811:     my ($uname,$udom,$query,%filters)=@_;
 8812:     my $uhome=&homeserver($uname,$udom);
 8813:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 8814:     my $uhost=&hostname($uhome);
 8815:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 8816:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 8817:                        $uhome);
 8818:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 8819:     return get_query_reply($queryid);
 8820: }
 8821: 
 8822: # -------------------------- Update MySQL table for portfolio file
 8823: 
 8824: sub update_portfolio_table {
 8825:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 8826:     if ($group ne '') {
 8827:         $file_name =~s /^\Q$group\E//;
 8828:     }
 8829:     my $homeserver = &homeserver($uname,$udom);
 8830:     my $queryid=
 8831:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 8832:                ':'.&escape($file_name).':'.$action,$homeserver);
 8833:     my $reply = &get_query_reply($queryid);
 8834:     return $reply;
 8835: }
 8836: 
 8837: # -------------------------- Update MySQL allusers table
 8838: 
 8839: sub update_allusers_table {
 8840:     my ($uname,$udom,$names) = @_;
 8841:     my $homeserver = &homeserver($uname,$udom);
 8842:     my $queryid=
 8843:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 8844:                'lastname='.&escape($names->{'lastname'}).'%%'.
 8845:                'firstname='.&escape($names->{'firstname'}).'%%'.
 8846:                'middlename='.&escape($names->{'middlename'}).'%%'.
 8847:                'generation='.&escape($names->{'generation'}).'%%'.
 8848:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 8849:                'id='.&escape($names->{'id'}),$homeserver);
 8850:     return;
 8851: }
 8852: 
 8853: # ------- Request retrieval of institutional classlists for course(s)
 8854: 
 8855: sub fetch_enrollment_query {
 8856:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 8857:     my ($homeserver,$sleep,$loopmax);
 8858:     my $maxtries = 1;
 8859:     if ($context eq 'automated') {
 8860:         $homeserver = $perlvar{'lonHostID'};
 8861:         $sleep = 2;
 8862:         $loopmax = 100;
 8863:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 8864:     } else {
 8865:         $homeserver = &homeserver($cnum,$dom);
 8866:     }
 8867:     my $host=&hostname($homeserver);
 8868:     my $cmd = '';
 8869:     foreach my $affiliate (keys(%{$affiliatesref})) {
 8870:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 8871:     }
 8872:     $cmd =~ s/%%$//;
 8873:     $cmd = &escape($cmd);
 8874:     my $query = 'fetchenrollment';
 8875:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 8876:     unless ($queryid=~/^\Q$host\E\_/) { 
 8877:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 8878:         return 'error: '.$queryid;
 8879:     }
 8880:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
 8881:     my $tries = 1;
 8882:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 8883:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
 8884:         $tries ++;
 8885:     }
 8886:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 8887:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 8888:     } else {
 8889:         my @responses = split(/:/,$reply);
 8890:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
 8891:             foreach my $line (@responses) {
 8892:                 my ($key,$value) = split(/=/,$line,2);
 8893:                 $$replyref{$key} = $value;
 8894:             }
 8895:         } else {
 8896:             my $pathname = LONCAPA::tempdir();
 8897:             foreach my $line (@responses) {
 8898:                 my ($key,$value) = split(/=/,$line);
 8899:                 $$replyref{$key} = $value;
 8900:                 if ($value > 0) {
 8901:                     foreach my $item (@{$$affiliatesref{$key}}) {
 8902:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 8903:                         my $destname = $pathname.'/'.$filename;
 8904:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 8905:                         if ($xml_classlist =~ /^error/) {
 8906:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 8907:                         } else {
 8908:                             if ( open(FILE,">",$destname) ) {
 8909:                                 print FILE &unescape($xml_classlist);
 8910:                                 close(FILE);
 8911:                             } else {
 8912:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 8913:                             }
 8914:                         }
 8915:                     }
 8916:                 }
 8917:             }
 8918:         }
 8919:         return 'ok';
 8920:     }
 8921:     return 'error';
 8922: }
 8923: 
 8924: sub get_query_reply {
 8925:     my ($queryid,$sleep,$loopmax) = @_;
 8926:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
 8927:         $sleep = 0.2;
 8928:     }
 8929:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
 8930:         $loopmax = 100;
 8931:     }
 8932:     my $replyfile=LONCAPA::tempdir().$queryid;
 8933:     my $reply='';
 8934:     for (1..$loopmax) {
 8935: 	sleep($sleep);
 8936:         if (-e $replyfile.'.end') {
 8937: 	    if (open(my $fh,"<",$replyfile)) {
 8938: 		$reply = join('',<$fh>);
 8939: 		close($fh);
 8940: 	   } else { return 'error: reply_file_error'; }
 8941:            return &unescape($reply);
 8942: 	}
 8943:     }
 8944:     return 'timeout:'.$queryid;
 8945: }
 8946: 
 8947: sub courselog_query {
 8948: #
 8949: # possible filters:
 8950: # url: url or symb
 8951: # username
 8952: # domain
 8953: # action: view, submit, grade
 8954: # start: timestamp
 8955: # end: timestamp
 8956: #
 8957:     my (%filters)=@_;
 8958:     unless ($env{'request.course.id'}) { return 'no_course'; }
 8959:     if ($filters{'url'}) {
 8960: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 8961:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 8962:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 8963:     }
 8964:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 8965:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 8966:     return &log_query($cname,$cdom,'courselog',%filters);
 8967: }
 8968: 
 8969: sub userlog_query {
 8970: #
 8971: # possible filters:
 8972: # action: log check role
 8973: # start: timestamp
 8974: # end: timestamp
 8975: #
 8976:     my ($uname,$udom,%filters)=@_;
 8977:     return &log_query($uname,$udom,'userlog',%filters);
 8978: }
 8979: 
 8980: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 8981: 
 8982: sub auto_run {
 8983:     my ($cnum,$cdom) = @_;
 8984:     my $response = 0;
 8985:     my $settings;
 8986:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 8987:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 8988:         $settings = $domconfig{'autoenroll'};
 8989:         if ($settings->{'run'} eq '1') {
 8990:             $response = 1;
 8991:         }
 8992:     } else {
 8993:         my $homeserver;
 8994:         if (&is_course($cdom,$cnum)) {
 8995:             $homeserver = &homeserver($cnum,$cdom);
 8996:         } else {
 8997:             $homeserver = &domain($cdom,'primary');
 8998:         }
 8999:         if ($homeserver ne 'no_host') {
 9000:             $response = &reply('autorun:'.$cdom,$homeserver);
 9001:         }
 9002:     }
 9003:     return $response;
 9004: }
 9005: 
 9006: sub auto_get_sections {
 9007:     my ($cnum,$cdom,$inst_coursecode) = @_;
 9008:     my $homeserver;
 9009:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
 9010:         $homeserver = &homeserver($cnum,$cdom);
 9011:     }
 9012:     if (!defined($homeserver)) { 
 9013:         if ($cdom =~ /^$match_domain$/) {
 9014:             $homeserver = &domain($cdom,'primary');
 9015:         }
 9016:     }
 9017:     my @secs;
 9018:     if (defined($homeserver)) {
 9019:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 9020:         unless ($response eq 'refused') {
 9021:             @secs = split(/:/,$response);
 9022:         }
 9023:     }
 9024:     return @secs;
 9025: }
 9026: 
 9027: sub auto_new_course {
 9028:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
 9029:     my $homeserver = &homeserver($cnum,$cdom);
 9030:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
 9031:     return $response;
 9032: }
 9033: 
 9034: sub auto_validate_courseID {
 9035:     my ($cnum,$cdom,$inst_course_id) = @_;
 9036:     my $homeserver = &homeserver($cnum,$cdom);
 9037:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 9038:     return $response;
 9039: }
 9040: 
 9041: sub auto_validate_instcode {
 9042:     my ($cnum,$cdom,$instcode,$owner) = @_;
 9043:     my ($homeserver,$response);
 9044:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 9045:         $homeserver = &homeserver($cnum,$cdom);
 9046:     }
 9047:     if (!defined($homeserver)) {
 9048:         if ($cdom =~ /^$match_domain$/) {
 9049:             $homeserver = &domain($cdom,'primary');
 9050:         }
 9051:     }
 9052:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
 9053:                         &escape($instcode).':'.&escape($owner),$homeserver));
 9054:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
 9055:     return ($outcome,$description,$defaultcredits);
 9056: }
 9057: 
 9058: sub auto_create_password {
 9059:     my ($cnum,$cdom,$authparam,$udom) = @_;
 9060:     my ($homeserver,$response);
 9061:     my $create_passwd = 0;
 9062:     my $authchk = '';
 9063:     if ($udom =~ /^$match_domain$/) {
 9064:         $homeserver = &domain($udom,'primary');
 9065:     }
 9066:     if ($homeserver eq '') {
 9067:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 9068:             $homeserver = &homeserver($cnum,$cdom);
 9069:         }
 9070:     }
 9071:     if ($homeserver eq '') {
 9072:         $authchk = 'nodomain';
 9073:     } else {
 9074:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 9075:         if ($response eq 'refused') {
 9076:             $authchk = 'refused';
 9077:         } else {
 9078:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 9079:         }
 9080:     }
 9081:     return ($authparam,$create_passwd,$authchk);
 9082: }
 9083: 
 9084: sub auto_photo_permission {
 9085:     my ($cnum,$cdom,$students) = @_;
 9086:     my $homeserver = &homeserver($cnum,$cdom);
 9087:     my ($outcome,$perm_reqd,$conditions) = 
 9088: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 9089:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 9090: 	return (undef,undef);
 9091:     }
 9092:     return ($outcome,$perm_reqd,$conditions);
 9093: }
 9094: 
 9095: sub auto_checkphotos {
 9096:     my ($uname,$udom,$pid) = @_;
 9097:     my $homeserver = &homeserver($uname,$udom);
 9098:     my ($result,$resulttype);
 9099:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 9100: 				   &escape($uname).':'.&escape($pid),
 9101: 				   $homeserver));
 9102:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 9103: 	return (undef,undef);
 9104:     }
 9105:     if ($outcome) {
 9106:         ($result,$resulttype) = split(/:/,$outcome);
 9107:     } 
 9108:     return ($result,$resulttype);
 9109: }
 9110: 
 9111: sub auto_photochoice {
 9112:     my ($cnum,$cdom) = @_;
 9113:     my $homeserver = &homeserver($cnum,$cdom);
 9114:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 9115: 						       &escape($cdom),
 9116: 						       $homeserver)));
 9117:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 9118: 	return (undef,undef);
 9119:     }
 9120:     return ($update,$comment);
 9121: }
 9122: 
 9123: sub auto_photoupdate {
 9124:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 9125:     my $homeserver = &homeserver($cnum,$dom);
 9126:     my $host=&hostname($homeserver);
 9127:     my $cmd = '';
 9128:     my $maxtries = 1;
 9129:     foreach my $affiliate (keys(%{$affiliatesref})) {
 9130:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 9131:     }
 9132:     $cmd =~ s/%%$//;
 9133:     $cmd = &escape($cmd);
 9134:     my $query = 'institutionalphotos';
 9135:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 9136:     unless ($queryid=~/^\Q$host\E\_/) {
 9137:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 9138:         return 'error: '.$queryid;
 9139:     }
 9140:     my $reply = &get_query_reply($queryid);
 9141:     my $tries = 1;
 9142:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 9143:         $reply = &get_query_reply($queryid);
 9144:         $tries ++;
 9145:     }
 9146:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 9147:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 9148:     } else {
 9149:         my @responses = split(/:/,$reply);
 9150:         my $outcome = shift(@responses); 
 9151:         foreach my $item (@responses) {
 9152:             my ($key,$value) = split(/=/,$item);
 9153:             $$photo{$key} = $value;
 9154:         }
 9155:         return $outcome;
 9156:     }
 9157:     return 'error';
 9158: }
 9159: 
 9160: sub auto_instcode_format {
 9161:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 9162: 	$cat_order) = @_;
 9163:     my $courses = '';
 9164:     my @homeservers;
 9165:     if ($caller eq 'global') {
 9166: 	my %servers = &get_servers($codedom,'library');
 9167: 	foreach my $tryserver (keys(%servers)) {
 9168: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 9169: 		push(@homeservers,$tryserver);
 9170: 	    }
 9171:         }
 9172:     } elsif ($caller eq 'requests') {
 9173:         if ($codedom =~ /^$match_domain$/) {
 9174:             my $chome = &domain($codedom,'primary');
 9175:             unless ($chome eq 'no_host') {
 9176:                 push(@homeservers,$chome);
 9177:             }
 9178:         }
 9179:     } else {
 9180:         push(@homeservers,&homeserver($caller,$codedom));
 9181:     }
 9182:     foreach my $code (keys(%{$instcodes})) {
 9183:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 9184:     }
 9185:     chop($courses);
 9186:     my $ok_response = 0;
 9187:     my $response;
 9188:     while (@homeservers > 0 && $ok_response == 0) {
 9189:         my $server = shift(@homeservers); 
 9190:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 9191:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 9192:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 9193: 		split(/:/,$response);
 9194:             %{$codes} = (%{$codes},&str2hash($codes_str));
 9195:             push(@{$codetitles},&str2array($codetitles_str));
 9196:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 9197:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 9198:             $ok_response = 1;
 9199:         }
 9200:     }
 9201:     if ($ok_response) {
 9202:         return 'ok';
 9203:     } else {
 9204:         return $response;
 9205:     }
 9206: }
 9207: 
 9208: sub auto_instcode_defaults {
 9209:     my ($domain,$returnhash,$code_order) = @_;
 9210:     my @homeservers;
 9211: 
 9212:     my %servers = &get_servers($domain,'library');
 9213:     foreach my $tryserver (keys(%servers)) {
 9214: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 9215: 	    push(@homeservers,$tryserver);
 9216: 	}
 9217:     }
 9218: 
 9219:     my $response;
 9220:     foreach my $server (@homeservers) {
 9221:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 9222:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 9223: 	
 9224: 	foreach my $pair (split(/\&/,$response)) {
 9225: 	    my ($name,$value)=split(/\=/,$pair);
 9226: 	    if ($name eq 'code_order') {
 9227: 		@{$code_order} = split(/\&/,&unescape($value));
 9228: 	    } else {
 9229: 		$returnhash->{&unescape($name)}=&unescape($value);
 9230: 	    }
 9231: 	}
 9232: 	return 'ok';
 9233:     }
 9234: 
 9235:     return $response;
 9236: }
 9237: 
 9238: sub auto_possible_instcodes {
 9239:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
 9240:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
 9241:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 9242:         return;
 9243:     }
 9244:     my (@homeservers,$uhome);
 9245:     if (defined(&domain($domain,'primary'))) {
 9246:         $uhome=&domain($domain,'primary');
 9247:         push(@homeservers,&domain($domain,'primary'));
 9248:     } else {
 9249:         my %servers = &get_servers($domain,'library');
 9250:         foreach my $tryserver (keys(%servers)) {
 9251:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 9252:                 push(@homeservers,$tryserver);
 9253:             }
 9254:         }
 9255:     }
 9256:     my $response;
 9257:     foreach my $server (@homeservers) {
 9258:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
 9259:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 9260:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
 9261:             split(':',$response);
 9262:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
 9263:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
 9264:         foreach my $item (split('&',$cat_title)) {   
 9265:             my ($name,$value)=split('=',$item);
 9266:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
 9267:         }
 9268:         foreach my $item (split('&',$cat_order)) {
 9269:             my ($name,$value)=split('=',$item);
 9270:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
 9271:         }
 9272:         return 'ok';
 9273:     }
 9274:     return $response;
 9275: }
 9276: 
 9277: sub auto_courserequest_checks {
 9278:     my ($dom) = @_;
 9279:     my ($homeserver,%validations);
 9280:     if ($dom =~ /^$match_domain$/) {
 9281:         $homeserver = &domain($dom,'primary');
 9282:     }
 9283:     unless ($homeserver eq 'no_host') {
 9284:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
 9285:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 9286:             my @items = split(/&/,$response);
 9287:             foreach my $item (@items) {
 9288:                 my ($key,$value) = split('=',$item);
 9289:                 $validations{&unescape($key)} = &thaw_unescape($value);
 9290:             }
 9291:         }
 9292:     }
 9293:     return %validations; 
 9294: }
 9295: 
 9296: sub auto_courserequest_validation {
 9297:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
 9298:     my ($homeserver,$response);
 9299:     if ($dom =~ /^$match_domain$/) {
 9300:         $homeserver = &domain($dom,'primary');
 9301:     }
 9302:     unless ($homeserver eq 'no_host') {
 9303:         my $customdata;
 9304:         if (ref($custominfo) eq 'HASH') {
 9305:             $customdata = &freeze_escape($custominfo);
 9306:         }
 9307:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
 9308:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
 9309:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
 9310:                                     $customdata,$homeserver));
 9311:     }
 9312:     return $response;
 9313: }
 9314: 
 9315: sub auto_validate_class_sec {
 9316:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 9317:     my $homeserver = &homeserver($cnum,$cdom);
 9318:     my $ownerlist;
 9319:     if (ref($owners) eq 'ARRAY') {
 9320:         $ownerlist = join(',',@{$owners});
 9321:     } else {
 9322:         $ownerlist = $owners;
 9323:     }
 9324:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 9325:                         &escape($ownerlist).':'.$cdom,$homeserver);
 9326:     return $response;
 9327: }
 9328: 
 9329: sub auto_validate_instclasses {
 9330:     my ($cdom,$cnum,$owners,$classesref) = @_;
 9331:     my ($homeserver,%validations);
 9332:     $homeserver = &homeserver($cnum,$cdom);
 9333:     unless ($homeserver eq 'no_host') {
 9334:         my $ownerlist;
 9335:         if (ref($owners) eq 'ARRAY') {
 9336:             $ownerlist = join(',',@{$owners});
 9337:         } else {
 9338:             $ownerlist = $owners;
 9339:         }
 9340:         if (ref($classesref) eq 'HASH') {
 9341:             my $classes = &freeze_escape($classesref);
 9342:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
 9343:                                 ':'.$cdom.':'.$classes,$homeserver);
 9344:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 9345:                 my @items = split(/&/,$response);
 9346:                 foreach my $item (@items) {
 9347:                     my ($key,$value) = split('=',$item);
 9348:                     $validations{&unescape($key)} = &thaw_unescape($value);
 9349:                 }
 9350:             }
 9351:         }
 9352:     }
 9353:     return %validations;
 9354: }
 9355: 
 9356: sub auto_crsreq_update {
 9357:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
 9358:         $code,$accessstart,$accessend,$inbound) = @_;
 9359:     my ($homeserver,%crsreqresponse);
 9360:     if ($cdom =~ /^$match_domain$/) {
 9361:         $homeserver = &domain($cdom,'primary');
 9362:     }
 9363:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
 9364:         my $info;
 9365:         if (ref($inbound) eq 'HASH') {
 9366:             $info = &freeze_escape($inbound);
 9367:         }
 9368:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
 9369:                             ':'.&escape($action).':'.&escape($ownername).':'.
 9370:                             &escape($ownerdomain).':'.&escape($fullname).':'.
 9371:                             &escape($title).':'.&escape($code).':'.
 9372:                             &escape($accessstart).':'.&escape($accessend).':'.$info,$homeserver);
 9373:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 9374:             my @items = split(/&/,$response);
 9375:             foreach my $item (@items) {
 9376:                 my ($key,$value) = split('=',$item);
 9377:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
 9378:             }
 9379:         }
 9380:     }
 9381:     return \%crsreqresponse;
 9382: }
 9383: 
 9384: sub auto_export_grades {
 9385:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
 9386:     my ($homeserver,%exportresponse);
 9387:     if ($cdom =~ /^$match_domain$/) {
 9388:         $homeserver = &domain($cdom,'primary');
 9389:     }
 9390:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
 9391:         my $info;
 9392:         if (ref($inforef) eq 'HASH') {
 9393:             $info = &freeze_escape($inforef);
 9394:         }
 9395:         if (ref($gradesref) eq 'HASH') {
 9396:             my $grades = &freeze_escape($gradesref);
 9397:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
 9398:                                 $info.':'.$grades,$homeserver);
 9399:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
 9400:                 my @items = split(/&/,$response);
 9401:                 foreach my $item (@items) {
 9402:                     my ($key,$value) = split('=',$item);
 9403:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
 9404:                 }
 9405:             }
 9406:         }
 9407:     }
 9408:     return \%exportresponse;
 9409: }
 9410: 
 9411: sub check_instcode_cloning {
 9412:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
 9413:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 9414:         return;
 9415:     }
 9416:     my $canclone;
 9417:     if (@{$code_order} > 0) {
 9418:         my $instcoderegexp ='^';
 9419:         my @clonecodes = split(/\&/,$cloner);
 9420:         foreach my $item (@{$code_order}) {
 9421:             if (grep(/^\Q$item\E=/,@clonecodes)) {
 9422:                 foreach my $pair (@clonecodes) {
 9423:                     my ($key,$val) = split(/\=/,$pair,2);
 9424:                     $val = &unescape($val);
 9425:                     if ($key eq $item) {
 9426:                         $instcoderegexp .= '('.$val.')';
 9427:                         last;
 9428:                     }
 9429:                 }
 9430:             } else {
 9431:                 $instcoderegexp .= $codedefaults->{$item};
 9432:             }
 9433:         }
 9434:         $instcoderegexp .= '$';
 9435:         my (@from,@to);
 9436:         eval {
 9437:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
 9438:                (@to) = ($clonetocode =~ /$instcoderegexp/);
 9439:         };
 9440:         if ((@from > 0) && (@to > 0)) {
 9441:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
 9442:             if (!@diffs) {
 9443:                 $canclone = 1;
 9444:             }
 9445:         }
 9446:     }
 9447:     return $canclone;
 9448: }
 9449: 
 9450: sub default_instcode_cloning {
 9451:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
 9452:     my (%codedefaults,@code_order,$canclone);
 9453:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
 9454:         %codedefaults = %{$codedefaultsref};
 9455:         @code_order = @{$codeorderref};
 9456:     } elsif ($clonedom) {
 9457:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
 9458:     }
 9459:     if (($domdefclone) && (@code_order)) {
 9460:         my @clonecodes = split(/\+/,$domdefclone);
 9461:         my $instcoderegexp ='^';
 9462:         foreach my $item (@code_order) {
 9463:             if (grep(/^\Q$item\E$/,@clonecodes)) {
 9464:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
 9465:             } else {
 9466:                 $instcoderegexp .= $codedefaults{$item};
 9467:             }
 9468:         }
 9469:         $instcoderegexp .= '$';
 9470:         my (@from,@to);
 9471:         eval {
 9472:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
 9473:             (@to) = ($clonetocode =~ /$instcoderegexp/);
 9474:         };
 9475:         if ((@from > 0) && (@to > 0)) {
 9476:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
 9477:             if (!@diffs) {
 9478:                 $canclone = 1;
 9479:             }
 9480:         }
 9481:     }
 9482:     return $canclone;
 9483: }
 9484: 
 9485: # ------------------------------------------------------- Course Group routines
 9486: 
 9487: sub get_coursegroups {
 9488:     my ($cdom,$cnum,$group,$namespace) = @_;
 9489:     return(&dump($namespace,$cdom,$cnum,$group));
 9490: }
 9491: 
 9492: sub modify_coursegroup {
 9493:     my ($cdom,$cnum,$groupsettings) = @_;
 9494:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 9495: }
 9496: 
 9497: sub toggle_coursegroup_status {
 9498:     my ($cdom,$cnum,$group,$action) = @_;
 9499:     my ($from_namespace,$to_namespace);
 9500:     if ($action eq 'delete') {
 9501:         $from_namespace = 'coursegroups';
 9502:         $to_namespace = 'deleted_groups';
 9503:     } else {
 9504:         $from_namespace = 'deleted_groups';
 9505:         $to_namespace = 'coursegroups';
 9506:     }
 9507:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 9508:     if (my $tmp = &error(%curr_group)) {
 9509:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 9510:         return ('read error',$tmp);
 9511:     } else {
 9512:         my %savedsettings = %curr_group; 
 9513:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 9514:         my $deloutcome;
 9515:         if ($result eq 'ok') {
 9516:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 9517:         } else {
 9518:             return ('write error',$result);
 9519:         }
 9520:         if ($deloutcome eq 'ok') {
 9521:             return 'ok';
 9522:         } else {
 9523:             return ('delete error',$deloutcome);
 9524:         }
 9525:     }
 9526: }
 9527: 
 9528: sub modify_group_roles {
 9529:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 9530:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 9531:     my $role = 'gr/'.&escape($userprivs);
 9532:     my ($uname,$udom) = split(/:/,$user);
 9533:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 9534:     if ($result eq 'ok') {
 9535:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 9536:     }
 9537:     return $result;
 9538: }
 9539: 
 9540: sub modify_coursegroup_membership {
 9541:     my ($cdom,$cnum,$membership) = @_;
 9542:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 9543:     return $result;
 9544: }
 9545: 
 9546: sub get_active_groups {
 9547:     my ($udom,$uname,$cdom,$cnum) = @_;
 9548:     my $now = time;
 9549:     my %groups = ();
 9550:     foreach my $key (keys(%env)) {
 9551:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 9552:             my ($start,$end) = split(/\./,$env{$key});
 9553:             if (($end!=0) && ($end<$now)) { next; }
 9554:             if (($start!=0) && ($start>$now)) { next; }
 9555:             if ($1 eq $cdom && $2 eq $cnum) {
 9556:                 $groups{$3} = $env{$key} ;
 9557:             }
 9558:         }
 9559:     }
 9560:     return %groups;
 9561: }
 9562: 
 9563: sub get_group_membership {
 9564:     my ($cdom,$cnum,$group) = @_;
 9565:     return(&dump('groupmembership',$cdom,$cnum,$group));
 9566: }
 9567: 
 9568: sub get_users_groups {
 9569:     my ($udom,$uname,$courseid) = @_;
 9570:     my @usersgroups;
 9571:     my $cachetime=1800;
 9572: 
 9573:     my $hashid="$udom:$uname:$courseid";
 9574:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 9575:     if (defined($cached)) {
 9576:         @usersgroups = split(/:/,$grouplist);
 9577:     } else {  
 9578:         $grouplist = '';
 9579:         my $courseurl = &courseid_to_courseurl($courseid);
 9580:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 9581:         my $access_end = $env{'course.'.$courseid.
 9582:                               '.default_enrollment_end_date'};
 9583:         my $now = time;
 9584:         foreach my $key (keys(%roleshash)) {
 9585:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 9586:                 my $group = $1;
 9587:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 9588:                     my $start = $2;
 9589:                     my $end = $1;
 9590:                     if ($start == -1) { next; } # deleted from group
 9591:                     if (($start!=0) && ($start>$now)) { next; }
 9592:                     if (($end!=0) && ($end<$now)) {
 9593:                         if ($access_end && $access_end < $now) {
 9594:                             if ($access_end - $end < 86400) {
 9595:                                 push(@usersgroups,$group);
 9596:                             }
 9597:                         }
 9598:                         next;
 9599:                     }
 9600:                     push(@usersgroups,$group);
 9601:                 }
 9602:             }
 9603:         }
 9604:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 9605:         $grouplist = join(':',@usersgroups);
 9606:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 9607:     }
 9608:     return @usersgroups;
 9609: }
 9610: 
 9611: sub devalidate_getgroups_cache {
 9612:     my ($udom,$uname,$cdom,$cnum)=@_;
 9613:     my $courseid = $cdom.'_'.$cnum;
 9614: 
 9615:     my $hashid="$udom:$uname:$courseid";
 9616:     &devalidate_cache_new('getgroups',$hashid);
 9617: }
 9618: 
 9619: # ------------------------------------------------------------------ Plain Text
 9620: 
 9621: sub plaintext {
 9622:     my ($short,$type,$cid,$forcedefault) = @_;
 9623:     if ($short =~ m{^cr/}) {
 9624: 	return (split('/',$short))[-1];
 9625:     }
 9626:     if (!defined($cid)) {
 9627:         $cid = $env{'request.course.id'};
 9628:     }
 9629:     my %rolenames = (
 9630:                       Course    => 'std',
 9631:                       Community => 'alt1',
 9632:                     );
 9633:     if ($cid ne '') {
 9634:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
 9635:             unless ($forcedefault) {
 9636:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
 9637:                 &Apache::lonlocal::mt_escape(\$roletext);
 9638:                 return &Apache::lonlocal::mt($roletext);
 9639:             }
 9640:         }
 9641:     }
 9642:     if ((defined($type)) && (defined($rolenames{$type})) &&
 9643:         (defined($rolenames{$type})) && 
 9644:         (defined($prp{$short}{$rolenames{$type}}))) {
 9645:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 9646:     } elsif ($cid ne '') {
 9647:         my $crstype = $env{'course.'.$cid.'.type'};
 9648:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
 9649:             (defined($prp{$short}{$rolenames{$crstype}}))) {
 9650:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
 9651:         }
 9652:     }
 9653:     return &Apache::lonlocal::mt($prp{$short}{'std'});
 9654: }
 9655: 
 9656: # ----------------------------------------------------------------- Assign Role
 9657: 
 9658: sub assignrole {
 9659:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
 9660:         $context)=@_;
 9661:     my $mrole;
 9662:     if ($role =~ /^cr\//) {
 9663:         my $cwosec=$url;
 9664:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 9665: 	unless (&allowed('ccr',$cwosec)) {
 9666:            my $refused = 1;
 9667:            if ($context eq 'requestcourses') {
 9668:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 9669:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
 9670:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
 9671:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 9672:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 9673:                            if ($crsenv{'internal.courseowner'} eq
 9674:                                $env{'user.name'}.':'.$env{'user.domain'}) {
 9675:                                $refused = '';
 9676:                            }
 9677:                        }
 9678:                    }
 9679:                }
 9680:            }
 9681:            if ($refused) {
 9682:                &logthis('Refused custom assignrole: '.
 9683:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
 9684:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
 9685:                return 'refused';
 9686:            }
 9687:         }
 9688:         $mrole='cr';
 9689:     } elsif ($role =~ /^gr\//) {
 9690:         my $cwogrp=$url;
 9691:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 9692:         unless (&allowed('mdg',$cwogrp)) {
 9693:             &logthis('Refused group assignrole: '.
 9694:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 9695:                     $env{'user.name'}.' at '.$env{'user.domain'});
 9696:             return 'refused';
 9697:         }
 9698:         $mrole='gr';
 9699:     } else {
 9700:         my $cwosec=$url;
 9701:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 9702:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 9703:             my $refused;
 9704:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 9705:                 if (!(&allowed('c'.$role,$url))) {
 9706:                     $refused = 1;
 9707:                 }
 9708:             } else {
 9709:                 $refused = 1;
 9710:             }
 9711:             if ($refused) {
 9712:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 9713:                 if (!$selfenroll && $context eq 'course') {
 9714:                     my %crsenv;
 9715:                     if ($role eq 'cc' || $role eq 'co') {
 9716:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 9717:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
 9718:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
 9719:                                 if ($crsenv{'internal.courseowner'} eq 
 9720:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 9721:                                     $refused = '';
 9722:                                 }
 9723:                             }
 9724:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
 9725:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
 9726:                                 if ($crsenv{'internal.courseowner'} eq 
 9727:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 9728:                                     $refused = '';
 9729:                                 }
 9730:                             }
 9731:                         }
 9732:                     }
 9733:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 9734:                     $refused = '';
 9735:                 } elsif ($context eq 'requestcourses') {
 9736:                     my @possroles = ('st','ta','ep','in','cc','co');
 9737:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
 9738:                         my $wrongcc;
 9739:                         if ($cnum =~ /^$match_community$/) {
 9740:                             $wrongcc = 1 if ($role eq 'cc');
 9741:                         } else {
 9742:                             $wrongcc = 1 if ($role eq 'co');
 9743:                         }
 9744:                         unless ($wrongcc) {
 9745:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 9746:                             if ($crsenv{'internal.courseowner'} eq 
 9747:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
 9748:                                 $refused = '';
 9749:                             }
 9750:                         }
 9751:                     }
 9752:                 } elsif ($context eq 'requestauthor') {
 9753:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 9754:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
 9755:                         if ($env{'environment.requestauthor'} eq 'automatic') {
 9756:                             $refused = '';
 9757:                         } else {
 9758:                             my %domdefaults = &get_domain_defaults($udom);
 9759:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
 9760:                                 my $checkbystatus;
 9761:                                 if ($env{'user.adv'}) {
 9762:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
 9763:                                     if ($disposition eq 'automatic') {
 9764:                                         $refused = '';
 9765:                                     } elsif ($disposition eq '') {
 9766:                                         $checkbystatus = 1;
 9767:                                     }
 9768:                                 } else {
 9769:                                     $checkbystatus = 1;
 9770:                                 }
 9771:                                 if ($checkbystatus) {
 9772:                                     if ($env{'environment.inststatus'}) {
 9773:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
 9774:                                         foreach my $type (@inststatuses) {
 9775:                                             if (($type ne '') &&
 9776:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
 9777:                                                 $refused = '';
 9778:                                             }
 9779:                                         }
 9780:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
 9781:                                         $refused = '';
 9782:                                     }
 9783:                                 }
 9784:                             }
 9785:                         }
 9786:                     }
 9787:                 }
 9788:                 if ($refused) {
 9789:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 9790:                              ' '.$role.' '.$end.' '.$start.' by '.
 9791: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
 9792:                     return 'refused';
 9793:                 }
 9794:             }
 9795:         } elsif ($role eq 'au') {
 9796:             if ($url ne '/'.$udom.'/') {
 9797:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
 9798:                          ' to assign author role for '.$uname.':'.$udom.
 9799:                          ' in domain: '.$url.' refused (wrong domain).');
 9800:                 return 'refused';
 9801:             }
 9802:         }
 9803:         $mrole=$role;
 9804:     }
 9805:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 9806:                 "$udom:$uname:$url".'_'."$mrole=$role";
 9807:     if ($end) { $command.='_'.$end; }
 9808:     if ($start) {
 9809: 	if ($end) { 
 9810:            $command.='_'.$start; 
 9811:         } else {
 9812:            $command.='_0_'.$start;
 9813:         }
 9814:     }
 9815:     my $origstart = $start;
 9816:     my $origend = $end;
 9817:     my $delflag;
 9818: # actually delete
 9819:     if ($deleteflag) {
 9820: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 9821: # modify command to delete the role
 9822:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 9823:                 "$udom:$uname:$url".'_'."$mrole";
 9824: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 9825: # set start and finish to negative values for userrolelog
 9826:            $start=-1;
 9827:            $end=-1;
 9828:            $delflag = 1;
 9829:         }
 9830:     }
 9831: # send command
 9832:     my $answer=&reply($command,&homeserver($uname,$udom));
 9833: # log new user role if status is ok
 9834:     if ($answer eq 'ok') {
 9835: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 9836:         if (($role eq 'cc') || ($role eq 'in') ||
 9837:             ($role eq 'ep') || ($role eq 'ad') ||
 9838:             ($role eq 'ta') || ($role eq 'st') ||
 9839:             ($role=~/^cr/) || ($role eq 'gr') ||
 9840:             ($role eq 'co')) {
 9841: # for course roles, perform group memberships changes triggered by role change.
 9842:             unless ($role =~ /^gr/) {
 9843:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 9844:                                                  $origstart,$selfenroll,$context);
 9845:             }
 9846:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 9847:                            $selfenroll,$context);
 9848:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
 9849:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
 9850:                  ($role eq 'da')) {
 9851:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 9852:                            $context);
 9853:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
 9854:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 9855:                              $context);
 9856:         }
 9857:         if ($role eq 'cc') {
 9858:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
 9859:         }
 9860:     }
 9861:     return $answer;
 9862: }
 9863: 
 9864: sub autoupdate_coowners {
 9865:     my ($url,$end,$start,$uname,$udom) = @_;
 9866:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
 9867:     if (($cdom ne '') && ($cnum ne '')) {
 9868:         my $now = time;
 9869:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
 9870:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
 9871:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
 9872:             my $instcode = $coursehash{'internal.coursecode'};
 9873:             if ($instcode ne '') {
 9874:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
 9875:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
 9876:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
 9877:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
 9878:                         if ($result eq 'valid') {
 9879:                             if ($coursehash{'internal.co-owners'}) {
 9880:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 9881:                                     push(@newcoowners,$coowner);
 9882:                                 }
 9883:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
 9884:                                     push(@newcoowners,$uname.':'.$udom);
 9885:                                 }
 9886:                                 @newcoowners = sort(@newcoowners);
 9887:                             } else {
 9888:                                 push(@newcoowners,$uname.':'.$udom);
 9889:                             }
 9890:                         } else {
 9891:                             if ($coursehash{'internal.co-owners'}) {
 9892:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 9893:                                     unless ($coowner eq $uname.':'.$udom) {
 9894:                                         push(@newcoowners,$coowner);
 9895:                                     }
 9896:                                 }
 9897:                                 unless (@newcoowners > 0) {
 9898:                                     $delcoowners = 1;
 9899:                                     $coowners = '';
 9900:                                 }
 9901:                             }
 9902:                         }
 9903:                         if (@newcoowners || $delcoowners) {
 9904:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
 9905:                                             $delcoowners,@newcoowners);
 9906:                         }
 9907:                     }
 9908:                 }
 9909:             }
 9910:         }
 9911:     }
 9912: }
 9913: 
 9914: sub store_coowners {
 9915:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
 9916:     my $cid = $cdom.'_'.$cnum;
 9917:     my ($coowners,$delresult,$putresult);
 9918:     if (@newcoowners) {
 9919:         $coowners = join(',',@newcoowners);
 9920:         my %coownershash = (
 9921:                             'internal.co-owners' => $coowners,
 9922:                            );
 9923:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
 9924:         if ($putresult eq 'ok') {
 9925:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
 9926:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
 9927:             }
 9928:         }
 9929:     }
 9930:     if ($delcoowners) {
 9931:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
 9932:         if ($delresult eq 'ok') {
 9933:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
 9934:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
 9935:             }
 9936:         }
 9937:     }
 9938:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
 9939:         my %crsinfo =
 9940:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 9941:         if (ref($crsinfo{$cid}) eq 'HASH') {
 9942:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
 9943:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
 9944:         }
 9945:     }
 9946: }
 9947: 
 9948: # -------------------------------------------------- Modify user authentication
 9949: # Overrides without validation
 9950: 
 9951: sub modifyuserauth {
 9952:     my ($udom,$uname,$umode,$upass)=@_;
 9953:     my $uhome=&homeserver($uname,$udom);
 9954:     my $allowed;
 9955:     if (&allowed('mau',$udom)) {
 9956:         $allowed = 1;
 9957:     } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
 9958:              ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
 9959:              (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
 9960:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 9961:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 9962:         if (($cdom ne '') && ($cnum ne '')) {
 9963:             my $is_owner = &is_course_owner($cdom,$cnum);
 9964:             if ($is_owner) {
 9965:                 $allowed = 1;
 9966:             }
 9967:         }
 9968:     }
 9969:     unless ($allowed) { return 'refused'; }
 9970:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 9971:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 9972:              ' in domain '.$env{'request.role.domain'});  
 9973:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 9974: 		     &escape($upass),$uhome);
 9975:     my $ip = &get_requestor_ip();
 9976:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 9977:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 9978:          '(Remote '.$ip.'): '.$reply);
 9979:     &log($udom,,$uname,$uhome,
 9980:         'Authentication changed by '.$env{'user.domain'}.', '.
 9981:                                      $env{'user.name'}.', '.$umode.
 9982:          '(Remote '.$ip.'): '.$reply);
 9983:     unless ($reply eq 'ok') {
 9984:         &logthis('Authentication mode error: '.$reply);
 9985: 	return 'error: '.$reply;
 9986:     }   
 9987:     return 'ok';
 9988: }
 9989: 
 9990: # --------------------------------------------------------------- Modify a user
 9991: 
 9992: sub modifyuser {
 9993:     my ($udom,    $uname, $uid,
 9994:         $umode,   $upass, $first,
 9995:         $middle,  $last,  $gene,
 9996:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
 9997:     $udom= &LONCAPA::clean_domain($udom);
 9998:     $uname=&LONCAPA::clean_username($uname);
 9999:     my $showcandelete = 'none';
10000:     if (ref($candelete) eq 'ARRAY') {
10001:         if (@{$candelete} > 0) {
10002:             $showcandelete = join(', ',@{$candelete});
10003:         }
10004:     }
10005:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
10006:              $umode.', '.$first.', '.$middle.', '.
10007: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
10008:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
10009:                                      ' desiredhome not specified'). 
10010:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
10011:              ' in domain '.$env{'request.role.domain'});
10012:     my $uhome=&homeserver($uname,$udom,'true');
10013:     my $newuser;
10014:     if ($uhome eq 'no_host') {
10015:         $newuser = 1;
10016:     }
10017: # ----------------------------------------------------------------- Create User
10018:     if (($uhome eq 'no_host') && 
10019: 	(($umode && $upass) || ($umode eq 'localauth'))) {
10020:         my $unhome='';
10021:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
10022:             $unhome = $desiredhome;
10023: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
10024: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
10025:         } else { # load balancing routine for determining $unhome
10026:             my $loadm=10000000;
10027: 	    my %servers = &get_servers($udom,'library');
10028: 	    foreach my $tryserver (keys(%servers)) {
10029: 		my $answer=reply('load',$tryserver);
10030: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
10031: 		    $loadm=$answer;
10032: 		    $unhome=$tryserver;
10033: 		}
10034: 	    }
10035:         }
10036:         if (($unhome eq '') || ($unhome eq 'no_host')) {
10037: 	    return 'error: unable to find a home server for '.$uname.
10038:                    ' in domain '.$udom;
10039:         }
10040:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
10041:                          &escape($upass),$unhome);
10042: 	unless ($reply eq 'ok') {
10043:             return 'error: '.$reply;
10044:         }   
10045:         $uhome=&homeserver($uname,$udom,'true');
10046:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
10047: 	    return 'error: unable verify users home machine.';
10048:         }
10049:     }   # End of creation of new user
10050: # ---------------------------------------------------------------------- Add ID
10051:     if ($uid) {
10052:        $uid=~tr/A-Z/a-z/;
10053:        my %uidhash=&idrget($udom,$uname);
10054:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
10055:          && (!$forceid)) {
10056: 	  unless ($uid eq $uidhash{$uname}) {
10057: 	      return 'error: user id "'.$uid.'" does not match '.
10058:                   'current user id "'.$uidhash{$uname}.'".';
10059:           }
10060:        } else {
10061: 	  &idput($udom,($uname => $uid));
10062:        }
10063:     }
10064: # -------------------------------------------------------------- Add names, etc
10065:     my @tmp=&get('environment',
10066: 		   ['firstname','middlename','lastname','generation','id',
10067:                     'permanentemail','inststatus'],
10068: 		   $udom,$uname);
10069:     my (%names,%oldnames);
10070:     if ($tmp[0] =~ m/^error:.*/) { 
10071:         %names=(); 
10072:     } else {
10073:         %names = @tmp;
10074:         %oldnames = %names;
10075:     }
10076: #
10077: # If name, email and/or uid are blank (e.g., because an uploaded file
10078: # of users did not contain them), do not overwrite existing values
10079: # unless field is in $candelete array ref.  
10080: #
10081: 
10082:     my @fields = ('firstname','middlename','lastname','generation',
10083:                   'permanentemail','id');
10084:     my %newvalues;
10085:     if (ref($candelete) eq 'ARRAY') {
10086:         foreach my $field (@fields) {
10087:             if (grep(/^\Q$field\E$/,@{$candelete})) {
10088:                 if ($field eq 'firstname') {
10089:                     $names{$field} = $first;
10090:                 } elsif ($field eq 'middlename') {
10091:                     $names{$field} = $middle;
10092:                 } elsif ($field eq 'lastname') {
10093:                     $names{$field} = $last;
10094:                 } elsif ($field eq 'generation') { 
10095:                     $names{$field} = $gene;
10096:                 } elsif ($field eq 'permanentemail') {
10097:                     $names{$field} = $email;
10098:                 } elsif ($field eq 'id') {
10099:                     $names{$field}  = $uid;
10100:                 }
10101:             }
10102:         }
10103:     }
10104:     if ($first)  { $names{'firstname'}  = $first; }
10105:     if (defined($middle)) { $names{'middlename'} = $middle; }
10106:     if ($last)   { $names{'lastname'}   = $last; }
10107:     if (defined($gene))   { $names{'generation'} = $gene; }
10108:     if ($email) {
10109:        $email=~s/[^\w\@\.\-\,]//gs;
10110:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
10111:     }
10112:     if ($uid) { $names{'id'}  = $uid; }
10113:     if (defined($inststatus)) {
10114:         $names{'inststatus'} = '';
10115:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
10116:         if (ref($usertypes) eq 'HASH') {
10117:             my @okstatuses; 
10118:             foreach my $item (split(/:/,$inststatus)) {
10119:                 if (defined($usertypes->{$item})) {
10120:                     push(@okstatuses,$item);  
10121:                 }
10122:             }
10123:             if (@okstatuses) {
10124:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
10125:             }
10126:         }
10127:     }
10128:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
10129:                  $umode.', '.$first.', '.$middle.', '.
10130:                  $last.', '.$gene.', '.$email.', '.$inststatus;
10131:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
10132:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
10133:     } else {
10134:         $logmsg .= ' during self creation';
10135:     }
10136:     my $changed;
10137:     if ($newuser) {
10138:         $changed = 1;
10139:     } else {
10140:         foreach my $field (@fields) {
10141:             if ($names{$field} ne $oldnames{$field}) {
10142:                 $changed = 1;
10143:                 last;
10144:             }
10145:         }
10146:     }
10147:     unless ($changed) {
10148:         $logmsg = 'No changes in user information needed for: '.$logmsg;
10149:         &logthis($logmsg);
10150:         return 'ok';
10151:     }
10152:     my $reply = &put('environment', \%names, $udom,$uname);
10153:     if ($reply ne 'ok') { 
10154:         return 'error: '.$reply;
10155:     }
10156:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
10157:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
10158:     }
10159:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
10160:     &devalidate_cache_new('namescache',$uname.':'.$udom);
10161:     $logmsg = 'Success modifying user '.$logmsg;
10162:     &logthis($logmsg);
10163:     return 'ok';
10164: }
10165: 
10166: # -------------------------------------------------------------- Modify student
10167: 
10168: sub modifystudent {
10169:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
10170:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
10171:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
10172:     if (!$cid) {
10173: 	unless ($cid=$env{'request.course.id'}) {
10174: 	    return 'not_in_class';
10175: 	}
10176:     }
10177: # --------------------------------------------------------------- Make the user
10178:     my $reply=&modifyuser
10179: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
10180:          $desiredhome,$email,$inststatus);
10181:     unless ($reply eq 'ok') { return $reply; }
10182:     # This will cause &modify_student_enrollment to get the uid from the
10183:     # student's environment
10184:     $uid = undef if (!$forceid);
10185:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
10186: 					$gene,$usec,$end,$start,$type,$locktype,
10187:                                         $cid,$selfenroll,$context,$credits,$instsec);
10188:     return $reply;
10189: }
10190: 
10191: sub modify_student_enrollment {
10192:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
10193:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
10194:     my ($cdom,$cnum,$chome);
10195:     if (!$cid) {
10196: 	unless ($cid=$env{'request.course.id'}) {
10197: 	    return 'not_in_class';
10198: 	}
10199: 	$cdom=$env{'course.'.$cid.'.domain'};
10200: 	$cnum=$env{'course.'.$cid.'.num'};
10201:     } else {
10202: 	($cdom,$cnum)=split(/_/,$cid);
10203:     }
10204:     $chome=$env{'course.'.$cid.'.home'};
10205:     if (!$chome) {
10206: 	$chome=&homeserver($cnum,$cdom);
10207:     }
10208:     if (!$chome) { return 'unknown_course'; }
10209:     # Make sure the user exists
10210:     my $uhome=&homeserver($uname,$udom);
10211:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
10212: 	return 'error: no such user';
10213:     }
10214:     # Get student data if we were not given enough information
10215:     if (!defined($first)  || $first  eq '' || 
10216:         !defined($last)   || $last   eq '' || 
10217:         !defined($uid)    || $uid    eq '' || 
10218:         !defined($middle) || $middle eq '' || 
10219:         !defined($gene)   || $gene   eq '') {
10220:         # They did not supply us with enough data to enroll the student, so
10221:         # we need to pick up more information.
10222:         my %tmp = &get('environment',
10223:                        ['firstname','middlename','lastname', 'generation','id']
10224:                        ,$udom,$uname);
10225: 
10226:         #foreach my $key (keys(%tmp)) {
10227:         #    &logthis("key $key = ".$tmp{$key});
10228:         #}
10229:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
10230:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
10231:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
10232:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
10233:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
10234:     }
10235:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
10236:     my $user = "$uname:$udom";
10237:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
10238:     my $reply=cput('classlist',
10239: 		   {$user => 
10240: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
10241: 		   $cdom,$cnum);
10242:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
10243:         &devalidate_getsection_cache($udom,$uname,$cid);
10244:     } else { 
10245: 	return 'error: '.$reply;
10246:     }
10247:     # Add student role to user
10248:     my $uurl='/'.$cid;
10249:     $uurl=~s/\_/\//g;
10250:     if ($usec) {
10251: 	$uurl.='/'.$usec;
10252:     }
10253:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
10254:                              $selfenroll,$context);
10255:     if ($result ne 'ok') {
10256:         if ($old_entry{$user} ne '') {
10257:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
10258:         } else {
10259:             $reply = &del('classlist',[$user],$cdom,$cnum);
10260:         }
10261:     }
10262:     return $result; 
10263: }
10264: 
10265: sub format_name {
10266:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
10267:     my $name;
10268:     if ($first ne 'lastname') {
10269: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
10270:     } else {
10271: 	if ($lastname=~/\S/) {
10272: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
10273: 	    $name=~s/\s+,/,/;
10274: 	} else {
10275: 	    $name.= $firstname.' '.$middlename.' '.$generation;
10276: 	}
10277:     }
10278:     $name=~s/^\s+//;
10279:     $name=~s/\s+$//;
10280:     $name=~s/\s+/ /g;
10281:     return $name;
10282: }
10283: 
10284: # ------------------------------------------------- Write to course preferences
10285: 
10286: sub writecoursepref {
10287:     my ($courseid,%prefs)=@_;
10288:     $courseid=~s/^\///;
10289:     $courseid=~s/\_/\//g;
10290:     my ($cdomain,$cnum)=split(/\//,$courseid);
10291:     my $chome=homeserver($cnum,$cdomain);
10292:     if (($chome eq '') || ($chome eq 'no_host')) { 
10293: 	return 'error: no such course';
10294:     }
10295:     my $cstring='';
10296:     foreach my $pref (keys(%prefs)) {
10297: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
10298:     }
10299:     $cstring=~s/\&$//;
10300:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
10301: }
10302: 
10303: # ---------------------------------------------------------- Make/modify course
10304: 
10305: sub createcourse {
10306:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
10307:         $course_owner,$crstype,$cnum,$context,$category)=@_;
10308:     $url=&declutter($url);
10309:     my $cid='';
10310:     if ($context eq 'requestcourses') {
10311:         my $can_create = 0;
10312:         my ($ownername,$ownerdom) = split(':',$course_owner);
10313:         if ($udom eq $ownerdom) {
10314:             if (&usertools_access($ownername,$ownerdom,$category,undef,
10315:                                   $context)) {
10316:                 $can_create = 1;
10317:             }
10318:         } else {
10319:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
10320:                                            $category);
10321:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
10322:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
10323:                 if (@curr > 0) {
10324:                     my @options = qw(approval validate autolimit);
10325:                     my $optregex = join('|',@options);
10326:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
10327:                         $can_create = 1;
10328:                     }
10329:                 }
10330:             }
10331:         }
10332:         if ($can_create) {
10333:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
10334:                 unless (&allowed('ccc',$udom)) {
10335:                     return 'refused'; 
10336:                 }
10337:             }
10338:         } else {
10339:             return 'refused';
10340:         }
10341:     } elsif (!&allowed('ccc',$udom)) {
10342:         return 'refused';
10343:     }
10344: # --------------------------------------------------------------- Get Unique ID
10345:     my $uname;
10346:     if ($cnum =~ /^$match_courseid$/) {
10347:         my $chome=&homeserver($cnum,$udom,'true');
10348:         if (($chome eq '') || ($chome eq 'no_host')) {
10349:             $uname = $cnum;
10350:         } else {
10351:             $uname = &generate_coursenum($udom,$crstype);
10352:         }
10353:     } else {
10354:         $uname = &generate_coursenum($udom,$crstype);
10355:     }
10356:     return $uname if ($uname =~ /^error/);
10357: # -------------------------------------------------- Check supplied server name
10358:     if (!defined($course_server)) {
10359:         if (defined(&domain($udom,'primary'))) {
10360:             $course_server = &domain($udom,'primary');
10361:         } else {
10362:             $course_server = $env{'user.home'}; 
10363:         }
10364:     }
10365:     my %host_servers =
10366:         &Apache::lonnet::get_servers($udom,'library');
10367:     unless ($host_servers{$course_server}) {
10368:         return 'error: invalid home server for course: '.$course_server;
10369:     }
10370: # ------------------------------------------------------------- Make the course
10371:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
10372:                       $course_server);
10373:     unless ($reply eq 'ok') { return 'error: '.$reply; }
10374:     my $uhome=&homeserver($uname,$udom,'true');
10375:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
10376: 	return 'error: no such course';
10377:     }
10378: # ----------------------------------------------------------------- Course made
10379: # log existence
10380:     my $now = time;
10381:     my $newcourse = {
10382:                     $udom.'_'.$uname => {
10383:                                      description => $description,
10384:                                      inst_code   => $inst_code,
10385:                                      owner       => $course_owner,
10386:                                      type        => $crstype,
10387:                                      creator     => $env{'user.name'}.':'.
10388:                                                     $env{'user.domain'},
10389:                                      created     => $now,
10390:                                      context     => $context,
10391:                                                 },
10392:                     };
10393:     &courseidput($udom,$newcourse,$uhome,'notime');
10394: # set toplevel url
10395:     my $topurl=$url;
10396:     unless ($nonstandard) {
10397: # ------------------------------------------ For standard courses, make top url
10398:         my $mapurl=&clutter($url);
10399:         if ($mapurl eq '/res/') { $mapurl=''; }
10400:         $env{'form.initmap'}=(<<ENDINITMAP);
10401: <map>
10402: <resource id="1" type="start"></resource>
10403: <resource id="2" src="$mapurl"></resource>
10404: <resource id="3" type="finish"></resource>
10405: <link index="1" from="1" to="2"></link>
10406: <link index="2" from="2" to="3"></link>
10407: </map>
10408: ENDINITMAP
10409:         $topurl=&declutter(
10410:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
10411:                           );
10412:     }
10413: # ----------------------------------------------------------- Write preferences
10414:     &writecoursepref($udom.'_'.$uname,
10415:                      ('description'              => $description,
10416:                       'url'                      => $topurl,
10417:                       'internal.creator'         => $env{'user.name'}.':'.
10418:                                                     $env{'user.domain'},
10419:                       'internal.created'         => $now,
10420:                       'internal.creationcontext' => $context)
10421:                     );
10422:     return '/'.$udom.'/'.$uname;
10423: }
10424: 
10425: # ------------------------------------------------------------------- Create ID
10426: sub generate_coursenum {
10427:     my ($udom,$crstype) = @_;
10428:     my $domdesc = &domain($udom);
10429:     return 'error: invalid domain' if ($domdesc eq '');
10430:     my $first;
10431:     if ($crstype eq 'Community') {
10432:         $first = '0';
10433:     } else {
10434:         $first = int(1+rand(9)); 
10435:     } 
10436:     my $uname=$first.
10437:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
10438:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
10439:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
10440: # ----------------------------------------------- Make sure that does not exist
10441:     my $uhome=&homeserver($uname,$udom,'true');
10442:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
10443:         if ($crstype eq 'Community') {
10444:             $first = '0';
10445:         } else {
10446:             $first = int(1+rand(9));
10447:         }
10448:         $uname=$first.
10449:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
10450:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
10451:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
10452:         $uhome=&homeserver($uname,$udom,'true');
10453:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
10454:             return 'error: unable to generate unique course-ID';
10455:         }
10456:     }
10457:     return $uname;
10458: }
10459: 
10460: sub is_course {
10461:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
10462:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
10463:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
10464:     my $uhome=&homeserver($cnum,$cdom);
10465:     my $iscourse;
10466:     if (grep { $_ eq $uhome } current_machine_ids()) {
10467:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
10468:     } else {
10469:         my $hashid = $cdom.':'.$cnum;
10470:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
10471:         unless (defined($cached)) {
10472:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
10473:                                         $cnum,undef,undef,'.');
10474:             $iscourse = 0;
10475:             if (exists($courses{$cdom.'_'.$cnum})) {
10476:                 $iscourse = 1;
10477:             }
10478:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
10479:         }
10480:     }
10481:     return unless($iscourse);
10482:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
10483: }
10484: 
10485: sub store_userdata {
10486:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
10487:     my $result;
10488:     if ($datakey ne '') {
10489:         if (ref($storehash) eq 'HASH') {
10490:             if ($udom eq '' || $uname eq '') {
10491:                 $udom = $env{'user.domain'};
10492:                 $uname = $env{'user.name'};
10493:             }
10494:             my $uhome=&homeserver($uname,$udom);
10495:             if (($uhome eq '') || ($uhome eq 'no_host')) {
10496:                 $result = 'error: no_host';
10497:             } else {
10498:                 $storehash->{'ip'} = &get_requestor_ip();
10499:                 $storehash->{'host'} = $perlvar{'lonHostID'};
10500: 
10501:                 my $namevalue='';
10502:                 foreach my $key (keys(%{$storehash})) {
10503:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
10504:                 }
10505:                 $namevalue=~s/\&$//;
10506:                 unless ($namespace eq 'courserequests') {
10507:                     $datakey = &escape($datakey);
10508:                 }
10509:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
10510:                                   $namevalue,$uhome);
10511:             }
10512:         } else {
10513:             $result = 'error: data to store was not a hash reference'; 
10514:         }
10515:     } else {
10516:         $result= 'error: invalid requestkey'; 
10517:     }
10518:     return $result;
10519: }
10520: 
10521: # ---------------------------------------------------------- Assign Custom Role
10522: 
10523: sub assigncustomrole {
10524:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
10525:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
10526:                        $end,$start,$deleteflag,$selfenroll,$context);
10527: }
10528: 
10529: # ----------------------------------------------------------------- Revoke Role
10530: 
10531: sub revokerole {
10532:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
10533:     my $now=time;
10534:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
10535: }
10536: 
10537: # ---------------------------------------------------------- Revoke Custom Role
10538: 
10539: sub revokecustomrole {
10540:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
10541:     my $now=time;
10542:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
10543:            $deleteflag,$selfenroll,$context);
10544: }
10545: 
10546: # ------------------------------------------------------------ Disk usage
10547: sub diskusage {
10548:     my ($udom,$uname,$directorypath,$getpropath)=@_;
10549:     $directorypath =~ s/\/$//;
10550:     my $listing=&reply('du2:'.&escape($directorypath).':'
10551:                        .&escape($getpropath).':'.&escape($uname).':'
10552:                        .&escape($udom),homeserver($uname,$udom));
10553:     if ($listing eq 'unknown_cmd') {
10554:         if ($getpropath) {
10555:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
10556:         }
10557:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
10558:     }
10559:     return $listing;
10560: }
10561: 
10562: sub is_locked {
10563:     my ($file_name, $domain, $user, $which) = @_;
10564:     my @check;
10565:     my $is_locked;
10566:     push (@check,$file_name);
10567:     my %locked = &get('file_permissions',\@check,
10568: 		      $env{'user.domain'},$env{'user.name'});
10569:     my ($tmp)=keys(%locked);
10570:     if ($tmp=~/^error:/) { undef(%locked); }
10571:     
10572:     if (ref($locked{$file_name}) eq 'ARRAY') {
10573:         $is_locked = 'false';
10574:         foreach my $entry (@{$locked{$file_name}}) {
10575:            if (ref($entry) eq 'ARRAY') {
10576:                $is_locked = 'true';
10577:                if (ref($which) eq 'ARRAY') {
10578:                    push(@{$which},$entry);
10579:                } else {
10580:                    last;
10581:                }
10582:            }
10583:        }
10584:     } else {
10585:         $is_locked = 'false';
10586:     }
10587:     return $is_locked;
10588: }
10589: 
10590: sub declutter_portfile {
10591:     my ($file) = @_;
10592:     $file =~ s{^(/portfolio/|portfolio/)}{/};
10593:     return $file;
10594: }
10595: 
10596: # ------------------------------------------------------------- Mark as Read Only
10597: 
10598: sub mark_as_readonly {
10599:     my ($domain,$user,$files,$what) = @_;
10600:     my %current_permissions = &dump('file_permissions',$domain,$user);
10601:     my ($tmp)=keys(%current_permissions);
10602:     if ($tmp=~/^error:/) { undef(%current_permissions); }
10603:     foreach my $file (@{$files}) {
10604: 	$file = &declutter_portfile($file);
10605:         push(@{$current_permissions{$file}},$what);
10606:     }
10607:     &put('file_permissions',\%current_permissions,$domain,$user);
10608:     return;
10609: }
10610: 
10611: # ------------------------------------------------------------Save Selected Files
10612: 
10613: sub save_selected_files {
10614:     my ($user, $path, @files) = @_;
10615:     my $filename = $user."savedfiles";
10616:     my @other_files = &files_not_in_path($user, $path);
10617:     open (OUT,'>',LONCAPA::tempdir().$filename);
10618:     foreach my $file (@files) {
10619:         print (OUT $env{'form.currentpath'}.$file."\n");
10620:     }
10621:     foreach my $file (@other_files) {
10622:         print (OUT $file."\n");
10623:     }
10624:     close (OUT);
10625:     return 'ok';
10626: }
10627: 
10628: sub clear_selected_files {
10629:     my ($user) = @_;
10630:     my $filename = $user."savedfiles";
10631:     open (OUT,'>',LONCAPA::tempdir().$filename);
10632:     print (OUT undef);
10633:     close (OUT);
10634:     return ("ok");    
10635: }
10636: 
10637: sub files_in_path {
10638:     my ($user, $path) = @_;
10639:     my $filename = $user."savedfiles";
10640:     my %return_files;
10641:     open (IN,'<',LONCAPA::tempdir().$filename);
10642:     while (my $line_in = <IN>) {
10643:         chomp ($line_in);
10644:         my @paths_and_file = split (m!/!, $line_in);
10645:         my $file_part = pop (@paths_and_file);
10646:         my $path_part = join ('/', @paths_and_file);
10647:         $path_part.='/';
10648:         my $path_and_file = $path_part.$file_part;
10649:         if ($path_part eq $path) {
10650:             $return_files{$file_part}= 'selected';
10651:         }
10652:     }
10653:     close (IN);
10654:     return (\%return_files);
10655: }
10656: 
10657: # called in portfolio select mode, to show files selected NOT in current directory
10658: sub files_not_in_path {
10659:     my ($user, $path) = @_;
10660:     my $filename = $user."savedfiles";
10661:     my @return_files;
10662:     my $path_part;
10663:     open(IN, '<',LONCAPA::tempdir().$filename);
10664:     while (my $line = <IN>) {
10665:         #ok, I know it's clunky, but I want it to work
10666:         my @paths_and_file = split(m|/|, $line);
10667:         my $file_part = pop(@paths_and_file);
10668:         chomp($file_part);
10669:         my $path_part = join('/', @paths_and_file);
10670:         $path_part .= '/';
10671:         my $path_and_file = $path_part.$file_part;
10672:         if ($path_part ne $path) {
10673:             push(@return_files, ($path_and_file));
10674:         }
10675:     }
10676:     close(OUT);
10677:     return (@return_files);
10678: }
10679: 
10680: #----------------------------------------------Get portfolio file permissions
10681: 
10682: sub get_portfile_permissions {
10683:     my ($domain,$user) = @_;
10684:     my %current_permissions = &dump('file_permissions',$domain,$user);
10685:     my ($tmp)=keys(%current_permissions);
10686:     if ($tmp=~/^error:/) { undef(%current_permissions); }
10687:     return \%current_permissions;
10688: }
10689: 
10690: #---------------------------------------------Get portfolio file access controls
10691: 
10692: sub get_access_controls {
10693:     my ($current_permissions,$group,$file) = @_;
10694:     my %access;
10695:     my $real_file = $file;
10696:     $file =~ s/\.meta$//;
10697:     if (defined($file)) {
10698:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
10699:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
10700:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
10701:             }
10702:         }
10703:     } else {
10704:         foreach my $key (keys(%{$current_permissions})) {
10705:             if ($key =~ /\0accesscontrol$/) {
10706:                 if (defined($group)) {
10707:                     if ($key !~ m-^\Q$group\E/-) {
10708:                         next;
10709:                     }
10710:                 }
10711:                 my ($fullpath) = split(/\0/,$key);
10712:                 if (ref($$current_permissions{$key}) eq 'HASH') {
10713:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
10714:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
10715:                     }
10716:                 }
10717:             }
10718:         }
10719:     }
10720:     return %access;
10721: }
10722: 
10723: sub modify_access_controls {
10724:     my ($file_name,$changes,$domain,$user)=@_;
10725:     my ($outcome,$deloutcome);
10726:     my %store_permissions;
10727:     my %new_values;
10728:     my %new_control;
10729:     my %translation;
10730:     my @deletions = ();
10731:     my $now = time;
10732:     if (exists($$changes{'activate'})) {
10733:         if (ref($$changes{'activate'}) eq 'HASH') {
10734:             my @newitems = sort(keys(%{$$changes{'activate'}}));
10735:             my $numnew = scalar(@newitems);
10736:             for (my $i=0; $i<$numnew; $i++) {
10737:                 my $newkey = $newitems[$i];
10738:                 my $newid = &Apache::loncommon::get_cgi_id();
10739:                 if ($newkey =~ /^\d+:/) { 
10740:                     $newkey =~ s/^(\d+)/$newid/;
10741:                     $translation{$1} = $newid;
10742:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
10743:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
10744:                     $translation{$1} = $newid;
10745:                 }
10746:                 $new_values{$file_name."\0".$newkey} = 
10747:                                           $$changes{'activate'}{$newitems[$i]};
10748:                 $new_control{$newkey} = $now;
10749:             }
10750:         }
10751:     }
10752:     my %todelete;
10753:     my %changed_items;
10754:     foreach my $action ('delete','update') {
10755:         if (exists($$changes{$action})) {
10756:             if (ref($$changes{$action}) eq 'HASH') {
10757:                 foreach my $key (keys(%{$$changes{$action}})) {
10758:                     my ($itemnum) = ($key =~ /^([^:]+):/);
10759:                     if ($action eq 'delete') { 
10760:                         $todelete{$itemnum} = 1;
10761:                     } else {
10762:                         $changed_items{$itemnum} = $key;
10763:                     }
10764:                 }
10765:             }
10766:         }
10767:     }
10768:     # get lock on access controls for file.
10769:     my $lockhash = {
10770:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
10771:                                                        ':'.$env{'user.domain'},
10772:                    }; 
10773:     my $tries = 0;
10774:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
10775:    
10776:     while (($gotlock ne 'ok') && $tries < 10) {
10777:         $tries ++;
10778:         sleep(0.1);
10779:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
10780:     }
10781:     if ($gotlock eq 'ok') {
10782:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
10783:         my ($tmp)=keys(%curr_permissions);
10784:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
10785:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
10786:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
10787:             if (ref($curr_controls) eq 'HASH') {
10788:                 foreach my $control_item (keys(%{$curr_controls})) {
10789:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
10790:                     if (defined($todelete{$itemnum})) {
10791:                         push(@deletions,$file_name."\0".$control_item);
10792:                     } else {
10793:                         if (defined($changed_items{$itemnum})) {
10794:                             $new_control{$changed_items{$itemnum}} = $now;
10795:                             push(@deletions,$file_name."\0".$control_item);
10796:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
10797:                         } else {
10798:                             $new_control{$control_item} = $$curr_controls{$control_item};
10799:                         }
10800:                     }
10801:                 }
10802:             }
10803:         }
10804:         my ($group);
10805:         if (&is_course($domain,$user)) {
10806:             ($group,my $file) = split(/\//,$file_name,2);
10807:         }
10808:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
10809:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
10810:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
10811:         #  remove lock
10812:         my @del_lock = ($file_name."\0".'locked_access_records');
10813:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
10814:         my $sqlresult =
10815:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
10816:                                     $group);
10817:     } else {
10818:         $outcome = "error: could not obtain lockfile\n";  
10819:     }
10820:     return ($outcome,$deloutcome,\%new_values,\%translation);
10821: }
10822: 
10823: sub make_public_indefinitely {
10824:     my ($requrl) = @_;
10825:     my $now = time;
10826:     my $action = 'activate';
10827:     my $aclnum = 0;
10828:     if (&is_portfolio_url($requrl)) {
10829:         my (undef,$udom,$unum,$file_name,$group) =
10830:             &parse_portfolio_url($requrl);
10831:         my $current_perms = &get_portfile_permissions($udom,$unum);
10832:         my %access_controls = &get_access_controls($current_perms,
10833:                                                    $group,$file_name);
10834:         foreach my $key (keys(%{$access_controls{$file_name}})) {
10835:             my ($num,$scope,$end,$start) = 
10836:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
10837:             if ($scope eq 'public') {
10838:                 if ($start <= $now && $end == 0) {
10839:                     $action = 'none';
10840:                 } else {
10841:                     $action = 'update';
10842:                     $aclnum = $num;
10843:                 }
10844:                 last;
10845:             }
10846:         }
10847:         if ($action eq 'none') {
10848:              return 'ok';
10849:         } else {
10850:             my %changes;
10851:             my $newend = 0;
10852:             my $newstart = $now;
10853:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
10854:             $changes{$action}{$newkey} = {
10855:                 type => 'public',
10856:                 time => {
10857:                     start => $newstart,
10858:                     end   => $newend,
10859:                 },
10860:             };
10861:             my ($outcome,$deloutcome,$new_values,$translation) =
10862:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
10863:             return $outcome;
10864:         }
10865:     } else {
10866:         return 'invalid';
10867:     }
10868: }
10869: 
10870: #------------------------------------------------------Get Marked as Read Only
10871: 
10872: sub get_marked_as_readonly {
10873:     my ($domain,$user,$what,$group) = @_;
10874:     my $current_permissions = &get_portfile_permissions($domain,$user);
10875:     my @readonly_files;
10876:     my $cmp1=$what;
10877:     if (ref($what)) { $cmp1=join('',@{$what}) };
10878:     while (my ($file_name,$value) = each(%{$current_permissions})) {
10879:         if (defined($group)) {
10880:             if ($file_name !~ m-^\Q$group\E/-) {
10881:                 next;
10882:             }
10883:         }
10884:         if (ref($value) eq "ARRAY"){
10885:             foreach my $stored_what (@{$value}) {
10886:                 my $cmp2=$stored_what;
10887:                 if (ref($stored_what) eq 'ARRAY') {
10888:                     $cmp2=join('',@{$stored_what});
10889:                 }
10890:                 if ($cmp1 eq $cmp2) {
10891:                     push(@readonly_files, $file_name);
10892:                     last;
10893:                 } elsif (!defined($what)) {
10894:                     push(@readonly_files, $file_name);
10895:                     last;
10896:                 }
10897:             }
10898:         }
10899:     }
10900:     return @readonly_files;
10901: }
10902: #-----------------------------------------------------------Get Marked as Read Only Hash
10903: 
10904: sub get_marked_as_readonly_hash {
10905:     my ($current_permissions,$group,$what) = @_;
10906:     my %readonly_files;
10907:     while (my ($file_name,$value) = each(%{$current_permissions})) {
10908:         if (defined($group)) {
10909:             if ($file_name !~ m-^\Q$group\E/-) {
10910:                 next;
10911:             }
10912:         }
10913:         if (ref($value) eq "ARRAY"){
10914:             foreach my $stored_what (@{$value}) {
10915:                 if (ref($stored_what) eq 'ARRAY') {
10916:                     foreach my $lock_descriptor(@{$stored_what}) {
10917:                         if ($lock_descriptor eq 'graded') {
10918:                             $readonly_files{$file_name} = 'graded';
10919:                         } elsif ($lock_descriptor eq 'handback') {
10920:                             $readonly_files{$file_name} = 'handback';
10921:                         } else {
10922:                             if (!exists($readonly_files{$file_name})) {
10923:                                 $readonly_files{$file_name} = 'locked';
10924:                             }
10925:                         }
10926:                     }
10927:                 } 
10928:             }
10929:         } 
10930:     }
10931:     return %readonly_files;
10932: }
10933: # ------------------------------------------------------------ Unmark as Read Only
10934: 
10935: sub unmark_as_readonly {
10936:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
10937:     # for portfolio submissions, $what contains [$symb,$crsid] 
10938:     my ($domain,$user,$what,$file_name,$group) = @_;
10939:     $file_name = &declutter_portfile($file_name);
10940:     my $symb_crs = $what;
10941:     if (ref($what)) { $symb_crs=join('',@$what); }
10942:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
10943:     my ($tmp)=keys(%current_permissions);
10944:     if ($tmp=~/^error:/) { undef(%current_permissions); }
10945:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
10946:     foreach my $file (@readonly_files) {
10947: 	my $clean_file = &declutter_portfile($file);
10948: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
10949: 	my $current_locks = $current_permissions{$file};
10950:         my @new_locks;
10951:         my @del_keys;
10952:         if (ref($current_locks) eq "ARRAY"){
10953:             foreach my $locker (@{$current_locks}) {
10954:                 my $compare=$locker;
10955:                 if (ref($locker) eq 'ARRAY') {
10956:                     $compare=join('',@{$locker});
10957:                     if ($compare ne $symb_crs) {
10958:                         push(@new_locks, $locker);
10959:                     }
10960:                 }
10961:             }
10962:             if (scalar(@new_locks) > 0) {
10963:                 $current_permissions{$file} = \@new_locks;
10964:             } else {
10965:                 push(@del_keys, $file);
10966:                 &del('file_permissions',\@del_keys, $domain, $user);
10967:                 delete($current_permissions{$file});
10968:             }
10969:         }
10970:     }
10971:     &put('file_permissions',\%current_permissions,$domain,$user);
10972:     return;
10973: }
10974: 
10975: # ------------------------------------------------------------ Directory lister
10976: 
10977: sub dirlist {
10978:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
10979:     $uri=~s/^\///;
10980:     $uri=~s/\/$//;
10981:     my ($udom, $uname);
10982:     if ($getuserdir) {
10983:         $udom = $userdomain;
10984:         $uname = $username;
10985:     } else {
10986:         (undef,$udom,$uname)=split(/\//,$uri);
10987:         if(defined($userdomain)) {
10988:             $udom = $userdomain;
10989:         }
10990:         if(defined($username)) {
10991:             $uname = $username;
10992:         }
10993:     }
10994:     my ($dirRoot,$listing,@listing_results);
10995: 
10996:     $dirRoot = $perlvar{'lonDocRoot'};
10997:     if (defined($getpropath)) {
10998:         $dirRoot = &propath($udom,$uname);
10999:         $dirRoot =~ s/\/$//;
11000:     } elsif (defined($getuserdir)) {
11001:         my $subdir=$uname.'__';
11002:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
11003:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
11004:                    ."/$udom/$subdir/$uname";
11005:     } elsif (defined($alternateRoot)) {
11006:         $dirRoot = $alternateRoot;
11007:     }
11008: 
11009:     if($udom) {
11010:         if($uname) {
11011:             my $uhome = &homeserver($uname,$udom);
11012:             if ($uhome eq 'no_host') {
11013:                 return ([],'no_host');
11014:             }
11015:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
11016:                               .$getuserdir.':'.&escape($dirRoot)
11017:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
11018:             if ($listing eq 'unknown_cmd') {
11019:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
11020:             } else {
11021:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
11022:             }
11023:             if ($listing eq 'unknown_cmd') {
11024:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
11025:                 @listing_results = split(/:/,$listing);
11026:             } else {
11027:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
11028:             }
11029:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
11030:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
11031:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11032:                 return ([],$listing);
11033:             } else {
11034:                 return (\@listing_results);
11035:             }
11036:         } elsif(!$alternateRoot) {
11037:             my (%allusers,%listerror);
11038: 	    my %servers = &get_servers($udom,'library');
11039:  	    foreach my $tryserver (keys(%servers)) {
11040:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
11041:                                   &escape($udom),$tryserver);
11042:                 if ($listing eq 'unknown_cmd') {
11043: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
11044: 				      $udom, $tryserver);
11045:                 } else {
11046:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
11047:                 }
11048: 		if ($listing eq 'unknown_cmd') {
11049: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
11050: 				      $udom, $tryserver);
11051: 		    @listing_results = split(/:/,$listing);
11052: 		} else {
11053: 		    @listing_results =
11054: 			map { &unescape($_); } split(/:/,$listing);
11055: 		}
11056:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
11057:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
11058:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11059:                     $listerror{$tryserver} = $listing;
11060:                 } else {
11061: 		    foreach my $line (@listing_results) {
11062: 			my ($entry) = split(/&/,$line,2);
11063: 			$allusers{$entry} = 1;
11064: 		    }
11065: 		}
11066:             }
11067:             my @alluserslist=();
11068:             foreach my $user (sort(keys(%allusers))) {
11069:                 push(@alluserslist,$user.'&user');
11070:             }
11071:             if (!%listerror) {
11072:                 # no errors
11073:                 return (\@alluserslist);
11074:             } elsif (scalar(keys(%servers)) == 1) {
11075:                 # one library server, one error
11076:                 my ($key) = keys(%listerror);
11077:                 return (\@alluserslist, $listerror{$key});
11078:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
11079:                 # con_lost indicates that we might miss data from at least one
11080:                 # library server
11081:                 return (\@alluserslist, 'con_lost');
11082:             } else {
11083:                 # multiple library servers and no con_lost -> data should be
11084:                 # complete.
11085:                 return (\@alluserslist);
11086:             }
11087: 
11088:         } else {
11089:             return ([],'missing username');
11090:         }
11091:     } elsif(!defined($getpropath)) {
11092:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
11093:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
11094:         return (\@all_domains);
11095:     } else {
11096:         return ([],'missing domain');
11097:     }
11098: }
11099: 
11100: # --------------------------------------------- GetFileTimestamp
11101: # This function utilizes dirlist and returns the date stamp for
11102: # when it was last modified.  It will also return an error of -1
11103: # if an error occurs
11104: 
11105: sub GetFileTimestamp {
11106:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
11107:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
11108:     $studentName   = &LONCAPA::clean_username($studentName);
11109:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
11110:                                     undef,$getuserdir);
11111:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11112:         return -1;
11113:     }
11114:     if (ref($fileref) eq 'ARRAY') {
11115:         my @stats = split('&',$fileref->[0]);
11116:         # @stats contains first the filename, then the stat output
11117:         return $stats[10]; # so this is 10 instead of 9.
11118:     } else {
11119:         return -1;
11120:     }
11121: }
11122: 
11123: sub stat_file {
11124:     my ($uri) = @_;
11125:     $uri = &clutter_with_no_wrapper($uri);
11126: 
11127:     my ($udom,$uname,$file);
11128:     if ($uri =~ m-^/(uploaded|editupload)/-) {
11129: 	($udom,$uname,$file) =
11130: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
11131: 	$file = 'userfiles/'.$file;
11132:     }
11133:     if ($uri =~ m-^/res/-) {
11134: 	($udom,$uname) = 
11135: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
11136: 	$file = $uri;
11137:     }
11138: 
11139:     if (!$udom || !$uname || !$file) {
11140: 	# unable to handle the uri
11141: 	return ();
11142:     }
11143:     my $getpropath;
11144:     if ($file =~ /^userfiles\//) {
11145:         $getpropath = 1;
11146:     }
11147:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
11148:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11149:         return ();
11150:     } else {
11151:         if (ref($listref) eq 'ARRAY') {
11152:             my @stats = split('&',$listref->[0]);
11153: 	    shift(@stats); #filename is first
11154: 	    return @stats;
11155:         }
11156:     }
11157:     return ();
11158: }
11159: 
11160: # -------------------------------------------------------- Value of a Condition
11161: 
11162: # gets the value of a specific preevaluated condition
11163: #    stored in the string  $env{user.state.<cid>}
11164: # or looks up a condition reference in the bighash and if if hasn't
11165: # already been evaluated recurses into docondval to get the value of
11166: # the condition, then memoizing it to 
11167: #   $env{user.state.<cid>.<condition>}
11168: sub directcondval {
11169:     my $number=shift;
11170:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
11171: 	&Apache::lonuserstate::evalstate();
11172:     }
11173:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
11174: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
11175:     } elsif ($number =~ /^_/) {
11176: 	my $sub_condition;
11177: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
11178: 		&GDBM_READER(),0640)) {
11179: 	    $sub_condition=$bighash{'conditions'.$number};
11180: 	    untie(%bighash);
11181: 	}
11182: 	my $value = &docondval($sub_condition);
11183: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
11184: 	return $value;
11185:     }
11186:     if ($env{'user.state.'.$env{'request.course.id'}}) {
11187:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
11188:     } else {
11189:        return 2;
11190:     }
11191: }
11192: 
11193: # get the collection of conditions for this resource
11194: sub condval {
11195:     my $condidx=shift;
11196:     my $allpathcond='';
11197:     foreach my $cond (split(/\|/,$condidx)) {
11198: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
11199: 	    $allpathcond.=
11200: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
11201: 	}
11202:     }
11203:     $allpathcond=~s/\|$//;
11204:     return &docondval($allpathcond);
11205: }
11206: 
11207: #evaluates an expression of conditions
11208: sub docondval {
11209:     my ($allpathcond) = @_;
11210:     my $result=0;
11211:     if ($env{'request.course.id'}
11212: 	&& defined($allpathcond)) {
11213: 	my $operand='|';
11214: 	my @stack;
11215: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
11216: 	    if ($chunk eq '(') {
11217: 		push @stack,($operand,$result);
11218: 	    } elsif ($chunk eq ')') {
11219: 		my $before=pop @stack;
11220: 		if (pop @stack eq '&') {
11221: 		    $result=$result>$before?$before:$result;
11222: 		} else {
11223: 		    $result=$result>$before?$result:$before;
11224: 		}
11225: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
11226: 		$operand=$chunk;
11227: 	    } else {
11228: 		my $new=directcondval($chunk);
11229: 		if ($operand eq '&') {
11230: 		    $result=$result>$new?$new:$result;
11231: 		} else {
11232: 		    $result=$result>$new?$result:$new;
11233: 		}
11234: 	    }
11235: 	}
11236:     }
11237:     return $result;
11238: }
11239: 
11240: # ---------------------------------------------------- Devalidate courseresdata
11241: 
11242: sub devalidatecourseresdata {
11243:     my ($coursenum,$coursedomain)=@_;
11244:     my $hashid=$coursenum.':'.$coursedomain;
11245:     &devalidate_cache_new('courseres',$hashid);
11246: }
11247: 
11248: 
11249: # --------------------------------------------------- Course Resourcedata Query
11250: #
11251: #  Parameters:
11252: #      $coursenum    - Number of the course.
11253: #      $coursedomain - Domain at which the course was created.
11254: #  Returns:
11255: #     A hash of the course parameters along (I think) with timestamps
11256: #     and version info.
11257: 
11258: sub get_courseresdata {
11259:     my ($coursenum,$coursedomain)=@_;
11260:     my $coursehom=&homeserver($coursenum,$coursedomain);
11261:     my $hashid=$coursenum.':'.$coursedomain;
11262:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
11263:     my %dumpreply;
11264:     unless (defined($cached)) {
11265: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
11266: 	$result=\%dumpreply;
11267: 	my ($tmp) = keys(%dumpreply);
11268: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
11269: 	    &do_cache_new('courseres',$hashid,$result,600);
11270: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
11271: 	    return $tmp;
11272: 	} elsif ($tmp =~ /^(error)/) {
11273: 	    $result=undef;
11274: 	    &do_cache_new('courseres',$hashid,$result,600);
11275: 	}
11276:     }
11277:     return $result;
11278: }
11279: 
11280: sub devalidateuserresdata {
11281:     my ($uname,$udom)=@_;
11282:     my $hashid="$udom:$uname";
11283:     &devalidate_cache_new('userres',$hashid);
11284: }
11285: 
11286: sub get_userresdata {
11287:     my ($uname,$udom)=@_;
11288:     #most student don\'t have any data set, check if there is some data
11289:     if (&EXT_cache_status($udom,$uname)) { return undef; }
11290: 
11291:     my $hashid="$udom:$uname";
11292:     my ($result,$cached)=&is_cached_new('userres',$hashid);
11293:     if (!defined($cached)) {
11294: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
11295: 	$result=\%resourcedata;
11296: 	&do_cache_new('userres',$hashid,$result,600);
11297:     }
11298:     my ($tmp)=keys(%$result);
11299:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
11300: 	return $result;
11301:     }
11302:     #error 2 occurs when the .db doesn't exist
11303:     if ($tmp!~/error: 2 /) {
11304:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
11305: 	    &logthis("<font color=\"blue\">WARNING:".
11306: 		     " Trying to get resource data for ".
11307: 		     $uname." at ".$udom.": ".
11308: 		     $tmp."</font>");
11309:         }
11310:     } elsif ($tmp=~/error: 2 /) {
11311: 	#&EXT_cache_set($udom,$uname);
11312: 	&do_cache_new('userres',$hashid,undef,600);
11313: 	undef($tmp); # not really an error so don't send it back
11314:     }
11315:     return $tmp;
11316: }
11317: #----------------------------------------------- resdata - return resource data
11318: #  Purpose:
11319: #    Return resource data for either users or for a course.
11320: #  Parameters:
11321: #     $name      - Course/user name.
11322: #     $domain    - Name of the domain the user/course is registered on.
11323: #     $type      - Type of thing $name is (must be 'course' or 'user'
11324: #     @which     - Array of names of resources desired.
11325: #  Returns:
11326: #     The value of the first reasource in @which that is found in the
11327: #     resource hash.
11328: #  Exceptional Conditions:
11329: #     If the $type passed in is not valid (not the string 'course' or 
11330: #     'user', an undefined  reference is returned.
11331: #     If none of the resources are found, an undef is returned
11332: sub resdata {
11333:     my ($name,$domain,$type,@which)=@_;
11334:     my $result;
11335:     if ($type eq 'course') {
11336: 	$result=&get_courseresdata($name,$domain);
11337:     } elsif ($type eq 'user') {
11338: 	$result=&get_userresdata($name,$domain);
11339:     }
11340:     if (!ref($result)) { return $result; }    
11341:     foreach my $item (@which) {
11342: 	if (defined($result->{$item->[0]})) {
11343: 	    return [$result->{$item->[0]},$item->[1]];
11344: 	}
11345:     }
11346:     return undef;
11347: }
11348: 
11349: sub get_numsuppfiles {
11350:     my ($cnum,$cdom,$ignorecache)=@_;
11351:     my $hashid=$cnum.':'.$cdom;
11352:     my ($suppcount,$cached);
11353:     unless ($ignorecache) {
11354:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
11355:     }
11356:     unless (defined($cached)) {
11357:         my $chome=&homeserver($cnum,$cdom);
11358:         unless ($chome eq 'no_host') {
11359:             ($suppcount,my $errors) = (0,0);
11360:             my $suppmap = 'supplemental.sequence';
11361:             ($suppcount,$errors) =
11362:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
11363:         }
11364:         &do_cache_new('suppcount',$hashid,$suppcount,600);
11365:     }
11366:     return $suppcount;
11367: }
11368: 
11369: #
11370: # EXT resource caching routines
11371: #
11372: 
11373: sub clear_EXT_cache_status {
11374:     &delenv('cache.EXT.');
11375: }
11376: 
11377: sub EXT_cache_status {
11378:     my ($target_domain,$target_user) = @_;
11379:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
11380:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
11381:         # We know already the user has no data
11382:         return 1;
11383:     } else {
11384:         return 0;
11385:     }
11386: }
11387: 
11388: sub EXT_cache_set {
11389:     my ($target_domain,$target_user) = @_;
11390:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
11391:     #&appenv({$cachename => time});
11392: }
11393: 
11394: # --------------------------------------------------------- Value of a Variable
11395: sub EXT {
11396: 
11397:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
11398:     unless ($varname) { return ''; }
11399:     #get real user name/domain, courseid and symb
11400:     my $courseid;
11401:     my $publicuser;
11402:     if ($symbparm) {
11403: 	$symbparm=&get_symb_from_alias($symbparm);
11404:     }
11405:     if (!($uname && $udom)) {
11406:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
11407:       if (!$symbparm) {	$symbparm=$cursymb; }
11408:     } else {
11409: 	$courseid=$env{'request.course.id'};
11410:     }
11411:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
11412:     my $rest;
11413:     if (defined($therest[0])) {
11414:        $rest=join('.',@therest);
11415:     } else {
11416:        $rest='';
11417:     }
11418: 
11419:     my $qualifierrest=$qualifier;
11420:     if ($rest) { $qualifierrest.='.'.$rest; }
11421:     my $spacequalifierrest=$space;
11422:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
11423:     if ($realm eq 'user') {
11424: # --------------------------------------------------------------- user.resource
11425: 	if ($space eq 'resource') {
11426: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
11427: 		  || defined($Apache::lonhomework::parsing_a_task))
11428: 		 &&
11429: 		 ($symbparm eq &symbread()) ) {	
11430: 		# if we are in the middle of processing the resource the
11431: 		# get the value we are planning on committing
11432:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
11433:                     return $Apache::lonhomework::results{$qualifierrest};
11434:                 } else {
11435:                     return $Apache::lonhomework::history{$qualifierrest};
11436:                 }
11437: 	    } else {
11438: 		my %restored;
11439: 		if ($publicuser || $env{'request.state'} eq 'construct') {
11440: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
11441: 		} else {
11442: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
11443: 		}
11444: 		return $restored{$qualifierrest};
11445: 	    }
11446: # ----------------------------------------------------------------- user.access
11447:         } elsif ($space eq 'access') {
11448: 	    # FIXME - not supporting calls for a specific user
11449:             return &allowed($qualifier,$rest);
11450: # ------------------------------------------ user.preferences, user.environment
11451:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
11452: 	    if (($uname eq $env{'user.name'}) &&
11453: 		($udom eq $env{'user.domain'})) {
11454: 		return $env{join('.',('environment',$qualifierrest))};
11455: 	    } else {
11456: 		my %returnhash;
11457: 		if (!$publicuser) {
11458: 		    %returnhash=&userenvironment($udom,$uname,
11459: 						 $qualifierrest);
11460: 		}
11461: 		return $returnhash{$qualifierrest};
11462: 	    }
11463: # ----------------------------------------------------------------- user.course
11464:         } elsif ($space eq 'course') {
11465: 	    # FIXME - not supporting calls for a specific user
11466:             return $env{join('.',('request.course',$qualifier))};
11467: # ------------------------------------------------------------------- user.role
11468:         } elsif ($space eq 'role') {
11469: 	    # FIXME - not supporting calls for a specific user
11470:             my ($role,$where)=split(/\./,$env{'request.role'});
11471:             if ($qualifier eq 'value') {
11472: 		return $role;
11473:             } elsif ($qualifier eq 'extent') {
11474:                 return $where;
11475:             }
11476: # ----------------------------------------------------------------- user.domain
11477:         } elsif ($space eq 'domain') {
11478:             return $udom;
11479: # ------------------------------------------------------------------- user.name
11480:         } elsif ($space eq 'name') {
11481:             return $uname;
11482: # ---------------------------------------------------- Any other user namespace
11483:         } else {
11484: 	    my %reply;
11485: 	    if (!$publicuser) {
11486: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
11487: 	    }
11488: 	    return $reply{$qualifierrest};
11489:         }
11490:     } elsif ($realm eq 'query') {
11491: # ---------------------------------------------- pull stuff out of query string
11492:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
11493: 						[$spacequalifierrest]);
11494: 	return $env{'form.'.$spacequalifierrest}; 
11495:    } elsif ($realm eq 'request') {
11496: # ------------------------------------------------------------- request.browser
11497:         if ($space eq 'browser') {
11498:             return $env{'browser.'.$qualifier};
11499: # ------------------------------------------------------------ request.filename
11500:         } else {
11501:             return $env{'request.'.$spacequalifierrest};
11502:         }
11503:     } elsif ($realm eq 'course') {
11504: # ---------------------------------------------------------- course.description
11505:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
11506:     } elsif ($realm eq 'resource') {
11507: 
11508: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
11509: 	    if (!$symbparm) { $symbparm=&symbread(); }
11510: 	}
11511: 
11512:         if ($qualifier eq '') {
11513: 	    if ($space eq 'title') {
11514: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
11515: 	        return &gettitle($symbparm);
11516: 	    }
11517: 	
11518: 	    if ($space eq 'map') {
11519: 	        my ($map) = &decode_symb($symbparm);
11520: 	        return &symbread($map);
11521: 	    }
11522:             if ($space eq 'maptitle') {
11523:                 my ($map) = &decode_symb($symbparm);
11524:                 return &gettitle($map);
11525:             }
11526: 	    if ($space eq 'filename') {
11527: 	        if ($symbparm) {
11528: 		    return &clutter((&decode_symb($symbparm))[2]);
11529: 	        }
11530: 	        return &hreflocation('',$env{'request.filename'});
11531: 	    }
11532: 
11533:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
11534:                 if ($space eq 'visibleparts') {
11535:                     my $navmap = Apache::lonnavmaps::navmap->new();
11536:                     my $item;
11537:                     if (ref($navmap)) {
11538:                         my $res = $navmap->getBySymb($symbparm);
11539:                         my $parts = $res->parts();
11540:                         if (ref($parts) eq 'ARRAY') {
11541:                             $item = join(',',@{$parts});
11542:                         }
11543:                         undef($navmap);
11544:                     }
11545:                     return $item;
11546:                 }
11547:             }
11548:         }
11549: 
11550: 	my ($section, $group, @groups);
11551: 	my ($courselevelm,$courselevel);
11552:         if (($courseid eq '') && ($cid)) {
11553:             $courseid = $cid;
11554:         }
11555: 	if (($symbparm && $courseid) && 
11556: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
11557: 
11558: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
11559: 
11560: # ----------------------------------------------------- Cascading lookup scheme
11561: 	    my $symbp=$symbparm;
11562: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
11563: 
11564: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
11565: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
11566: 
11567: 	    if (($env{'user.name'} eq $uname) &&
11568: 		($env{'user.domain'} eq $udom)) {
11569: 		$section=$env{'request.course.sec'};
11570:                 @groups = split(/:/,$env{'request.course.groups'});  
11571:                 @groups=&sort_course_groups($courseid,@groups); 
11572: 	    } else {
11573: 		if (! defined($usection)) {
11574: 		    $section=&getsection($udom,$uname,$courseid);
11575: 		} else {
11576: 		    $section = $usection;
11577: 		}
11578:                 @groups = &get_users_groups($udom,$uname,$courseid);
11579: 	    }
11580: 
11581: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
11582: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
11583: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
11584: 
11585: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
11586: 	    my $courselevelr=$courseid.'.'.$symbparm;
11587: 	    $courselevelm=$courseid.'.'.$mapparm;
11588: 
11589: # ----------------------------------------------------------- first, check user
11590: 
11591: 	    my $userreply=&resdata($uname,$udom,'user',
11592: 				       ([$courselevelr,'resource'],
11593: 					[$courselevelm,'map'     ],
11594: 					[$courselevel, 'course'  ]));
11595: 	    if (defined($userreply)) { return &get_reply($userreply); }
11596: 
11597: # ------------------------------------------------ second, check some of course
11598:             my $coursereply;
11599:             if (@groups > 0) {
11600:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
11601:                                        $mapparm,$spacequalifierrest);
11602:                 if (defined($coursereply)) { return &get_reply($coursereply); }
11603:             }
11604: 
11605: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
11606: 				  $env{'course.'.$courseid.'.domain'},
11607: 				  'course',
11608: 				  ([$seclevelr,   'resource'],
11609: 				   [$seclevelm,   'map'     ],
11610: 				   [$seclevel,    'course'  ],
11611: 				   [$courselevelr,'resource']));
11612: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
11613: 
11614: # ------------------------------------------------------ third, check map parms
11615: 	    my %parmhash=();
11616: 	    my $thisparm='';
11617: 	    if (tie(%parmhash,'GDBM_File',
11618: 		    $env{'request.course.fn'}.'_parms.db',
11619: 		    &GDBM_READER(),0640)) {
11620: 		$thisparm=$parmhash{$symbparm};
11621: 		untie(%parmhash);
11622: 	    }
11623: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
11624: 	}
11625: # ------------------------------------------ fourth, look in resource metadata
11626: 
11627: 	$spacequalifierrest=~s/\./\_/;
11628: 	my $filename;
11629: 	if (!$symbparm) { $symbparm=&symbread(); }
11630: 	if ($symbparm) {
11631: 	    $filename=(&decode_symb($symbparm))[2];
11632: 	} else {
11633: 	    $filename=$env{'request.filename'};
11634: 	}
11635: 	my $metadata=&metadata($filename,$spacequalifierrest);
11636: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
11637: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
11638: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
11639: 
11640: # ---------------------------------------------- fourth, look in rest of course
11641: 	if ($symbparm && defined($courseid) && 
11642: 	    $courseid eq $env{'request.course.id'}) {
11643: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
11644: 				     $env{'course.'.$courseid.'.domain'},
11645: 				     'course',
11646: 				     ([$courselevelm,'map'   ],
11647: 				      [$courselevel, 'course']));
11648: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
11649: 	}
11650: # ------------------------------------------------------------------ Cascade up
11651: 	unless ($space eq '0') {
11652: 	    my @parts=split(/_/,$space);
11653: 	    my $id=pop(@parts);
11654: 	    my $part=join('_',@parts);
11655: 	    if ($part eq '') { $part='0'; }
11656: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
11657: 				 $symbparm,$udom,$uname,$section,1);
11658: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
11659: 	}
11660: 	if ($recurse) { return undef; }
11661: 	my $pack_def=&packages_tab_default($filename,$varname);
11662: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
11663: # ---------------------------------------------------- Any other user namespace
11664:     } elsif ($realm eq 'environment') {
11665: # ----------------------------------------------------------------- environment
11666: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
11667: 	    return $env{'environment.'.$spacequalifierrest};
11668: 	} else {
11669: 	    if ($uname eq 'anonymous' && $udom eq '') {
11670: 		return '';
11671: 	    }
11672: 	    my %returnhash=&userenvironment($udom,$uname,
11673: 					    $spacequalifierrest);
11674: 	    return $returnhash{$spacequalifierrest};
11675: 	}
11676:     } elsif ($realm eq 'system') {
11677: # ----------------------------------------------------------------- system.time
11678: 	if ($space eq 'time') {
11679: 	    return time;
11680:         }
11681:     } elsif ($realm eq 'server') {
11682: # ----------------------------------------------------------------- system.time
11683: 	if ($space eq 'name') {
11684: 	    return $ENV{'SERVER_NAME'};
11685:         }
11686:     }
11687:     return '';
11688: }
11689: 
11690: sub get_reply {
11691:     my ($reply_value) = @_;
11692:     if (ref($reply_value) eq 'ARRAY') {
11693:         if (wantarray) {
11694: 	    return @$reply_value;
11695:         }
11696:         return $reply_value->[0];
11697:     } else {
11698:         return $reply_value;
11699:     }
11700: }
11701: 
11702: sub check_group_parms {
11703:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
11704:     my @groupitems = ();
11705:     my $resultitem;
11706:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
11707:     foreach my $group (@{$groups}) {
11708:         foreach my $level (@levels) {
11709:              my $item = $courseid.'.['.$group.'].'.$level->[0];
11710:              push(@groupitems,[$item,$level->[1]]);
11711:         }
11712:     }
11713:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
11714:                             $env{'course.'.$courseid.'.domain'},
11715:                                      'course',@groupitems);
11716:     return $coursereply;
11717: }
11718: 
11719: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
11720:     my ($courseid,@groups) = @_;
11721:     @groups = sort(@groups);
11722:     return @groups;
11723: }
11724: 
11725: sub packages_tab_default {
11726:     my ($uri,$varname)=@_;
11727:     my (undef,$part,$name)=split(/\./,$varname);
11728: 
11729:     my (@extension,@specifics,$do_default);
11730:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
11731: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
11732: 	if ($pack_type eq 'default') {
11733: 	    $do_default=1;
11734: 	} elsif ($pack_type eq 'extension') {
11735: 	    push(@extension,[$package,$pack_type,$pack_part]);
11736: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
11737: 	    # only look at packages defaults for packages that this id is
11738: 	    push(@specifics,[$package,$pack_type,$pack_part]);
11739: 	}
11740:     }
11741:     # first look for a package that matches the requested part id
11742:     foreach my $package (@specifics) {
11743: 	my (undef,$pack_type,$pack_part)=@{$package};
11744: 	next if ($pack_part ne $part);
11745: 	if (defined($packagetab{"$pack_type&$name&default"})) {
11746: 	    return $packagetab{"$pack_type&$name&default"};
11747: 	}
11748:     }
11749:     # look for any possible matching non extension_ package
11750:     foreach my $package (@specifics) {
11751: 	my (undef,$pack_type,$pack_part)=@{$package};
11752: 	if (defined($packagetab{"$pack_type&$name&default"})) {
11753: 	    return $packagetab{"$pack_type&$name&default"};
11754: 	}
11755: 	if ($pack_type eq 'part') { $pack_part='0'; }
11756: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
11757: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
11758: 	}
11759:     }
11760:     # look for any posible extension_ match
11761:     foreach my $package (@extension) {
11762: 	my ($package,$pack_type)=@{$package};
11763: 	if (defined($packagetab{"$pack_type&$name&default"})) {
11764: 	    return $packagetab{"$pack_type&$name&default"};
11765: 	}
11766: 	if (defined($packagetab{$package."&$name&default"})) {
11767: 	    return $packagetab{$package."&$name&default"};
11768: 	}
11769:     }
11770:     # look for a global default setting
11771:     if ($do_default && defined($packagetab{"default&$name&default"})) {
11772: 	return $packagetab{"default&$name&default"};
11773:     }
11774:     return undef;
11775: }
11776: 
11777: sub add_prefix_and_part {
11778:     my ($prefix,$part)=@_;
11779:     my $keyroot;
11780:     if (defined($prefix) && $prefix !~ /^__/) {
11781: 	# prefix that has a part already
11782: 	$keyroot=$prefix;
11783:     } elsif (defined($prefix)) {
11784: 	# prefix that is missing a part
11785: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
11786:     } else {
11787: 	# no prefix at all
11788: 	if (defined($part)) { $keyroot='_'.$part; }
11789:     }
11790:     return $keyroot;
11791: }
11792: 
11793: # ---------------------------------------------------------------- Get metadata
11794: 
11795: my %metaentry;
11796: my %importedpartids;
11797: my %importedrespids;
11798: sub metadata {
11799:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
11800:     $uri=&declutter($uri);
11801:     # if it is a non metadata possible uri return quickly
11802:     if (($uri eq '') || 
11803: 	(($uri =~ m|^/*adm/|) && 
11804: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
11805:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
11806: 	return undef;
11807:     }
11808:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
11809: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
11810: 	return undef;
11811:     }
11812:     my $filename=$uri;
11813:     $uri=~s/\.meta$//;
11814: #
11815: # Is the metadata already cached?
11816: # Look at timestamp of caching
11817: # Everything is cached by the main uri, libraries are never directly cached
11818: #
11819:     if (!defined($liburi)) {
11820: 	my ($result,$cached)=&is_cached_new('meta',$uri);
11821: 	if (defined($cached)) { return $result->{':'.$what}; }
11822:     }
11823:     {
11824: # Imported parts would go here
11825:         my @origfiletagids=();
11826:         my $importedparts=0;
11827: 
11828: # Imported responseids would go here
11829:         my $importedresponses=0;
11830: #
11831: # Is this a recursive call for a library?
11832: #
11833: #	if (! exists($metacache{$uri})) {
11834: #	    $metacache{$uri}={};
11835: #	}
11836: 	my $cachetime = 60*60;
11837:         if ($liburi) {
11838: 	    $liburi=&declutter($liburi);
11839:             $filename=$liburi;
11840:         } else {
11841: 	    &devalidate_cache_new('meta',$uri);
11842: 	    undef(%metaentry);
11843: 	}
11844:         my %metathesekeys=();
11845:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
11846: 	my $metastring;
11847: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
11848: 	    my $which = &hreflocation('','/'.($liburi || $uri));
11849: 	    $metastring = 
11850: 		&Apache::lonnet::ssi_body($which,
11851: 					  ('grade_target' => 'meta'));
11852: 	    $cachetime = 1; # only want this cached in the child not long term
11853: 	} elsif (($uri !~ m -^(editupload)/-) && 
11854:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
11855: 	    my $file=&filelocation('',&clutter($filename));
11856: 	    #push(@{$metaentry{$uri.'.file'}},$file);
11857: 	    $metastring=&getfile($file);
11858: 	}
11859:         my $parser=HTML::LCParser->new(\$metastring);
11860:         my $token;
11861:         undef %metathesekeys;
11862:         while ($token=$parser->get_token) {
11863: 	    if ($token->[0] eq 'S') {
11864: 		if (defined($token->[2]->{'package'})) {
11865: #
11866: # This is a package - get package info
11867: #
11868: 		    my $package=$token->[2]->{'package'};
11869: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11870: 		    if (defined($token->[2]->{'id'})) { 
11871: 			$keyroot.='_'.$token->[2]->{'id'}; 
11872: 		    }
11873: 		    if ($metaentry{':packages'}) {
11874: 			$metaentry{':packages'}.=','.$package.$keyroot;
11875: 		    } else {
11876: 			$metaentry{':packages'}=$package.$keyroot;
11877: 		    }
11878: 		    foreach my $pack_entry (keys(%packagetab)) {
11879: 			my $part=$keyroot;
11880: 			$part=~s/^\_//;
11881: 			if ($pack_entry=~/^\Q$package\E\&/ || 
11882: 			    $pack_entry=~/^\Q$package\E_0\&/) {
11883: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
11884: 			    # ignore package.tab specified default values
11885:                             # here &package_tab_default() will fetch those
11886: 			    if ($subp eq 'default') { next; }
11887: 			    my $value=$packagetab{$pack_entry};
11888: 			    my $unikey;
11889: 			    if ($pack =~ /_0$/) {
11890: 				$unikey='parameter_0_'.$name;
11891: 				$part=0;
11892: 			    } else {
11893: 				$unikey='parameter'.$keyroot.'_'.$name;
11894: 			    }
11895: 			    if ($subp eq 'display') {
11896: 				$value.=' [Part: '.$part.']';
11897: 			    }
11898: 			    $metaentry{':'.$unikey.'.part'}=$part;
11899: 			    $metathesekeys{$unikey}=1;
11900: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
11901: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
11902: 			    }
11903: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
11904: 				$metaentry{':'.$unikey}=
11905: 				    $metaentry{':'.$unikey.'.default'};
11906: 			    }
11907: 			}
11908: 		    }
11909: 		} else {
11910: #
11911: # This is not a package - some other kind of start tag
11912: #
11913: 		    my $entry=$token->[1];
11914: 		    my $unikey='';
11915: 
11916: 		    if ($entry eq 'import') {
11917: #
11918: # Importing a library here
11919: #
11920:                         my $location=$parser->get_text('/import');
11921:                         my $dir=$filename;
11922:                         $dir=~s|[^/]*$||;
11923:                         $location=&filelocation($dir,$location);
11924: 
11925:                         my $importid=$token->[2]->{'id'};
11926:                         my $importmode=$token->[2]->{'importmode'};
11927: #
11928: # Check metadata for imported file to
11929: # see if it contained response items
11930: #
11931:                         my %currmetaentry = %metaentry;
11932:                         my $libresponseorder = &metadata($location,'responseorder');
11933:                         my $origfile;
11934:                         if ($libresponseorder ne '') {
11935:                             if ($#origfiletagids<0) {
11936:                                 undef(%importedrespids);
11937:                                 undef(%importedpartids);
11938:                             }
11939:                             @{$importedrespids{$importid}} = split(/\s*,\s*/,$libresponseorder);
11940:                             if (@{$importedrespids{$importid}} > 0) {
11941:                                 $importedresponses = 1;
11942: # We need to get the original file and the imported file to get the response order correct
11943: # Load and inspect original file
11944:                                 if ($#origfiletagids<0) {
11945:                                     my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
11946:                                     $origfile=&getfile($origfilelocation);
11947:                                     @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
11948:                                 }
11949:                             }
11950:                         }
11951: # Do not overwrite contents of %metaentry hash for resource itself with 
11952: # hash populated for imported library file
11953:                         %metaentry = %currmetaentry;
11954:                         undef(%currmetaentry);
11955:                         if ($importmode eq 'problem') {
11956: # Import as problem/response
11957:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11958:                         } elsif ($importmode eq 'part') {
11959: # Import as part(s)
11960:                            $importedparts=1;
11961: # We need to get the original file and the imported file to get the part order correct
11962: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
11963: # Load and inspect original file if we didn't do that already
11964:                            if ($#origfiletagids<0) {
11965:                                undef(%importedrespids);
11966:                                undef(%importedpartids);
11967:                                if ($origfile eq '') {
11968:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
11969:                                    $origfile=&getfile($origfilelocation);
11970:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
11971:                                }
11972:                            }
11973: 
11974: # Load and inspect imported file
11975:                            my $impfile=&getfile($location);
11976:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
11977:                            if ($#impfilepartids>=0) {
11978: # This problem had parts
11979:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
11980:                            } else {
11981: # Importing by turning a single problem into a problem part
11982: # It gets the import-tags ID as part-ID
11983:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
11984:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
11985:                            }
11986:                         } else {
11987: # Normal import
11988:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11989:                            if (defined($token->[2]->{'id'})) {
11990:                               $unikey.='_'.$token->[2]->{'id'};
11991:                            }
11992:                         }
11993: 
11994: 			if ($depthcount<20) {
11995: 			    my $metadata = 
11996: 				&metadata($uri,'keys', $location,$unikey,
11997: 					  $depthcount+1);
11998: 			    foreach my $meta (split(',',$metadata)) {
11999: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
12000: 				$metathesekeys{$meta}=1;
12001: 			    }
12002: 			
12003:                         }
12004: 		    } else {
12005: #
12006: # Not importing, some other kind of non-package, non-library start tag
12007: # 
12008:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
12009:                         if (defined($token->[2]->{'id'})) {
12010:                             $unikey.='_'.$token->[2]->{'id'};
12011:                         }
12012: 			if (defined($token->[2]->{'name'})) { 
12013: 			    $unikey.='_'.$token->[2]->{'name'}; 
12014: 			}
12015: 			$metathesekeys{$unikey}=1;
12016: 			foreach my $param (@{$token->[3]}) {
12017: 			    $metaentry{':'.$unikey.'.'.$param} =
12018: 				$token->[2]->{$param};
12019: 			}
12020: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
12021: 			my $default=$metaentry{':'.$unikey.'.default'};
12022: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
12023: 		 # only ws inside the tag, and not in default, so use default
12024: 		 # as value
12025: 			    $metaentry{':'.$unikey}=$default;
12026: 			} elsif ( $internaltext =~ /\S/ ) {
12027: 		  # something interesting inside the tag
12028: 			    $metaentry{':'.$unikey}=$internaltext;
12029: 			} else {
12030: 		  # no interesting values, don't set a default
12031: 			}
12032: # end of not-a-package not-a-library import
12033: 		    }
12034: # end of not-a-package start tag
12035: 		}
12036: # the next is the end of "start tag"
12037: 	    }
12038: 	}
12039: 	my ($extension) = ($uri =~ /\.(\w+)$/);
12040: 	$extension = lc($extension);
12041: 	if ($extension eq 'htm') { $extension='html'; }
12042: 
12043: 	foreach my $key (keys(%packagetab)) {
12044: 	    #no specific packages #how's our extension
12045: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
12046: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
12047: 					 \%metathesekeys);
12048: 	}
12049: 
12050: 	if (!exists($metaentry{':packages'})
12051: 	    || $packagetab{"import_defaults&extension_$extension"}) {
12052: 	    foreach my $key (keys(%packagetab)) {
12053: 		#no specific packages well let's get default then
12054: 		if ($key!~/^default&/) { next; }
12055: 		&metadata_create_package_def($uri,$key,'default',
12056: 					     \%metathesekeys);
12057: 	    }
12058: 	}
12059: # are there custom rights to evaluate
12060: 	if ($metaentry{':copyright'} eq 'custom') {
12061: 
12062:     #
12063:     # Importing a rights file here
12064:     #
12065: 	    unless ($depthcount) {
12066: 		my $location=$metaentry{':customdistributionfile'};
12067: 		my $dir=$filename;
12068: 		$dir=~s|[^/]*$||;
12069: 		$location=&filelocation($dir,$location);
12070: 		my $rights_metadata =
12071: 		    &metadata($uri,'keys',$location,'_rights',
12072: 			      $depthcount+1);
12073: 		foreach my $rights (split(',',$rights_metadata)) {
12074: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
12075: 		    $metathesekeys{$rights}=1;
12076: 		}
12077: 	    }
12078: 	}
12079: 	# uniqifiy package listing
12080: 	my %seen;
12081: 	my @uniq_packages =
12082: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
12083: 	$metaentry{':packages'} = join(',',@uniq_packages);
12084: 
12085:         if (($importedresponses) || ($importedparts)) {
12086:             if ($importedparts) {
12087: # We had imported parts and need to rebuild partorder
12088:                 $metaentry{':partorder'}='';
12089:                 $metathesekeys{'partorder'}=1;
12090:             }
12091:             if ($importedresponses) {
12092: # We had imported responses and need to rebuild responseorder
12093:                 $metaentry{':responseorder'}='';
12094:                 $metathesekeys{'responseorder'}=1;
12095:             }
12096:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
12097:                 my $origid = $origfiletagids[$index+1];
12098:                 if ($origfiletagids[$index] eq 'part') {
12099: # Original part, part of the problem
12100:                     if ($importedparts) {
12101:                         $metaentry{':partorder'}.=','.$origid;
12102:                     }
12103:                 } elsif ($origfiletagids[$index] eq 'import') {
12104:                     if ($importedparts) {
12105: # We have imported parts at this position
12106:                         $metaentry{':partorder'}.=','.$importedpartids{$origid};
12107:                     }
12108:                     if ($importedresponses) {
12109: # We have imported responses at this position
12110:                         if (ref($importedrespids{$origid}) eq 'ARRAY') {
12111:                             $metaentry{':responseorder'}.=','.join(',',map { $origid.'_'.$_ } @{$importedrespids{$origid}});
12112:                         }
12113:                     }
12114:                 } else {
12115: # Original response item, part of the problem
12116:                     if ($importedresponses) {
12117:                         $metaentry{':responseorder'}.=','.$origid;
12118:                     }
12119:                 }
12120:             }
12121:             if ($importedparts) {
12122:                 $metaentry{':partorder'}=~s/^\,//;
12123:             }
12124:             if ($importedresponses) {
12125:                 $metaentry{':responseorder'}=~s/^\,//;
12126:             }
12127:         }
12128: 
12129: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
12130: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
12131: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
12132: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
12133: # this is the end of "was not already recently cached
12134:     }
12135:     return $metaentry{':'.$what};
12136: }
12137: 
12138: sub metadata_create_package_def {
12139:     my ($uri,$key,$package,$metathesekeys)=@_;
12140:     my ($pack,$name,$subp)=split(/\&/,$key);
12141:     if ($subp eq 'default') { next; }
12142:     
12143:     if (defined($metaentry{':packages'})) {
12144: 	$metaentry{':packages'}.=','.$package;
12145:     } else {
12146: 	$metaentry{':packages'}=$package;
12147:     }
12148:     my $value=$packagetab{$key};
12149:     my $unikey;
12150:     $unikey='parameter_0_'.$name;
12151:     $metaentry{':'.$unikey.'.part'}=0;
12152:     $$metathesekeys{$unikey}=1;
12153:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
12154: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
12155:     }
12156:     if (defined($metaentry{':'.$unikey.'.default'})) {
12157: 	$metaentry{':'.$unikey}=
12158: 	    $metaentry{':'.$unikey.'.default'};
12159:     }
12160: }
12161: 
12162: sub metadata_generate_part0 {
12163:     my ($metadata,$metacache,$uri) = @_;
12164:     my %allnames;
12165:     foreach my $metakey (keys(%$metadata)) {
12166: 	if ($metakey=~/^parameter\_(.*)/) {
12167: 	  my $part=$$metacache{':'.$metakey.'.part'};
12168: 	  my $name=$$metacache{':'.$metakey.'.name'};
12169: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
12170: 	    $allnames{$name}=$part;
12171: 	  }
12172: 	}
12173:     }
12174:     foreach my $name (keys(%allnames)) {
12175:       $$metadata{"parameter_0_$name"}=1;
12176:       my $key=":parameter_0_$name";
12177:       $$metacache{"$key.part"}='0';
12178:       $$metacache{"$key.name"}=$name;
12179:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
12180: 					   $allnames{$name}.'_'.$name.
12181: 					   '.type'};
12182:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
12183: 			     '.display'};
12184:       my $expr='[Part: '.$allnames{$name}.']';
12185:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
12186:       $$metacache{"$key.display"}=$olddis;
12187:     }
12188: }
12189: 
12190: # ------------------------------------------------------ Devalidate title cache
12191: 
12192: sub devalidate_title_cache {
12193:     my ($url)=@_;
12194:     if (!$env{'request.course.id'}) { return; }
12195:     my $symb=&symbread($url);
12196:     if (!$symb) { return; }
12197:     my $key=$env{'request.course.id'}."\0".$symb;
12198:     &devalidate_cache_new('title',$key);
12199: }
12200: 
12201: # ------------------------------------------------- Get the title of a course
12202: 
12203: sub current_course_title {
12204:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
12205: }
12206: # ------------------------------------------------- Get the title of a resource
12207: 
12208: sub gettitle {
12209:     my $urlsymb=shift;
12210:     my $symb=&symbread($urlsymb);
12211:     if ($symb) {
12212: 	my $key=$env{'request.course.id'}."\0".$symb;
12213: 	my ($result,$cached)=&is_cached_new('title',$key);
12214: 	if (defined($cached)) { 
12215: 	    return $result;
12216: 	}
12217: 	my ($map,$resid,$url)=&decode_symb($symb);
12218: 	my $title='';
12219: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
12220: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
12221: 	} else {
12222: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12223: 		    &GDBM_READER(),0640)) {
12224: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
12225: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
12226: 		untie(%bighash);
12227: 	    }
12228: 	}
12229: 	$title=~s/\&colon\;/\:/gs;
12230: 	if ($title) {
12231: # Remember both $symb and $title for dynamic metadata
12232:             $accesshash{$symb.'___crstitle'}=$title;
12233:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
12234: # Cache this title and then return it
12235: 	    return &do_cache_new('title',$key,$title,600);
12236: 	}
12237: 	$urlsymb=$url;
12238:     }
12239:     my $title=&metadata($urlsymb,'title');
12240:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
12241:     return $title;
12242: }
12243: 
12244: sub get_slot {
12245:     my ($which,$cnum,$cdom)=@_;
12246:     if (!$cnum || !$cdom) {
12247: 	(undef,my $courseid)=&whichuser();
12248: 	$cdom=$env{'course.'.$courseid.'.domain'};
12249: 	$cnum=$env{'course.'.$courseid.'.num'};
12250:     }
12251:     my $key=join("\0",'slots',$cdom,$cnum,$which);
12252:     my %slotinfo;
12253:     if (exists($remembered{$key})) {
12254: 	$slotinfo{$which} = $remembered{$key};
12255:     } else {
12256: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
12257: 	&Apache::lonhomework::showhash(%slotinfo);
12258: 	my ($tmp)=keys(%slotinfo);
12259: 	if ($tmp=~/^error:/) { return (); }
12260: 	$remembered{$key} = $slotinfo{$which};
12261:     }
12262:     if (ref($slotinfo{$which}) eq 'HASH') {
12263: 	return %{$slotinfo{$which}};
12264:     }
12265:     return $slotinfo{$which};
12266: }
12267: 
12268: sub get_reservable_slots {
12269:     my ($cnum,$cdom,$uname,$udom) = @_;
12270:     my $now = time;
12271:     my $reservable_info;
12272:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
12273:     if (exists($remembered{$key})) {
12274:         $reservable_info = $remembered{$key};
12275:     } else {
12276:         my %resv;
12277:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
12278:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
12279:         $reservable_info = \%resv;
12280:         $remembered{$key} = $reservable_info;
12281:     }
12282:     return $reservable_info;
12283: }
12284: 
12285: sub get_course_slots {
12286:     my ($cnum,$cdom) = @_;
12287:     my $hashid=$cnum.':'.$cdom;
12288:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
12289:     if (defined($cached)) {
12290:         if (ref($result) eq 'HASH') {
12291:             return %{$result};
12292:         }
12293:     } else {
12294:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
12295:         my ($tmp) = keys(%slots);
12296:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
12297:             &do_cache_new('allslots',$hashid,\%slots,600);
12298:             return %slots;
12299:         }
12300:     }
12301:     return;
12302: }
12303: 
12304: sub devalidate_slots_cache {
12305:     my ($cnum,$cdom)=@_;
12306:     my $hashid=$cnum.':'.$cdom;
12307:     &devalidate_cache_new('allslots',$hashid);
12308: }
12309: 
12310: sub get_coursechange {
12311:     my ($cdom,$cnum) = @_;
12312:     if ($cdom eq '' || $cnum eq '') {
12313:         return unless ($env{'request.course.id'});
12314:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
12315:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
12316:     }
12317:     my $hashid=$cdom.'_'.$cnum;
12318:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
12319:     if ((defined($cached)) && ($change ne '')) {
12320:         return $change;
12321:     } else {
12322:         my %crshash;
12323:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
12324:         if ($crshash{'internal.contentchange'} eq '') {
12325:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
12326:             if ($change eq '') {
12327:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
12328:                 $change = $crshash{'internal.created'};
12329:             }
12330:         } else {
12331:             $change = $crshash{'internal.contentchange'};
12332:         }
12333:         my $cachetime = 600;
12334:         &do_cache_new('crschange',$hashid,$change,$cachetime);
12335:     }
12336:     return $change;
12337: }
12338: 
12339: sub devalidate_coursechange_cache {
12340:     my ($cnum,$cdom)=@_;
12341:     my $hashid=$cnum.':'.$cdom;
12342:     &devalidate_cache_new('crschange',$hashid);
12343: }
12344: 
12345: # ------------------------------------------------- Update symbolic store links
12346: 
12347: sub symblist {
12348:     my ($mapname,%newhash)=@_;
12349:     $mapname=&deversion(&declutter($mapname));
12350:     my %hash;
12351:     if (($env{'request.course.fn'}) && (%newhash)) {
12352:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
12353:                       &GDBM_WRCREAT(),0640)) {
12354: 	    foreach my $url (keys(%newhash)) {
12355: 		next if ($url eq 'last_known'
12356: 			 && $env{'form.no_update_last_known'});
12357: 		$hash{declutter($url)}=&encode_symb($mapname,
12358: 						    $newhash{$url}->[1],
12359: 						    $newhash{$url}->[0]);
12360:             }
12361:             if (untie(%hash)) {
12362: 		return 'ok';
12363:             }
12364:         }
12365:     }
12366:     return 'error';
12367: }
12368: 
12369: # --------------------------------------------------------------- Verify a symb
12370: 
12371: sub symbverify {
12372:     my ($symb,$thisurl,$encstate)=@_;
12373:     my $thisfn=$thisurl;
12374:     $thisfn=&declutter($thisfn);
12375: # direct jump to resource in page or to a sequence - will construct own symbs
12376:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
12377: # check URL part
12378:     my ($map,$resid,$url)=&decode_symb($symb);
12379: 
12380:     unless ($url eq $thisfn) { return 0; }
12381: 
12382:     $symb=&symbclean($symb);
12383:     $thisurl=&deversion($thisurl);
12384:     $thisfn=&deversion($thisfn);
12385: 
12386:     my %bighash;
12387:     my $okay=0;
12388: 
12389:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12390:                             &GDBM_READER(),0640)) {
12391:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
12392:             $thisurl =~ s/\?.+$//;
12393:             if ($map =~ m{^uploaded/.+\.page$}) {
12394:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
12395:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
12396:             }
12397:         }
12398:         my $ids;
12399:         if ($map =~ m{^uploaded/.+\.page$}) {
12400:             $ids=$bighash{'ids_'.&clutter_with_no_wrapper($thisurl)};
12401:         } else {
12402:             $ids=$bighash{'ids_'.&clutter($thisurl)};
12403:         }
12404:         unless ($ids) {
12405:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
12406:             $ids=$bighash{$idkey};
12407:         }
12408:         if ($ids) {
12409: # ------------------------------------------------------------------- Has ID(s)
12410:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
12411:                 $symb =~ s/\?.+$//;
12412:             }
12413: 	    foreach my $id (split(/\,/,$ids)) {
12414: 	       my ($mapid,$resid)=split(/\./,$id);
12415:                if (
12416:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
12417:    eq $symb) {
12418:                    if (ref($encstate)) {
12419:                        $$encstate = $bighash{'encrypted_'.$id};
12420:                    }
12421:                    if (($env{'request.role.adv'}) ||
12422:                        ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
12423:                        ($thisurl eq '/adm/navmaps')) {
12424:                        $okay=1;
12425:                        last;
12426:                    }
12427:                }
12428:            }
12429:         }
12430: 	untie(%bighash);
12431:     }
12432:     return $okay;
12433: }
12434: 
12435: # --------------------------------------------------------------- Clean-up symb
12436: 
12437: sub symbclean {
12438:     my $symb=shift;
12439:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
12440: # remove version from map
12441:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
12442: 
12443: # remove version from URL
12444:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
12445: 
12446: # remove wrapper
12447: 
12448:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
12449:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
12450:     return $symb;
12451: }
12452: 
12453: # ---------------------------------------------- Split symb to find map and url
12454: 
12455: sub encode_symb {
12456:     my ($map,$resid,$url)=@_;
12457:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
12458: }
12459: 
12460: sub decode_symb {
12461:     my $symb=shift;
12462:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
12463:     my ($map,$resid,$url)=split(/___/,$symb);
12464:     return (&fixversion($map),$resid,&fixversion($url));
12465: }
12466: 
12467: sub fixversion {
12468:     my $fn=shift;
12469:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
12470:     my %bighash;
12471:     my $uri=&clutter($fn);
12472:     my $key=$env{'request.course.id'}.'_'.$uri;
12473: # is this cached?
12474:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
12475:     if (defined($cached)) { return $result; }
12476: # unfortunately not cached, or expired
12477:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12478: 	    &GDBM_READER(),0640)) {
12479:  	if ($bighash{'version_'.$uri}) {
12480:  	    my $version=$bighash{'version_'.$uri};
12481:  	    unless (($version eq 'mostrecent') || 
12482: 		    ($version==&getversion($uri))) {
12483:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
12484:  	    }
12485:  	}
12486:  	untie %bighash;
12487:     }
12488:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
12489: }
12490: 
12491: sub deversion {
12492:     my $url=shift;
12493:     $url=~s/\.\d+\.(\w+)$/\.$1/;
12494:     return $url;
12495: }
12496: 
12497: # ------------------------------------------------------ Return symb list entry
12498: 
12499: sub symbread {
12500:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles,
12501:         $ignoresymbdb,$noenccheck)=@_;
12502:     my $cache_str='request.symbread.cached.'.$thisfn;
12503:     if (defined($env{$cache_str})) {
12504:         unless (ref($possibles) eq 'HASH') {
12505:             if ($ignorecachednull) {
12506:                 return $env{$cache_str} unless ($env{$cache_str} eq '');
12507:             } else {
12508:                 return $env{$cache_str};
12509:             }
12510:         }
12511:     }
12512: # no filename provided? try from environment
12513:     unless ($thisfn) {
12514:         if ($env{'request.symb'}) {
12515:             return $env{$cache_str}=&symbclean($env{'request.symb'});
12516:         }
12517:         $thisfn=$env{'request.filename'};
12518:     }
12519:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
12520: # is that filename actually a symb? Verify, clean, and return
12521:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
12522: 	if (&symbverify($thisfn,$1)) {
12523: 	    return $env{$cache_str}=&symbclean($thisfn);
12524: 	}
12525:     }
12526:     $thisfn=declutter($thisfn);
12527:     my %hash;
12528:     my %bighash;
12529:     my $syval='';
12530:     if (($env{'request.course.fn'}) && ($thisfn)) {
12531:         my $targetfn = $thisfn;
12532:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
12533:             $targetfn = 'adm/wrapper/'.$thisfn;
12534:         }
12535: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
12536: 	    $targetfn=$1;
12537: 	}
12538:         unless ($ignoresymbdb) {
12539:             if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
12540:                           &GDBM_READER(),0640)) {
12541: 	        $syval=$hash{$targetfn};
12542:                 untie(%hash);
12543:             }
12544:             if ($syval && $checkforblock) {
12545:                 my @blockers = &has_comm_blocking('bre',$syval,$thisfn,$ignoresymbdb,$noenccheck);
12546:                 if (@blockers) {
12547:                     $syval='';
12548:                 }
12549:             }
12550:         }
12551: # ---------------------------------------------------------- There was an entry
12552:         if ($syval) {
12553: 	    #unless ($syval=~/\_\d+$/) {
12554: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
12555: 		    #&appenv({'request.ambiguous' => $thisfn});
12556: 		    #return $env{$cache_str}='';
12557: 		#}    
12558: 		#$syval.=$1;
12559: 	    #}
12560:         } else {
12561: # ------------------------------------------------------- Was not in symb table
12562:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12563:                             &GDBM_READER(),0640)) {
12564: # ---------------------------------------------- Get ID(s) for current resource
12565:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
12566:               unless ($ids) { 
12567:                  $ids=$bighash{'ids_/'.$thisfn};
12568:               }
12569:               unless ($ids) {
12570: # alias?
12571: 		  $ids=$bighash{'mapalias_'.$thisfn};
12572:               }
12573:               if ($ids) {
12574: # ------------------------------------------------------------------- Has ID(s)
12575:                  my @possibilities=split(/\,/,$ids);
12576:                  if ($#possibilities==0) {
12577: # ----------------------------------------------- There is only one possibility
12578: 		     my ($mapid,$resid)=split(/\./,$ids);
12579: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
12580: 						    $resid,$thisfn);
12581:                      if (ref($possibles) eq 'HASH') {
12582:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
12583:                              $possibles->{$syval} = 1;
12584:                          }
12585:                      }
12586:                      if ($checkforblock) {
12587:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
12588:                              my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids},'',$noenccheck);
12589:                              if (@blockers) {
12590:                                  $syval = '';
12591:                                  untie(%bighash);
12592:                                  return $env{$cache_str}='';
12593:                              }
12594:                          }
12595:                      }
12596:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
12597: # ------------------------------------------ There is more than one possibility
12598:                      my $realpossible=0;
12599:                      foreach my $id (@possibilities) {
12600: 			 my $file=$bighash{'src_'.$id};
12601:                          my $canaccess;
12602:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
12603:                              $canaccess = 1;
12604:                          } else {
12605:                              $canaccess = &allowed('bre',$file);
12606:                          }
12607:                          if ($canaccess) {
12608:          		     my ($mapid,$resid)=split(/\./,$id);
12609:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
12610:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
12611:                                                              $resid,$thisfn);
12612:                                  next if ($bighash{'randomout_'.$id} && !$env{'request.role.adv'});
12613:                                  next unless (($noenccheck) || ($bighash{'encrypted_'.$id} eq $env{'request.enc'}));
12614:                                  if ($checkforblock) {
12615:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file,'',$noenccheck);
12616:                                      if (@blockers > 0) {
12617:                                          $syval = '';
12618:                                      } else {
12619:                                          $syval = $poss_syval;
12620:                                          $realpossible++;
12621:                                      }
12622:                                  } else {
12623:                                      $syval = $poss_syval;
12624:                                      $realpossible++;
12625:                                  }
12626:                                  if ($syval) {
12627:                                      if (ref($possibles) eq 'HASH') {
12628:                                          $possibles->{$syval} = 1;
12629:                                      }
12630:                                  }
12631:                              }
12632: 			 }
12633:                      }
12634: 		     if ($realpossible!=1) { $syval=''; }
12635:                  } else {
12636:                      $syval='';
12637:                  }
12638: 	      }
12639:               untie(%bighash);
12640:            }
12641:         }
12642:         if ($syval) {
12643: 	    return $env{$cache_str}=$syval;
12644:         }
12645:     }
12646:     &appenv({'request.ambiguous' => $thisfn});
12647:     return $env{$cache_str}='';
12648: }
12649: 
12650: # ---------------------------------------------------------- Return random seed
12651: 
12652: sub numval {
12653:     my $txt=shift;
12654:     $txt=~tr/A-J/0-9/;
12655:     $txt=~tr/a-j/0-9/;
12656:     $txt=~tr/K-T/0-9/;
12657:     $txt=~tr/k-t/0-9/;
12658:     $txt=~tr/U-Z/0-5/;
12659:     $txt=~tr/u-z/0-5/;
12660:     $txt=~s/\D//g;
12661:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
12662:     return int($txt);
12663: }
12664: 
12665: sub numval2 {
12666:     my $txt=shift;
12667:     $txt=~tr/A-J/0-9/;
12668:     $txt=~tr/a-j/0-9/;
12669:     $txt=~tr/K-T/0-9/;
12670:     $txt=~tr/k-t/0-9/;
12671:     $txt=~tr/U-Z/0-5/;
12672:     $txt=~tr/u-z/0-5/;
12673:     $txt=~s/\D//g;
12674:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
12675:     my $total;
12676:     foreach my $val (@txts) { $total+=$val; }
12677:     if ($_64bit) { if ($total > 2**32) { return -1; } }
12678:     return int($total);
12679: }
12680: 
12681: sub numval3 {
12682:     use integer;
12683:     my $txt=shift;
12684:     $txt=~tr/A-J/0-9/;
12685:     $txt=~tr/a-j/0-9/;
12686:     $txt=~tr/K-T/0-9/;
12687:     $txt=~tr/k-t/0-9/;
12688:     $txt=~tr/U-Z/0-5/;
12689:     $txt=~tr/u-z/0-5/;
12690:     $txt=~s/\D//g;
12691:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
12692:     my $total;
12693:     foreach my $val (@txts) { $total+=$val; }
12694:     if ($_64bit) { $total=(($total<<32)>>32); }
12695:     return $total;
12696: }
12697: 
12698: sub digest {
12699:     my ($data)=@_;
12700:     my $digest=&Digest::MD5::md5($data);
12701:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
12702:     my ($e,$f);
12703:     {
12704:         use integer;
12705:         $e=($a+$b);
12706:         $f=($c+$d);
12707:         if ($_64bit) {
12708:             $e=(($e<<32)>>32);
12709:             $f=(($f<<32)>>32);
12710:         }
12711:     }
12712:     if (wantarray) {
12713: 	return ($e,$f);
12714:     } else {
12715: 	my $g;
12716: 	{
12717: 	    use integer;
12718: 	    $g=($e+$f);
12719: 	    if ($_64bit) {
12720: 		$g=(($g<<32)>>32);
12721: 	    }
12722: 	}
12723: 	return $g;
12724:     }
12725: }
12726: 
12727: sub latest_rnd_algorithm_id {
12728:     return '64bit5';
12729: }
12730: 
12731: sub get_rand_alg {
12732:     my ($courseid)=@_;
12733:     if (!$courseid) { $courseid=(&whichuser())[1]; }
12734:     if ($courseid) {
12735: 	return $env{"course.$courseid.rndseed"};
12736:     }
12737:     return &latest_rnd_algorithm_id();
12738: }
12739: 
12740: sub validCODE {
12741:     my ($CODE)=@_;
12742:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
12743:     return 0;
12744: }
12745: 
12746: sub getCODE {
12747:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
12748:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
12749: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
12750: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
12751: 	return $Apache::lonhomework::history{'resource.CODE'};
12752:     }
12753:     return undef;
12754: }
12755: #
12756: #  Determines the random seed for a specific context:
12757: #
12758: # parameters:
12759: #   symb      - in course context the symb for the seed.
12760: #   course_id - The course id of the form domain_coursenum.
12761: #   domain    - Domain for the user.
12762: #   course    - Course for the user.
12763: #   cenv      - environment of the course.
12764: #
12765: # NOTE:
12766: #   All parameters are picked out of the environment if missing
12767: #   or not defined.
12768: #   If a symb cannot be determined the current time is used instead.
12769: #
12770: #  For a given well defined symb, courside, domain, username,
12771: #  and course environment, the seed is reproducible.
12772: #
12773: sub rndseed {
12774:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
12775:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
12776:     if (!defined($symb)) {
12777: 	unless ($symb=$wsymb) { return time; }
12778:     }
12779:     if (!defined $courseid) { 
12780: 	$courseid=$wcourseid; 
12781:     }
12782:     if (!defined $domain) { $domain=$wdomain; }
12783:     if (!defined $username) { $username=$wusername }
12784: 
12785:     my $which;
12786:     if (defined($cenv->{'rndseed'})) {
12787: 	$which = $cenv->{'rndseed'};
12788:     } else {
12789: 	$which =&get_rand_alg($courseid);
12790:     }
12791:     if (defined(&getCODE())) {
12792: 	if ($which eq '64bit5') {
12793: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
12794: 	} elsif ($which eq '64bit4') {
12795: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
12796: 	} else {
12797: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
12798: 	}
12799:     } elsif ($which eq '64bit5') {
12800: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
12801:     } elsif ($which eq '64bit4') {
12802: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
12803:     } elsif ($which eq '64bit3') {
12804: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
12805:     } elsif ($which eq '64bit2') {
12806: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
12807:     } elsif ($which eq '64bit') {
12808: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
12809:     }
12810:     return &rndseed_32bit($symb,$courseid,$domain,$username);
12811: }
12812: 
12813: sub rndseed_32bit {
12814:     my ($symb,$courseid,$domain,$username)=@_;
12815:     {
12816: 	use integer;
12817: 	my $symbchck=unpack("%32C*",$symb) << 27;
12818: 	my $symbseed=numval($symb) << 22;
12819: 	my $namechck=unpack("%32C*",$username) << 17;
12820: 	my $nameseed=numval($username) << 12;
12821: 	my $domainseed=unpack("%32C*",$domain) << 7;
12822: 	my $courseseed=unpack("%32C*",$courseid);
12823: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
12824: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12825: 	#&logthis("rndseed :$num:$symb");
12826: 	if ($_64bit) { $num=(($num<<32)>>32); }
12827: 	return $num;
12828:     }
12829: }
12830: 
12831: sub rndseed_64bit {
12832:     my ($symb,$courseid,$domain,$username)=@_;
12833:     {
12834: 	use integer;
12835: 	my $symbchck=unpack("%32S*",$symb) << 21;
12836: 	my $symbseed=numval($symb) << 10;
12837: 	my $namechck=unpack("%32S*",$username);
12838: 	
12839: 	my $nameseed=numval($username) << 21;
12840: 	my $domainseed=unpack("%32S*",$domain) << 10;
12841: 	my $courseseed=unpack("%32S*",$courseid);
12842: 	
12843: 	my $num1=$symbchck+$symbseed+$namechck;
12844: 	my $num2=$nameseed+$domainseed+$courseseed;
12845: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12846: 	#&logthis("rndseed :$num:$symb");
12847: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
12848: 	return "$num1,$num2";
12849:     }
12850: }
12851: 
12852: sub rndseed_64bit2 {
12853:     my ($symb,$courseid,$domain,$username)=@_;
12854:     {
12855: 	use integer;
12856: 	# strings need to be an even # of cahracters long, it it is odd the
12857:         # last characters gets thrown away
12858: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
12859: 	my $symbseed=numval($symb) << 10;
12860: 	my $namechck=unpack("%32S*",$username.' ');
12861: 	
12862: 	my $nameseed=numval($username) << 21;
12863: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
12864: 	my $courseseed=unpack("%32S*",$courseid.' ');
12865: 	
12866: 	my $num1=$symbchck+$symbseed+$namechck;
12867: 	my $num2=$nameseed+$domainseed+$courseseed;
12868: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12869: 	#&logthis("rndseed :$num:$symb");
12870: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
12871: 	return "$num1,$num2";
12872:     }
12873: }
12874: 
12875: sub rndseed_64bit3 {
12876:     my ($symb,$courseid,$domain,$username)=@_;
12877:     {
12878: 	use integer;
12879: 	# strings need to be an even # of cahracters long, it it is odd the
12880:         # last characters gets thrown away
12881: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
12882: 	my $symbseed=numval2($symb) << 10;
12883: 	my $namechck=unpack("%32S*",$username.' ');
12884: 	
12885: 	my $nameseed=numval2($username) << 21;
12886: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
12887: 	my $courseseed=unpack("%32S*",$courseid.' ');
12888: 	
12889: 	my $num1=$symbchck+$symbseed+$namechck;
12890: 	my $num2=$nameseed+$domainseed+$courseseed;
12891: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12892: 	#&logthis("rndseed :$num1:$num2:$_64bit");
12893: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
12894: 	
12895: 	return "$num1:$num2";
12896:     }
12897: }
12898: 
12899: sub rndseed_64bit4 {
12900:     my ($symb,$courseid,$domain,$username)=@_;
12901:     {
12902: 	use integer;
12903: 	# strings need to be an even # of cahracters long, it it is odd the
12904:         # last characters gets thrown away
12905: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
12906: 	my $symbseed=numval3($symb) << 10;
12907: 	my $namechck=unpack("%32S*",$username.' ');
12908: 	
12909: 	my $nameseed=numval3($username) << 21;
12910: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
12911: 	my $courseseed=unpack("%32S*",$courseid.' ');
12912: 	
12913: 	my $num1=$symbchck+$symbseed+$namechck;
12914: 	my $num2=$nameseed+$domainseed+$courseseed;
12915: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12916: 	#&logthis("rndseed :$num1:$num2:$_64bit");
12917: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
12918: 	
12919: 	return "$num1:$num2";
12920:     }
12921: }
12922: 
12923: sub rndseed_64bit5 {
12924:     my ($symb,$courseid,$domain,$username)=@_;
12925:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
12926:     return "$num1:$num2";
12927: }
12928: 
12929: sub rndseed_CODE_64bit {
12930:     my ($symb,$courseid,$domain,$username)=@_;
12931:     {
12932: 	use integer;
12933: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
12934: 	my $symbseed=numval2($symb);
12935: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
12936: 	my $CODEseed=numval(&getCODE());
12937: 	my $courseseed=unpack("%32S*",$courseid.' ');
12938: 	my $num1=$symbseed+$CODEchck;
12939: 	my $num2=$CODEseed+$courseseed+$symbchck;
12940: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
12941: 	#&logthis("rndseed :$num1:$num2:$symb");
12942: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
12943: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
12944: 	return "$num1:$num2";
12945:     }
12946: }
12947: 
12948: sub rndseed_CODE_64bit4 {
12949:     my ($symb,$courseid,$domain,$username)=@_;
12950:     {
12951: 	use integer;
12952: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
12953: 	my $symbseed=numval3($symb);
12954: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
12955: 	my $CODEseed=numval3(&getCODE());
12956: 	my $courseseed=unpack("%32S*",$courseid.' ');
12957: 	my $num1=$symbseed+$CODEchck;
12958: 	my $num2=$CODEseed+$courseseed+$symbchck;
12959: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
12960: 	#&logthis("rndseed :$num1:$num2:$symb");
12961: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
12962: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
12963: 	return "$num1:$num2";
12964:     }
12965: }
12966: 
12967: sub rndseed_CODE_64bit5 {
12968:     my ($symb,$courseid,$domain,$username)=@_;
12969:     my $code = &getCODE();
12970:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
12971:     return "$num1:$num2";
12972: }
12973: 
12974: sub setup_random_from_rndseed {
12975:     my ($rndseed)=@_;
12976:     if ($rndseed =~/([,:])/) {
12977: 	my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
12978:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
12979:             &Math::Random::random_set_seed_from_phrase($rndseed);
12980:         } else {
12981:             &Math::Random::random_set_seed($num1,$num2);
12982:         }
12983:     } else {
12984: 	&Math::Random::random_set_seed_from_phrase($rndseed);
12985:     }
12986: }
12987: 
12988: sub latest_receipt_algorithm_id {
12989:     return 'receipt3';
12990: }
12991: 
12992: sub recunique {
12993:     my $fucourseid=shift;
12994:     my $unique;
12995:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
12996: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
12997: 	$unique=$env{"course.$fucourseid.internal.encseed"};
12998:     } else {
12999: 	$unique=$perlvar{'lonReceipt'};
13000:     }
13001:     return unpack("%32C*",$unique);
13002: }
13003: 
13004: sub recprefix {
13005:     my $fucourseid=shift;
13006:     my $prefix;
13007:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
13008: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
13009: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
13010:     } else {
13011: 	$prefix=$perlvar{'lonHostID'};
13012:     }
13013:     return unpack("%32C*",$prefix);
13014: }
13015: 
13016: sub ireceipt {
13017:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
13018: 
13019:     my $return =&recprefix($fucourseid).'-';
13020: 
13021:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
13022: 	$env{'request.state'} eq 'construct') {
13023: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
13024: 	return $return;
13025:     }
13026: 
13027:     my $cuname=unpack("%32C*",$funame);
13028:     my $cudom=unpack("%32C*",$fudom);
13029:     my $cucourseid=unpack("%32C*",$fucourseid);
13030:     my $cusymb=unpack("%32C*",$fusymb);
13031:     my $cunique=&recunique($fucourseid);
13032:     my $cpart=unpack("%32S*",$part);
13033:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
13034: 
13035: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
13036: 			       
13037: 	$return.= ($cunique%$cuname+
13038: 		   $cunique%$cudom+
13039: 		   $cusymb%$cuname+
13040: 		   $cusymb%$cudom+
13041: 		   $cucourseid%$cuname+
13042: 		   $cucourseid%$cudom+
13043: 		   $cpart%$cuname+
13044: 		   $cpart%$cudom);
13045:     } else {
13046: 	$return.= ($cunique%$cuname+
13047: 		   $cunique%$cudom+
13048: 		   $cusymb%$cuname+
13049: 		   $cusymb%$cudom+
13050: 		   $cucourseid%$cuname+
13051: 		   $cucourseid%$cudom);
13052:     }
13053:     return $return;
13054: }
13055: 
13056: sub receipt {
13057:     my ($part)=@_;
13058:     my ($symb,$courseid,$domain,$name) = &whichuser();
13059:     return &ireceipt($name,$domain,$courseid,$symb,$part);
13060: }
13061: 
13062: sub whichuser {
13063:     my ($passedsymb)=@_;
13064:     my ($symb,$courseid,$domain,$name,$publicuser);
13065:     if (defined($env{'form.grade_symb'})) {
13066: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
13067: 	my $allowed=&allowed('vgr',$tmp_courseid);
13068: 	if (!$allowed &&
13069: 	    exists($env{'request.course.sec'}) &&
13070: 	    $env{'request.course.sec'} !~ /^\s*$/) {
13071: 	    $allowed=&allowed('vgr',$tmp_courseid.
13072: 			      '/'.$env{'request.course.sec'});
13073: 	}
13074: 	if ($allowed) {
13075: 	    ($symb)=&get_env_multiple('form.grade_symb');
13076: 	    $courseid=$tmp_courseid;
13077: 	    ($domain)=&get_env_multiple('form.grade_domain');
13078: 	    ($name)=&get_env_multiple('form.grade_username');
13079: 	    return ($symb,$courseid,$domain,$name,$publicuser);
13080: 	}
13081:     }
13082:     if (!$passedsymb) {
13083: 	$symb=&symbread();
13084:     } else {
13085: 	$symb=$passedsymb;
13086:     }
13087:     $courseid=$env{'request.course.id'};
13088:     $domain=$env{'user.domain'};
13089:     $name=$env{'user.name'};
13090:     if ($name eq 'public' && $domain eq 'public') {
13091: 	if (!defined($env{'form.username'})) {
13092: 	    $env{'form.username'}.=time.rand(10000000);
13093: 	}
13094: 	$name.=$env{'form.username'};
13095:     }
13096:     return ($symb,$courseid,$domain,$name,$publicuser);
13097: 
13098: }
13099: 
13100: # ------------------------------------------------------------ Serves up a file
13101: # returns either the contents of the file or 
13102: # -1 if the file doesn't exist
13103: #
13104: # if the target is a file that was uploaded via DOCS, 
13105: # a check will be made to see if a current copy exists on the local server,
13106: # if it does this will be served, otherwise a copy will be retrieved from
13107: # the home server for the course and stored in /home/httpd/html/userfiles on
13108: # the local server.   
13109: 
13110: sub getfile {
13111:     my ($file) = @_;
13112:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
13113:     &repcopy($file);
13114:     return &readfile($file);
13115: }
13116: 
13117: sub repcopy_userfile {
13118:     my ($file)=@_;
13119:     my $londocroot = $perlvar{'lonDocRoot'};
13120:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
13121:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
13122:     my ($cdom,$cnum,$filename) = 
13123: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
13124:     my $uri="/uploaded/$cdom/$cnum/$filename";
13125:     if (-e "$file") {
13126: # we already have a local copy, check it out
13127: 	my @fileinfo = stat($file);
13128: 	my $rtncode;
13129: 	my $info;
13130: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
13131: 	if ($lwpresp ne 'ok') {
13132: # there is no such file anymore, even though we had a local copy
13133: 	    if ($rtncode eq '404') {
13134: 		unlink($file);
13135: 	    }
13136: 	    return -1;
13137: 	}
13138: 	if ($info < $fileinfo[9]) {
13139: # nice, the file we have is up-to-date, just say okay
13140: 	    return 'ok';
13141: 	} else {
13142: # the file is outdated, get rid of it
13143: 	    unlink($file);
13144: 	}
13145:     }
13146: # one way or the other, at this point, we don't have the file
13147: # construct the correct path for the file
13148:     my @parts = ($cdom,$cnum); 
13149:     if ($filename =~ m|^(.+)/[^/]+$|) {
13150: 	push @parts, split(/\//,$1);
13151:     }
13152:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
13153:     foreach my $part (@parts) {
13154: 	$path .= '/'.$part;
13155: 	if (!-e $path) {
13156: 	    mkdir($path,0770);
13157: 	}
13158:     }
13159: # now the path exists for sure
13160: # get a user agent
13161:     my $ua=new LWP::UserAgent;
13162:     my $transferfile=$file.'.in.transfer';
13163: # FIXME: this should flock
13164:     if (-e $transferfile) { return 'ok'; }
13165:     my $request;
13166:     $uri=~s/^\///;
13167:     my $homeserver = &homeserver($cnum,$cdom);
13168:     my $hostname = &hostname($homeserver);
13169:     my $protocol = $protocol{$homeserver};
13170:     $protocol = 'http' if ($protocol ne 'https');
13171:     $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
13172:     my $response=$ua->request($request,$transferfile);
13173: # did it work?
13174:     if ($response->is_error()) {
13175: 	unlink($transferfile);
13176: 	&logthis("Userfile repcopy failed for $uri");
13177: 	return -1;
13178:     }
13179: # worked, rename the transfer file
13180:     rename($transferfile,$file);
13181:     return 'ok';
13182: }
13183: 
13184: sub tokenwrapper {
13185:     my $uri=shift;
13186:     $uri=~s|^https?\://([^/]+)||;
13187:     $uri=~s|^/||;
13188:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
13189:     my $token=$1;
13190:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
13191:     if ($udom && $uname && $file) {
13192: 	$file=~s|(\?\.*)*$||;
13193:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
13194:         my $homeserver = &homeserver($uname,$udom);
13195:         my $hostname = &hostname($homeserver);
13196:         my $protocol = $protocol{$homeserver};
13197:         $protocol = 'http' if ($protocol ne 'https');
13198:         return $protocol.'://'.$hostname.'/'.$uri.
13199:                (($uri=~/\?/)?'&':'?').'token='.$token.
13200:                                '&tokenissued='.$perlvar{'lonHostID'};
13201:     } else {
13202:         return '/adm/notfound.html';
13203:     }
13204: }
13205: 
13206: # call with reqtype HEAD: get last modification time
13207: # call with reqtype GET: get the file contents
13208: # Do not call this with reqtype GET for large files! It loads everything into memory
13209: #
13210: sub getuploaded {
13211:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
13212:     $uri=~s/^\///;
13213:     my $homeserver = &homeserver($cnum,$cdom);
13214:     my $hostname = &hostname($homeserver);
13215:     my $protocol = $protocol{$homeserver};
13216:     $protocol = 'http' if ($protocol ne 'https');
13217:     $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
13218:     my $ua=new LWP::UserAgent;
13219:     my $request=new HTTP::Request($reqtype,$uri);
13220:     my $response=$ua->request($request);
13221:     $$rtncode = $response->code;
13222:     if (! $response->is_success()) {
13223: 	return 'failed';
13224:     }      
13225:     if ($reqtype eq 'HEAD') {
13226: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
13227:     } elsif ($reqtype eq 'GET') {
13228: 	$$info = $response->content;
13229:     }
13230:     return 'ok';
13231: }
13232: 
13233: sub readfile {
13234:     my $file = shift;
13235:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
13236:     my $fh;
13237:     open($fh,"<",$file);
13238:     my $a='';
13239:     while (my $line = <$fh>) { $a .= $line; }
13240:     return $a;
13241: }
13242: 
13243: sub filelocation {
13244:     my ($dir,$file) = @_;
13245:     my $location;
13246:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
13247: 
13248:     if ($file =~ m-^/adm/-) {
13249: 	$file=~s-^/adm/wrapper/-/-;
13250: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
13251:     }
13252: 
13253:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
13254:         $location = $file;
13255:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
13256:         my ($udom,$uname,$filename)=
13257:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
13258:         my $home=&homeserver($uname,$udom);
13259:         my $is_me=0;
13260:         my @ids=&current_machine_ids();
13261:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
13262:         if ($is_me) {
13263:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
13264:         } else {
13265:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
13266:   	      $udom.'/'.$uname.'/'.$filename;
13267:         }
13268:     } elsif ($file =~ m-^/adm/-) {
13269: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
13270:     } else {
13271:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
13272:         $file=~s:^/(res|priv)/:/:;
13273:         my $space=$1;
13274:         if ( !( $file =~ m:^/:) ) {
13275:             $location = $dir. '/'.$file;
13276:         } else {
13277:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
13278:         }
13279:     }
13280:     $location=~s://+:/:g; # remove duplicate /
13281:     while ($location=~m{/\.\./}) {
13282: 	if ($location =~ m{/[^/]+/\.\./}) {
13283: 	    $location=~ s{/[^/]+/\.\./}{/}g;
13284: 	} else {
13285: 	    $location=~ s{/\.\./}{/}g;
13286: 	}
13287:     } #remove dir/..
13288:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
13289:     return $location;
13290: }
13291: 
13292: sub hreflocation {
13293:     my ($dir,$file)=@_;
13294:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
13295: 	$file=filelocation($dir,$file);
13296:     } elsif ($file=~m-^/adm/-) {
13297: 	$file=~s-^/adm/wrapper/-/-;
13298: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
13299:     }
13300:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
13301: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
13302:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
13303: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
13304: 	        {/uploaded/$1/$2/}x;
13305:     }
13306:     if ($file=~ m{^/userfiles/}) {
13307: 	$file =~ s{^/userfiles/}{/uploaded/};
13308:     }
13309:     return $file;
13310: }
13311: 
13312: 
13313: 
13314: 
13315: 
13316: sub current_machine_domains {
13317:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
13318: }
13319: 
13320: sub machine_domains {
13321:     my ($hostname) = @_;
13322:     my @domains;
13323:     my %hostname = &all_hostnames();
13324:     while( my($id, $name) = each(%hostname)) {
13325: #	&logthis("-$id-$name-$hostname-");
13326: 	if ($hostname eq $name) {
13327: 	    push(@domains,&host_domain($id));
13328: 	}
13329:     }
13330:     return @domains;
13331: }
13332: 
13333: sub current_machine_ids {
13334:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
13335: }
13336: 
13337: sub machine_ids {
13338:     my ($hostname) = @_;
13339:     $hostname ||= &hostname($perlvar{'lonHostID'});
13340:     my @ids;
13341:     my %name_to_host = &all_names();
13342:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
13343: 	return @{ $name_to_host{$hostname} };
13344:     }
13345:     return;
13346: }
13347: 
13348: sub additional_machine_domains {
13349:     my @domains;
13350:     open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab");
13351:     while( my $line = <$fh>) {
13352:         $line =~ s/\s//g;
13353:         push(@domains,$line);
13354:     }
13355:     return @domains;
13356: }
13357: 
13358: sub default_login_domain {
13359:     my $domain = $perlvar{'lonDefDomain'};
13360:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
13361:     foreach my $posdom (&current_machine_domains(),
13362:                         &additional_machine_domains()) {
13363:         if (lc($posdom) eq lc($testdomain)) {
13364:             $domain=$posdom;
13365:             last;
13366:         }
13367:     }
13368:     return $domain;
13369: }
13370: 
13371: sub shared_institution {
13372:     my ($dom,$lonhost) = @_;
13373:     if ($lonhost eq '') {
13374:         $lonhost = $perlvar{'lonHostID'};
13375:     }
13376:     my $same_intdom;
13377:     my $hostintdom = &internet_dom($lonhost);
13378:     if ($hostintdom ne '') {
13379:         my %iphost = &get_iphost();
13380:         my $primary_id = &domain($dom,'primary');
13381:         my $primary_ip = &get_host_ip($primary_id);
13382:         if (ref($iphost{$primary_ip}) eq 'ARRAY') {
13383:             foreach my $id (@{$iphost{$primary_ip}}) {
13384:                 my $intdom = &internet_dom($id);
13385:                 if ($intdom eq $hostintdom) {
13386:                     $same_intdom = 1;
13387:                     last;
13388:                 }
13389:             }
13390:         }
13391:     }
13392:     return $same_intdom;
13393: }
13394: 
13395: sub uses_sts {
13396:     my ($ignore_cache) = @_;
13397:     my $lonhost = $perlvar{'lonHostID'};
13398:     my $hostname = &hostname($lonhost);
13399:     my $sts_on;
13400:     if ($protocol{$lonhost} eq 'https') {
13401:         my $cachetime = 12*3600;
13402:         if (!$ignore_cache) {
13403:             ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
13404:             if (defined($cached)) {
13405:                 return $sts_on;
13406:             }
13407:         }
13408:         my $ua=new LWP::UserAgent;
13409:         my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
13410:         my $request=new HTTP::Request('HEAD',$url);
13411:         my $response=$ua->request($request);
13412:         if ($response->is_success) {
13413:             my $has_sts = $response->header('Strict-Transport-Security');
13414:             if ($has_sts eq '') {
13415:                 $sts_on = 0;
13416:             } else {
13417:                 if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
13418:                     my $maxage = $1;
13419:                     if ($maxage) {
13420:                         $sts_on = 1;
13421:                     } else {
13422:                         $sts_on = 0;
13423:                     }
13424:                 } else {
13425:                     $sts_on = 0;
13426:                 }
13427:             }
13428:             return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
13429:         }
13430:     }
13431:     return;
13432: }
13433: 
13434: sub get_requestor_ip {
13435:     my ($r,$nolookup,$noproxy) = @_;
13436:     my $from_ip;
13437:     if (ref($r)) {
13438:         $from_ip = $r->get_remote_host($nolookup);
13439:     } else {
13440:         $from_ip = $ENV{'REMOTE_ADDR'};
13441:     }
13442:     return $from_ip;
13443: }
13444: 
13445: # ------------------------------------------------------------- Declutters URLs
13446: 
13447: sub declutter {
13448:     my $thisfn=shift;
13449:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
13450:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
13451:         $thisfn=~s{^/home/httpd/html}{};
13452:     }
13453:     $thisfn=~s/^\///;
13454:     $thisfn=~s|^adm/wrapper/||;
13455:     $thisfn=~s|^adm/coursedocs/showdoc/||;
13456:     $thisfn=~s/^res\///;
13457:     $thisfn=~s/^priv\///;
13458:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
13459:         $thisfn=~s/\?.+$//;
13460:     }
13461:     return $thisfn;
13462: }
13463: 
13464: # ------------------------------------------------------------- Clutter up URLs
13465: 
13466: sub clutter {
13467:     my $thisfn='/'.&declutter(shift);
13468:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
13469: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
13470:        $thisfn='/res'.$thisfn; 
13471:     }
13472:     if ($thisfn !~m|^/adm|) {
13473: 	if ($thisfn =~ m|^/ext/|) {
13474: 	    $thisfn='/adm/wrapper'.$thisfn;
13475: 	} else {
13476: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
13477: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
13478: 	    if ($embstyle eq 'ssi'
13479: 		|| ($embstyle eq 'hdn')
13480: 		|| ($embstyle eq 'rat')
13481: 		|| ($embstyle eq 'prv')
13482: 		|| ($embstyle eq 'ign')) {
13483: 		#do nothing with these
13484: 	    } elsif (($embstyle eq 'img') 
13485: 		|| ($embstyle eq 'emb')
13486: 		|| ($embstyle eq 'wrp')) {
13487: 		$thisfn='/adm/wrapper'.$thisfn;
13488: 	    } elsif ($embstyle eq 'unk'
13489: 		     && $thisfn!~/\.(sequence|page)$/) {
13490: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
13491: 	    } else {
13492: #		&logthis("Got a blank emb style");
13493: 	    }
13494: 	}
13495:     }
13496:     return $thisfn;
13497: }
13498: 
13499: sub clutter_with_no_wrapper {
13500:     my $uri = &clutter(shift);
13501:     if ($uri =~ m-^/adm/-) {
13502: 	$uri =~ s-^/adm/wrapper/-/-;
13503: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
13504:     }
13505:     return $uri;
13506: }
13507: 
13508: sub freeze_escape {
13509:     my ($value)=@_;
13510:     if (ref($value)) {
13511: 	$value=&nfreeze($value);
13512: 	return '__FROZEN__'.&escape($value);
13513:     }
13514:     return &escape($value);
13515: }
13516: 
13517: 
13518: sub thaw_unescape {
13519:     my ($value)=@_;
13520:     if ($value =~ /^__FROZEN__/) {
13521: 	substr($value,0,10,undef);
13522: 	$value=&unescape($value);
13523: 	return &thaw($value);
13524:     }
13525:     return &unescape($value);
13526: }
13527: 
13528: sub correct_line_ends {
13529:     my ($result)=@_;
13530:     $$result =~s/\r\n/\n/mg;
13531:     $$result =~s/\r/\n/mg;
13532: }
13533: # ================================================================ Main Program
13534: 
13535: sub goodbye {
13536:    &logthis("Starting Shut down");
13537: #not converted to using infrastruture and probably shouldn't be
13538:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
13539: #converted
13540: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
13541:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
13542: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
13543: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
13544: #1.1 only
13545: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
13546: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
13547: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
13548: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
13549:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
13550:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
13551:    &logthis(sprintf("%-20s is %s",'hits',$hits));
13552:    &flushcourselogs();
13553:    &logthis("Shutting down");
13554: }
13555: 
13556: sub get_dns {
13557:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
13558:     if (!$ignore_cache) {
13559: 	my ($content,$cached)=
13560: 	    &Apache::lonnet::is_cached_new('dns',$url);
13561: 	if ($cached) {
13562: 	    &$func($content,$hashref);
13563: 	    return;
13564: 	}
13565:     }
13566: 
13567:     my %alldns;
13568:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
13569:         foreach my $dns (<$config>) {
13570: 	    next if ($dns !~ /^\^(\S*)/x);
13571:             my $line = $1;
13572:             my ($host,$protocol) = split(/:/,$line);
13573:             if ($protocol ne 'https') {
13574:                 $protocol = 'http';
13575:             }
13576: 	    $alldns{$host} = $protocol;
13577:         }
13578:         close($config);
13579:     }
13580:     while (%alldns) {
13581: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
13582: 	my $ua=new LWP::UserAgent;
13583:         $ua->timeout(30);
13584: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
13585: 	my $response=$ua->request($request);
13586:         delete($alldns{$dns});
13587: 	next if ($response->is_error());
13588: 	my @content = split("\n",$response->content);
13589:         unless ($nocache) {
13590: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
13591:         }
13592: 	&$func(\@content,$hashref);
13593: 	return;
13594:     }
13595:     my $which = (split('/',$url))[3];
13596:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
13597:     if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
13598:         my @content = <$config>;
13599:         &$func(\@content,$hashref);
13600:     }
13601:     return;
13602: }
13603: 
13604: # ------------------------------------------------------Get DNS checksums file
13605: sub parse_dns_checksums_tab {
13606:     my ($lines,$hashref) = @_;
13607:     my $lonhost = $perlvar{'lonHostID'};
13608:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
13609:     my $loncaparev = &get_server_loncaparev($machine_dom);
13610:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
13611:     my $webconfdir = '/etc/httpd/conf';
13612:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
13613:         $webconfdir = '/etc/apache2';
13614:     } elsif ($distro =~ /^sles(\d+)$/) {
13615:         if ($1 >= 10) {
13616:             $webconfdir = '/etc/apache2';
13617:         }
13618:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
13619:         if ($1 >= 10.0) {
13620:             $webconfdir = '/etc/apache2';
13621:         }
13622:     }
13623:     my ($release,$timestamp) = split(/\-/,$loncaparev);
13624:     my (%chksum,%revnum);
13625:     if (ref($lines) eq 'ARRAY') {
13626:         chomp(@{$lines});
13627:         my $version = shift(@{$lines});
13628:         if ($version eq $release) {
13629:             foreach my $line (@{$lines}) {
13630:                 my ($file,$version,$shasum) = split(/,/,$line);
13631:                 if ($file =~ m{^/etc/httpd/conf}) {
13632:                     if ($webconfdir eq '/etc/apache2') {
13633:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
13634:                     }
13635:                 }
13636:                 $chksum{$file} = $shasum;
13637:                 $revnum{$file} = $version;
13638:             }
13639:             if (ref($hashref) eq 'HASH') {
13640:                 %{$hashref} = (
13641:                                 sums     => \%chksum,
13642:                                 versions => \%revnum,
13643:                               );
13644:             }
13645:         }
13646:     }
13647:     return;
13648: }
13649: 
13650: sub fetch_dns_checksums {
13651:     my %checksums;
13652:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
13653:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
13654:     my ($release,$timestamp) = split(/\-/,$loncaparev);
13655:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
13656:              \%checksums);
13657:     return \%checksums;
13658: }
13659: 
13660: # ------------------------------------------------------------ Read domain file
13661: {
13662:     my $loaded;
13663:     my %domain;
13664: 
13665:     sub parse_domain_tab {
13666: 	my ($lines) = @_;
13667: 	foreach my $line (@$lines) {
13668: 	    next if ($line =~ /^(\#|\s*$ )/x);
13669: 
13670: 	    chomp($line);
13671: 	    my ($name,@elements) = split(/:/,$line,9);
13672: 	    my %this_domain;
13673: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
13674: 			       'lang_def', 'city', 'longi', 'lati',
13675: 			       'primary') {
13676: 		$this_domain{$field} = shift(@elements);
13677: 	    }
13678: 	    $domain{$name} = \%this_domain;
13679: 	}
13680:     }
13681: 
13682:     sub reset_domain_info {
13683: 	undef($loaded);
13684: 	undef(%domain);
13685:     }
13686: 
13687:     sub load_domain_tab {
13688: 	my ($ignore_cache,$nocache) = @_;
13689: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
13690: 	my $fh;
13691: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
13692: 	    my @lines = <$fh>;
13693: 	    &parse_domain_tab(\@lines);
13694: 	}
13695: 	close($fh);
13696: 	$loaded = 1;
13697:     }
13698: 
13699:     sub domain {
13700: 	&load_domain_tab() if (!$loaded);
13701: 
13702: 	my ($name,$what) = @_;
13703: 	return if ( !exists($domain{$name}) );
13704: 
13705: 	if (!$what) {
13706: 	    return $domain{$name}{'description'};
13707: 	}
13708: 	return $domain{$name}{$what};
13709:     }
13710: 
13711:     sub domain_info {
13712:         &load_domain_tab() if (!$loaded);
13713:         return %domain;
13714:     }
13715: 
13716: }
13717: 
13718: 
13719: # ------------------------------------------------------------- Read hosts file
13720: {
13721:     my %hostname;
13722:     my %hostdom;
13723:     my %libserv;
13724:     my $loaded;
13725:     my %name_to_host;
13726:     my %internetdom;
13727:     my %LC_dns_serv;
13728: 
13729:     sub parse_hosts_tab {
13730: 	my ($file) = @_;
13731: 	foreach my $configline (@$file) {
13732: 	    next if ($configline =~ /^(\#|\s*$ )/x);
13733:             chomp($configline);
13734: 	    if ($configline =~ /^\^/) {
13735:                 if ($configline =~ /^\^([\w.\-]+)/) {
13736:                     $LC_dns_serv{$1} = 1;
13737:                 }
13738:                 next;
13739:             }
13740: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
13741: 	    $name=~s/\s//g;
13742: 	    if ($id && $domain && $role && $name) {
13743:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
13744:                     my $curr = $hostname{$id};
13745:                     my $skip;
13746:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
13747:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
13748:                             $skip = 1;
13749:                         } else {
13750:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
13751:                         }
13752:                     }
13753:                     unless ($skip) {
13754:                         push(@{$name_to_host{$name}},$id);
13755:                     }
13756:                 } else {
13757:                     push(@{$name_to_host{$name}},$id);
13758:                 }
13759: 		$hostname{$id}=$name;
13760: 		$hostdom{$id}=$domain;
13761: 		if ($role eq 'library') { $libserv{$id}=$name; }
13762:                 if (defined($protocol)) {
13763:                     if ($protocol eq 'https') {
13764:                         $protocol{$id} = $protocol;
13765:                     } else {
13766:                         $protocol{$id} = 'http'; 
13767:                     }
13768:                 } else {
13769:                     $protocol{$id} = 'http';
13770:                 }
13771:                 if (defined($intdom)) {
13772:                     $internetdom{$id} = $intdom;
13773:                 }
13774: 	    }
13775: 	}
13776:     }
13777:     
13778:     sub reset_hosts_info {
13779: 	&purge_remembered();
13780: 	&reset_domain_info();
13781: 	&reset_hosts_ip_info();
13782: 	undef(%name_to_host);
13783: 	undef(%hostname);
13784: 	undef(%hostdom);
13785: 	undef(%libserv);
13786: 	undef($loaded);
13787:     }
13788: 
13789:     sub load_hosts_tab {
13790: 	my ($ignore_cache,$nocache) = @_;
13791: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
13792: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
13793: 	my @config = <$config>;
13794: 	&parse_hosts_tab(\@config);
13795: 	close($config);
13796: 	$loaded=1;
13797:     }
13798: 
13799:     sub hostname {
13800: 	&load_hosts_tab() if (!$loaded);
13801: 
13802: 	my ($lonid) = @_;
13803: 	return $hostname{$lonid};
13804:     }
13805: 
13806:     sub all_hostnames {
13807: 	&load_hosts_tab() if (!$loaded);
13808: 
13809: 	return %hostname;
13810:     }
13811: 
13812:     sub all_names {
13813:         my ($ignore_cache,$nocache) = @_;
13814: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
13815: 
13816: 	return %name_to_host;
13817:     }
13818: 
13819:     sub all_host_domain {
13820:         &load_hosts_tab() if (!$loaded);
13821:         return %hostdom;
13822:     }
13823: 
13824:     sub is_library {
13825: 	&load_hosts_tab() if (!$loaded);
13826: 
13827: 	return exists($libserv{$_[0]});
13828:     }
13829: 
13830:     sub all_library {
13831: 	&load_hosts_tab() if (!$loaded);
13832: 
13833: 	return %libserv;
13834:     }
13835: 
13836:     sub unique_library {
13837: 	#2x reverse removes all hostnames that appear more than once
13838:         my %unique = reverse &all_library();
13839:         return reverse %unique;
13840:     }
13841: 
13842:     sub get_servers {
13843: 	&load_hosts_tab() if (!$loaded);
13844: 
13845: 	my ($domain,$type) = @_;
13846: 	my %possible_hosts = ($type eq 'library') ? %libserv
13847: 	                                          : %hostname;
13848: 	my %result;
13849: 	if (ref($domain) eq 'ARRAY') {
13850: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
13851: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
13852: 		    $result{$host} = $hostname;
13853: 		}
13854: 	    }
13855: 	} else {
13856: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
13857: 		if ($hostdom{$host} eq $domain) {
13858: 		    $result{$host} = $hostname;
13859: 		}
13860: 	    }
13861: 	}
13862: 	return %result;
13863:     }
13864: 
13865:     sub get_unique_servers {
13866:         my %unique = reverse &get_servers(@_);
13867: 	return reverse %unique;
13868:     }
13869: 
13870:     sub host_domain {
13871: 	&load_hosts_tab() if (!$loaded);
13872: 
13873: 	my ($lonid) = @_;
13874: 	return $hostdom{$lonid};
13875:     }
13876: 
13877:     sub all_domains {
13878: 	&load_hosts_tab() if (!$loaded);
13879: 
13880: 	my %seen;
13881: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
13882: 	return @uniq;
13883:     }
13884: 
13885:     sub internet_dom {
13886:         &load_hosts_tab() if (!$loaded);
13887: 
13888:         my ($lonid) = @_;
13889:         return $internetdom{$lonid};
13890:     }
13891: 
13892:     sub is_LC_dns {
13893:         &load_hosts_tab() if (!$loaded);
13894: 
13895:         my ($hostname) = @_;
13896:         return exists($LC_dns_serv{$hostname});
13897:     }
13898: 
13899: }
13900: 
13901: { 
13902:     my %iphost;
13903:     my %name_to_ip;
13904:     my %lonid_to_ip;
13905: 
13906:     sub get_hosts_from_ip {
13907: 	my ($ip) = @_;
13908: 	my %iphosts = &get_iphost();
13909: 	if (ref($iphosts{$ip})) {
13910: 	    return @{$iphosts{$ip}};
13911: 	}
13912: 	return;
13913:     }
13914:     
13915:     sub reset_hosts_ip_info {
13916: 	undef(%iphost);
13917: 	undef(%name_to_ip);
13918: 	undef(%lonid_to_ip);
13919:     }
13920: 
13921:     sub get_host_ip {
13922: 	my ($lonid) = @_;
13923: 	if (exists($lonid_to_ip{$lonid})) {
13924: 	    return $lonid_to_ip{$lonid};
13925: 	}
13926: 	my $name=&hostname($lonid);
13927:    	my $ip = gethostbyname($name);
13928: 	return if (!$ip || length($ip) ne 4);
13929: 	$ip=inet_ntoa($ip);
13930: 	$name_to_ip{$name}   = $ip;
13931: 	$lonid_to_ip{$lonid} = $ip;
13932: 	return $ip;
13933:     }
13934:     
13935:     sub get_iphost {
13936: 	my ($ignore_cache,$nocache) = @_;
13937: 
13938: 	if (!$ignore_cache) {
13939: 	    if (%iphost) {
13940: 		return %iphost;
13941: 	    }
13942: 	    my ($ip_info,$cached)=
13943: 		&Apache::lonnet::is_cached_new('iphost','iphost');
13944: 	    if ($cached) {
13945: 		%iphost      = %{$ip_info->[0]};
13946: 		%name_to_ip  = %{$ip_info->[1]};
13947: 		%lonid_to_ip = %{$ip_info->[2]};
13948: 		return %iphost;
13949: 	    }
13950: 	}
13951: 
13952: 	# get yesterday's info for fallback
13953: 	my %old_name_to_ip;
13954: 	my ($ip_info,$cached)=
13955: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
13956: 	if ($cached) {
13957: 	    %old_name_to_ip = %{$ip_info->[1]};
13958: 	}
13959: 
13960: 	my %name_to_host = &all_names($ignore_cache,$nocache);
13961: 	foreach my $name (keys(%name_to_host)) {
13962: 	    my $ip;
13963: 	    if (!exists($name_to_ip{$name})) {
13964: 		$ip = gethostbyname($name);
13965: 		if (!$ip || length($ip) ne 4) {
13966: 		    if (defined($old_name_to_ip{$name})) {
13967: 			$ip = $old_name_to_ip{$name};
13968: 			&logthis("Can't find $name defaulting to old $ip");
13969: 		    } else {
13970: 			&logthis("Name $name no IP found");
13971: 			next;
13972: 		    }
13973: 		} else {
13974: 		    $ip=inet_ntoa($ip);
13975: 		}
13976: 		$name_to_ip{$name} = $ip;
13977: 	    } else {
13978: 		$ip = $name_to_ip{$name};
13979: 	    }
13980: 	    foreach my $id (@{ $name_to_host{$name} }) {
13981: 		$lonid_to_ip{$id} = $ip;
13982: 	    }
13983: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
13984: 	}
13985:         unless ($nocache) {
13986: 	    &do_cache_new('iphost','iphost',
13987: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
13988: 		          48*60*60);
13989:         }
13990: 
13991: 	return %iphost;
13992:     }
13993: 
13994:     #
13995:     #  Given a DNS returns the loncapa host name for that DNS 
13996:     # 
13997:     sub host_from_dns {
13998:         my ($dns) = @_;
13999:         my @hosts;
14000:         my $ip;
14001: 
14002:         if (exists($name_to_ip{$dns})) {
14003:             $ip = $name_to_ip{$dns};
14004:         }
14005:         if (!$ip) {
14006:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
14007:             if (length($ip) == 4) { 
14008: 	        $ip   = &IO::Socket::inet_ntoa($ip);
14009:             }
14010:         }
14011:         if ($ip) {
14012: 	    @hosts = get_hosts_from_ip($ip);
14013: 	    return $hosts[0];
14014:         }
14015:         return undef;
14016:     }
14017: 
14018:     sub get_internet_names {
14019:         my ($lonid) = @_;
14020:         return if ($lonid eq '');
14021:         my ($idnref,$cached)=
14022:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
14023:         if ($cached) {
14024:             return $idnref;
14025:         }
14026:         my $ip = &get_host_ip($lonid);
14027:         my @hosts = &get_hosts_from_ip($ip);
14028:         my %iphost = &get_iphost();
14029:         my (@idns,%seen);
14030:         foreach my $id (@hosts) {
14031:             my $dom = &host_domain($id);
14032:             my $prim_id = &domain($dom,'primary');
14033:             my $prim_ip = &get_host_ip($prim_id);
14034:             next if ($seen{$prim_ip});
14035:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
14036:                 foreach my $id (@{$iphost{$prim_ip}}) {
14037:                     my $intdom = &internet_dom($id);
14038:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
14039:                         push(@idns,$intdom);
14040:                     }
14041:                 }
14042:             }
14043:             $seen{$prim_ip} = 1;
14044:         }
14045:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
14046:     }
14047: 
14048: }
14049: 
14050: sub all_loncaparevs {
14051:     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);
14052: }
14053: 
14054: # ------------------------------------------------------- Read loncaparev table
14055: {
14056:     sub load_loncaparevs {
14057:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
14058:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
14059:                 while (my $configline=<$config>) {
14060:                     chomp($configline);
14061:                     my ($hostid,$loncaparev)=split(/:/,$configline);
14062:                     $loncaparevs{$hostid}=$loncaparev;
14063:                 }
14064:                 close($config);
14065:             }
14066:         }
14067:     }
14068: }
14069: 
14070: # ----------------------------------------------------- Read serverhostID table
14071: {
14072:     sub load_serverhomeIDs {
14073:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
14074:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
14075:                 while (my $configline=<$config>) {
14076:                     chomp($configline);
14077:                     my ($name,$id)=split(/:/,$configline);
14078:                     $serverhomeIDs{$name}=$id;
14079:                 }
14080:                 close($config);
14081:             }
14082:         }
14083:     }
14084: }
14085: 
14086: 
14087: BEGIN {
14088: 
14089: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
14090:     unless ($readit) {
14091: {
14092:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
14093:     %perlvar = (%perlvar,%{$configvars});
14094: }
14095: 
14096: 
14097: # ------------------------------------------------------ Read spare server file
14098: {
14099:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
14100: 
14101:     while (my $configline=<$config>) {
14102:        chomp($configline);
14103:        if ($configline) {
14104: 	   my ($host,$type) = split(':',$configline,2);
14105: 	   if (!defined($type) || $type eq '') { $type = 'default' };
14106: 	   push(@{ $spareid{$type} }, $host);
14107:        }
14108:     }
14109:     close($config);
14110: }
14111: # ------------------------------------------------------------ Read permissions
14112: {
14113:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
14114: 
14115:     while (my $configline=<$config>) {
14116: 	chomp($configline);
14117: 	if ($configline) {
14118: 	    my ($role,$perm)=split(/ /,$configline);
14119: 	    if ($perm ne '') { $pr{$role}=$perm; }
14120: 	}
14121:     }
14122:     close($config);
14123: }
14124: 
14125: # -------------------------------------------- Read plain texts for permissions
14126: {
14127:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
14128: 
14129:     while (my $configline=<$config>) {
14130: 	chomp($configline);
14131: 	if ($configline) {
14132: 	    my ($short,@plain)=split(/:/,$configline);
14133:             %{$prp{$short}} = ();
14134: 	    if (@plain > 0) {
14135:                 $prp{$short}{'std'} = $plain[0];
14136:                 for (my $i=1; $i<@plain; $i++) {
14137:                     $prp{$short}{'alt'.$i} = $plain[$i];  
14138:                 }
14139:             }
14140: 	}
14141:     }
14142:     close($config);
14143: }
14144: 
14145: # ---------------------------------------------------------- Read package table
14146: {
14147:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
14148: 
14149:     while (my $configline=<$config>) {
14150: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
14151: 	chomp($configline);
14152: 	my ($short,$plain)=split(/:/,$configline);
14153: 	my ($pack,$name)=split(/\&/,$short);
14154: 	if ($plain ne '') {
14155: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
14156: 	    $packagetab{$short}=$plain; 
14157: 	}
14158:     }
14159:     close($config);
14160: }
14161: 
14162: # --------------------------------------------------------- Read loncaparev table
14163: 
14164: &load_loncaparevs();
14165: 
14166: # ------------------------------------------------------- Read serverhostID table
14167: 
14168: &load_serverhomeIDs();
14169: 
14170: # ---------------------------------------------------------- Read releaseslist XML
14171: {
14172:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
14173:     if (-e $file) {
14174:         my $parser = HTML::LCParser->new($file);
14175:         while (my $token = $parser->get_token()) {
14176:             if ($token->[0] eq 'S') {
14177:                 my $item = $token->[1];
14178:                 my $name = $token->[2]{'name'};
14179:                 my $value = $token->[2]{'value'};
14180:                 if ($item ne '' && $name ne '' && $value ne '') {
14181:                     my $release = $parser->get_text();
14182:                     $release =~ s/(^\s*|\s*$ )//gx;
14183:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
14184:                 }
14185:             }
14186:         }
14187:     }
14188: }
14189: 
14190: # ---------------------------------------------------------- Read managers table
14191: {
14192:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
14193:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
14194:             while (my $configline=<$config>) {
14195:                 chomp($configline);
14196:                 next if ($configline =~ /^\#/);
14197:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
14198:                     $managerstab{$configline} = 1;
14199:                 }
14200:             }
14201:             close($config);
14202:         }
14203:     }
14204: }
14205: 
14206: # ------------- set up temporary directory
14207: {
14208:     $tmpdir = LONCAPA::tempdir();
14209: 
14210: }
14211: 
14212: # ------------- set default texengine (domain default overrides this)
14213: {
14214:     $deftex = LONCAPA::texengine();
14215: }
14216: 
14217: # ------------- set default minimum length for passwords for internal auth users
14218: {
14219:     $passwdmin = LONCAPA::passwd_min();
14220: }
14221: 
14222: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
14223: 				'compress_threshold'=> 20_000,
14224:  			        });
14225: 
14226: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
14227: $dumpcount=0;
14228: $locknum=0;
14229: 
14230: &logtouch();
14231: &logthis('<font color="yellow">INFO: Read configuration</font>');
14232: $readit=1;
14233:     {
14234: 	use integer;
14235: 	my $test=(2**32)+1;
14236: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
14237: 	&logthis(" Detected 64bit platform ($_64bit)");
14238:     }
14239: }
14240: }
14241: 
14242: 1;
14243: __END__
14244: 
14245: =pod
14246: 
14247: =head1 NAME
14248: 
14249: Apache::lonnet - Subroutines to ask questions about things in the network.
14250: 
14251: =head1 SYNOPSIS
14252: 
14253: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
14254: 
14255:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
14256: 
14257: Common parameters:
14258: 
14259: =over 4
14260: 
14261: =item *
14262: 
14263: $uname : an internal username (if $cname expecting a course Id specifically)
14264: 
14265: =item *
14266: 
14267: $udom : a domain (if $cdom expecting a course's domain specifically)
14268: 
14269: =item *
14270: 
14271: $symb : a resource instance identifier
14272: 
14273: =item *
14274: 
14275: $namespace : the name of a .db file that contains the data needed or
14276: being set.
14277: 
14278: =back
14279: 
14280: =head1 OVERVIEW
14281: 
14282: lonnet provides subroutines which interact with the
14283: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
14284: about classes, users, and resources.
14285: 
14286: For many of these objects you can also use this to store data about
14287: them or modify them in various ways.
14288: 
14289: =head2 Symbs
14290: 
14291: To identify a specific instance of a resource, LON-CAPA uses symbols
14292: or "symbs"X<symb>. These identifiers are built from the URL of the
14293: map, the resource number of the resource in the map, and the URL of
14294: the resource itself. The latter is somewhat redundant, but might help
14295: if maps change.
14296: 
14297: An example is
14298: 
14299:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
14300: 
14301: The respective map entry is
14302: 
14303:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
14304:   title="Problem 2">
14305:  </resource>
14306: 
14307: Symbs are used by the random number generator, as well as to store and
14308: restore data specific to a certain instance of for example a problem.
14309: 
14310: =head2 Storing And Retrieving Data
14311: 
14312: X<store()>X<cstore()>X<restore()>Three of the most important functions
14313: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
14314: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
14315: is is the non-critical message twin of cstore. These functions are for
14316: handlers to store a perl hash to a user's permanent data space in an
14317: easy manner, and to retrieve it again on another call. It is expected
14318: that a handler would use this once at the beginning to retrieve data,
14319: and then again once at the end to send only the new data back.
14320: 
14321: The data is stored in the user's data directory on the user's
14322: homeserver under the ID of the course.
14323: 
14324: The hash that is returned by restore will have all of the previous
14325: value for all of the elements of the hash.
14326: 
14327: Example:
14328: 
14329:  #creating a hash
14330:  my %hash;
14331:  $hash{'foo'}='bar';
14332: 
14333:  #storing it
14334:  &Apache::lonnet::cstore(\%hash);
14335: 
14336:  #changing a value
14337:  $hash{'foo'}='notbar';
14338: 
14339:  #adding a new value
14340:  $hash{'bar'}='foo';
14341:  &Apache::lonnet::cstore(\%hash);
14342: 
14343:  #retrieving the hash
14344:  my %history=&Apache::lonnet::restore();
14345: 
14346:  #print the hash
14347:  foreach my $key (sort(keys(%history))) {
14348:    print("\%history{$key} = $history{$key}");
14349:  }
14350: 
14351: Will print out:
14352: 
14353:  %history{1:foo} = bar
14354:  %history{1:keys} = foo:timestamp
14355:  %history{1:timestamp} = 990455579
14356:  %history{2:bar} = foo
14357:  %history{2:foo} = notbar
14358:  %history{2:keys} = foo:bar:timestamp
14359:  %history{2:timestamp} = 990455580
14360:  %history{bar} = foo
14361:  %history{foo} = notbar
14362:  %history{timestamp} = 990455580
14363:  %history{version} = 2
14364: 
14365: Note that the special hash entries C<keys>, C<version> and
14366: C<timestamp> were added to the hash. C<version> will be equal to the
14367: total number of versions of the data that have been stored. The
14368: C<timestamp> attribute will be the UNIX time the hash was
14369: stored. C<keys> is available in every historical section to list which
14370: keys were added or changed at a specific historical revision of a
14371: hash.
14372: 
14373: B<Warning>: do not store the hash that restore returns directly. This
14374: will cause a mess since it will restore the historical keys as if the
14375: were new keys. I.E. 1:foo will become 1:1:foo etc.
14376: 
14377: Calling convention:
14378: 
14379:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
14380:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
14381: 
14382: For more detailed information, see lonnet specific documentation.
14383: 
14384: =head1 RETURN MESSAGES
14385: 
14386: =over 4
14387: 
14388: =item * B<con_lost>: unable to contact remote host
14389: 
14390: =item * B<con_delayed>: unable to contact remote host, message will be delivered
14391: when the connection is brought back up
14392: 
14393: =item * B<con_failed>: unable to contact remote host and unable to save message
14394: for later delivery
14395: 
14396: =item * B<error:>: an error a occurred, a description of the error follows the :
14397: 
14398: =item * B<no_such_host>: unable to fund a host associated with the user/domain
14399: that was requested
14400: 
14401: =back
14402: 
14403: =head1 PUBLIC SUBROUTINES
14404: 
14405: =head2 Session Environment Functions
14406: 
14407: =over 4
14408: 
14409: =item * 
14410: X<appenv()>
14411: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
14412: the user envirnoment file, and will be restored for each access this
14413: user makes during this session, also modifies the %env for the current
14414: process. Optional rolesarrayref - if defined contains a reference to an array
14415: of roles which are exempt from the restriction on modifying user.role entries 
14416: in the user's environment.db and in %env.    
14417: 
14418: =item *
14419: X<delenv()>
14420: B<delenv($delthis,$regexp)>: removes all items from the session
14421: environment file that begin with $delthis. If the 
14422: optional second arg - $regexp - is true, $delthis is treated as a 
14423: regular expression, otherwise \Q$delthis\E is used. 
14424: The values are also deleted from the current processes %env.
14425: 
14426: =item * get_env_multiple($name) 
14427: 
14428: gets $name from the %env hash, it seemlessly handles the cases where multiple
14429: values may be defined and end up as an array ref.
14430: 
14431: returns an array of values
14432: 
14433: =back
14434: 
14435: =head2 User Information
14436: 
14437: =over 4
14438: 
14439: =item *
14440: X<queryauthenticate()>
14441: B<queryauthenticate($uname,$udom)>: try to determine user's current 
14442: authentication scheme
14443: 
14444: =item *
14445: X<authenticate()>
14446: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
14447: authenticate user from domain's lib servers (first use the current
14448: one). C<$upass> should be the users password.
14449: $checkdefauth is optional (value is 1 if a check should be made to
14450:    authenticate user using default authentication method, and allow
14451:    account creation if username does not have account in the domain).
14452: $clientcancheckhost is optional (value is 1 if checking whether the
14453:    server can host will occur on the client side in lonauth.pm).   
14454: 
14455: =item *
14456: X<homeserver()>
14457: B<homeserver($uname,$udom)>: find the server which has
14458: the user's directory and files (there must be only one), this caches
14459: the answer, and also caches if there is a borken connection.
14460: 
14461: =item *
14462: X<idget()>
14463: B<idget($udom,@ids)>: find the usernames behind a list of IDs
14464: (IDs are a unique resource in a domain, there must be only 1 ID per
14465: username, and only 1 username per ID in a specific domain) (returns
14466: hash: id=>name,id=>name)
14467: 
14468: =item *
14469: X<idrget()>
14470: B<idrget($udom,@unames)>: find the IDs behind a list of
14471: usernames (returns hash: name=>id,name=>id)
14472: 
14473: =item *
14474: X<idput()>
14475: B<idput($udom,%ids)>: store away a list of names and associated IDs
14476: 
14477: =item *
14478: X<rolesinit()>
14479: B<rolesinit($udom,$username)>: get user privileges.
14480: returns user role, first access and timer interval hashes
14481: 
14482: =item *
14483: X<privileged()>
14484: B<privileged($username,$domain)>: returns a true if user has a
14485: privileged and active role (i.e. su or dc), false otherwise.
14486: 
14487: =item *
14488: X<getsection()>
14489: B<getsection($udom,$uname,$cname)>: finds the section of student in the
14490: course $cname, return section name/number or '' for "not in course"
14491: and '-1' for "no section"
14492: 
14493: =item *
14494: X<userenvironment()>
14495: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
14496: passed in @what from the requested user's environment, returns a hash
14497: 
14498: =item * 
14499: X<userlog_query()>
14500: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
14501: activity.log file. %filters defines filters applied when parsing the
14502: log file. These can be start or end timestamps, or the type of action
14503: - log to look for Login or Logout events, check for Checkin or
14504: Checkout, role for role selection. The response is in the form
14505: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
14506: escaped strings of the action recorded in the activity.log file.
14507: 
14508: =back
14509: 
14510: =head2 User Roles
14511: 
14512: =over 4
14513: 
14514: =item *
14515: 
14516: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
14517: returns codes for allowed actions.
14518: 
14519: The first argument is required, all others are optional.
14520: 
14521: $priv is the privilege being checked.
14522: $uri contains additional information about what is being checked for access (e.g.,
14523: URL, course ID etc.).
14524: $symb is the unique resource instance identifier in a course; if needed,
14525: but not provided, it will be retrieved via a call to &symbread().
14526: $role is the role for which a priv is being checked (only used if priv is evb).
14527: $clientip is the user's IP address (only used when checking for access to portfolio
14528: files).
14529: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
14530: prevents recursive calls to &allowed.
14531: 
14532:  F: full access
14533:  U,I,K: authentication modes (cxx only)
14534:  '': forbidden
14535:  1: user needs to choose course
14536:  2: browse allowed
14537:  A: passphrase authentication needed
14538:  B: access temporarily blocked because of a blocking event in a course.
14539: 
14540: =item *
14541: 
14542: constructaccess($url,$setpriv) : check for access to construction space URL
14543: 
14544: See if the owner domain and name in the URL match those in the
14545: expected environment.  If so, return three element list
14546: ($ownername,$ownerdomain,$ownerhome).
14547: 
14548: Otherwise return the null string.
14549: 
14550: If second argument 'setpriv' is true, it assigns the privileges,
14551: and returns the same three element list, unless the owner has
14552: blocked "ad hoc" Domain Coordinator access to the Author Space,
14553: in which case the null string is returned.
14554: 
14555: =item *
14556: 
14557: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
14558: define a custom role rolename set privileges in format of lonTabs/roles.tab
14559: for system, domain, and course level. $uname and $udom are optional (current
14560: user's username and domain will be used when either of $uname or $udom are absent.
14561: 
14562: =item *
14563: 
14564: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
14565: (rolesplain.tab); plain text explanation of a user role term.
14566: $type is Course (default) or Community.
14567: If $forcedefault evaluates to true, text returned will be default 
14568: text for $type. Otherwise, if this is a course, the text returned 
14569: will be a custom name for the role (if defined in the course's 
14570: environment).  If no custom name is defined the default is returned.
14571:    
14572: =item *
14573: 
14574: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
14575: All arguments are optional. Returns a hash of a roles, either for
14576: co-author/assistant author roles for a user's Construction Space
14577: (default), or if $context is 'userroles', roles for the user himself,
14578: In the hash, keys are set to colon-separated $uname,$udom,$role, and
14579: (optionally) if $withsec is true, a fourth colon-separated item - $section.
14580: For each key, value is set to colon-separated start and end times for
14581: the role.  If no username and domain are specified, will default to
14582: current user/domain. Types, roles, and roledoms are references to arrays
14583: of role statuses (active, future or previous), roles 
14584: (e.g., cc,in, st etc.) and domains of the roles which can be used
14585: to restrict the list of roles reported. If no array ref is 
14586: provided for types, will default to return only active roles.
14587: 
14588: =item *
14589: 
14590: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
14591: user: $uname:$udom has a role in the course: $cdom_$cnum.
14592: 
14593: Additional optional arguments are: $type (if role checking is to be restricted
14594: to certain user status types -- previous (expired roles), active (currently
14595: available roles) or future (roles available in the future), and
14596: $hideprivileged -- if true will not report course roles for users who
14597: have active Domain Coordinator role in course's domain or in additional
14598: domains (specified in 'Domains to check for privileged users' in course
14599: environment -- set via:  Course Settings -> Classlists and staff listing).
14600: 
14601: =item *
14602: 
14603: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
14604: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
14605: $possdomains and $possroles are optional array refs -- to domains to check and
14606: roles to check.  If $possdomains is not specified, a dump will be done of the
14607: users' roles.db to check for a dc or su role in any domain. This can be
14608: time consuming if &privileged is called repeatedly (e.g., when displaying a
14609: classlist), so in such cases, supplying a $possdomains array is preferred, as
14610: this then allows &privileged_by_domain() to be used, which caches the identity
14611: of privileged users, eliminating the need for repeated calls to &dump().
14612: 
14613: =item *
14614: 
14615: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
14616: where the outer hash keys are domains specified in the $possdomains array ref,
14617: next inner hash keys are privileged roles specified in the $roles array ref,
14618: and the innermost hash contains key = value pairs for username:domain = end:start
14619: for active or future "privileged" users with that role in that domain. To avoid
14620: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
14621: innerhash are cached using priv_$role and $dom as the identifiers.
14622: 
14623: =back
14624: 
14625: =head2 User Modification
14626: 
14627: =over 4
14628: 
14629: =item *
14630: 
14631: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
14632: user for the level given by URL.  Optional start and end dates (leave empty
14633: string or zero for "no date")
14634: 
14635: =item *
14636: 
14637: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
14638: change a users, password, possible return values are: ok,
14639: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
14640: refused
14641: 
14642: =item *
14643: 
14644: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
14645: 
14646: =item *
14647: 
14648: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
14649:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
14650: 
14651: will update user information (firstname,middlename,lastname,generation,
14652: permanentemail), and if forceid is true, student/employee ID also.
14653: A user's institutional affiliation(s) can also be updated.
14654: User information fields will not be overwritten with empty entries 
14655: unless the field is included in the $candelete array reference.
14656: This array is included when a single user is modified via "Manage Users",
14657: or when Autoupdate.pl is run by cron in a domain.
14658: 
14659: =item *
14660: 
14661: modifystudent
14662: 
14663: modify a student's enrollment and identification information.
14664: The course id is resolved based on the current user's environment.  
14665: This means the invoking user must be a course coordinator or otherwise
14666: associated with a course.
14667: 
14668: This call is essentially a wrapper for lonnet::modifyuser and
14669: lonnet::modify_student_enrollment
14670: 
14671: Inputs: 
14672: 
14673: =over 4
14674: 
14675: =item B<$udom> Student's loncapa domain
14676: 
14677: =item B<$uname> Student's loncapa login name
14678: 
14679: =item B<$uid> Student/Employee ID
14680: 
14681: =item B<$umode> Student's authentication mode
14682: 
14683: =item B<$upass> Student's password
14684: 
14685: =item B<$first> Student's first name
14686: 
14687: =item B<$middle> Student's middle name
14688: 
14689: =item B<$last> Student's last name
14690: 
14691: =item B<$gene> Student's generation
14692: 
14693: =item B<$usec> Student's section in course
14694: 
14695: =item B<$end> Unix time of the roles expiration
14696: 
14697: =item B<$start> Unix time of the roles start date
14698: 
14699: =item B<$forceid> If defined, allow $uid to be changed
14700: 
14701: =item B<$desiredhome> server to use as home server for student
14702: 
14703: =item B<$email> Student's permanent e-mail address
14704: 
14705: =item B<$type> Type of enrollment (auto or manual)
14706: 
14707: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
14708: 
14709: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
14710: 
14711: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
14712: 
14713: =item B<$context> role change context (shown in User Management Logs display in a course)
14714: 
14715: =item B<$inststatus> institutional status of user - : separated string of escaped status types
14716: 
14717: =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.
14718: 
14719: =back
14720: 
14721: =item *
14722: 
14723: modify_student_enrollment
14724: 
14725: Change a student's enrollment status in a class.  The environment variable
14726: 'role.request.course' must be defined for this function to proceed.
14727: 
14728: Inputs:
14729: 
14730: =over 4
14731: 
14732: =item $udom, student's domain
14733: 
14734: =item $uname, student's name
14735: 
14736: =item $uid, student's user id
14737: 
14738: =item $first, student's first name
14739: 
14740: =item $middle
14741: 
14742: =item $last
14743: 
14744: =item $gene
14745: 
14746: =item $usec
14747: 
14748: =item $end
14749: 
14750: =item $start
14751: 
14752: =item $type
14753: 
14754: =item $locktype
14755: 
14756: =item $cid
14757: 
14758: =item $selfenroll
14759: 
14760: =item $context
14761: 
14762: =item $credits, number of credits student will earn from this class
14763: 
14764: =item $instsec, institutional course section code for student
14765: 
14766: =back
14767: 
14768: 
14769: =item *
14770: 
14771: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
14772: custom role; give a custom role to a user for the level given by URL.  Specify
14773: name and domain of role author, and role name
14774: 
14775: =item *
14776: 
14777: revokerole($udom,$uname,$url,$role) : revoke a role for url
14778: 
14779: =item *
14780: 
14781: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
14782: 
14783: =back
14784: 
14785: =head2 Course Infomation
14786: 
14787: =over 4
14788: 
14789: =item *
14790: 
14791: coursedescription($courseid,$options) : returns a hash of information about the
14792: specified course id, including all environment settings for the
14793: course, the description of the course will be in the hash under the
14794: key 'description'
14795: 
14796: $options is an optional parameter that if supplied is a hash reference that controls
14797: what how this function works.  It has the following key/values:
14798: 
14799: =over 4
14800: 
14801: =item freshen_cache
14802: 
14803: If defined, and the environment cache for the course is valid, it is 
14804: returned in the returned hash.
14805: 
14806: =item one_time
14807: 
14808: If defined, the last cache time is set to _now_
14809: 
14810: =item user
14811: 
14812: If defined, the supplied username is used instead of the current user.
14813: 
14814: 
14815: =back
14816: 
14817: =item *
14818: 
14819: resdata($name,$domain,$type,@which) : request for current parameter
14820: setting for a specific $type, where $type is either 'course' or 'user',
14821: @what should be a list of parameters to ask about. This routine caches
14822: answers for 10 minutes.
14823: 
14824: =item *
14825: 
14826: get_courseresdata($courseid, $domain) : dump the entire course resource
14827: data base, returning a hash that is keyed by the resource name and has
14828: values that are the resource value.  I believe that the timestamps and
14829: versions are also returned.
14830: 
14831: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
14832: supplemental content area. This routine caches the number of files for
14833: 10 minutes.
14834: 
14835: =back
14836: 
14837: =head2 Course Modification
14838: 
14839: =over 4
14840: 
14841: =item *
14842: 
14843: writecoursepref($courseid,%prefs) : write preferences (environment
14844: database) for a course
14845: 
14846: =item *
14847: 
14848: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
14849: 
14850: =item *
14851: 
14852: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
14853: 
14854: =item *
14855: 
14856: is_course($courseid), is_course($cdom, $cnum)
14857: 
14858: Accepts either a combined $courseid (in the form of domain_courseid) or the
14859: two component version $cdom, $cnum. It checks if the specified course exists.
14860: 
14861: Returns:
14862:     undef if the course doesn't exist, otherwise
14863:     in scalar context the combined courseid.
14864:     in list context the two components of the course identifier, domain and 
14865:     courseid.    
14866: 
14867: =back
14868: 
14869: =head2 Bubblesheet Configuration
14870: 
14871: =over 4
14872: 
14873: =item *
14874: 
14875: get_scantron_config($which)
14876: 
14877: $which - the name of the configuration to parse from the file.
14878: 
14879: Parses and returns the bubblesheet configuration line selected as a
14880: hash of configuration file fields.
14881: 
14882: 
14883: Returns:
14884:     If the named configuration is not in the file, an empty
14885:     hash is returned.
14886: 
14887:     a hash with the fields
14888:       name         - internal name for the this configuration setup
14889:       description  - text to display to operator that describes this config
14890:       CODElocation - if 0 or the string 'none'
14891:                           - no CODE exists for this config
14892:                      if -1 || the string 'letter'
14893:                           - a CODE exists for this config and is
14894:                             a string of letters
14895:                      Unsupported value (but planned for future support)
14896:                           if a positive integer
14897:                                - The CODE exists as the first n items from
14898:                                  the question section of the form
14899:                           if the string 'number'
14900:                                - The CODE exists for this config and is
14901:                                  a string of numbers
14902:       CODEstart   - (only matter if a CODE exists) column in the line where
14903:                      the CODE starts
14904:       CODElength  - length of the CODE
14905:       IDstart     - column where the student/employee ID starts
14906:       IDlength    - length of the student/employee ID info
14907:       Qstart      - column where the information from the bubbled
14908:                     'questions' start
14909:       Qlength     - number of columns comprising a single bubble line from
14910:                     the sheet. (usually either 1 or 10)
14911:       Qon         - either a single character representing the character used
14912:                     to signal a bubble was chosen in the positional setup, or
14913:                     the string 'letter' if the letter of the chosen bubble is
14914:                     in the final, or 'number' if a number representing the
14915:                     chosen bubble is in the file (1->A 0->J)
14916:       Qoff        - the character used to represent that a bubble was
14917:                     left blank
14918:       PaperID     - if the scanning process generates a unique number for each
14919:                     sheet scanned the column that this ID number starts in
14920:       PaperIDlength - number of columns that comprise the unique ID number
14921:                       for the sheet of paper
14922:       FirstName   - column that the first name starts in
14923:       FirstNameLength - number of columns that the first name spans
14924:       LastName    - column that the last name starts in
14925:       LastNameLength - number of columns that the last name spans
14926:       BubblesPerRow - number of bubbles available in each row used to
14927:                       bubble an answer. (If not specified, 10 assumed).
14928: 
14929: 
14930: =item *
14931: 
14932: get_scantronformat_file($cdom)
14933: 
14934: $cdom - the course's domain (optional); if not supplied, uses
14935: domain for current $env{'request.course.id'}.
14936: 
14937: Returns an array containing lines from the scantron format file for
14938: the domain of the course.
14939: 
14940: If a url for a custom.tab file is listed in domain's configuration.db,
14941: lines are from this file.
14942: 
14943: Otherwise, if a default.tab has been published in RES space by the
14944: domainconfig user, lines are from this file.
14945: 
14946: Otherwise, fall back to getting lines from the legacy file on the
14947: local server:  /home/httpd/lonTabs/default_scantronformat.tab
14948: 
14949: =back
14950: 
14951: =head2 Resource Subroutines
14952: 
14953: =over 4
14954: 
14955: =item *
14956: 
14957: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
14958: 
14959: =item *
14960: 
14961: repcopy($filename) : subscribes to the requested file, and attempts to
14962: replicate from the owning library server, Might return
14963: 'unavailable', 'not_found', 'forbidden', 'ok', or
14964: 'bad_request', also attempts to grab the metadata for the
14965: resource. Expects the local filesystem pathname
14966: (/home/httpd/html/res/....)
14967: 
14968: =back
14969: 
14970: =head2 Resource Information
14971: 
14972: =over 4
14973: 
14974: =item *
14975: 
14976: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
14977: and returns the value of a variety of different possible values,
14978: $varname should be a request string, and the other parameters can be
14979: used to specify who and what one is asking about. Ordinarily, $cid 
14980: does not need to be specified, as it is retrived from 
14981: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
14982: within lonuserstate::loadmap() when initializing a course, before
14983: $env{'request.course.id'} has been set, so it needs to be provided
14984: in that one case.
14985: 
14986: Possible values for $varname are environment.lastname (or other item
14987: from the envirnment hash), user.name (or someother aspect about the
14988: user), resource.0.maxtries (or some other part and parameter of a
14989: resource)
14990: 
14991: =item *
14992: 
14993: directcondval($number) : get current value of a condition; reads from a state
14994: string
14995: 
14996: =item *
14997: 
14998: condval($condidx) : value of condition index based on state
14999: 
15000: =item *
15001: 
15002: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
15003: resource's metadata, $what should be either a specific key, or either
15004: 'keys' (to get a list of possible keys) or 'packages' to get a list of
15005: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
15006: 
15007: this function automatically caches all requests
15008: 
15009: =item *
15010: 
15011: metadata_query($query,$custom,$customshow) : make a metadata query against the
15012: network of library servers; returns file handle of where SQL and regex results
15013: will be stored for query
15014: 
15015: =item *
15016: 
15017: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
15018: return symbolic list entry (all arguments optional).
15019: 
15020: Args: filename is the filename (including path) for the file for which a symb
15021: is required; donotrecurse, if true will prevent calls to allowed() being made
15022: to check access status if more than one resource was found in the bighash
15023: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
15024: a randompick); ignorecachednull, if true will prevent a symb of '' being
15025: returned if $env{$cache_str} is defined as ''; checkforblock if true will
15026: cause possible symbs to be checked to determine if they are subject to content
15027: blocking, if so they will not be included as possible symbs; possibles is a
15028: ref to a hash, which, as a side effect, will be populated with all possible
15029: symbs (content blocking not tested).
15030: 
15031: returns the data handle
15032: 
15033: =item *
15034: 
15035: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
15036: and is a possible symb for the URL in $thisfn, and if is an encrypted
15037: resource that the user accessed using /enc/ returns a 1 on success, 0
15038: on failure, user must be in a course, as it assumes the existence of
15039: the course initial hash, and uses $env('request.course.id'}.  The third
15040: arg is an optional reference to a scalar.  If this arg is passed in the
15041: call to symbverify, it will be set to 1 if the symb has been set to be 
15042: encrypted; otherwise it will be null.
15043: 
15044: =item *
15045: 
15046: symbclean($symb) : removes versions numbers from a symb, returns the
15047: cleaned symb
15048: 
15049: =item *
15050: 
15051: is_on_map($uri) : checks if the $uri is somewhere on the current
15052: course map, user must be in a course for it to work.
15053: 
15054: =item *
15055: 
15056: numval($salt) : return random seed value (addend for rndseed)
15057: 
15058: =item *
15059: 
15060: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
15061: a random seed, all arguments are optional, if they aren't sent it uses the
15062: environment to derive them. Note: if symb isn't sent and it can't get one
15063: from &symbread it will use the current time as its return value
15064: 
15065: =item *
15066: 
15067: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
15068: unfakeable, receipt
15069: 
15070: =item *
15071: 
15072: receipt() : API to ireceipt working off of env values; given out to users
15073: 
15074: =item *
15075: 
15076: countacc($url) : count the number of accesses to a given URL
15077: 
15078: =item *
15079: 
15080: 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
15081: 
15082: =item *
15083: 
15084: 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)
15085: 
15086: =item *
15087: 
15088: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
15089: 
15090: =item *
15091: 
15092: devalidate($symb) : devalidate temporary spreadsheet calculations,
15093: forcing spreadsheet to reevaluate the resource scores next time.
15094: 
15095: =item *
15096: 
15097: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
15098: when viewing in course context.
15099: 
15100:  input: six args -- filename (decluttered), course number, course domain,
15101:                     url, symb (if registered) and group (if this is a
15102:                     group item -- e.g., bulletin board, group page etc.).
15103: 
15104:  output: array of five scalars --
15105:          $cfile -- url for file editing if editable on current server
15106:          $home -- homeserver of resource (i.e., for author if published,
15107:                                           or course if uploaded.).
15108:          $switchserver --  1 if server switch will be needed.
15109:          $forceedit -- 1 if icon/link should be to go to edit mode
15110:          $forceview -- 1 if icon/link should be to go to view mode
15111: 
15112: =item *
15113: 
15114: is_course_upload($file,$cnum,$cdom)
15115: 
15116: Used in course context to determine if current file was uploaded to
15117: the course (i.e., would be found in /userfiles/docs on the course's
15118: homeserver.
15119: 
15120:   input: 3 args -- filename (decluttered), course number and course domain.
15121:   output: boolean -- 1 if file was uploaded.
15122: 
15123: =back
15124: 
15125: =head2 Storing/Retreiving Data
15126: 
15127: =over 4
15128: 
15129: =item *
15130: 
15131: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash 
15132: permanently for this url; hashref needs to be given and should be a \%hashname;
15133: the remaining args aren't required and if they aren't passed or are '' they will
15134: be derived from the env (with the exception of $laststore, which is an
15135: optional arg used when a user's submission is stored in grading).
15136: $laststore is $version=$timestamp, where $version is the most recent version
15137: number retrieved for the corresponding $symb in the $namespace db file, and
15138: $timestamp is the timestamp for that transaction (UNIX time).
15139: $laststore is currently only passed when cstore() is called by
15140: structuretags::finalize_storage().
15141: 
15142: =item *
15143: 
15144: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store 
15145: but uses critical subroutine
15146: 
15147: =item *
15148: 
15149: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
15150: all args are optional
15151: 
15152: =item *
15153: 
15154: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
15155: dumps the complete (or key matching regexp) namespace into a hash
15156: ($udom, $uname, $regexp, $range are optional) for a namespace that is
15157: normally &store()ed into
15158: 
15159: $range should be either an integer '100' (give me the first 100
15160:                                            matching records)
15161:               or be  two integers sperated by a - with no spaces
15162:                  '30-50' (give me the 30th through the 50th matching
15163:                           records)
15164: 
15165: 
15166: =item *
15167: 
15168: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
15169: replaces a &store() version of data with a replacement set of data
15170: for a particular resource in a namespace passed in the $storehash hash 
15171: reference. If $tolog is true, the transaction is logged in the courselog
15172: with an action=PUTSTORE.
15173: 
15174: =item *
15175: 
15176: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
15177: works very similar to store/cstore, but all data is stored in a
15178: temporary location and can be reset using tmpreset, $storehash should
15179: be a hash reference, returns nothing on success
15180: 
15181: =item *
15182: 
15183: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
15184: similar to restore, but all data is stored in a temporary location and
15185: can be reset using tmpreset. Returns a hash of values on success,
15186: error string otherwise.
15187: 
15188: =item *
15189: 
15190: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
15191: deltes all keys for $symb form the temporary storage hash.
15192: 
15193: =item *
15194: 
15195: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
15196: reference filled in from namesp ($udom and $uname are optional)
15197: 
15198: =item *
15199: 
15200: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
15201: namesp ($udom and $uname are optional)
15202: 
15203: =item *
15204: 
15205: dump($namespace,$udom,$uname,$regexp,$range) : 
15206: dumps the complete (or key matching regexp) namespace into a hash
15207: ($udom, $uname, $regexp, $range are optional)
15208: 
15209: $range should be either an integer '100' (give me the first 100
15210:                                            matching records)
15211:               or be  two integers sperated by a - with no spaces
15212:                  '30-50' (give me the 30th through the 50th matching
15213:                           records)
15214: =item *
15215: 
15216: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
15217: $store can be a scalar, an array reference, or if the amount to be 
15218: incremented is > 1, a hash reference.
15219: 
15220: ($udom and $uname are optional)
15221: 
15222: =item *
15223: 
15224: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
15225: ($udom and $uname are optional)
15226: 
15227: =item *
15228: 
15229: cput($namespace,$storehash,$udom,$uname) : critical put
15230: ($udom and $uname are optional)
15231: 
15232: =item *
15233: 
15234: newput($namespace,$storehash,$udom,$uname) :
15235: 
15236: Attempts to store the items in the $storehash, but only if they don't
15237: currently exist, if this succeeds you can be certain that you have 
15238: successfully created a new key value pair in the $namespace db.
15239: 
15240: 
15241: Args:
15242:  $namespace: name of database to store values to
15243:  $storehash: hashref to store to the db
15244:  $udom: (optional) domain of user containing the db
15245:  $uname: (optional) name of user caontaining the db
15246: 
15247: Returns:
15248:  'ok' -> succeeded in storing all keys of $storehash
15249:  'key_exists: <key>' -> failed to anything out of $storehash, as at
15250:                         least <key> already existed in the db (other
15251:                         requested keys may also already exist)
15252:  'error: <msg>' -> unable to tie the DB or other error occurred
15253:  'con_lost' -> unable to contact request server
15254:  'refused' -> action was not allowed by remote machine
15255: 
15256: 
15257: =item *
15258: 
15259: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
15260: reference filled in from namesp (encrypts the return communication)
15261: ($udom and $uname are optional)
15262: 
15263: =item *
15264: 
15265: log($udom,$name,$home,$message) : write to permanent log for user; use
15266: critical subroutine
15267: 
15268: =item *
15269: 
15270: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
15271: array reference filled in from namespace found in domain level on either
15272: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
15273: 
15274: =item *
15275: 
15276: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
15277: domain level either on specified domain server ($uhome) or primary domain 
15278: server ($udom and $uhome are optional)
15279: 
15280: =item * 
15281: 
15282: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
15283: for: authentication, language, quotas, timezone, date locale, and portal URL in
15284: the target domain.
15285: 
15286: May also include additional key => value pairs for the following groups:
15287: 
15288: =over
15289: 
15290: =item
15291: disk quotas (MB allocated by default to portfolios and authoring spaces).
15292: 
15293: =over
15294: 
15295: =item defaultquota, authorquota
15296: 
15297: =back
15298: 
15299: =item
15300: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
15301: portfolio for users).
15302: 
15303: =over
15304: 
15305: =item
15306: aboutme, blog, webdav, portfolio
15307: 
15308: =back
15309: 
15310: =item
15311: requestcourses: ability to request courses, and how requests are processed.
15312: 
15313: =over
15314: 
15315: =item
15316: official, unofficial, community, textbook
15317: 
15318: =back
15319: 
15320: =item
15321: inststatus: types of institutional affiliation, and order in which they are displayed.
15322: 
15323: =over
15324: 
15325: =item
15326: inststatustypes, inststatusorder, inststatusguest
15327: 
15328: =back
15329: 
15330: =item
15331: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
15332: for course's uploaded content.
15333: 
15334: =over
15335: 
15336: =item
15337: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
15338: communityquota, textbookquota
15339: 
15340: =back
15341: 
15342: =item
15343: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
15344: on your servers.
15345: 
15346: =over
15347: 
15348: =item
15349: remotesessions, hostedsessions
15350: 
15351: =back
15352: 
15353: =back
15354: 
15355: In cases where a domain coordinator has never used the "Set Domain Configuration"
15356: utility to create a configuration.db file on a domain's primary library server
15357: only the following domain defaults: auth_def, auth_arg_def, lang_def
15358: -- corresponding values are authentication type (internal, krb4, krb5,
15359: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
15360: will be available. Values are retrieved from cache (if current), unless the
15361: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
15362: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
15363: 
15364: Typical usage:
15365: 
15366: %domdefaults = &get_domain_defaults($target_domain);
15367: 
15368: =back
15369: 
15370: =head2 Network Status Functions
15371: 
15372: =over 4
15373: 
15374: =item *
15375: 
15376: dirlist() : return directory list based on URI (first arg).
15377: 
15378: Inputs: 1 required, 5 optional.
15379: 
15380: =over
15381: 
15382: =item 
15383: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
15384: 
15385: =item
15386: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
15387: 
15388: =item
15389: $username -  username of user/course to be listed. Extracted from $uri if absent. 
15390: 
15391: =item
15392: $getpropath - boolean: 1 if prepend path using &propath(). 
15393: 
15394: =item
15395: $getuserdir - boolean: 1 if prepend path for "userfiles".
15396: 
15397: =item 
15398: $alternateRoot - path to prepend in place of path from $uri.
15399: 
15400: =back
15401: 
15402: Returns: Array of up to two items.
15403: 
15404: =over
15405: 
15406: a reference to an array of files/subdirectories
15407: 
15408: =over
15409: 
15410: Each element in the array of files/subdirectories is a & separated list of
15411: item name and the result of running stat on the item.  If dirlist was requested
15412: for a file instead of a directory, the item name will be ''. For a directory 
15413: listing, if the item is a metadata file, the element will end &N&M 
15414: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
15415: default copyright set (1).  
15416: 
15417: =back
15418: 
15419: a scalar containing error condition (if encountered).
15420: 
15421: =over
15422: 
15423: =item 
15424: no_host (no homeserver identified for $username:$domain).
15425: 
15426: =item 
15427: no_such_host (server contacted for listing not identified as valid host).
15428: 
15429: =item 
15430: con_lost (connection to remote server failed).
15431: 
15432: =item 
15433: refused (invalid $username:$domain received on lond side).
15434: 
15435: =item 
15436: no_such_dir (directory at specified path on lond side does not exist). 
15437: 
15438: =item 
15439: empty (directory at specified path on lond side is empty).
15440: 
15441: =over
15442: 
15443: This is currently not encountered because the &ls3, &ls2, 
15444: &ls (_handler) routines on the lond side do not filter out
15445: . and .. from a directory listing. 
15446: 
15447: =back
15448: 
15449: =back
15450: 
15451: =back
15452: 
15453: =item *
15454: 
15455: spareserver() : find server with least workload from spare.tab
15456: 
15457: 
15458: =item *
15459: 
15460: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
15461: if there is no corresponding loncapa host.
15462: 
15463: =back
15464: 
15465: 
15466: =head2 Apache Request
15467: 
15468: =over 4
15469: 
15470: =item *
15471: 
15472: ssi($url,%hash) : server side include, does a complete request cycle on url to
15473: localhost, posts hash
15474: 
15475: =back
15476: 
15477: =head2 Data to String to Data
15478: 
15479: =over 4
15480: 
15481: =item *
15482: 
15483: hash2str(%hash) : convert a hash into a string complete with escaping and '='
15484: and '&' separators, supports elements that are arrayrefs and hashrefs
15485: 
15486: =item *
15487: 
15488: hashref2str($hashref) : convert a hashref into a string complete with
15489: escaping and '=' and '&' separators, supports elements that are
15490: arrayrefs and hashrefs
15491: 
15492: =item *
15493: 
15494: arrayref2str($arrayref) : convert an arrayref into a string complete
15495: with escaping and '&' separators, supports elements that are arrayrefs
15496: and hashrefs
15497: 
15498: =item *
15499: 
15500: str2hash($string) : convert string to hash using unescaping and
15501: splitting on '=' and '&', supports elements that are arrayrefs and
15502: hashrefs
15503: 
15504: =item *
15505: 
15506: str2array($string) : convert string to hash using unescaping and
15507: splitting on '&', supports elements that are arrayrefs and hashrefs
15508: 
15509: =back
15510: 
15511: =head2 Logging Routines
15512: 
15513: 
15514: These routines allow one to make log messages in the lonnet.log and
15515: lonnet.perm logfiles.
15516: 
15517: =over 4
15518: 
15519: =item *
15520: 
15521: logtouch() : make sure the logfile, lonnet.log, exists
15522: 
15523: =item *
15524: 
15525: logthis() : append message to the normal lonnet.log file, it gets
15526: preiodically rolled over and deleted.
15527: 
15528: =item *
15529: 
15530: logperm() : append a permanent message to lonnet.perm.log, this log
15531: file never gets deleted by any automated portion of the system, only
15532: messages of critical importance should go in here.
15533: 
15534: 
15535: =back
15536: 
15537: =head2 General File Helper Routines
15538: 
15539: =over 4
15540: 
15541: =item *
15542: 
15543: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
15544: (a) files in /uploaded
15545:   (i) If a local copy of the file exists - 
15546:       compares modification date of local copy with last-modified date for 
15547:       definitive version stored on home server for course. If local copy is 
15548:       stale, requests a new version from the home server and stores it. 
15549:       If the original has been removed from the home server, then local copy 
15550:       is unlinked.
15551:   (ii) If local copy does not exist -
15552:       requests the file from the home server and stores it. 
15553:   
15554:   If $caller is 'uploadrep':  
15555:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
15556:     for request for files originally uploaded via DOCS. 
15557:      - returns 'ok' if fresh local copy now available, -1 otherwise.
15558:   
15559:   Otherwise:
15560:      This indicates a call from the content generation phase of the request.
15561:      -  returns the entire contents of the file or -1.
15562:      
15563: (b) files in /res
15564:    - returns the entire contents of a file or -1; 
15565:    it properly subscribes to and replicates the file if neccessary.
15566: 
15567: 
15568: =item *
15569: 
15570: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
15571:                   reference
15572: 
15573: returns either a stat() list of data about the file or an empty list
15574: if the file doesn't exist or couldn't find out about it (connection
15575: problems or user unknown)
15576: 
15577: =item *
15578: 
15579: filelocation($dir,$file) : returns file system location of a file
15580: based on URI; meant to be "fairly clean" absolute reference, $dir is a
15581: directory that relative $file lookups are to looked in ($dir of /a/dir
15582: and a file of ../bob will become /a/bob)
15583: 
15584: =item *
15585: 
15586: hreflocation($dir,$file) : returns file system location or a URL; same as
15587: filelocation except for hrefs
15588: 
15589: =item *
15590: 
15591: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
15592: also removes beginning /home/httpd/html unless /priv/ follows it.
15593: 
15594: =back
15595: 
15596: =head2 Usererfile file routines (/uploaded*)
15597: 
15598: =over 4
15599: 
15600: =item *
15601: 
15602: userfileupload(): main rotine for putting a file in a user or course's
15603:                   filespace, arguments are,
15604: 
15605:  formname - required - this is the name of the element in $env where the
15606:            filename, and the contents of the file to create/modifed exist
15607:            the filename is in $env{'form.'.$formname.'.filename'} and the
15608:            contents of the file is located in $env{'form.'.$formname}
15609:  context - if coursedoc, store the file in the course of the active role
15610:              of the current user; 
15611:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
15612:            if 'canceloverwrite': delete file in tmp/overwrites directory
15613:  subdir - required - subdirectory to put the file in under ../userfiles/
15614:          if undefined, it will be placed in "unknown"
15615: 
15616:  (This routine calls clean_filename() to remove any dangerous
15617:  characters from the filename, and then calls finuserfileupload() to
15618:  complete the transaction)
15619: 
15620:  returns either the url of the uploaded file (/uploaded/....) if successful
15621:  and /adm/notfound.html if unsuccessful
15622: 
15623: =item *
15624: 
15625: clean_filename(): routine for cleaing a filename up for storage in
15626:                  userfile space, argument is:
15627: 
15628:  filename - proposed filename
15629: 
15630: returns: the new clean filename
15631: 
15632: =item *
15633: 
15634: finishuserfileupload(): routine that creates and sends the file to
15635: userspace, probably shouldn't be called directly
15636: 
15637:   docuname: username or courseid of destination for the file
15638:   docudom: domain of user/course of destination for the file
15639:   formname: same as for userfileupload()
15640:   fname: filename (including subdirectories) for the file
15641:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
15642:           if hashref, and context is scantron, will convert csv format to standard format
15643:   allfiles: reference to hash used to store objects found by parser
15644:   codebase: reference to hash used for codebases of java objects found by parser
15645:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
15646:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
15647:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
15648:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
15649:   context: if 'overwrite', will move the uploaded file from its temporary location to
15650:             userfiles to facilitate overwriting a previously uploaded file with same name.
15651:   mimetype: reference to scalar to accommodate mime type determined
15652:             from File::MMagic if $parser = parse.
15653: 
15654:  returns either the url of the uploaded file (/uploaded/....) if successful
15655:  and /adm/notfound.html if unsuccessful (or an error message if context 
15656:  was 'overwrite').
15657:  
15658: 
15659: =item *
15660: 
15661: renameuserfile(): renames an existing userfile to a new name
15662: 
15663:   Args:
15664:    docuname: username or courseid of destination for the file
15665:    docudom: domain of user/course of destination for the file
15666:    old: current file name (including any subdirs under userfiles)
15667:    new: desired file name (including any subdirs under userfiles)
15668: 
15669: =item *
15670: 
15671: mkdiruserfile(): creates a directory is a userfiles dir
15672: 
15673:   Args:
15674:    docuname: username or courseid of destination for the file
15675:    docudom: domain of user/course of destination for the file
15676:    dir: dir to create (including any subdirs under userfiles)
15677: 
15678: =item *
15679: 
15680: removeuserfile(): removes a file that exists in userfiles
15681: 
15682:   Args:
15683:    docuname: username or courseid of destination for the file
15684:    docudom: domain of user/course of destination for the file
15685:    fname: filname to delete (including any subdirs under userfiles)
15686: 
15687: =item *
15688: 
15689: removeuploadedurl(): convience function for removeuserfile()
15690: 
15691:   Args:
15692:    url:  a full /uploaded/... url to delete
15693: 
15694: =item * 
15695: 
15696: get_portfile_permissions():
15697:   Args:
15698:     domain: domain of user or course contain the portfolio files
15699:     user: name of user or num of course contain the portfolio files
15700:   Returns:
15701:     hashref of a dump of the proper file_permissions.db
15702:    
15703: 
15704: =item * 
15705: 
15706: get_access_controls():
15707: 
15708: Args:
15709:   current_permissions: the hash ref returned from get_portfile_permissions()
15710:   group: (optional) the group you want the files associated with
15711:   file: (optional) the file you want access info on
15712: 
15713: Returns:
15714:     a hash (keys are file names) of hashes containing
15715:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
15716:         values are XML containing access control settings (see below) 
15717: 
15718: Internal notes:
15719: 
15720:  access controls are stored in file_permissions.db as key=value pairs.
15721:     key -> path to file/file_name\0uniqueID:scope_end_start
15722:         where scope -> public,guest,course,group,domains or users.
15723:               end -> UNIX time for end of access (0 -> no end date)
15724:               start -> UNIX time for start of access
15725: 
15726:     value -> XML description of access control
15727:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
15728:             <start></start>
15729:             <end></end>
15730: 
15731:             <password></password>  for scope type = guest
15732: 
15733:             <domain></domain>     for scope type = course or group
15734:             <number></number>
15735:             <roles id="">
15736:              <role></role>
15737:              <access></access>
15738:              <section></section>
15739:              <group></group>
15740:             </roles>
15741: 
15742:             <dom></dom>         for scope type = domains
15743: 
15744:             <users>             for scope type = users
15745:              <user>
15746:               <uname></uname>
15747:               <udom></udom>
15748:              </user>
15749:             </users>
15750:            </scope> 
15751:               
15752:  Access data is also aggregated for each file in an additional key=value pair:
15753:  key -> path to file/file_name\0accesscontrol 
15754:  value -> reference to hash
15755:           hash contains key = value pairs
15756:           where key = uniqueID:scope_end_start
15757:                 value = UNIX time record was last updated
15758: 
15759:           Used to improve speed of look-ups of access controls for each file.  
15760:  
15761:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
15762: 
15763: =item *
15764: 
15765: modify_access_controls():
15766: 
15767: Modifies access controls for a portfolio file
15768: Args
15769: 1. file name
15770: 2. reference to hash of required changes,
15771: 3. domain
15772: 4. username
15773:   where domain,username are the domain of the portfolio owner 
15774:   (either a user or a course) 
15775: 
15776: Returns:
15777: 1. result of additions or updates ('ok' or 'error', with error message). 
15778: 2. result of deletions ('ok' or 'error', with error message).
15779: 3. reference to hash of any new or updated access controls.
15780: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
15781:    key = integer (inbound ID)
15782:    value = uniqueID
15783: 
15784: =item *
15785: 
15786: get_timebased_id():
15787: 
15788: Attempts to get a unique timestamp-based suffix for use with items added to a
15789: course via the Course Editor (e.g., folders, composite pages,
15790: group bulletin boards).
15791: 
15792: Args: (first three required; six others optional)
15793: 
15794: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
15795:    docssequence, or name of group
15796: 
15797: 2. keyid (alphanumeric): name of temporary locking key in hash,
15798:    e.g., num, boardids
15799: 
15800: 3. namespace: name of gdbm file used to store suffixes already assigned;
15801:    file will be named nohist_namespace.db
15802: 
15803: 4. cdom: domain of course; default is current course domain from %env
15804: 
15805: 5. cnum: course number; default is current course number from %env
15806: 
15807: 6. idtype: set to concat if an additional digit is to be appended to the
15808:    unix timestamp to form the suffix, if the plain timestamp is already
15809:    in use.  Default is to not do this, but simply increment the unix
15810:    timestamp by 1 until a unique key is obtained.
15811: 
15812: 7. who: holder of locking key; defaults to user:domain for user.
15813: 
15814: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
15815:    retrying); default is 3.
15816: 
15817: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
15818: 
15819: Returns:
15820: 
15821: 1. suffix obtained (numeric)
15822: 
15823: 2. result of deleting locking key (ok if deleted, or lock never obtained)
15824: 
15825: 3. error: contains (localized) error message if an error occurred.
15826: 
15827: 
15828: =back
15829: 
15830: =head2 HTTP Helper Routines
15831: 
15832: =over 4
15833: 
15834: =item *
15835: 
15836: escape() : unpack non-word characters into CGI-compatible hex codes
15837: 
15838: =item *
15839: 
15840: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
15841: 
15842: =back
15843: 
15844: =head1 PRIVATE SUBROUTINES
15845: 
15846: =head2 Underlying communication routines (Shouldn't call)
15847: 
15848: =over 4
15849: 
15850: =item *
15851: 
15852: subreply() : tries to pass a message to lonc, returns con_lost if incapable
15853: 
15854: =item *
15855: 
15856: reply() : uses subreply to send a message to remote machine, logs all failures
15857: 
15858: =item *
15859: 
15860: critical() : passes a critical message to another server; if cannot
15861: get through then place message in connection buffer directory and
15862: returns con_delayed, if incapable of saving message, returns
15863: con_failed
15864: 
15865: =item *
15866: 
15867: reconlonc() : tries to reconnect lonc client processes.
15868: 
15869: =back
15870: 
15871: =head2 Resource Access Logging
15872: 
15873: =over 4
15874: 
15875: =item *
15876: 
15877: flushcourselogs() : flush (save) buffer logs and access logs
15878: 
15879: =item *
15880: 
15881: courselog($what) : save message for course in hash
15882: 
15883: =item *
15884: 
15885: courseacclog($what) : save message for course using &courselog().  Perform
15886: special processing for specific resource types (problems, exams, quizzes, etc).
15887: 
15888: =item *
15889: 
15890: goodbye() : flush course logs and log shutting down; it is called in srm.conf
15891: as a PerlChildExitHandler
15892: 
15893: =back
15894: 
15895: =head2 Other
15896: 
15897: =over 4
15898: 
15899: =item *
15900: 
15901: symblist($mapname,%newhash) : update symbolic storage links
15902: 
15903: =back
15904: 
15905: =cut
15906: 

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