File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1172.2.118.2.16: download - view: text, annotated - select for diffs
Mon Feb 1 00:34:27 2021 UTC (3 years, 5 months ago) by raeburn
Branches: version_2_11_3_msu
- For 2.11.3 (modified)
  Include changes in 1.1440

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1172.2.118.2.16 2021/02/01 00:34:27 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 ($namespace =~ /^enc/) {
 1903:             $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
 1904:         } else {
 1905:             $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
 1906:         }
 1907:         my %returnhash;
 1908:         if ($rep eq '' || $rep =~ /^error: 2 /) {
 1909:             return %returnhash;
 1910:         }
 1911:         my @pairs=split(/\&/,$rep);
 1912:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 1913:             return @pairs;
 1914:         }
 1915:         my $i=0;
 1916:         foreach my $item (@$storearr) {
 1917:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
 1918:             $i++;
 1919:         }
 1920:         return %returnhash;
 1921:     } else {
 1922:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
 1923:     }
 1924: }
 1925: 
 1926: # -------------------------------------------- put items in domain db files 
 1927: 
 1928: sub put_dom {
 1929:     my ($namespace,$storehash,$udom,$uhome)=@_;
 1930:     if (!$udom) {
 1931:         $udom=$env{'user.domain'};
 1932:         if (defined(&domain($udom,'primary'))) {
 1933:             $uhome=&domain($udom,'primary');
 1934:         } else {
 1935:             undef($uhome);
 1936:         }
 1937:     } else {
 1938:         if (!$uhome) {
 1939:             if (defined(&domain($udom,'primary'))) {
 1940:                 $uhome=&domain($udom,'primary');
 1941:             }
 1942:         }
 1943:     } 
 1944:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1945:         my $items='';
 1946:         foreach my $item (keys(%$storehash)) {
 1947:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 1948:         }
 1949:         $items=~s/\&$//;
 1950:         if ($namespace =~ /^enc/) {
 1951:             return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
 1952:         } else {
 1953:             return &reply("putdom:$udom:$namespace:$items",$uhome);
 1954:         }
 1955:     } else {
 1956:         &logthis("put_dom failed - no homeserver and/or domain");
 1957:     }
 1958: }
 1959: 
 1960: # --------------------- newput for items in db file owned by domainconfig user
 1961: sub newput_dom {
 1962:     my ($namespace,$storehash,$udom) = @_;
 1963:     my $result;
 1964:     if (!$udom) {
 1965:         $udom=$env{'user.domain'};
 1966:     }
 1967:     if ($udom) {
 1968:         my $uname = &get_domainconfiguser($udom);
 1969:         $result = &newput($namespace,$storehash,$udom,$uname);
 1970:     }
 1971:     return $result;
 1972: }
 1973: 
 1974: # --------------------- delete for items in db file owned by domainconfig user
 1975: sub del_dom {
 1976:     my ($namespace,$storearr,$udom)=@_;
 1977:     if (ref($storearr) eq 'ARRAY') {
 1978:         if (!$udom) {
 1979:             $udom=$env{'user.domain'};
 1980:         }
 1981:         if ($udom) {
 1982:             my $uname = &get_domainconfiguser($udom); 
 1983:             return &del($namespace,$storearr,$udom,$uname);
 1984:         }
 1985:     }
 1986: }
 1987: 
 1988: # ----------------------------------construct domainconfig user for a domain 
 1989: sub get_domainconfiguser {
 1990:     my ($udom) = @_;
 1991:     return $udom.'-domainconfig';
 1992: }
 1993: 
 1994: sub retrieve_inst_usertypes {
 1995:     my ($udom) = @_;
 1996:     my (%returnhash,@order);
 1997:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 1998:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
 1999:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
 2000:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
 2001:     } else {
 2002:         if (defined(&domain($udom,'primary'))) {
 2003:             my $uhome=&domain($udom,'primary');
 2004:             my $rep=&reply("inst_usertypes:$udom",$uhome);
 2005:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
 2006:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
 2007:                 return (\%returnhash,\@order);
 2008:             }
 2009:             my ($hashitems,$orderitems) = split(/:/,$rep); 
 2010:             my @pairs=split(/\&/,$hashitems);
 2011:             foreach my $item (@pairs) {
 2012:                 my ($key,$value)=split(/=/,$item,2);
 2013:                 $key = &unescape($key);
 2014:                 next if ($key =~ /^error: 2 /);
 2015:                 $returnhash{$key}=&thaw_unescape($value);
 2016:             }
 2017:             my @esc_order = split(/\&/,$orderitems);
 2018:             foreach my $item (@esc_order) {
 2019:                 push(@order,&unescape($item));
 2020:             }
 2021:         } else {
 2022:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
 2023:         }
 2024:         return (\%returnhash,\@order);
 2025:     }
 2026: }
 2027: 
 2028: sub is_domainimage {
 2029:     my ($url) = @_;
 2030:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
 2031:         if (&domain($1) ne '') {
 2032:             return '1';
 2033:         }
 2034:     }
 2035:     return;
 2036: }
 2037: 
 2038: sub inst_directory_query {
 2039:     my ($srch) = @_;
 2040:     my $udom = $srch->{'srchdomain'};
 2041:     my %results;
 2042:     my $homeserver = &domain($udom,'primary');
 2043:     my $outcome;
 2044:     if ($homeserver ne '') {
 2045:         unless ($homeserver eq $perlvar{'lonHostID'}) {
 2046:             if ($srch->{'srchby'} eq 'email') {
 2047:                 my $lcrev = &get_server_loncaparev($udom,$homeserver);
 2048:                 my ($major,$minor,$subver) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.(\d+)[\w.\-]+\'?$/);
 2049:                 if (($major eq '' && $minor eq '') || ($major < 2) ||
 2050:                     (($major == 2) && ($minor < 11)) ||
 2051:                     (($major == 2) && ($minor == 11) && ($subver < 3))) {
 2052:                     return;
 2053:                 }
 2054:             }
 2055:         }
 2056: 	my $queryid=&reply("querysend:instdirsearch:".
 2057: 			   &escape($srch->{'srchby'}).':'.
 2058: 			   &escape($srch->{'srchterm'}).':'.
 2059: 			   &escape($srch->{'srchtype'}),$homeserver);
 2060: 	my $host=&hostname($homeserver);
 2061: 	if ($queryid !~/^\Q$host\E\_/) {
 2062: 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
 2063: 	    return;
 2064: 	}
 2065: 	my $response = &get_query_reply($queryid);
 2066: 	my $maxtries = 5;
 2067: 	my $tries = 1;
 2068: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 2069: 	    $response = &get_query_reply($queryid);
 2070: 	    $tries ++;
 2071: 	}
 2072: 
 2073:         if (!&error($response) && $response ne 'refused') {
 2074:             if ($response eq 'unavailable') {
 2075:                 $outcome = $response;
 2076:             } else {
 2077:                 $outcome = 'ok';
 2078:                 my @matches = split(/\n/,$response);
 2079:                 foreach my $match (@matches) {
 2080:                     my ($key,$value) = split(/=/,$match);
 2081:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 2082:                 }
 2083:             }
 2084:         }
 2085:     }
 2086:     return ($outcome,%results);
 2087: }
 2088: 
 2089: sub usersearch {
 2090:     my ($srch) = @_;
 2091:     my $dom = $srch->{'srchdomain'};
 2092:     my %results;
 2093:     my %libserv = &all_library();
 2094:     my $query = 'usersearch';
 2095:     foreach my $tryserver (keys(%libserv)) {
 2096:         if (&host_domain($tryserver) eq $dom) {
 2097:             unless ($tryserver eq $perlvar{'lonHostID'}) {
 2098:                 if ($srch->{'srchby'} eq 'email') {
 2099:                     my $lcrev = &get_server_loncaparev($dom,$tryserver);
 2100:                     my ($major,$minor,$subver) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.(\d+)[\w.\-]+\'?$/);
 2101:                     next if (($major eq '' && $minor eq '') || ($major < 2) ||
 2102:                              (($major == 2) && ($minor < 11)) ||
 2103:                              (($major == 2) && ($minor == 11) && ($subver < 3)));
 2104:                 }
 2105:             }
 2106:             my $host=&hostname($tryserver);
 2107:             my $queryid=
 2108:                 &reply("querysend:".&escape($query).':'.
 2109:                        &escape($srch->{'srchby'}).':'.
 2110:                        &escape($srch->{'srchtype'}).':'.
 2111:                        &escape($srch->{'srchterm'}),$tryserver);
 2112:             if ($queryid !~/^\Q$host\E\_/) {
 2113:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 2114:                 next;
 2115:             }
 2116:             my $reply = &get_query_reply($queryid);
 2117:             my $maxtries = 1;
 2118:             my $tries = 1;
 2119:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 2120:                 $reply = &get_query_reply($queryid);
 2121:                 $tries ++;
 2122:             }
 2123:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 2124:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 2125:             } else {
 2126:                 my @matches;
 2127:                 if ($reply =~ /\n/) {
 2128:                     @matches = split(/\n/,$reply);
 2129:                 } else {
 2130:                     @matches = split(/\&/,$reply);
 2131:                 }
 2132:                 foreach my $match (@matches) {
 2133:                     my ($uname,$udom,%userhash);
 2134:                     foreach my $entry (split(/:/,$match)) {
 2135:                         my ($key,$value) =
 2136:                             map {&unescape($_);} split(/=/,$entry);
 2137:                         $userhash{$key} = $value;
 2138:                         if ($key eq 'username') {
 2139:                             $uname = $value;
 2140:                         } elsif ($key eq 'domain') {
 2141:                             $udom = $value;
 2142:                         }
 2143:                     }
 2144:                     $results{$uname.':'.$udom} = \%userhash;
 2145:                 }
 2146:             }
 2147:         }
 2148:     }
 2149:     return %results;
 2150: }
 2151: 
 2152: sub get_instuser {
 2153:     my ($udom,$uname,$id) = @_;
 2154:     my $homeserver = &domain($udom,'primary');
 2155:     my ($outcome,%results);
 2156:     if ($homeserver ne '') {
 2157:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 2158:                            &escape($id).':'.&escape($udom),$homeserver);
 2159:         my $host=&hostname($homeserver);
 2160:         if ($queryid !~/^\Q$host\E\_/) {
 2161:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 2162:             return;
 2163:         }
 2164:         my $response = &get_query_reply($queryid);
 2165:         my $maxtries = 5;
 2166:         my $tries = 1;
 2167:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 2168:             $response = &get_query_reply($queryid);
 2169:             $tries ++;
 2170:         }
 2171:         if (!&error($response) && $response ne 'refused') {
 2172:             if ($response eq 'unavailable') {
 2173:                 $outcome = $response;
 2174:             } else {
 2175:                 $outcome = 'ok';
 2176:                 my @matches = split(/\n/,$response);
 2177:                 foreach my $match (@matches) {
 2178:                     my ($key,$value) = split(/=/,$match);
 2179:                     $results{&unescape($key)} = &thaw_unescape($value);
 2180:                 }
 2181:             }
 2182:         }
 2183:     }
 2184:     my %userinfo;
 2185:     if (ref($results{$uname}) eq 'HASH') {
 2186:         %userinfo = %{$results{$uname}};
 2187:     } 
 2188:     return ($outcome,%userinfo);
 2189: }
 2190: 
 2191: sub get_multiple_instusers {
 2192:     my ($udom,$users,$caller) = @_;
 2193:     my ($outcome,$results);
 2194:     if (ref($users) eq 'HASH') {
 2195:         my $count = keys(%{$users});
 2196:         my $requested = &freeze_escape($users);
 2197:         my $homeserver = &domain($udom,'primary');
 2198:         if ($homeserver ne '') {
 2199:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
 2200:             my $host=&hostname($homeserver);
 2201:             if ($queryid !~/^\Q$host\E\_/) {
 2202:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
 2203:                          ' for host: '.$homeserver.'in domain '.$udom);
 2204:                 return ($outcome,$results);
 2205:             }
 2206:             my $response = &get_query_reply($queryid);
 2207:             my $maxtries = 5;
 2208:             if ($count > 100) {
 2209:                 $maxtries = 1+int($count/20);
 2210:             }
 2211:             my $tries = 1;
 2212:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
 2213:                 $response = &get_query_reply($queryid);
 2214:                 $tries ++;
 2215:             }
 2216:             if ($response eq '') {
 2217:                 $results = {};
 2218:                 foreach my $key (keys(%{$users})) {
 2219:                     my ($uname,$id);
 2220:                     if ($caller eq 'id') {
 2221:                         $id = $key;
 2222:                     } else {
 2223:                         $uname = $key;
 2224:                     }
 2225:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
 2226:                     $outcome = $resp;
 2227:                     if ($resp eq 'ok') {
 2228:                         %{$results} = (%{$results}, %info);
 2229:                     } else {
 2230:                         last;
 2231:                     }
 2232:                 }
 2233:             } elsif(!&error($response) && ($response ne 'refused')) {
 2234:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
 2235:                     $outcome = $response;
 2236:                 } else {
 2237:                     ($outcome,my $userdata) = split(/=/,$response,2);
 2238:                     if ($outcome eq 'ok') {
 2239:                         $results = &thaw_unescape($userdata);
 2240:                     }
 2241:                 }
 2242:             }
 2243:         }
 2244:     }
 2245:     return ($outcome,$results);
 2246: }
 2247: 
 2248: sub inst_rulecheck {
 2249:     my ($udom,$uname,$id,$item,$rules) = @_;
 2250:     my %returnhash;
 2251:     if ($udom ne '') {
 2252:         if (ref($rules) eq 'ARRAY') {
 2253:             @{$rules} = map {&escape($_);} (@{$rules});
 2254:             my $rulestr = join(':',@{$rules});
 2255:             my $homeserver=&domain($udom,'primary');
 2256:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 2257:                 my $response;
 2258:                 if ($item eq 'username') {                
 2259:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 2260:                                               ':'.&escape($uname).':'.$rulestr,
 2261:                                               $homeserver));
 2262:                 } elsif ($item eq 'id') {
 2263:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 2264:                                               ':'.&escape($id).':'.$rulestr,
 2265:                                               $homeserver));
 2266:                 } elsif ($item eq 'selfcreate') {
 2267:                     $response=&unescape(&reply('instselfcreatecheck:'.
 2268:                                                &escape($udom).':'.&escape($uname).
 2269:                                               ':'.$rulestr,$homeserver));
 2270:                 }
 2271:                 if ($response ne 'refused') {
 2272:                     my @pairs=split(/\&/,$response);
 2273:                     foreach my $item (@pairs) {
 2274:                         my ($key,$value)=split(/=/,$item,2);
 2275:                         $key = &unescape($key);
 2276:                         next if ($key =~ /^error: 2 /);
 2277:                         $returnhash{$key}=&thaw_unescape($value);
 2278:                     }
 2279:                 }
 2280:             }
 2281:         }
 2282:     }
 2283:     return %returnhash;
 2284: }
 2285: 
 2286: sub inst_userrules {
 2287:     my ($udom,$check) = @_;
 2288:     my (%ruleshash,@ruleorder);
 2289:     if ($udom ne '') {
 2290:         my $homeserver=&domain($udom,'primary');
 2291:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 2292:             my $response;
 2293:             if ($check eq 'id') {
 2294:                 $response=&reply('instidrules:'.&escape($udom),
 2295:                                  $homeserver);
 2296:             } elsif ($check eq 'email') {
 2297:                 $response=&reply('instemailrules:'.&escape($udom),
 2298:                                  $homeserver);
 2299:             } else {
 2300:                 $response=&reply('instuserrules:'.&escape($udom),
 2301:                                  $homeserver);
 2302:             }
 2303:             if (($response ne 'refused') && ($response ne 'error') && 
 2304:                 ($response ne 'unknown_cmd') && 
 2305:                 ($response ne 'no_such_host')) {
 2306:                 my ($hashitems,$orderitems) = split(/:/,$response);
 2307:                 my @pairs=split(/\&/,$hashitems);
 2308:                 foreach my $item (@pairs) {
 2309:                     my ($key,$value)=split(/=/,$item,2);
 2310:                     $key = &unescape($key);
 2311:                     next if ($key =~ /^error: 2 /);
 2312:                     $ruleshash{$key}=&thaw_unescape($value);
 2313:                 }
 2314:                 my @esc_order = split(/\&/,$orderitems);
 2315:                 foreach my $item (@esc_order) {
 2316:                     push(@ruleorder,&unescape($item));
 2317:                 }
 2318:             }
 2319:         }
 2320:     }
 2321:     return (\%ruleshash,\@ruleorder);
 2322: }
 2323: 
 2324: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 2325: 
 2326: sub get_domain_defaults {
 2327:     my ($domain,$ignore_cache) = @_;
 2328:     return if (($domain eq '') || ($domain eq 'public'));
 2329:     my $cachetime = 60*60*24;
 2330:     unless ($ignore_cache) {
 2331:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 2332:         if (defined($cached)) {
 2333:             if (ref($result) eq 'HASH') {
 2334:                 return %{$result};
 2335:             }
 2336:         }
 2337:     }
 2338:     my %domdefaults;
 2339:     my %domconfig =
 2340:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
 2341:                                   'requestcourses','inststatus',
 2342:                                   'coursedefaults','usersessions',
 2343:                                   'requestauthor','selfenrollment',
 2344:                                   'coursecategories','autoenroll',
 2345:                                   'helpsettings'],$domain);
 2346:     my @coursetypes = ('official','unofficial','community','textbook');
 2347:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 2348:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 2349:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 2350:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 2351:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 2352:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
 2353:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
 2354:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
 2355:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
 2356:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
 2357:     } else {
 2358:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 2359:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 2360:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 2361:     }
 2362:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 2363:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 2364:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 2365:         } else {
 2366:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 2367:         }
 2368:         my @usertools = ('aboutme','blog','webdav','portfolio');
 2369:         foreach my $item (@usertools) {
 2370:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 2371:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 2372:             }
 2373:         }
 2374:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
 2375:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
 2376:         }
 2377:     }
 2378:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 2379:         foreach my $item ('official','unofficial','community','textbook') {
 2380:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
 2381:         }
 2382:     }
 2383:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
 2384:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
 2385:     }
 2386:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
 2387:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
 2388:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
 2389:         }
 2390:     }
 2391:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
 2392:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
 2393:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
 2394:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
 2395:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
 2396:         }
 2397:         foreach my $type (@coursetypes) {
 2398:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
 2399:                 unless ($type eq 'community') {
 2400:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
 2401:                 }
 2402:             }
 2403:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
 2404:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
 2405:             }
 2406:             if ($domdefaults{'postsubmit'} eq 'on') {
 2407:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
 2408:                     $domdefaults{$type.'postsubtimeout'} =
 2409:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
 2410:                 }
 2411:             }
 2412:         }
 2413:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
 2414:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
 2415:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
 2416:                 if (@clonecodes) {
 2417:                     $domdefaults{'canclone'} = join('+',@clonecodes);
 2418:                 }
 2419:             }
 2420:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
 2421:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
 2422:         }
 2423:         if ($domconfig{'coursedefaults'}{'texengine'}) {
 2424:             $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
 2425:         }
 2426:     }
 2427:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
 2428:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
 2429:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
 2430:         }
 2431:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
 2432:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
 2433:         }
 2434:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
 2435:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
 2436:         }
 2437:         if (ref($domconfig{'usersessions'}{'offloadoth'}) eq 'HASH') {
 2438:             $domdefaults{'offloadoth'} = $domconfig{'usersessions'}{'offloadoth'};
 2439:         }
 2440:     }
 2441:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
 2442:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
 2443:             my @settings = ('types','registered','enroll_dates','access_dates','section',
 2444:                             'approval','limit');
 2445:             foreach my $type (@coursetypes) {
 2446:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
 2447:                     my @mgrdc = ();
 2448:                     foreach my $item (@settings) {
 2449:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
 2450:                             push(@mgrdc,$item);
 2451:                         }
 2452:                     }
 2453:                     if (@mgrdc) {
 2454:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
 2455:                     }
 2456:                 }
 2457:             }
 2458:         }
 2459:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
 2460:             foreach my $type (@coursetypes) {
 2461:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
 2462:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
 2463:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
 2464:                     }
 2465:                 }
 2466:             }
 2467:         }
 2468:     }
 2469:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 2470:         $domdefaults{'catauth'} = 'std';
 2471:         $domdefaults{'catunauth'} = 'std';
 2472:         if ($domconfig{'coursecategories'}{'auth'}) {
 2473:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
 2474:         }
 2475:         if ($domconfig{'coursecategories'}{'unauth'}) {
 2476:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
 2477:         }
 2478:     }
 2479:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 2480:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
 2481:     }
 2482:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
 2483:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
 2484:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
 2485:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
 2486:         }
 2487:     }
 2488:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
 2489:     return %domdefaults;
 2490: }
 2491: 
 2492: sub get_dom_cats {
 2493:     my ($dom) = @_;
 2494:     return unless (&domain($dom));
 2495:     my ($cats,$cached)=&is_cached_new('cats',$dom);
 2496:     unless (defined($cached)) {
 2497:         my %domconfig = &get_dom('configuration',['coursecategories'],$dom);
 2498:         if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 2499:             if (ref($domconfig{'coursecategories'}{'cats'}) eq 'HASH') {
 2500:                 %{$cats} = %{$domconfig{'coursecategories'}{'cats'}};
 2501:             } else {
 2502:                 $cats = {};
 2503:             }
 2504:         } else {
 2505:             $cats = {};
 2506:         }
 2507:         &Apache::lonnet::do_cache_new('cats',$dom,$cats,3600);
 2508:     }
 2509:     return $cats;
 2510: }
 2511: 
 2512: sub get_dom_instcats {
 2513:     my ($dom) = @_;
 2514:     return unless (&domain($dom));
 2515:     my ($instcats,$cached)=&is_cached_new('instcats',$dom);
 2516:     unless (defined($cached)) {
 2517:         my (%coursecodes,%codes,@codetitles,%cat_titles,%cat_order);
 2518:         my $totcodes = &retrieve_instcodes(\%coursecodes,$dom);
 2519:         if ($totcodes > 0) {
 2520:             my $caller = 'global';
 2521:             if (&auto_instcode_format($caller,$dom,\%coursecodes,\%codes,
 2522:                                       \@codetitles,\%cat_titles,\%cat_order) eq 'ok') {
 2523:                 $instcats = {
 2524:                                 codes => \%codes,
 2525:                                 codetitles => \@codetitles,
 2526:                                 cat_titles => \%cat_titles,
 2527:                                 cat_order => \%cat_order,
 2528:                             };
 2529:                 &do_cache_new('instcats',$dom,$instcats,3600);
 2530:             }
 2531:         }
 2532:     }
 2533:     return $instcats;
 2534: }
 2535: 
 2536: sub retrieve_instcodes {
 2537:     my ($coursecodes,$dom) = @_;
 2538:     my $totcodes;
 2539:     my %courses = &courseiddump($dom,'.',1,'.','.','.',undef,undef,'Course');
 2540:     foreach my $course (keys(%courses)) {
 2541:         if (ref($courses{$course}) eq 'HASH') {
 2542:             if ($courses{$course}{'inst_code'} ne '') {
 2543:                 $$coursecodes{$course} = $courses{$course}{'inst_code'};
 2544:                 $totcodes ++;
 2545:             }
 2546:         }
 2547:     }
 2548:     return $totcodes;
 2549: }
 2550: 
 2551: # --------------------------------------------- Get domain config for passwords
 2552: 
 2553: sub get_passwdconf {
 2554:     my ($dom) = @_;
 2555:     my (%passwdconf,$gotconf,$lookup);
 2556:     my ($result,$cached)=&is_cached_new('passwdconf',$dom);
 2557:     if (defined($cached)) {
 2558:         if (ref($result) eq 'HASH') {
 2559:             %passwdconf = %{$result};
 2560:             $gotconf = 1;
 2561:         }
 2562:     }
 2563:     unless ($gotconf) {
 2564:         my %domconfig = &get_dom('configuration',['passwords'],$dom);
 2565:         if (ref($domconfig{'passwords'}) eq 'HASH') {
 2566:             %passwdconf = %{$domconfig{'passwords'}};
 2567:         }
 2568:         my $cachetime = 24*60*60;
 2569:         &do_cache_new('passwdconf',$dom,\%passwdconf,$cachetime);
 2570:     }
 2571:     return %passwdconf;
 2572: }
 2573: 
 2574: sub course_portal_url {
 2575:     my ($cnum,$cdom) = @_;
 2576:     my $chome = &homeserver($cnum,$cdom);
 2577:     my $hostname = &hostname($chome);
 2578:     my $protocol = $protocol{$chome};
 2579:     $protocol = 'http' if ($protocol ne 'https');
 2580:     my %domdefaults = &get_domain_defaults($cdom);
 2581:     my $firsturl;
 2582:     if ($domdefaults{'portal_def'}) {
 2583:         $firsturl = $domdefaults{'portal_def'};
 2584:     } else {
 2585:         $firsturl = $protocol.'://'.$hostname;
 2586:     }
 2587:     return $firsturl;
 2588: }
 2589: 
 2590: # --------------------------------------------------- Assign a key to a student
 2591: 
 2592: sub assign_access_key {
 2593: #
 2594: # a valid key looks like uname:udom#comments
 2595: # comments are being appended
 2596: #
 2597:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 2598:     $kdom=
 2599:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 2600:     $knum=
 2601:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 2602:     $cdom=
 2603:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2604:     $cnum=
 2605:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2606:     $udom=$env{'user.name'} unless (defined($udom));
 2607:     $uname=$env{'user.domain'} unless (defined($uname));
 2608:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 2609:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 2610:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 2611:                                                   # assigned to this person
 2612:                                                   # - this should not happen,
 2613:                                                   # unless something went wrong
 2614:                                                   # the first time around
 2615: # ready to assign
 2616:         $logentry=$1.'; '.$logentry;
 2617:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 2618:                                                  $kdom,$knum) eq 'ok') {
 2619: # key now belongs to user
 2620: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 2621:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 2622:                 &appenv({'environment.'.$envkey => $ckey});
 2623:                 return 'ok';
 2624:             } else {
 2625:                 return 
 2626:   'error: Count not permanently assign key, will need to be re-entered later.';
 2627: 	    }
 2628:         } else {
 2629:             return 'error: Could not assign key, try again later.';
 2630:         }
 2631:     } elsif (!$existing{$ckey}) {
 2632: # the key does not exist
 2633: 	return 'error: The key does not exist';
 2634:     } else {
 2635: # the key is somebody else's
 2636: 	return 'error: The key is already in use';
 2637:     }
 2638: }
 2639: 
 2640: # ------------------------------------------ put an additional comment on a key
 2641: 
 2642: sub comment_access_key {
 2643: #
 2644: # a valid key looks like uname:udom#comments
 2645: # comments are being appended
 2646: #
 2647:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 2648:     $cdom=
 2649:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2650:     $cnum=
 2651:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2652:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2653:     if ($existing{$ckey}) {
 2654:         $existing{$ckey}.='; '.$logentry;
 2655: # ready to assign
 2656:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 2657:                                                  $cdom,$cnum) eq 'ok') {
 2658: 	    return 'ok';
 2659:         } else {
 2660: 	    return 'error: Count not store comment.';
 2661:         }
 2662:     } else {
 2663: # the key does not exist
 2664: 	return 'error: The key does not exist';
 2665:     }
 2666: }
 2667: 
 2668: # ------------------------------------------------------ Generate a set of keys
 2669: 
 2670: sub generate_access_keys {
 2671:     my ($number,$cdom,$cnum,$logentry)=@_;
 2672:     $cdom=
 2673:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2674:     $cnum=
 2675:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2676:     unless (&allowed('mky',$cdom)) { return 0; }
 2677:     unless (($cdom) && ($cnum)) { return 0; }
 2678:     if ($number>10000) { return 0; }
 2679:     sleep(2); # make sure don't get same seed twice
 2680:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 2681:     my $total=0;
 2682:     for (my $i=1;$i<=$number;$i++) {
 2683:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 2684:                   sprintf("%lx",int(100000*rand)).'-'.
 2685:                   sprintf("%lx",int(100000*rand));
 2686:        $newkey=~s/1/g/g; # folks mix up 1 and l
 2687:        $newkey=~s/0/h/g; # and also 0 and O
 2688:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 2689:        if ($existing{$newkey}) {
 2690:            $i--;
 2691:        } else {
 2692: 	  if (&put('accesskeys',
 2693:               { $newkey => '# generated '.localtime().
 2694:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 2695:                            '; '.$logentry },
 2696: 		   $cdom,$cnum) eq 'ok') {
 2697:               $total++;
 2698: 	  }
 2699:        }
 2700:     }
 2701:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 2702:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 2703:     return $total;
 2704: }
 2705: 
 2706: # ------------------------------------------------------- Validate an accesskey
 2707: 
 2708: sub validate_access_key {
 2709:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 2710:     $cdom=
 2711:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2712:     $cnum=
 2713:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2714:     $udom=$env{'user.domain'} unless (defined($udom));
 2715:     $uname=$env{'user.name'} unless (defined($uname));
 2716:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2717:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 2718: }
 2719: 
 2720: # ------------------------------------- Find the section of student in a course
 2721: sub devalidate_getsection_cache {
 2722:     my ($udom,$unam,$courseid)=@_;
 2723:     my $hashid="$udom:$unam:$courseid";
 2724:     &devalidate_cache_new('getsection',$hashid);
 2725: }
 2726: 
 2727: sub courseid_to_courseurl {
 2728:     my ($courseid) = @_;
 2729:     #already url style courseid
 2730:     return $courseid if ($courseid =~ m{^/});
 2731: 
 2732:     if (exists($env{'course.'.$courseid.'.num'})) {
 2733: 	my $cnum = $env{'course.'.$courseid.'.num'};
 2734: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 2735: 	return "/$cdom/$cnum";
 2736:     }
 2737: 
 2738:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 2739:     if (exists($courseinfo{'num'})) {
 2740: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 2741:     }
 2742: 
 2743:     return undef;
 2744: }
 2745: 
 2746: sub getsection {
 2747:     my ($udom,$unam,$courseid)=@_;
 2748:     my $cachetime=1800;
 2749: 
 2750:     my $hashid="$udom:$unam:$courseid";
 2751:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 2752:     if (defined($cached)) { return $result; }
 2753: 
 2754:     my %Pending; 
 2755:     my %Expired;
 2756:     #
 2757:     # Each role can either have not started yet (pending), be active, 
 2758:     #    or have expired.
 2759:     #
 2760:     # If there is an active role, we are done.
 2761:     #
 2762:     # If there is more than one role which has not started yet, 
 2763:     #     choose the one which will start sooner
 2764:     # If there is one role which has not started yet, return it.
 2765:     #
 2766:     # If there is more than one expired role, choose the one which ended last.
 2767:     # If there is a role which has expired, return it.
 2768:     #
 2769:     $courseid = &courseid_to_courseurl($courseid);
 2770:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 2771:     foreach my $key (keys(%roleshash)) {
 2772:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 2773:         my $section=$1;
 2774:         if ($key eq $courseid.'_st') { $section=''; }
 2775:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 2776:         my $now=time;
 2777:         if (defined($end) && $end && ($now > $end)) {
 2778:             $Expired{$end}=$section;
 2779:             next;
 2780:         }
 2781:         if (defined($start) && $start && ($now < $start)) {
 2782:             $Pending{$start}=$section;
 2783:             next;
 2784:         }
 2785:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 2786:     }
 2787:     #
 2788:     # Presumedly there will be few matching roles from the above
 2789:     # loop and the sorting time will be negligible.
 2790:     if (scalar(keys(%Pending))) {
 2791:         my ($time) = sort {$a <=> $b} keys(%Pending);
 2792:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 2793:     } 
 2794:     if (scalar(keys(%Expired))) {
 2795:         my @sorted = sort {$a <=> $b} keys(%Expired);
 2796:         my $time = pop(@sorted);
 2797:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 2798:     }
 2799:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 2800: }
 2801: 
 2802: sub save_cache {
 2803:     &purge_remembered();
 2804:     #&Apache::loncommon::validate_page();
 2805:     undef(%env);
 2806:     undef($env_loaded);
 2807: }
 2808: 
 2809: my $to_remember=-1;
 2810: my %remembered;
 2811: my %accessed;
 2812: my $kicks=0;
 2813: my $hits=0;
 2814: sub make_key {
 2815:     my ($name,$id) = @_;
 2816:     if (length($id) > 65 
 2817: 	&& length(&escape($id)) > 200) {
 2818: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 2819:     }
 2820:     return &escape($name.':'.$id);
 2821: }
 2822: 
 2823: sub devalidate_cache_new {
 2824:     my ($name,$id,$debug) = @_;
 2825:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 2826:     my $remembered_id=$name.':'.$id;
 2827:     $id=&make_key($name,$id);
 2828:     $memcache->delete($id);
 2829:     delete($remembered{$remembered_id});
 2830:     delete($accessed{$remembered_id});
 2831: }
 2832: 
 2833: sub is_cached_new {
 2834:     my ($name,$id,$debug) = @_;
 2835:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) for 
 2836:                                      # keys in %remembered hash, which persists for
 2837:                                      # duration of request (no restriction on key length).
 2838:     if (exists($remembered{$remembered_id})) {
 2839: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
 2840: 	$accessed{$remembered_id}=[&gettimeofday()];
 2841: 	$hits++;
 2842: 	return ($remembered{$remembered_id},1);
 2843:     }
 2844:     $id=&make_key($name,$id);
 2845:     my $value = $memcache->get($id);
 2846:     if (!(defined($value))) {
 2847: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 2848: 	return (undef,undef);
 2849:     }
 2850:     if ($value eq '__undef__') {
 2851: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 2852: 	$value=undef;
 2853:     }
 2854:     &make_room($remembered_id,$value,$debug);
 2855:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 2856:     return ($value,1);
 2857: }
 2858: 
 2859: sub do_cache_new {
 2860:     my ($name,$id,$value,$time,$debug) = @_;
 2861:     my $remembered_id=$name.':'.$id;
 2862:     $id=&make_key($name,$id);
 2863:     my $setvalue=$value;
 2864:     if (!defined($setvalue)) {
 2865: 	$setvalue='__undef__';
 2866:     }
 2867:     if (!defined($time) ) {
 2868: 	$time=600;
 2869:     }
 2870:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 2871:     my $result = $memcache->set($id,$setvalue,$time);
 2872:     if (! $result) {
 2873: 	&logthis("caching of id -> $id  failed");
 2874: 	$memcache->disconnect_all();
 2875:     }
 2876:     # need to make a copy of $value
 2877:     &make_room($remembered_id,$value,$debug);
 2878:     return $value;
 2879: }
 2880: 
 2881: sub make_room {
 2882:     my ($remembered_id,$value,$debug)=@_;
 2883: 
 2884:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
 2885:                                     : $value;
 2886:     if ($to_remember<0) { return; }
 2887:     $accessed{$remembered_id}=[&gettimeofday()];
 2888:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 2889:     my $to_kick;
 2890:     my $max_time=0;
 2891:     foreach my $other (keys(%accessed)) {
 2892: 	if (&tv_interval($accessed{$other}) > $max_time) {
 2893: 	    $to_kick=$other;
 2894: 	    $max_time=&tv_interval($accessed{$other});
 2895: 	}
 2896:     }
 2897:     delete($remembered{$to_kick});
 2898:     delete($accessed{$to_kick});
 2899:     $kicks++;
 2900:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 2901:     return;
 2902: }
 2903: 
 2904: sub purge_remembered {
 2905:     #&logthis("Tossing ".scalar(keys(%remembered)));
 2906:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 2907:     undef(%remembered);
 2908:     undef(%accessed);
 2909: }
 2910: # ------------------------------------- Read an entry from a user's environment
 2911: 
 2912: sub userenvironment {
 2913:     my ($udom,$unam,@what)=@_;
 2914:     my $items;
 2915:     foreach my $item (@what) {
 2916:         $items.=&escape($item).'&';
 2917:     }
 2918:     $items=~s/\&$//;
 2919:     my %returnhash=();
 2920:     my $uhome = &homeserver($unam,$udom);
 2921:     unless ($uhome eq 'no_host') {
 2922:         my @answer=split(/\&/, 
 2923:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
 2924:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
 2925:             return %returnhash;
 2926:         }
 2927:         my $i;
 2928:         for ($i=0;$i<=$#what;$i++) {
 2929: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
 2930:         }
 2931:     }
 2932:     return %returnhash;
 2933: }
 2934: 
 2935: # ---------------------------------------------------------- Get a studentphoto
 2936: sub studentphoto {
 2937:     my ($udom,$unam,$ext) = @_;
 2938:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 2939:     if (defined($env{'request.course.id'})) {
 2940:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 2941:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 2942:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 2943:             } else {
 2944:                 my ($result,$perm_reqd)=
 2945: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 2946:                 if ($result eq 'ok') {
 2947:                     if (!($perm_reqd eq 'yes')) {
 2948:                         return(&retrievestudentphoto($udom,$unam,$ext));
 2949:                     }
 2950:                 }
 2951:             }
 2952:         }
 2953:     } else {
 2954:         my ($result,$perm_reqd) = 
 2955: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 2956:         if ($result eq 'ok') {
 2957:             if (!($perm_reqd eq 'yes')) {
 2958:                 return(&retrievestudentphoto($udom,$unam,$ext));
 2959:             }
 2960:         }
 2961:     }
 2962:     return '/adm/lonKaputt/lonlogo_broken.gif';
 2963: }
 2964: 
 2965: sub retrievestudentphoto {
 2966:     my ($udom,$unam,$ext,$type) = @_;
 2967:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 2968:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 2969:     if ($ret eq 'ok') {
 2970:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 2971:         if ($type eq 'thumbnail') {
 2972:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 2973:         }
 2974:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 2975:         return $tokenurl;
 2976:     } else {
 2977:         if ($type eq 'thumbnail') {
 2978:             return '/adm/lonKaputt/genericstudent_tn.gif';
 2979:         } else { 
 2980:             return '/adm/lonKaputt/lonlogo_broken.gif';
 2981:         }
 2982:     }
 2983: }
 2984: 
 2985: # -------------------------------------------------------------------- New chat
 2986: 
 2987: sub chatsend {
 2988:     my ($newentry,$anon,$group)=@_;
 2989:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 2990:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2991:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 2992:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 2993: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 2994: 		   &escape($newentry)).':'.$group,$chome);
 2995: }
 2996: 
 2997: # ------------------------------------------ Find current version of a resource
 2998: 
 2999: sub getversion {
 3000:     my $fname=&clutter(shift);
 3001:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
 3002:     return &currentversion(&filelocation('',$fname));
 3003: }
 3004: 
 3005: sub currentversion {
 3006:     my $fname=shift;
 3007:     my $author=$fname;
 3008:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3009:     my ($udom,$uname)=split(/\//,$author);
 3010:     my $home=&homeserver($uname,$udom);
 3011:     if ($home eq 'no_host') { 
 3012:         return -1; 
 3013:     }
 3014:     my $answer=&reply("currentversion:$fname",$home);
 3015:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 3016: 	return -1;
 3017:     }
 3018:     return $answer;
 3019: }
 3020: 
 3021: #
 3022: # Return special version number of resource if set by override, empty otherwise
 3023: #
 3024: sub usedversion {
 3025:     my $fname=shift;
 3026:     unless ($fname) { $fname=$env{'request.uri'}; }
 3027:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
 3028:     if ($urlversion) { return $urlversion; }
 3029:     return '';
 3030: }
 3031: 
 3032: # ----------------------------- Subscribe to a resource, return URL if possible
 3033: 
 3034: sub subscribe {
 3035:     my $fname=shift;
 3036:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 3037:     $fname=~s/[\n\r]//g;
 3038:     my $author=$fname;
 3039:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3040:     my ($udom,$uname)=split(/\//,$author);
 3041:     my $home=homeserver($uname,$udom);
 3042:     if ($home eq 'no_host') {
 3043:         return 'not_found';
 3044:     }
 3045:     my $answer=reply("sub:$fname",$home);
 3046:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 3047: 	$answer.=' by '.$home;
 3048:     }
 3049:     return $answer;
 3050: }
 3051:     
 3052: # -------------------------------------------------------------- Replicate file
 3053: 
 3054: sub repcopy {
 3055:     my $filename=shift;
 3056:     $filename=~s/\/+/\//g;
 3057:     my $londocroot = $perlvar{'lonDocRoot'};
 3058:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
 3059:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
 3060:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
 3061: 	$filename=~m{^/*(uploaded|editupload)/}) {
 3062: 	return &repcopy_userfile($filename);
 3063:     }
 3064:     $filename=~s/[\n\r]//g;
 3065:     my $transname="$filename.in.transfer";
 3066: # FIXME: this should flock
 3067:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 3068:     my $remoteurl=subscribe($filename);
 3069:     if ($remoteurl =~ /^con_lost by/) {
 3070: 	   &logthis("Subscribe returned $remoteurl: $filename");
 3071:            return 'unavailable';
 3072:     } elsif ($remoteurl eq 'not_found') {
 3073: 	   #&logthis("Subscribe returned not_found: $filename");
 3074: 	   return 'not_found';
 3075:     } elsif ($remoteurl =~ /^rejected by/) {
 3076: 	   &logthis("Subscribe returned $remoteurl: $filename");
 3077:            return 'forbidden';
 3078:     } elsif ($remoteurl eq 'directory') {
 3079:            return 'ok';
 3080:     } else {
 3081:         my $author=$filename;
 3082:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3083:         my ($udom,$uname)=split(/\//,$author);
 3084:         my $home=homeserver($uname,$udom);
 3085:         unless ($home eq $perlvar{'lonHostID'}) {
 3086:            my @parts=split(/\//,$filename);
 3087:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 3088:            if ($path ne "$londocroot/res") {
 3089:                &logthis("Malconfiguration for replication: $filename");
 3090: 	       return 'bad_request';
 3091:            }
 3092:            my $count;
 3093:            for ($count=5;$count<$#parts;$count++) {
 3094:                $path.="/$parts[$count]";
 3095:                if ((-e $path)!=1) {
 3096: 		   mkdir($path,0777);
 3097:                }
 3098:            }
 3099:            my $ua=new LWP::UserAgent;
 3100:            my $request=new HTTP::Request('GET',"$remoteurl");
 3101:            my $response=$ua->request($request,$transname);
 3102:            if ($response->is_error()) {
 3103: 	       unlink($transname);
 3104:                my $message=$response->status_line;
 3105:                &logthis("<font color=\"blue\">WARNING:"
 3106:                        ." LWP get: $message: $filename</font>");
 3107:                return 'unavailable';
 3108:            } else {
 3109: 	       if ($remoteurl!~/\.meta$/) {
 3110:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 3111:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
 3112:                   if ($mresponse->is_error()) {
 3113: 		      unlink($filename.'.meta');
 3114:                       &logthis(
 3115:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 3116:                   }
 3117: 	       }
 3118:                rename($transname,$filename);
 3119:                return 'ok';
 3120:            }
 3121:        }
 3122:     }
 3123: }
 3124: 
 3125: # ------------------------------------------------- Unsubscribe from a resource
 3126: 
 3127: sub unsubscribe {
 3128:     my ($fname) = @_;
 3129:     my $answer;
 3130:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return $answer; }
 3131:     $fname=~s/[\n\r]//g;
 3132:     my $author=$fname;
 3133:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3134:     my ($udom,$uname)=split(/\//,$author);
 3135:     my $home=homeserver($uname,$udom);
 3136:     if ($home eq 'no_host') {
 3137:         $answer = 'no_host';
 3138:     } elsif (grep { $_ eq $home } &current_machine_ids()) {
 3139:         $answer = 'home';
 3140:     } else {
 3141:         $answer = reply("unsub:$fname",$home);
 3142:     }
 3143:     return $answer;
 3144: }
 3145: 
 3146: # ------------------------------------------------ Get server side include body
 3147: sub ssi_body {
 3148:     my ($filelink,%form)=@_;
 3149:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 3150:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 3151:     }
 3152:     my $output='';
 3153:     my $response;
 3154:     if ($filelink=~/^https?\:/) {
 3155:        ($output,$response)=&externalssi($filelink);
 3156:     } else {
 3157:        $filelink .= $filelink=~/\?/ ? '&' : '?';
 3158:        $filelink .= 'inhibitmenu=yes';
 3159:        ($output,$response)=&ssi($filelink,%form);
 3160:     }
 3161:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 3162:     $output=~s/^.*?\<body[^\>]*\>//si;
 3163:     $output=~s/\<\/body\s*\>.*?$//si;
 3164:     if (wantarray) {
 3165:         return ($output, $response);
 3166:     } else {
 3167:         return $output;
 3168:     }
 3169: }
 3170: 
 3171: # --------------------------------------------------------- Server Side Include
 3172: 
 3173: sub absolute_url {
 3174:     my ($host_name) = @_;
 3175:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 3176:     if ($host_name eq '') {
 3177: 	$host_name = $ENV{'SERVER_NAME'};
 3178:     }
 3179:     return $protocol.$host_name;
 3180: }
 3181: 
 3182: #
 3183: #   Server side include.
 3184: # Parameters:
 3185: #  fn     Possibly encrypted resource name/id.
 3186: #  form   Hash that describes how the rendering should be done
 3187: #         and other things.
 3188: # Returns:
 3189: #   Scalar context: The content of the response.
 3190: #   Array context:  2 element list of the content and the full response object.
 3191: #     
 3192: sub ssi {
 3193: 
 3194:     my ($fn,%form)=@_;
 3195:     my ($request,$response);
 3196: 
 3197:     $form{'no_update_last_known'}=1;
 3198:     &Apache::lonenc::check_encrypt(\$fn);
 3199:     if (%form) {
 3200:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 3201:       $request->content(join('&',map {
 3202:             my $name = escape($_);
 3203:             "$name=" . ( ref($form{$_}) eq 'ARRAY'
 3204:             ? join("&$name=", map {escape($_) } @{$form{$_}})
 3205:             : &escape($form{$_}) );
 3206:         } keys(%form)));
 3207:     } else {
 3208:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 3209:     }
 3210: 
 3211:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 3212: 
 3213:     if (($env{'request.course.id'}) &&
 3214:         ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
 3215:         ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
 3216:         ($form{'grade_symb'} ne '') &&
 3217:         (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
 3218:                                  ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
 3219:         if (LWP::UserAgent->VERSION >= 5.834) {
 3220:             my $ua=new LWP::UserAgent;
 3221:             $ua->local_address('127.0.0.1');
 3222:             $response = $ua->request($request);
 3223:         } else {
 3224:             {
 3225:                 require LWP::Protocol::http;
 3226:                 local @LWP::Protocol::http::EXTRA_SOCK_OPTS = (LocalAddr => '127.0.0.1');
 3227:                 my $ua=new LWP::UserAgent;
 3228:                 $response = $ua->request($request);
 3229:                 @LWP::Protocol::http::EXTRA_SOCK_OPTS = ();
 3230:             }
 3231:         }
 3232:     } else {
 3233:         my $ua=new LWP::UserAgent;
 3234:         $response = $ua->request($request);
 3235:     }
 3236:     if (wantarray) {
 3237: 	return ($response->content, $response);
 3238:     } else {
 3239: 	return $response->content;
 3240:     }
 3241: }
 3242: 
 3243: sub externalssi {
 3244:     my ($url)=@_;
 3245:     my $ua=new LWP::UserAgent;
 3246:     my $request=new HTTP::Request('GET',$url);
 3247:     my $response=$ua->request($request);
 3248:     if (wantarray) {
 3249:         return ($response->content, $response);
 3250:     } else {
 3251:         return $response->content;
 3252:     }
 3253: }
 3254: 
 3255: # If the local copy of a replicated resource is outdated, trigger a
 3256: # connection from the homeserver to flush the delayed queue. If no update
 3257: # happens, remove local copies of outdated resource (and corresponding
 3258: # metadata file).
 3259: 
 3260: sub remove_stale_resfile {
 3261:     my ($url) = @_;
 3262:     my $removed;
 3263:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
 3264:         my $audom = $1;
 3265:         my $auname = $2;
 3266:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
 3267:             my $homeserver = &homeserver($auname,$audom);
 3268:             unless (($homeserver eq 'no_host') ||
 3269:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
 3270:                 my $fname = &filelocation('',$url);
 3271:                 if (-e $fname) {
 3272:                     my $hostname = &hostname($homeserver);
 3273:                     if ($hostname) {
 3274:                         my $protocol = $protocol{$homeserver};
 3275:                         $protocol = 'http' if ($protocol ne 'https');
 3276:                         my $uri = $protocol.'://'.$hostname.'/raw/'.&declutter($url);
 3277:                         my $ua=new LWP::UserAgent;
 3278:                         $ua->timeout(5);
 3279:                         my $request=new HTTP::Request('HEAD',$uri);
 3280:                         my $response=$ua->request($request);
 3281:                         if ($response->is_success()) {
 3282:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
 3283:                             my $locmodtime = (stat($fname))[9];
 3284:                             if ($locmodtime < $remmodtime) {
 3285:                                 my $stale;
 3286:                                 my $answer = &reply('pong',$homeserver);
 3287:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
 3288:                                     sleep(0.2);
 3289:                                     $locmodtime = (stat($fname))[9];
 3290:                                     if ($locmodtime < $remmodtime) {
 3291:                                         my $posstransfer = $fname.'.in.transfer';
 3292:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
 3293:                                             $removed = 1;
 3294:                                         } else {
 3295:                                             $stale = 1;
 3296:                                         }
 3297:                                     } else {
 3298:                                         $removed = 1;
 3299:                                     }
 3300:                                 } else {
 3301:                                     $stale = 1;
 3302:                                 }
 3303:                                 if ($stale) {
 3304:                                     if (unlink($fname)) {
 3305:                                         if ($uri!~/\.meta$/) {
 3306:                                             if (-e $fname.'.meta') {
 3307:                                                 unlink($fname.'.meta');
 3308:                                             }
 3309:                                         }
 3310:                                         my $unsubresult = &unsubscribe($fname);
 3311:                                         unless ($unsubresult eq 'ok') {
 3312:                                             &logthis("no unsub of $fname from $homeserver, reason: $unsubresult");
 3313:                                         }
 3314:                                         $removed = 1;
 3315:                                     }
 3316:                                 }
 3317:                             }
 3318:                         }
 3319:                     }
 3320:                 }
 3321:             }
 3322:         }
 3323:     }
 3324:     return $removed;
 3325: }
 3326: 
 3327: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 3328: 
 3329: sub allowuploaded {
 3330:     my ($srcurl,$url)=@_;
 3331:     $url=&clutter(&declutter($url));
 3332:     my $dir=$url;
 3333:     $dir=~s/\/[^\/]+$//;
 3334:     my %httpref=();
 3335:     my $httpurl=&hreflocation('',$url);
 3336:     $httpref{'httpref.'.$httpurl}=$srcurl;
 3337:     &Apache::lonnet::appenv(\%httpref);
 3338: }
 3339: 
 3340: #
 3341: # Determine if the current user should be able to edit a particular resource,
 3342: # when viewing in course context.
 3343: # (a) When viewing resource used to determine if "Edit" item is included in
 3344: #     Functions.
 3345: # (b) When displaying folder contents in course editor, used to determine if
 3346: #     "Edit" link will be displayed alongside resource.
 3347: #
 3348: #  input: six args -- filename (decluttered), course number, course domain,
 3349: #                   url, symb (if registered) and group (if this is a group
 3350: #                   item -- e.g., bulletin board, group page etc.).
 3351: #  output: array of five scalars --
 3352: #          $cfile -- url for file editing if editable on current server
 3353: #          $home -- homeserver of resource (i.e., for author if published,
 3354: #                                           or course if uploaded.).
 3355: #          $switchserver --  1 if server switch will be needed.
 3356: #          $forceedit -- 1 if icon/link should be to go to edit mode
 3357: #          $forceview -- 1 if icon/link should be to go to view mode
 3358: #
 3359: 
 3360: sub can_edit_resource {
 3361:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
 3362:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
 3363: #
 3364: # For aboutme pages user can only edit his/her own.
 3365: #
 3366:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
 3367:         my ($sdom,$sname) = ($1,$2);
 3368:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
 3369:             $home = $env{'user.home'};
 3370:             $cfile = $resurl;
 3371:             if ($env{'form.forceedit'}) {
 3372:                 $forceview = 1;
 3373:             } else {
 3374:                 $forceedit = 1;
 3375:             }
 3376:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
 3377:         } else {
 3378:             return;
 3379:         }
 3380:     }
 3381: 
 3382:     if ($env{'request.course.id'}) {
 3383:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
 3384:         if ($group ne '') {
 3385: # if this is a group homepage or group bulletin board, check group privs
 3386:             my $allowed = 0;
 3387:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
 3388:                 if ((&allowed('mdg',$env{'request.course.id'}.
 3389:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 3390:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 3391:                     $allowed = 1;
 3392:                 }
 3393:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
 3394:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 3395:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 3396:                     $allowed = 1;
 3397:                 }
 3398:             }
 3399:             if ($allowed) {
 3400:                 $home=&homeserver($cnum,$cdom);
 3401:                 if ($env{'form.forceedit'}) {
 3402:                     $forceview = 1;
 3403:                 } else {
 3404:                     $forceedit = 1;
 3405:                 }
 3406:                 $cfile = $resurl;
 3407:             } else {
 3408:                 return;
 3409:             }
 3410:         } else {
 3411:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
 3412:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
 3413:                     return;
 3414:                 }
 3415:             } elsif (!$crsedit) {
 3416: #
 3417: # No edit allowed where CC has switched to student role.
 3418: #
 3419:                 return;
 3420:             }
 3421:         }
 3422:     }
 3423: 
 3424:     if ($file ne '') {
 3425:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
 3426:             if (&is_course_upload($file,$cnum,$cdom)) {
 3427:                 $uploaded = 1;
 3428:                 $incourse = 1;
 3429:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
 3430:                     $cfile = &hreflocation('',$file);
 3431:                     if ($env{'form.forceedit'}) {
 3432:                         $forceview = 1;
 3433:                     } else {
 3434:                         $forceedit = 1;
 3435:                     }
 3436:                 }
 3437:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
 3438:                 $incourse = 1;
 3439:                 if ($env{'form.forceedit'}) {
 3440:                     $forceview = 1;
 3441:                 } else {
 3442:                     $forceedit = 1;
 3443:                 }
 3444:                 $cfile = $resurl;
 3445:             } elsif (($resurl ne '') && (&is_on_map($resurl))) {
 3446:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
 3447:                     $incourse = 1;
 3448:                     if ($env{'form.forceedit'}) {
 3449:                         $forceview = 1;
 3450:                     } else {
 3451:                         $forceedit = 1;
 3452:                     }
 3453:                     $cfile = $resurl;
 3454:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
 3455:                     $incourse = 1;
 3456:                     $cfile = $resurl.'/smpedit';
 3457:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
 3458:                     $incourse = 1;
 3459:                     if ($env{'form.forceedit'}) {
 3460:                         $forceview = 1;
 3461:                     } else {
 3462:                         $forceedit = 1;
 3463:                     }
 3464:                     $cfile = $resurl;
 3465:                 } elsif (($resurl =~ m{^/ext/}) && ($symb ne '')) {
 3466:                     my ($map,$id,$res) = &decode_symb($symb);
 3467:                     if ($map =~ /\.page$/) {
 3468:                         $incourse = 1;
 3469:                         if ($env{'form.forceedit'}) {
 3470:                             $forceview = 1;
 3471:                             $cfile = $map;
 3472:                         } else {
 3473:                             $forceedit = 1;
 3474:                             $cfile =  '/adm/wrapper'.$resurl;
 3475:                         }
 3476:                     }
 3477:                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
 3478:                     $incourse = 1;
 3479:                     if ($env{'form.forceedit'}) {
 3480:                         $forceview = 1;
 3481:                     } else {
 3482:                         $forceedit = 1;
 3483:                     }
 3484:                     $cfile = $resurl;
 3485:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 3486:                     $incourse = 1;
 3487:                     if ($env{'form.forceedit'}) {
 3488:                         $forceview = 1;
 3489:                     } else {
 3490:                         $forceedit = 1;
 3491:                     }
 3492:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 3493:                 }
 3494:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
 3495:                 my $template = '/res/lib/templates/simpleproblem.problem';
 3496:                 if (&is_on_map($template)) {
 3497:                     $incourse = 1;
 3498:                     $forceview = 1;
 3499:                     $cfile = $template;
 3500:                 }
 3501:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 3502:                 $incourse = 1;
 3503:                 if ($env{'form.forceedit'}) {
 3504:                     $forceview = 1;
 3505:                 } else {
 3506:                     $forceedit = 1;
 3507:                 }
 3508:                 $cfile = $resurl;
 3509:             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 3510:                 $incourse = 1;
 3511:                 if ($env{'form.forceedit'}) {
 3512:                     $forceview = 1;
 3513:                 } else {
 3514:                     $forceedit = 1;
 3515:                 }
 3516:                 $cfile = $resurl;
 3517:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
 3518:                 $incourse = 1;
 3519:                 $forceview = 1;
 3520:                 if ($symb) {
 3521:                     my ($map,$id,$res)=&decode_symb($symb);
 3522:                     $env{'request.symb'} = $symb;
 3523:                     $cfile = &clutter($res);
 3524:                 } else {
 3525:                     $cfile = $env{'form.suppurl'};
 3526:                     my $escfile = &unescape($cfile);
 3527:                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
 3528:                         $cfile = '/adm/wrapper'.$escfile;
 3529:                     } else {
 3530:                         $escfile =~ s{^http://}{};
 3531:                         $cfile = &escape("/adm/wrapper/ext/$escfile");
 3532:                     }
 3533:                 }
 3534:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 3535:                 if ($env{'form.forceedit'}) {
 3536:                     $forceview = 1;
 3537:                 } else {
 3538:                     $forceedit = 1;
 3539:                 }
 3540:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 3541:             }
 3542:         }
 3543:         if ($uploaded || $incourse) {
 3544:             $home=&homeserver($cnum,$cdom);
 3545:         } elsif ($file !~ m{/$}) {
 3546:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
 3547:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
 3548:             # Check that the user has permission to edit this resource
 3549:             my $setpriv = 1;
 3550:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
 3551:             if (defined($cfudom)) {
 3552:                 $home=&homeserver($cfuname,$cfudom);
 3553:                 $cfile=$file;
 3554:             }
 3555:         }
 3556:         if (($cfile ne '') && (!$incourse || $uploaded) &&
 3557:             (($home ne '') && ($home ne 'no_host'))) {
 3558:             my @ids=&current_machine_ids();
 3559:             unless (grep(/^\Q$home\E$/,@ids)) {
 3560:                 $switchserver=1;
 3561:             }
 3562:         }
 3563:     }
 3564:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
 3565: }
 3566: 
 3567: sub is_course_upload {
 3568:     my ($file,$cnum,$cdom) = @_;
 3569:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
 3570:     $uploadpath =~ s{^\/}{};
 3571:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
 3572:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
 3573:         return 1;
 3574:     }
 3575:     return;
 3576: }
 3577: 
 3578: sub in_course {
 3579:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
 3580:     if ($hideprivileged) {
 3581:         my $skipuser;
 3582:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
 3583:         my @possdoms = ($cdom);
 3584:         if ($coursehash{'checkforpriv'}) {
 3585:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
 3586:         }
 3587:         if (&privileged($uname,$udom,\@possdoms)) {
 3588:             $skipuser = 1;
 3589:             if ($coursehash{'nothideprivileged'}) {
 3590:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3591:                     my $user;
 3592:                     if ($item =~ /:/) {
 3593:                         $user = $item;
 3594:                     } else {
 3595:                         $user = join(':',split(/[\@]/,$item));
 3596:                     }
 3597:                     if ($user eq $uname.':'.$udom) {
 3598:                         undef($skipuser);
 3599:                         last;
 3600:                     }
 3601:                 }
 3602:             }
 3603:             if ($skipuser) {
 3604:                 return 0;
 3605:             }
 3606:         }
 3607:     }
 3608:     $type ||= 'any';
 3609:     if (!defined($cdom) || !defined($cnum)) {
 3610:         my $cid  = $env{'request.course.id'};
 3611:         $cdom = $env{'course.'.$cid.'.domain'};
 3612:         $cnum = $env{'course.'.$cid.'.num'};
 3613:     }
 3614:     my $typesref;
 3615:     if (($type eq 'any') || ($type eq 'all')) {
 3616:         $typesref = ['active','previous','future'];
 3617:     } elsif ($type eq 'previous' || $type eq 'future') {
 3618:         $typesref = [$type];
 3619:     }
 3620:     my %roles = &get_my_roles($uname,$udom,'userroles',
 3621:                               $typesref,undef,[$cdom]);
 3622:     my ($tmp) = keys(%roles);
 3623:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
 3624:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
 3625:     if (@course_roles > 0) {
 3626:         return 1;
 3627:     }
 3628:     return 0;
 3629: }
 3630: 
 3631: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 3632: # input: action, courseID, current domain, intended
 3633: #        path to file, source of file, instruction to parse file for objects,
 3634: #        ref to hash for embedded objects,
 3635: #        ref to hash for codebase of java objects.
 3636: #        reference to scalar to accommodate mime type determined
 3637: #          from File::MMagic if $parser = parse.
 3638: #
 3639: # output: url to file (if action was uploaddoc), 
 3640: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 3641: #
 3642: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 3643: # course.
 3644: #
 3645: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3646: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 3647: #          course's home server.
 3648: #
 3649: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 3650: #          be copied from $source (current location) to 
 3651: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3652: #         and will then be copied to
 3653: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 3654: #         course's home server.
 3655: #
 3656: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3657: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 3658: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3659: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 3660: #         in course's home server.
 3661: #
 3662: 
 3663: sub process_coursefile {
 3664:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
 3665:         $mimetype)=@_;
 3666:     my $fetchresult;
 3667:     my $home=&homeserver($docuname,$docudom);
 3668:     if ($action eq 'propagate') {
 3669:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3670: 			     $home);
 3671:     } else {
 3672:         my $fpath = '';
 3673:         my $fname = $file;
 3674:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3675:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3676:         my $filepath = &build_filepath($fpath);
 3677:         if ($action eq 'copy') {
 3678:             if ($source eq '') {
 3679:                 $fetchresult = 'no source file';
 3680:                 return $fetchresult;
 3681:             } else {
 3682:                 my $destination = $filepath.'/'.$fname;
 3683:                 rename($source,$destination);
 3684:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3685:                                  $home);
 3686:             }
 3687:         } elsif ($action eq 'uploaddoc') {
 3688:             open(my $fh,'>',$filepath.'/'.$fname);
 3689:             print $fh $env{'form.'.$source};
 3690:             close($fh);
 3691:             if ($parser eq 'parse') {
 3692:                 my $mm = new File::MMagic;
 3693:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
 3694:                 if ($type eq 'text/html') {
 3695:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 3696:                     unless ($parse_result eq 'ok') {
 3697:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 3698:                     }
 3699:                 }
 3700:                 if (ref($mimetype)) {
 3701:                     $$mimetype = $type;
 3702:                 } 
 3703:             }
 3704:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3705:                                  $home);
 3706:             if ($fetchresult eq 'ok') {
 3707:                 return '/uploaded/'.$fpath.'/'.$fname;
 3708:             } else {
 3709:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3710:                         ' to host '.$home.': '.$fetchresult);
 3711:                 return '/adm/notfound.html';
 3712:             }
 3713:         }
 3714:     }
 3715:     unless ( $fetchresult eq 'ok') {
 3716:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3717:              ' to host '.$home.': '.$fetchresult);
 3718:     }
 3719:     return $fetchresult;
 3720: }
 3721: 
 3722: sub build_filepath {
 3723:     my ($fpath) = @_;
 3724:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 3725:     unless ($fpath eq '') {
 3726:         my @parts=split('/',$fpath);
 3727:         foreach my $part (@parts) {
 3728:             $filepath.= '/'.$part;
 3729:             if ((-e $filepath)!=1) {
 3730:                 mkdir($filepath,0777);
 3731:             }
 3732:         }
 3733:     }
 3734:     return $filepath;
 3735: }
 3736: 
 3737: sub store_edited_file {
 3738:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 3739:     my $file = $primary_url;
 3740:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 3741:     my $fpath = '';
 3742:     my $fname = $file;
 3743:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3744:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3745:     my $filepath = &build_filepath($fpath);
 3746:     open(my $fh,'>',$filepath.'/'.$fname);
 3747:     print $fh $content;
 3748:     close($fh);
 3749:     my $home=&homeserver($docuname,$docudom);
 3750:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3751: 			  $home);
 3752:     if ($$fetchresult eq 'ok') {
 3753:         return '/uploaded/'.$fpath.'/'.$fname;
 3754:     } else {
 3755:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3756: 		 ' to host '.$home.': '.$$fetchresult);
 3757:         return '/adm/notfound.html';
 3758:     }
 3759: }
 3760: 
 3761: sub clean_filename {
 3762:     my ($fname,$args)=@_;
 3763: # Replace Windows backslashes by forward slashes
 3764:     $fname=~s/\\/\//g;
 3765:     if (!$args->{'keep_path'}) {
 3766:         # Get rid of everything but the actual filename
 3767: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 3768:     }
 3769: # Replace spaces by underscores
 3770:     $fname=~s/\s+/\_/g;
 3771: # Transliterate non-ascii text to ascii
 3772:     my $lang = &Apache::lonlocal::current_language();
 3773:     $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
 3774: # Replace all other weird characters by nothing
 3775:     $fname=~s{[^/\w\.\-]}{}g;
 3776: # Replace all .\d. sequences with _\d. so they no longer look like version
 3777: # numbers
 3778:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 3779:     return $fname;
 3780: }
 3781: 
 3782: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
 3783: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
 3784: # image with the same aspect ratio as the original, but with dimensions which do 
 3785: # not exceed $resizewidth and $resizeheight.
 3786:  
 3787: sub resizeImage {
 3788:     my ($img_path,$resizewidth,$resizeheight) = @_;
 3789:     my $ima = Image::Magick->new;
 3790:     my $resized;
 3791:     if (-e $img_path) {
 3792:         $ima->Read($img_path);
 3793:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
 3794:             my $width = $ima->Get('width');
 3795:             my $height = $ima->Get('height');
 3796:             if ($width > $resizewidth) {
 3797: 	        my $factor = $width/$resizewidth;
 3798:                 my $newheight = $height/$factor;
 3799:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
 3800:                 $resized = 1;
 3801:             }
 3802:         }
 3803:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
 3804:             my $width = $ima->Get('width');
 3805:             my $height = $ima->Get('height');
 3806:             if ($height > $resizeheight) {
 3807:                 my $factor = $height/$resizeheight;
 3808:                 my $newwidth = $width/$factor;
 3809:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
 3810:                 $resized = 1;
 3811:             }
 3812:         }
 3813:         if ($resized) {
 3814:             $ima->Write($img_path);
 3815:         }
 3816:     }
 3817:     return;
 3818: }
 3819: 
 3820: # --------------- Take an uploaded file and put it into the userfiles directory
 3821: # input: $formname - the contents of the file are in $env{"form.$formname"}
 3822: #                    the desired filename is in $env{"form.$formname.filename"}
 3823: #        $context - possible values: coursedoc, existingfile, overwrite, 
 3824: #                                    canceloverwrite, scantron or ''. 
 3825: #                   if 'coursedoc': upload to the current course
 3826: #                   if 'existingfile': write file to tmp/overwrites directory 
 3827: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
 3828: #                   $context is passed as argument to &finishuserfileupload
 3829: #        $subdir - directory in userfile to store the file into
 3830: #        $parser - instruction to parse file for objects ($parser = parse) or
 3831: #                  if context is 'scantron', $parser is hashref of csv column mapping
 3832: #                  (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3,
 3833: #                          Section => 4, CODE => 5, FirstQuestion => 9 }).
 3834: #        $allfiles - reference to hash for embedded objects
 3835: #        $codebase - reference to hash for codebase of java objects
 3836: #        $desuname - username for permanent storage of uploaded file
 3837: #        $dsetudom - domain for permanaent storage of uploaded file
 3838: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 3839: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 3840: #        $resizewidth - width (pixels) to which to resize uploaded image
 3841: #        $resizeheight - height (pixels) to which to resize uploaded image
 3842: #        $mimetype - reference to scalar to accommodate mime type determined
 3843: #                    from File::MMagic.
 3844: # 
 3845: # output: url of file in userspace, or error: <message> 
 3846: #             or /adm/notfound.html if failure to upload occurse
 3847: 
 3848: sub userfileupload {
 3849:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
 3850:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
 3851:     if (!defined($subdir)) { $subdir='unknown'; }
 3852:     my $fname=$env{'form.'.$formname.'.filename'};
 3853:     $fname=&clean_filename($fname);
 3854:     # See if there is anything left
 3855:     unless ($fname) { return 'error: no uploaded file'; }
 3856:     # If filename now begins with a . prepend unix timestamp _ milliseconds
 3857:     if ($fname =~ /^\./) {
 3858:         my ($s,$usec) = &gettimeofday();
 3859:         while (length($usec) < 6) {
 3860:             $usec = '0'.$usec;
 3861:         }
 3862:         $fname = $s.'_'.substr($usec,0,3).$fname;
 3863:     }
 3864:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
 3865:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
 3866:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
 3867:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3868:         my $now = time;
 3869:         my $filepath;
 3870:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
 3871:              $filepath = 'tmp/helprequests/'.$now;
 3872:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
 3873:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 3874:                          '_'.$env{'user.domain'}.'/pending';
 3875:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3876:             my ($docuname,$docudom);
 3877:             if ($destudom =~ /^$match_domain$/) {
 3878:                 $docudom = $destudom;
 3879:             } else {
 3880:                 $docudom = $env{'user.domain'};
 3881:             }
 3882:             if ($destuname =~ /^$match_username$/) { 
 3883:                 $docuname = $destuname;
 3884:             } else {
 3885:                 $docuname = $env{'user.name'};
 3886:             }
 3887:             if (exists($env{'form.group'})) {
 3888:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3889:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3890:             }
 3891:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
 3892:             if ($context eq 'canceloverwrite') {
 3893:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
 3894:                 if (-e  $tempfile) {
 3895:                     my @info = stat($tempfile);
 3896:                     if ($info[9] eq $env{'form.timestamp'}) {
 3897:                         unlink($tempfile);
 3898:                     }
 3899:                 }
 3900:                 return;
 3901:             }
 3902:         }
 3903:         # Create the directory if not present
 3904:         my @parts=split(/\//,$filepath);
 3905:         my $fullpath = $perlvar{'lonDaemons'};
 3906:         for (my $i=0;$i<@parts;$i++) {
 3907:             $fullpath .= '/'.$parts[$i];
 3908:             if ((-e $fullpath)!=1) {
 3909:                 mkdir($fullpath,0777);
 3910:             }
 3911:         }
 3912:         open(my $fh,'>',$fullpath.'/'.$fname);
 3913:         print $fh $env{'form.'.$formname};
 3914:         close($fh);
 3915:         if ($context eq 'existingfile') {
 3916:             my @info = stat($fullpath.'/'.$fname);
 3917:             return ($fullpath.'/'.$fname,$info[9]);
 3918:         } else {
 3919:             return $fullpath.'/'.$fname;
 3920:         }
 3921:     }
 3922:     if ($subdir eq 'scantron') {
 3923:         $fname = 'scantron_orig_'.$fname;
 3924:     } else {
 3925:         $fname="$subdir/$fname";
 3926:     }
 3927:     if ($context eq 'coursedoc') {
 3928: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3929: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3930:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 3931:             return &finishuserfileupload($docuname,$docudom,
 3932: 					 $formname,$fname,$parser,$allfiles,
 3933: 					 $codebase,$thumbwidth,$thumbheight,
 3934:                                          $resizewidth,$resizeheight,$context,$mimetype);
 3935:         } else {
 3936:             if ($env{'form.folder'}) {
 3937:                 $fname=$env{'form.folder'}.'/'.$fname;
 3938:             }
 3939:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 3940: 				       $fname,$formname,$parser,
 3941: 				       $allfiles,$codebase,$mimetype);
 3942:         }
 3943:     } elsif (defined($destuname)) {
 3944:         my $docuname=$destuname;
 3945:         my $docudom=$destudom;
 3946: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 3947: 				     $parser,$allfiles,$codebase,
 3948:                                      $thumbwidth,$thumbheight,
 3949:                                      $resizewidth,$resizeheight,$context,$mimetype);
 3950:     } else {
 3951:         my $docuname=$env{'user.name'};
 3952:         my $docudom=$env{'user.domain'};
 3953:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
 3954:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3955:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3956:         }
 3957: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 3958: 				     $parser,$allfiles,$codebase,
 3959:                                      $thumbwidth,$thumbheight,
 3960:                                      $resizewidth,$resizeheight,$context,$mimetype);
 3961:     }
 3962: }
 3963: 
 3964: sub finishuserfileupload {
 3965:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 3966:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
 3967:     my $path=$docudom.'/'.$docuname.'/';
 3968:     my $filepath=$perlvar{'lonDocRoot'};
 3969:   
 3970:     my ($fnamepath,$file,$fetchthumb);
 3971:     $file=$fname;
 3972:     if ($fname=~m|/|) {
 3973:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 3974: 	$path.=$fnamepath.'/';
 3975:     }
 3976:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 3977:     my $count;
 3978:     for ($count=4;$count<=$#parts;$count++) {
 3979:         $filepath.="/$parts[$count]";
 3980:         if ((-e $filepath)!=1) {
 3981: 	    mkdir($filepath,0777);
 3982:         }
 3983:     }
 3984: 
 3985: # Save the file
 3986:     {
 3987: 	if (!open(FH,'>',$filepath.'/'.$file)) {
 3988: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 3989: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 3990: 	    return '/adm/notfound.html';
 3991: 	}
 3992:         if ($context eq 'overwrite') {
 3993:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
 3994:             my $target = $filepath.'/'.$file;
 3995:             if (-e $source) {
 3996:                 my @info = stat($source);
 3997:                 if ($info[9] eq $env{'form.timestamp'}) {   
 3998:                     unless (&File::Copy::move($source,$target)) {
 3999:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
 4000:                         return "Moving from $source failed";
 4001:                     }
 4002:                 } else {
 4003:                     return "Temporary file: $source had unexpected date/time for last modification";
 4004:                 }
 4005:             } else {
 4006:                 return "Temporary file: $source missing";
 4007:             }
 4008:         } elsif (!print FH ($env{'form.'.$formname})) {
 4009: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 4010: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 4011: 	    return '/adm/notfound.html';
 4012: 	}
 4013: 	close(FH);
 4014:         if ($resizewidth && $resizeheight) {
 4015:             my $mm = new File::MMagic;
 4016:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
 4017:             if ($mime_type =~ m{^image/}) {
 4018: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
 4019:             }  
 4020: 	}
 4021:     }
 4022:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
 4023:         if (ref($mimetype)) {
 4024:             if ($$mimetype eq '') {
 4025:                 my $mm = new File::MMagic;
 4026:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
 4027:                 $$mimetype = $type;
 4028:             }
 4029:         }
 4030:     }
 4031:     if (($context ne 'scantron') && ($parser eq 'parse')) {
 4032:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
 4033:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
 4034:                                                        $allfiles,$codebase);
 4035:             unless ($parse_result eq 'ok') {
 4036:                 &logthis('Failed to parse '.$filepath.$file.
 4037: 	   	         ' for embedded media: '.$parse_result); 
 4038:             }
 4039:         }
 4040:     } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
 4041:         my $format = $env{'form.scantron_format'};
 4042:         &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
 4043:     }
 4044:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 4045:         my $input = $filepath.'/'.$file;
 4046:         my $output = $filepath.'/'.'tn-'.$file;
 4047:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 4048:         my @args = ('convert','-sample',$thumbsize,$input,$output);
 4049:         system({$args[0]} @args);
 4050:         if (-e $filepath.'/'.'tn-'.$file) {
 4051:             $fetchthumb  = 1; 
 4052:         }
 4053:     }
 4054:  
 4055: # Notify homeserver to grep it
 4056: #
 4057:     my $docuhome=&homeserver($docuname,$docudom);	
 4058:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 4059:     if ($fetchresult eq 'ok') {
 4060:         if ($fetchthumb) {
 4061:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 4062:             if ($thumbresult ne 'ok') {
 4063:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 4064:                          $docuhome.': '.$thumbresult);
 4065:             }
 4066:         }
 4067: #
 4068: # Return the URL to it
 4069:         return '/uploaded/'.$path.$file;
 4070:     } else {
 4071:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 4072: 		 ': '.$fetchresult);
 4073:         return '/adm/notfound.html';
 4074:     }
 4075: }
 4076: 
 4077: sub extract_embedded_items {
 4078:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 4079:     my @state = ();
 4080:     my (%lastids,%related,%shockwave,%flashvars);
 4081:     my %javafiles = (
 4082:                       codebase => '',
 4083:                       code => '',
 4084:                       archive => ''
 4085:                     );
 4086:     my %mediafiles = (
 4087:                       src => '',
 4088:                       movie => '',
 4089:                      );
 4090:     my $p;
 4091:     if ($content) {
 4092:         $p = HTML::LCParser->new($content);
 4093:     } else {
 4094:         $p = HTML::LCParser->new($fullpath);
 4095:     }
 4096:     while (my $t=$p->get_token()) {
 4097: 	if ($t->[0] eq 'S') {
 4098: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 4099: 	    push(@state, $tagname);
 4100:             if (lc($tagname) eq 'allow') {
 4101:                 &add_filetype($allfiles,$attr->{'src'},'src');
 4102:             }
 4103: 	    if (lc($tagname) eq 'img') {
 4104: 		&add_filetype($allfiles,$attr->{'src'},'src');
 4105: 	    }
 4106: 	    if (lc($tagname) eq 'a') {
 4107:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
 4108: 		    &add_filetype($allfiles,$attr->{'href'},'href');
 4109:                 }
 4110: 	    }
 4111:             if (lc($tagname) eq 'script') {
 4112:                 my $src;
 4113:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 4114:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 4115:                 } else {
 4116:                     if ($attr->{'src'} ne '') {
 4117:                         $src = $attr->{'src'};
 4118:                         &add_filetype($allfiles,$src,'src');
 4119:                     }
 4120:                 }
 4121:                 my $text = $p->get_trimmed_text();
 4122:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
 4123:                     my @swfargs = split(/,/,$1);
 4124:                     foreach my $item (@swfargs) {
 4125:                         $item =~ s/["']//g;
 4126:                         $item =~ s/^\s+//;
 4127:                         $item =~ s/\s+$//;
 4128:                     }
 4129:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
 4130:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
 4131:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
 4132:                         } else {
 4133:                             $related{$swfargs[0]} = [$swfargs[2]];
 4134:                         }
 4135:                     }
 4136:                 }
 4137:             }
 4138:             if (lc($tagname) eq 'link') {
 4139:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 4140:                     &add_filetype($allfiles,$attr->{'href'},'href');
 4141:                 }
 4142:             }
 4143: 	    if (lc($tagname) eq 'object' ||
 4144: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 4145: 		foreach my $item (keys(%javafiles)) {
 4146: 		    $javafiles{$item} = '';
 4147: 		}
 4148:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
 4149:                     $lastids{lc($tagname)} = $attr->{'id'};
 4150:                 }
 4151: 	    }
 4152: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 4153: 		my $name = lc($attr->{'name'});
 4154: 		foreach my $item (keys(%javafiles)) {
 4155: 		    if ($name eq $item) {
 4156: 			$javafiles{$item} = $attr->{'value'};
 4157: 			last;
 4158: 		    }
 4159: 		}
 4160:                 my $pathfrom;
 4161: 		foreach my $item (keys(%mediafiles)) {
 4162: 		    if ($name eq $item) {
 4163:                         $pathfrom = $attr->{'value'};
 4164:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
 4165: 			&add_filetype($allfiles,$pathfrom,$name);
 4166: 			last;
 4167: 		    }
 4168: 		}
 4169:                 if ($name eq 'flashvars') {
 4170:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
 4171:                 }
 4172:                 if ($pathfrom ne '') {
 4173:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
 4174:                                          $pathfrom);
 4175:                 }
 4176: 	    }
 4177: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 4178: 		foreach my $item (keys(%javafiles)) {
 4179: 		    if ($attr->{$item}) {
 4180: 			$javafiles{$item} = $attr->{$item};
 4181: 			last;
 4182: 		    }
 4183: 		}
 4184: 		foreach my $item (keys(%mediafiles)) {
 4185: 		    if ($attr->{$item}) {
 4186: 			&add_filetype($allfiles,$attr->{$item},$item);
 4187: 			last;
 4188: 		    }
 4189: 		}
 4190:                 if (lc($tagname) eq 'embed') {
 4191:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
 4192:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
 4193:                                              $attr->{'src'});
 4194:                     }
 4195:                 }
 4196: 	    }
 4197:             if (lc($tagname) eq 'iframe') {
 4198:                 my $src = $attr->{'src'} ;
 4199:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
 4200:                     &add_filetype($allfiles,$src,'src');
 4201:                 } elsif ($src =~ m{^/}) {
 4202:                     if ($env{'request.course.id'}) {
 4203:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4204:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4205:                         my $url = &hreflocation('',$fullpath);
 4206:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
 4207:                             my $relpath = $1;
 4208:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
 4209:                                 &add_filetype($allfiles,$1,'src');
 4210:                             }
 4211:                         }
 4212:                     }
 4213:                 }
 4214:             }
 4215:             if ($t->[4] =~ m{/>$}) {
 4216:                 pop(@state);
 4217:             }
 4218: 	} elsif ($t->[0] eq 'E') {
 4219: 	    my ($tagname) = ($t->[1]);
 4220: 	    if ($javafiles{'codebase'} ne '') {
 4221: 		$javafiles{'codebase'} .= '/';
 4222: 	    }  
 4223: 	    if (lc($tagname) eq 'applet' ||
 4224: 		lc($tagname) eq 'object' ||
 4225: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 4226: 		) {
 4227: 		foreach my $item (keys(%javafiles)) {
 4228: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 4229: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 4230: 			&add_filetype($allfiles,$file,$item);
 4231: 		    }
 4232: 		}
 4233: 	    } 
 4234: 	    pop @state;
 4235: 	}
 4236:     }
 4237:     foreach my $id (sort(keys(%flashvars))) {
 4238:         if ($shockwave{$id} ne '') {
 4239:             my @pairs = split(/\&/,$flashvars{$id});
 4240:             foreach my $pair (@pairs) {
 4241:                 my ($key,$value) = split(/\=/,$pair);
 4242:                 if ($key eq 'thumb') {
 4243:                     &add_filetype($allfiles,$value,$key);
 4244:                 } elsif ($key eq 'content') {
 4245:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
 4246:                     my ($ext) = ($value =~ /\.([^.]+)$/);
 4247:                     if ($ext ne '') {
 4248:                         &add_filetype($allfiles,$path.$value,$ext);
 4249:                     }
 4250:                 }
 4251:             }
 4252:         }
 4253:     }
 4254:     return 'ok';
 4255: }
 4256: 
 4257: sub add_filetype {
 4258:     my ($allfiles,$file,$type)=@_;
 4259:     if (exists($allfiles->{$file})) {
 4260: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 4261: 	    push(@{$allfiles->{$file}}, &escape($type));
 4262: 	}
 4263:     } else {
 4264: 	@{$allfiles->{$file}} = (&escape($type));
 4265:     }
 4266: }
 4267: 
 4268: sub embedded_dependency {
 4269:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
 4270:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
 4271:         if (($identifier ne '') &&
 4272:             (ref($related->{$identifier}) eq 'ARRAY') &&
 4273:             ($pathfrom ne '')) {
 4274:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
 4275:             foreach my $dep (@{$related->{$identifier}}) {
 4276:                 &add_filetype($allfiles,$path.$dep,'object');
 4277:             }
 4278:         }
 4279:     }
 4280:     return;
 4281: }
 4282: 
 4283: sub bubblesheet_converter {
 4284:     my ($cdom,$fullpath,$config,$format) = @_;
 4285:     if ((&domain($cdom) ne '') &&
 4286:         ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
 4287:         (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
 4288:         my (%csvcols,%csvoptions);
 4289:         if (ref($config->{'fields'}) eq 'HASH') {
 4290:             %csvcols = %{$config->{'fields'}};
 4291:         }
 4292:         if (ref($config->{'options'}) eq 'HASH') {
 4293:             %csvoptions = %{$config->{'options'}};
 4294:         }
 4295:         my %csvbynum = reverse(%csvcols);
 4296:         my %scantronconf = &get_scantron_config($format,$cdom);
 4297:         if (keys(%scantronconf)) {
 4298:             my %bynum = (
 4299:                           $scantronconf{CODEstart} => 'CODEstart',
 4300:                           $scantronconf{IDstart}   => 'IDstart',
 4301:                           $scantronconf{PaperID}   => 'PaperID',
 4302:                           $scantronconf{FirstName} => 'FirstName',
 4303:                           $scantronconf{LastName}  => 'LastName',
 4304:                           $scantronconf{Qstart}    => 'Qstart',
 4305:                         );
 4306:             my @ordered;
 4307:             foreach my $item (sort { $a <=> $b } keys(%bynum)) {
 4308:                 push(@ordered,$bynum{$item});
 4309:             }
 4310:             my %mapstart = (
 4311:                               CODEstart => 'CODE',
 4312:                               IDstart   => 'ID',
 4313:                               PaperID   => 'PaperID',
 4314:                               FirstName => 'FirstName',
 4315:                               LastName  => 'LastName',
 4316:                               Qstart    => 'FirstQuestion',
 4317:                            );
 4318:             my %maplength = (
 4319:                               CODEstart => 'CODElength',
 4320:                               IDstart   => 'IDlength',
 4321:                               PaperID   => 'PaperIDlength',
 4322:                               FirstName => 'FirstNamelength',
 4323:                               LastName  => 'LastNamelength',
 4324:             );
 4325:             if (open(my $fh,'<',$fullpath)) {
 4326:                 my $output;
 4327:                 my %lettdig = &letter_to_digits();
 4328:                 my %diglett = reverse(%lettdig);
 4329:                 my $numletts = scalar(keys(%lettdig));
 4330:                 my $num = 0;
 4331:                 while (my $line=<$fh>) {
 4332:                     $num ++;
 4333:                     next if (($num == 1) && ($csvoptions{'hdr'} == 1));
 4334:                     $line =~ s{[\r\n]+$}{};
 4335:                     my %found;
 4336:                     my @values = split(/,/,$line);
 4337:                     my ($qstart,$record);
 4338:                     for (my $i=0; $i<@values; $i++) {
 4339:                         if ((($qstart ne '') && ($i > $qstart)) ||
 4340:                             ($csvbynum{$i} eq 'FirstQuestion')) {
 4341:                             if ($values[$i] eq '') {
 4342:                                 $values[$i] = $scantronconf{'Qoff'};
 4343:                             } elsif ($scantronconf{'Qon'} eq 'number') {
 4344:                                 if ($values[$i] =~ /^[A-Ja-j]$/) {
 4345:                                     $values[$i] = $lettdig{uc($values[$i])};
 4346:                                 }
 4347:                             } elsif ($scantronconf{'Qon'} eq 'letter') {
 4348:                                 if ($values[$i] =~ /^[0-9]$/) {
 4349:                                     $values[$i] = $diglett{$values[$i]};
 4350:                                 }
 4351:                             } else {
 4352:                                 if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
 4353:                                     my $digit;
 4354:                                     if ($values[$i] =~ /^[A-Ja-j]$/) {
 4355:                                         $digit = $lettdig{uc($values[$i])}-1;
 4356:                                         if ($values[$i] eq 'J') {
 4357:                                             $digit += $numletts;
 4358:                                         }
 4359:                                     } elsif ($values[$i] =~ /^[0-9]$/) {
 4360:                                         $digit = $values[$i]-1;
 4361:                                         if ($values[$i] eq '0') {
 4362:                                             $digit += $numletts;
 4363:                                         }
 4364:                                     }
 4365:                                     my $qval='';
 4366:                                     for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
 4367:                                         if ($j == $digit) {
 4368:                                             $qval .= $scantronconf{'Qon'};
 4369:                                         } else {
 4370:                                             $qval .= $scantronconf{'Qoff'};
 4371:                                         }
 4372:                                     }
 4373:                                     $values[$i] = $qval;
 4374:                                 }
 4375:                             }
 4376:                             if (length($values[$i]) > $scantronconf{'Qlength'}) {
 4377:                                 $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
 4378:                             }
 4379:                             my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
 4380:                             if ($numblank > 0) {
 4381:                                  $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
 4382:                             }
 4383:                             if ($csvbynum{$i} eq 'FirstQuestion') {
 4384:                                 $qstart = $i;
 4385:                                 $found{$csvbynum{$i}} = $values[$i];
 4386:                             } else {
 4387:                                 $found{'FirstQuestion'} .= $values[$i];
 4388:                             }
 4389:                         } elsif (exists($csvbynum{$i})) {
 4390:                             if ($csvoptions{'rem'}) {
 4391:                                 $values[$i] =~ s/^\s+//;
 4392:                             }
 4393:                             if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
 4394:                                 while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
 4395:                                     $values[$i] = '0'.$values[$i];
 4396:                                 }
 4397:                             }
 4398:                             $found{$csvbynum{$i}} = $values[$i];
 4399:                         }
 4400:                     }
 4401:                     foreach my $item (@ordered) {
 4402:                         my $currlength = 1+length($record);
 4403:                         my $numspaces = $scantronconf{$item} - $currlength;
 4404:                         if ($numspaces > 0) {
 4405:                             $record .= (' ' x $numspaces);
 4406:                         }
 4407:                         if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
 4408:                             unless ($item eq 'Qstart') {
 4409:                                 if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
 4410:                                     $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
 4411:                                 }
 4412:                             }
 4413:                             $record .= $found{$mapstart{$item}};
 4414:                         }
 4415:                     }
 4416:                     $output .= "$record\n";
 4417:                 }
 4418:                 close($fh);
 4419:                 if ($output) {
 4420:                     if (open(my $fh,'>',$fullpath)) {
 4421:                         print $fh $output;
 4422:                         close($fh);
 4423:                     }
 4424:                 }
 4425:             }
 4426:         }
 4427:         return;
 4428:     }
 4429: }
 4430: 
 4431: sub letter_to_digits {
 4432:     my %lettdig = (
 4433:                     A => 1,
 4434:                     B => 2,
 4435:                     C => 3,
 4436:                     D => 4,
 4437:                     E => 5,
 4438:                     F => 6,
 4439:                     G => 7,
 4440:                     H => 8,
 4441:                     I => 9,
 4442:                     J => 0,
 4443:                   );
 4444:     return %lettdig;
 4445: }
 4446: 
 4447: sub get_scantron_config {
 4448:     my ($which,$cdom) = @_;
 4449:     my @lines = &get_scantronformat_file($cdom);
 4450:     my %config;
 4451:     #FIXME probably should move to XML it has already gotten a bit much now
 4452:     foreach my $line (@lines) {
 4453:         my ($name,$descrip)=split(/:/,$line);
 4454:         if ($name ne $which ) { next; }
 4455:         chomp($line);
 4456:         my @config=split(/:/,$line);
 4457:         $config{'name'}=$config[0];
 4458:         $config{'description'}=$config[1];
 4459:         $config{'CODElocation'}=$config[2];
 4460:         $config{'CODEstart'}=$config[3];
 4461:         $config{'CODElength'}=$config[4];
 4462:         $config{'IDstart'}=$config[5];
 4463:         $config{'IDlength'}=$config[6];
 4464:         $config{'Qstart'}=$config[7];
 4465:         $config{'Qlength'}=$config[8];
 4466:         $config{'Qoff'}=$config[9];
 4467:         $config{'Qon'}=$config[10];
 4468:         $config{'PaperID'}=$config[11];
 4469:         $config{'PaperIDlength'}=$config[12];
 4470:         $config{'FirstName'}=$config[13];
 4471:         $config{'FirstNamelength'}=$config[14];
 4472:         $config{'LastName'}=$config[15];
 4473:         $config{'LastNamelength'}=$config[16];
 4474:         $config{'BubblesPerRow'}=$config[17];
 4475:         last;
 4476:     }
 4477:     return %config;
 4478: }
 4479: 
 4480: sub get_scantronformat_file {
 4481:     my ($cdom) = @_;
 4482:     if ($cdom eq '') {
 4483:         $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 4484:     }
 4485:     my %domconfig = &get_dom('configuration',['scantron'],$cdom);
 4486:     my $gottab = 0;
 4487:     my @lines;
 4488:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 4489:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
 4490:             my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
 4491:             if ($formatfile ne '-1') {
 4492:                 @lines = split("\n",$formatfile,-1);
 4493:                 $gottab = 1;
 4494:             }
 4495:         }
 4496:     }
 4497:     if (!$gottab) {
 4498:         my $confname = $cdom.'-domainconfig';
 4499:         my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
 4500:         my $formatfile = &getfile($default);
 4501:         if ($formatfile ne '-1') {
 4502:             @lines = split("\n",$formatfile,-1);
 4503:             $gottab = 1;
 4504:         }
 4505:     }
 4506:     if (!$gottab) {
 4507:         my @domains = &current_machine_domains();
 4508:         if (grep(/^\Q$cdom\E$/,@domains)) {
 4509:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
 4510:                 @lines = <$fh>;
 4511:                 close($fh);
 4512:             }
 4513:         } else {
 4514:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
 4515:                 @lines = <$fh>;
 4516:                 close($fh);
 4517:             }
 4518:         }
 4519:     }
 4520:     return @lines;
 4521: }
 4522: 
 4523: sub removeuploadedurl {
 4524:     my ($url)=@_;	
 4525:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 4526:     return &removeuserfile($uname,$udom,$fname);
 4527: }
 4528: 
 4529: sub removeuserfile {
 4530:     my ($docuname,$docudom,$fname)=@_;
 4531:     my $home=&homeserver($docuname,$docudom);    
 4532:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 4533:     if ($result eq 'ok') {	
 4534:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 4535:             my $metafile = $fname.'.meta';
 4536:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 4537: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 4538:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 4539:             my $sqlresult = 
 4540:                 &update_portfolio_table($docuname,$docudom,$file,
 4541:                                         'portfolio_metadata',$group,
 4542:                                         'delete');
 4543:         }
 4544:     }
 4545:     return $result;
 4546: }
 4547: 
 4548: sub mkdiruserfile {
 4549:     my ($docuname,$docudom,$dir)=@_;
 4550:     my $home=&homeserver($docuname,$docudom);
 4551:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 4552: }
 4553: 
 4554: sub renameuserfile {
 4555:     my ($docuname,$docudom,$old,$new)=@_;
 4556:     my $home=&homeserver($docuname,$docudom);
 4557:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 4558:                         &escape("$old").':'.&escape("$new"),$home);
 4559:     if ($result eq 'ok') {
 4560:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 4561:             my $oldmeta = $old.'.meta';
 4562:             my $newmeta = $new.'.meta';
 4563:             my $metaresult = 
 4564:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 4565: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 4566:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 4567:             my $sqlresult = 
 4568:                 &update_portfolio_table($docuname,$docudom,$file,
 4569:                                         'portfolio_metadata',$group,
 4570:                                         'delete');
 4571:         }
 4572:     }
 4573:     return $result;
 4574: }
 4575: 
 4576: # ------------------------------------------------------------------------- Log
 4577: 
 4578: sub log {
 4579:     my ($dom,$nam,$hom,$what)=@_;
 4580:     return critical("log:$dom:$nam:$what",$hom);
 4581: }
 4582: 
 4583: # ------------------------------------------------------------------ Course Log
 4584: #
 4585: # This routine flushes several buffers of non-mission-critical nature
 4586: #
 4587: 
 4588: sub flushcourselogs {
 4589:     &logthis('Flushing log buffers');
 4590: #
 4591: # course logs
 4592: # This is a log of all transactions in a course, which can be used
 4593: # for data mining purposes
 4594: #
 4595: # It also collects the courseid database, which lists last transaction
 4596: # times and course titles for all courseids
 4597: #
 4598:     my %courseidbuffer=();
 4599:     foreach my $crsid (keys(%courselogs)) {
 4600:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 4601: 		          &escape($courselogs{$crsid}),
 4602: 		          $coursehombuf{$crsid}) eq 'ok') {
 4603: 	    delete $courselogs{$crsid};
 4604:         } else {
 4605:             &logthis('Failed to flush log buffer for '.$crsid);
 4606:             if (length($courselogs{$crsid})>40000) {
 4607:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 4608:                         " exceeded maximum size, deleting.</font>");
 4609:                delete $courselogs{$crsid};
 4610:             }
 4611:         }
 4612:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 4613:             'description' => $coursedescrbuf{$crsid},
 4614:             'inst_code'    => $courseinstcodebuf{$crsid},
 4615:             'type'        => $coursetypebuf{$crsid},
 4616:             'owner'       => $courseownerbuf{$crsid},
 4617:         };
 4618:     }
 4619: #
 4620: # Write course id database (reverse lookup) to homeserver of courses 
 4621: # Is used in pickcourse
 4622: #
 4623:     foreach my $crs_home (keys(%courseidbuffer)) {
 4624:         my $response = &courseidput(&host_domain($crs_home),
 4625:                                     $courseidbuffer{$crs_home},
 4626:                                     $crs_home,'timeonly');
 4627:     }
 4628: #
 4629: # File accesses
 4630: # Writes to the dynamic metadata of resources to get hit counts, etc.
 4631: #
 4632:     foreach my $entry (keys(%accesshash)) {
 4633:         if ($entry =~ /___count$/) {
 4634:             my ($dom,$name);
 4635:             ($dom,$name,undef)=
 4636: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 4637:             if (! defined($dom) || $dom eq '' || 
 4638:                 ! defined($name) || $name eq '') {
 4639:                 my $cid = $env{'request.course.id'};
 4640:                 $dom  = $env{'request.'.$cid.'.domain'};
 4641:                 $name = $env{'request.'.$cid.'.num'};
 4642:             }
 4643:             my $value = $accesshash{$entry};
 4644:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 4645:             my %temphash=($url => $value);
 4646:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 4647:             if ($result eq 'ok') {
 4648:                 delete $accesshash{$entry};
 4649:             }
 4650:         } else {
 4651:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 4652:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
 4653:             my %temphash=($entry => $accesshash{$entry});
 4654:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 4655:                 delete $accesshash{$entry};
 4656:             }
 4657:         }
 4658:     }
 4659: #
 4660: # Roles
 4661: # Reverse lookup of user roles for course faculty/staff and co-authorship
 4662: #
 4663:     foreach my $entry (keys(%userrolehash)) {
 4664:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 4665: 	    split(/\:/,$entry);
 4666:         if (&Apache::lonnet::put('nohist_userroles',
 4667:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 4668:                 $rudom,$runame) eq 'ok') {
 4669: 	    delete $userrolehash{$entry};
 4670:         }
 4671:     }
 4672: #
 4673: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
 4674: #
 4675:     my %domrolebuffer = ();
 4676:     foreach my $entry (keys(%domainrolehash)) {
 4677:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 4678:         if ($domrolebuffer{$rudom}) {
 4679:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 4680:                       '='.&escape($domainrolehash{$entry});
 4681:         } else {
 4682:             $domrolebuffer{$rudom}.=&escape($entry).
 4683:                       '='.&escape($domainrolehash{$entry});
 4684:         }
 4685:         delete $domainrolehash{$entry};
 4686:     }
 4687:     foreach my $dom (keys(%domrolebuffer)) {
 4688:         my %servers;
 4689:         if (defined(&domain($dom,'primary'))) {
 4690:             my $primary=&domain($dom,'primary');
 4691:             my $hostname=&hostname($primary);
 4692:             $servers{$primary} = $hostname;
 4693:         } else {
 4694:             %servers = &get_servers($dom,'library');
 4695:         }
 4696: 	foreach my $tryserver (keys(%servers)) {
 4697: 	    if (&reply('domroleput:'.$dom.':'.
 4698: 	               $domrolebuffer{$dom},$tryserver) eq 'ok') {
 4699: 	        last;
 4700: 	    } else {
 4701: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 4702: 	    }
 4703:         }
 4704:     }
 4705:     $dumpcount++;
 4706: }
 4707: 
 4708: sub courselog {
 4709:     my $what=shift;
 4710:     $what=time.':'.$what;
 4711:     unless ($env{'request.course.id'}) { return ''; }
 4712:     $coursedombuf{$env{'request.course.id'}}=
 4713:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 4714:     $coursenumbuf{$env{'request.course.id'}}=
 4715:        $env{'course.'.$env{'request.course.id'}.'.num'};
 4716:     $coursehombuf{$env{'request.course.id'}}=
 4717:        $env{'course.'.$env{'request.course.id'}.'.home'};
 4718:     $coursedescrbuf{$env{'request.course.id'}}=
 4719:        $env{'course.'.$env{'request.course.id'}.'.description'};
 4720:     $courseinstcodebuf{$env{'request.course.id'}}=
 4721:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 4722:     $courseownerbuf{$env{'request.course.id'}}=
 4723:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 4724:     $coursetypebuf{$env{'request.course.id'}}=
 4725:        $env{'course.'.$env{'request.course.id'}.'.type'};
 4726:     if (defined $courselogs{$env{'request.course.id'}}) {
 4727: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 4728:     } else {
 4729: 	$courselogs{$env{'request.course.id'}}.=$what;
 4730:     }
 4731:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 4732: 	&flushcourselogs();
 4733:     }
 4734: }
 4735: 
 4736: sub courseacclog {
 4737:     my $fnsymb=shift;
 4738:     unless ($env{'request.course.id'}) { return ''; }
 4739:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 4740:     if ($fnsymb=~/$LONCAPA::assess_re/) {
 4741:         $what.=':POST';
 4742:         # FIXME: Probably ought to escape things....
 4743: 	foreach my $key (keys(%env)) {
 4744:             if ($key=~/^form\.(.*)/) {
 4745:                 my $formitem = $1;
 4746:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 4747:                     $what.=':'.$formitem.'='.$env{$key};
 4748:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 4749:                     if ($formitem eq 'proctorpassword') {
 4750:                         $what.=':'.$formitem.'=' . '*' x length($env{$key});
 4751:                     } else {
 4752:                         $what.=':'.$formitem.'='.$env{$key};
 4753:                     }
 4754:                 }
 4755:             }
 4756:         }
 4757:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 4758:         # FIXME: We should not be depending on a form parameter that someone
 4759:         # editing lonsearchcat.pm might change in the future.
 4760:         if ($env{'form.phase'} eq 'course_search') {
 4761:             $what.= ':POST';
 4762:             # FIXME: Probably ought to escape things....
 4763:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 4764:                                  'crsdiscuss') {
 4765:                 $what.=':'.$element.'='.$env{'form.'.$element};
 4766:             }
 4767:         }
 4768:     }
 4769:     &courselog($what);
 4770: }
 4771: 
 4772: sub countacc {
 4773:     my $url=&declutter(shift);
 4774:     return if (! defined($url) || $url eq '');
 4775:     unless ($env{'request.course.id'}) { return ''; }
 4776: #
 4777: # Mark that this url was used in this course
 4778: #
 4779:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 4780: #
 4781: # Increase the access count for this resource in this child process
 4782: #
 4783:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 4784:     $accesshash{$key}++;
 4785: }
 4786: 
 4787: sub linklog {
 4788:     my ($from,$to)=@_;
 4789:     $from=&declutter($from);
 4790:     $to=&declutter($to);
 4791:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 4792:     $accesshash{$to.'___'.$from.'___goto'}=1;
 4793: }
 4794: 
 4795: sub statslog {
 4796:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
 4797:     if ($users<2) { return; }
 4798:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
 4799:             'course'       => $env{'request.course.id'},
 4800:             'sections'     => '"all"',
 4801:             'num_students' => $users,
 4802:             'part'         => $part,
 4803:             'symb'         => $symb,
 4804:             'mean_tries'   => $av_attempts,
 4805:             'deg_of_diff'  => $degdiff});
 4806:     foreach my $key (keys(%dynstore)) {
 4807:         $accesshash{$key}=$dynstore{$key};
 4808:     }
 4809: }
 4810:   
 4811: sub userrolelog {
 4812:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 4813:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
 4814:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 4815:        $userrolehash
 4816:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 4817:                     =$tend.':'.$tstart;
 4818:     }
 4819:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
 4820:        $userrolehash
 4821:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 4822:                     =$tend.':'.$tstart;
 4823:     }
 4824:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
 4825:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 4826:        $domainrolehash
 4827:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 4828:                     = $tend.':'.$tstart;
 4829:     }
 4830: }
 4831: 
 4832: sub courserolelog {
 4833:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 4834:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 4835:         my $cdom = $1;
 4836:         my $cnum = $2;
 4837:         my $sec = $3;
 4838:         my $namespace = 'rolelog';
 4839:         my %storehash = (
 4840:                            role    => $trole,
 4841:                            start   => $tstart,
 4842:                            end     => $tend,
 4843:                            selfenroll => $selfenroll,
 4844:                            context    => $context,
 4845:                         );
 4846:         if ($trole eq 'gr') {
 4847:             $namespace = 'groupslog';
 4848:             $storehash{'group'} = $sec;
 4849:         } else {
 4850:             $storehash{'section'} = $sec;
 4851:         }
 4852:         &write_log('course',$namespace,\%storehash,$delflag,$username,
 4853:                    $domain,$cnum,$cdom);
 4854:         if (($trole ne 'st') || ($sec ne '')) {
 4855:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 4856:         }
 4857:     }
 4858:     return;
 4859: }
 4860: 
 4861: sub domainrolelog {
 4862:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 4863:     if ($area =~ m{^/($match_domain)/$}) {
 4864:         my $cdom = $1;
 4865:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
 4866:         my $namespace = 'rolelog';
 4867:         my %storehash = (
 4868:                            role    => $trole,
 4869:                            start   => $tstart,
 4870:                            end     => $tend,
 4871:                            context => $context,
 4872:                         );
 4873:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
 4874:                    $domain,$domconfiguser,$cdom);
 4875:     }
 4876:     return;
 4877: 
 4878: }
 4879: 
 4880: sub coauthorrolelog {
 4881:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 4882:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
 4883:         my $audom = $1;
 4884:         my $auname = $2;
 4885:         my $namespace = 'rolelog';
 4886:         my %storehash = (
 4887:                            role    => $trole,
 4888:                            start   => $tstart,
 4889:                            end     => $tend,
 4890:                            context => $context,
 4891:                         );
 4892:         &write_log('author',$namespace,\%storehash,$delflag,$username,
 4893:                    $domain,$auname,$audom);
 4894:     }
 4895:     return;
 4896: }
 4897: 
 4898: sub get_course_adv_roles {
 4899:     my ($cid,$codes) = @_;
 4900:     $cid=$env{'request.course.id'} unless (defined($cid));
 4901:     my %coursehash=&coursedescription($cid);
 4902:     my $crstype = &Apache::loncommon::course_type($cid);
 4903:     my %nothide=();
 4904:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 4905:         if ($user !~ /:/) {
 4906: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 4907:         } else {
 4908:             $nothide{$user}=1;
 4909:         }
 4910:     }
 4911:     my @possdoms = ($coursehash{'domain'});
 4912:     if ($coursehash{'checkforpriv'}) {
 4913:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
 4914:     }
 4915:     my %returnhash=();
 4916:     my %dumphash=
 4917:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 4918:     my $now=time;
 4919:     my %privileged;
 4920:     foreach my $entry (keys(%dumphash)) {
 4921: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 4922:         if (($tstart) && ($tstart<0)) { next; }
 4923:         if (($tend) && ($tend<$now)) { next; }
 4924:         if (($tstart) && ($now<$tstart)) { next; }
 4925:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 4926: 	if ($username eq '' || $domain eq '') { next; }
 4927:         if ((&privileged($username,$domain,\@possdoms)) &&
 4928:             (!$nothide{$username.':'.$domain})) { next; }
 4929: 	if ($role eq 'cr') { next; }
 4930:         if ($codes) {
 4931:             if ($section) { $role .= ':'.$section; }
 4932:             if ($returnhash{$role}) {
 4933:                 $returnhash{$role}.=','.$username.':'.$domain;
 4934:             } else {
 4935:                 $returnhash{$role}=$username.':'.$domain;
 4936:             }
 4937:         } else {
 4938:             my $key=&plaintext($role,$crstype);
 4939:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 4940:             if ($returnhash{$key}) {
 4941: 	        $returnhash{$key}.=','.$username.':'.$domain;
 4942:             } else {
 4943:                 $returnhash{$key}=$username.':'.$domain;
 4944:             }
 4945:         }
 4946:     }
 4947:     return %returnhash;
 4948: }
 4949: 
 4950: sub get_my_roles {
 4951:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 4952:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 4953:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 4954:     my (%dumphash,%nothide);
 4955:     if ($context eq 'userroles') {
 4956:         %dumphash = &dump('roles',$udom,$uname);
 4957:     } else {
 4958:         %dumphash = &dump('nohist_userroles',$udom,$uname);
 4959:         if ($hidepriv) {
 4960:             my %coursehash=&coursedescription($udom.'_'.$uname);
 4961:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 4962:                 if ($user !~ /:/) {
 4963:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 4964:                 } else {
 4965:                     $nothide{$user} = 1;
 4966:                 }
 4967:             }
 4968:         }
 4969:     }
 4970:     my %returnhash=();
 4971:     my $now=time;
 4972:     my %privileged;
 4973:     foreach my $entry (keys(%dumphash)) {
 4974:         my ($role,$tend,$tstart);
 4975:         if ($context eq 'userroles') {
 4976:             next if ($entry =~ /^rolesdef/);
 4977: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 4978:         } else {
 4979:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 4980:         }
 4981:         if (($tstart) && ($tstart<0)) { next; }
 4982:         my $status = 'active';
 4983:         if (($tend) && ($tend<=$now)) {
 4984:             $status = 'previous';
 4985:         } 
 4986:         if (($tstart) && ($now<$tstart)) {
 4987:             $status = 'future';
 4988:         }
 4989:         if (ref($types) eq 'ARRAY') {
 4990:             if (!grep(/^\Q$status\E$/,@{$types})) {
 4991:                 next;
 4992:             } 
 4993:         } else {
 4994:             if ($status ne 'active') {
 4995:                 next;
 4996:             }
 4997:         }
 4998:         my ($rolecode,$username,$domain,$section,$area);
 4999:         if ($context eq 'userroles') {
 5000:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
 5001:             (undef,$domain,$username,$section) = split(/\//,$area);
 5002:         } else {
 5003:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 5004:         }
 5005:         if (ref($roledoms) eq 'ARRAY') {
 5006:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 5007:                 next;
 5008:             }
 5009:         }
 5010:         if (ref($roles) eq 'ARRAY') {
 5011:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 5012:                 if ($role =~ /^cr\//) {
 5013:                     if (!grep(/^cr$/,@{$roles})) {
 5014:                         next;
 5015:                     }
 5016:                 } elsif ($role =~ /^gr\//) {
 5017:                     if (!grep(/^gr$/,@{$roles})) {
 5018:                         next;
 5019:                     }
 5020:                 } else {
 5021:                     next;
 5022:                 }
 5023:             }
 5024:         }
 5025:         if ($hidepriv) {
 5026:             my @privroles = ('dc','su');
 5027:             if ($context eq 'userroles') {
 5028:                 next if (grep(/^\Q$role\E$/,@privroles));
 5029:             } else {
 5030:                 my $possdoms = [$domain];
 5031:                 if (ref($roledoms) eq 'ARRAY') {
 5032:                    push(@{$possdoms},@{$roledoms});
 5033:                 }
 5034:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
 5035:                     if (!$nothide{$username.':'.$domain}) {
 5036:                         next;
 5037:                     }
 5038:                 }
 5039:             }
 5040:         }
 5041:         if ($withsec) {
 5042:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 5043:                 $tstart.':'.$tend;
 5044:         } else {
 5045:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 5046:         }
 5047:     }
 5048:     return %returnhash;
 5049: }
 5050: 
 5051: sub get_all_adhocroles {
 5052:     my ($dom) = @_;
 5053:     my @roles_by_num = ();
 5054:     my %domdefaults = &get_domain_defaults($dom);
 5055:     my (%description,%access_in_dom,%access_info);
 5056:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
 5057:         my $count = 0;
 5058:         my %domcurrent = %{$domdefaults{'adhocroles'}};
 5059:         my %ordered;
 5060:         foreach my $role (sort(keys(%domcurrent))) {
 5061:             my ($order,$desc,$access_in_dom);
 5062:             if (ref($domcurrent{$role}) eq 'HASH') {
 5063:                 $order = $domcurrent{$role}{'order'};
 5064:                 $desc = $domcurrent{$role}{'desc'};
 5065:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
 5066:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
 5067:             }
 5068:             if ($order eq '') {
 5069:                 $order = $count;
 5070:             }
 5071:             $ordered{$order} = $role;
 5072:             if ($desc ne '') {
 5073:                 $description{$role} = $desc;
 5074:             } else {
 5075:                 $description{$role}= $role;
 5076:             }
 5077:             $count++;
 5078:         }
 5079:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 5080:             push(@roles_by_num,$ordered{$item});
 5081:         }
 5082:     }
 5083:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
 5084: }
 5085: 
 5086: sub get_my_adhocroles {
 5087:     my ($cid,$checkreg) = @_;
 5088:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
 5089:     if ($env{'request.course.id'} eq $cid) {
 5090:         $cdom = $env{'course.'.$cid.'.domain'};
 5091:         $cnum = $env{'course.'.$cid.'.num'};
 5092:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
 5093:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
 5094:         $cdom = $1;
 5095:         $cnum = $2;
 5096:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
 5097:                                      $cdom,$cnum);
 5098:     }
 5099:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
 5100:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
 5101:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
 5102:         if ($rosterhash{$user} ne '') {
 5103:             my $type = (split(/:/,$rosterhash{$user}))[5];
 5104:             return ([],{}) if ($type eq 'auto');
 5105:         }
 5106:     }
 5107:     if (($cdom ne '') && ($cnum ne ''))  {
 5108:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
 5109:             my $then=$env{'user.login.time'};
 5110:             my $update=$env{'user.update.time'};
 5111:             if (!$update) {
 5112:                 $update = $then;
 5113:             }
 5114:             my @liveroles;
 5115:             foreach my $role ('dh','da') {
 5116:                 if ($env{"user.role.$role./$cdom/"}) {
 5117:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
 5118:                     my $limit = $update;
 5119:                     if ($env{'request.role'} eq "$role./$cdom/") {
 5120:                         $limit = $then;
 5121:                     }
 5122:                     my $activerole = 1;
 5123:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
 5124:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
 5125:                     if ($activerole) {
 5126:                         push(@liveroles,$role);
 5127:                     }
 5128:                 }
 5129:             }
 5130:             if (@liveroles) {
 5131:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
 5132:                     my ($accessref,$accessinfo,%access_in_dom);
 5133:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
 5134:                     if (ref($roles_by_num) eq 'ARRAY') {
 5135:                         if (@{$roles_by_num}) {
 5136:                             my %settings;
 5137:                             if ($env{'request.course.id'} eq $cid) {
 5138:                                 foreach my $envkey (keys(%env)) {
 5139:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
 5140:                                         $settings{$1} = $env{$envkey};
 5141:                                     }
 5142:                                 }
 5143:                             } else {
 5144:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
 5145:                             }
 5146:                             my %setincrs;
 5147:                             if ($settings{'internal.adhocaccess'}) {
 5148:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
 5149:                             }
 5150:                             my @statuses;
 5151:                             if ($env{'environment.inststatus'}) {
 5152:                                 @statuses = split(/,/,$env{'environment.inststatus'});
 5153:                             }
 5154:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
 5155:                             if (ref($accessref) eq 'HASH') {
 5156:                                 %access_in_dom = %{$accessref};
 5157:                             }
 5158:                             foreach my $role (@{$roles_by_num}) {
 5159:                                 my ($curraccess,@okstatus,@personnel);
 5160:                                 if ($setincrs{$role}) {
 5161:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
 5162:                                     if ($curraccess eq 'status') {
 5163:                                         @okstatus = split(/\&/,$rest);
 5164:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5165:                                         @personnel = split(/\&/,$rest);
 5166:                                     }
 5167:                                 } else {
 5168:                                     $curraccess = $access_in_dom{$role};
 5169:                                     if (ref($accessinfo) eq 'HASH') {
 5170:                                         if ($curraccess eq 'status') {
 5171:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
 5172:                                                 @okstatus = @{$accessinfo->{$role}};
 5173:                                             }
 5174:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5175:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
 5176:                                                 @personnel = @{$accessinfo->{$role}};
 5177:                                             }
 5178:                                         }
 5179:                                     }
 5180:                                 }
 5181:                                 if ($curraccess eq 'none') {
 5182:                                     next;
 5183:                                 } elsif ($curraccess eq 'all') {
 5184:                                     push(@possroles,$role);
 5185:                                 } elsif ($curraccess eq 'dh') {
 5186:                                     if (grep(/^dh$/,@liveroles)) {
 5187:                                         push(@possroles,$role);
 5188:                                     } else {
 5189:                                         next;
 5190:                                     }
 5191:                                 } elsif ($curraccess eq 'da') {
 5192:                                     if (grep(/^da$/,@liveroles)) {
 5193:                                         push(@possroles,$role);
 5194:                                     } else {
 5195:                                         next;
 5196:                                     }
 5197:                                 } elsif ($curraccess eq 'status') {
 5198:                                     if (@okstatus) {
 5199:                                         if (!@statuses) {
 5200:                                             if (grep(/^default$/,@okstatus)) {
 5201:                                                 push(@possroles,$role);
 5202:                                             }
 5203:                                         } else {
 5204:                                             foreach my $status (@okstatus) {
 5205:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
 5206:                                                     push(@possroles,$role);
 5207:                                                     last;
 5208:                                                 }
 5209:                                             }
 5210:                                         }
 5211:                                     }
 5212:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5213:                                     if (grep(/^\Q$user\E$/,@personnel)) {
 5214:                                         if ($curraccess eq 'exc') {
 5215:                                             push(@possroles,$role);
 5216:                                         }
 5217:                                     } elsif ($curraccess eq 'inc') {
 5218:                                         push(@possroles,$role);
 5219:                                     }
 5220:                                 }
 5221:                             }
 5222:                         }
 5223:                     }
 5224:                 }
 5225:             }
 5226:         }
 5227:     }
 5228:     unless (ref($description) eq 'HASH') {
 5229:         if (ref($roles_by_num) eq 'ARRAY') {
 5230:             my %desc;
 5231:             map { $desc{$_} = $_; } (@{$roles_by_num});
 5232:             $description = \%desc;
 5233:         } else {
 5234:             $description = {};
 5235:         }
 5236:     }
 5237:     return (\@possroles,$description);
 5238: }
 5239: 
 5240: # ----------------------------------------------------- Frontpage Announcements
 5241: #
 5242: #
 5243: 
 5244: sub postannounce {
 5245:     my ($server,$text)=@_;
 5246:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 5247:     unless ($text=~/\w/) { $text=''; }
 5248:     return &reply('setannounce:'.&escape($text),$server);
 5249: }
 5250: 
 5251: sub getannounce {
 5252: 
 5253:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 5254: 	my $announcement='';
 5255: 	while (my $line = <$fh>) { $announcement .= $line; }
 5256: 	close($fh);
 5257: 	if ($announcement=~/\w/) { 
 5258: 	    return 
 5259:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 5260:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 5261: 	} else {
 5262: 	    return '';
 5263: 	}
 5264:     } else {
 5265: 	return '';
 5266:     }
 5267: }
 5268: 
 5269: # ---------------------------------------------------------- Course ID routines
 5270: # Deal with domain's nohist_courseid.db files
 5271: #
 5272: 
 5273: sub courseidput {
 5274:     my ($domain,$storehash,$coursehome,$caller) = @_;
 5275:     return unless (ref($storehash) eq 'HASH');
 5276:     my $outcome;
 5277:     if ($caller eq 'timeonly') {
 5278:         my $cids = '';
 5279:         foreach my $item (keys(%$storehash)) {
 5280:             $cids.=&escape($item).'&';
 5281:         }
 5282:         $cids=~s/\&$//;
 5283:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 5284:                           $coursehome);       
 5285:     } else {
 5286:         my $items = '';
 5287:         foreach my $item (keys(%$storehash)) {
 5288:             $items.= &escape($item).'='.
 5289:                      &freeze_escape($$storehash{$item}).'&';
 5290:         }
 5291:         $items=~s/\&$//;
 5292:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 5293:                           $coursehome);
 5294:     }
 5295:     if ($outcome eq 'unknown_cmd') {
 5296:         my $what;
 5297:         foreach my $cid (keys(%$storehash)) {
 5298:             $what .= &escape($cid).'=';
 5299:             foreach my $item ('description','inst_code','owner','type') {
 5300:                 $what .= &escape($storehash->{$cid}{$item}).':';
 5301:             }
 5302:             $what =~ s/\:$/&/;
 5303:         }
 5304:         $what =~ s/\&$//;  
 5305:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 5306:     } else {
 5307:         return $outcome;
 5308:     }
 5309: }
 5310: 
 5311: sub courseiddump {
 5312:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 5313:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 5314:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
 5315:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
 5316:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
 5317:     my $as_hash = 1;
 5318:     my %returnhash;
 5319:     if (!$domfilter) { $domfilter=''; }
 5320:     my %libserv = &all_library();
 5321:     foreach my $tryserver (keys(%libserv)) {
 5322:         if ( (  $hostidflag == 1 
 5323: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 5324: 	     || (!defined($hostidflag)) ) {
 5325: 
 5326: 	    if (($domfilter eq '') ||
 5327: 		(&host_domain($tryserver) eq $domfilter)) {
 5328:                 my $rep;
 5329:                 if (grep { $_ eq $tryserver } &current_machine_ids()) {
 5330:                     $rep = &LONCAPA::Lond::dump_course_id_handler(
 5331:                         join(":", (&host_domain($tryserver), $sincefilter,
 5332:                                 &escape($descfilter), &escape($instcodefilter),
 5333:                                 &escape($ownerfilter), &escape($coursefilter),
 5334:                                 &escape($typefilter), &escape($regexp_ok),
 5335:                                 $as_hash, &escape($selfenrollonly),
 5336:                                 &escape($catfilter), $showhidden, $caller,
 5337:                                 &escape($cloner), &escape($cc_clone), $cloneonly,
 5338:                                 &escape($createdbefore), &escape($createdafter),
 5339:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
 5340:                                 $reqcrsdom,&escape($reqinstcode))));
 5341:                 } else {
 5342:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
 5343:                              $sincefilter.':'.&escape($descfilter).':'.
 5344:                              &escape($instcodefilter).':'.&escape($ownerfilter).
 5345:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
 5346:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
 5347:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
 5348:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
 5349:                              &escape($cc_clone).':'.$cloneonly.':'.
 5350:                              &escape($createdbefore).':'.&escape($createdafter).':'.
 5351:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
 5352:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
 5353:                 }
 5354: 
 5355:                 my @pairs=split(/\&/,$rep);
 5356:                 foreach my $item (@pairs) {
 5357:                     my ($key,$value)=split(/\=/,$item,2);
 5358:                     $key = &unescape($key);
 5359:                     next if ($key =~ /^error: 2 /);
 5360:                     my $result = &thaw_unescape($value);
 5361:                     if (ref($result) eq 'HASH') {
 5362:                         $returnhash{$key}=$result;
 5363:                     } else {
 5364:                         my @responses = split(/:/,$value);
 5365:                         my @items = ('description','inst_code','owner','type');
 5366:                         for (my $i=0; $i<@responses; $i++) {
 5367:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 5368:                         }
 5369:                     }
 5370:                 }
 5371:             }
 5372:         }
 5373:     }
 5374:     return %returnhash;
 5375: }
 5376: 
 5377: sub courselastaccess {
 5378:     my ($cdom,$cnum,$hostidref) = @_;
 5379:     my %returnhash;
 5380:     if ($cdom && $cnum) {
 5381:         my $chome = &homeserver($cnum,$cdom);
 5382:         if ($chome ne 'no_host') {
 5383:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
 5384:             &extract_lastaccess(\%returnhash,$rep);
 5385:         }
 5386:     } else {
 5387:         if (!$cdom) { $cdom=''; }
 5388:         my %libserv = &all_library();
 5389:         foreach my $tryserver (keys(%libserv)) {
 5390:             if (ref($hostidref) eq 'ARRAY') {
 5391:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
 5392:             } 
 5393:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
 5394:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
 5395:                 &extract_lastaccess(\%returnhash,$rep);
 5396:             }
 5397:         }
 5398:     }
 5399:     return %returnhash;
 5400: }
 5401: 
 5402: sub extract_lastaccess {
 5403:     my ($returnhash,$rep) = @_;
 5404:     if (ref($returnhash) eq 'HASH') {
 5405:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
 5406:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
 5407:                  $rep eq '') {
 5408:             my @pairs=split(/\&/,$rep);
 5409:             foreach my $item (@pairs) {
 5410:                 my ($key,$value)=split(/\=/,$item,2);
 5411:                 $key = &unescape($key);
 5412:                 next if ($key =~ /^error: 2 /);
 5413:                 $returnhash->{$key} = &thaw_unescape($value);
 5414:             }
 5415:         }
 5416:     }
 5417:     return;
 5418: }
 5419: 
 5420: # ---------------------------------------------------------- DC e-mail
 5421: 
 5422: sub dcmailput {
 5423:     my ($domain,$msgid,$message,$server)=@_;
 5424:     my $status = &Apache::lonnet::critical(
 5425:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 5426:        &escape($message),$server);
 5427:     return $status;
 5428: }
 5429: 
 5430: sub dcmaildump {
 5431:     my ($dom,$startdate,$enddate,$senders) = @_;
 5432:     my %returnhash=();
 5433: 
 5434:     if (defined(&domain($dom,'primary'))) {
 5435:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 5436:                                                          &escape($enddate).':';
 5437: 	my @esc_senders=map { &escape($_)} @$senders;
 5438: 	$cmd.=&escape(join('&',@esc_senders));
 5439: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 5440:             my ($key,$value) = split(/\=/,$line,2);
 5441:             if (($key) && ($value)) {
 5442:                 $returnhash{&unescape($key)} = &unescape($value);
 5443:             }
 5444:         }
 5445:     }
 5446:     return %returnhash;
 5447: }
 5448: # ---------------------------------------------------------- Domain roles
 5449: 
 5450: sub get_domain_roles {
 5451:     my ($dom,$roles,$startdate,$enddate)=@_;
 5452:     if ((!defined($startdate)) || ($startdate eq '')) {
 5453:         $startdate = '.';
 5454:     }
 5455:     if ((!defined($enddate)) || ($enddate eq '')) {
 5456:         $enddate = '.';
 5457:     }
 5458:     my $rolelist;
 5459:     if (ref($roles) eq 'ARRAY') {
 5460:         $rolelist = join('&',@{$roles});
 5461:     }
 5462:     my %personnel = ();
 5463: 
 5464:     my %servers = &get_servers($dom,'library');
 5465:     foreach my $tryserver (keys(%servers)) {
 5466: 	%{$personnel{$tryserver}}=();
 5467: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 5468: 					    &escape($startdate).':'.
 5469: 					    &escape($enddate).':'.
 5470: 					    &escape($rolelist), $tryserver))) {
 5471: 	    my ($key,$value) = split(/\=/,$line,2);
 5472: 	    if (($key) && ($value)) {
 5473: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 5474: 	    }
 5475: 	}
 5476:     }
 5477:     return %personnel;
 5478: }
 5479: 
 5480: sub get_active_domroles {
 5481:     my ($dom,$roles) = @_;
 5482:     return () unless (ref($roles) eq 'ARRAY');
 5483:     my $now = time;
 5484:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
 5485:     my %domroles;
 5486:     foreach my $server (keys(%dompersonnel)) {
 5487:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
 5488:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
 5489:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
 5490:         }
 5491:     }
 5492:     return %domroles;
 5493: }
 5494: 
 5495: # ----------------------------------------------------------- Interval timing 
 5496: 
 5497: {
 5498: # Caches needed for speedup of navmaps
 5499: # We don't want to cache this for very long at all (5 seconds at most)
 5500: # 
 5501: # The user for whom we cache
 5502: my $cachedkey='';
 5503: # The cached times for this user
 5504: my %cachedtimes=();
 5505: # When this was last done
 5506: my $cachedtime='';
 5507: 
 5508: sub load_all_first_access {
 5509:     my ($uname,$udom,$ignorecache)=@_;
 5510:     if (($cachedkey eq $uname.':'.$udom) &&
 5511:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
 5512:         (!$ignorecache)) {
 5513:         return;
 5514:     }
 5515:     $cachedtime=time;
 5516:     $cachedkey=$uname.':'.$udom;
 5517:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
 5518: }
 5519: 
 5520: sub get_first_access {
 5521:     my ($type,$argsymb,$argmap,$ignorecache)=@_;
 5522:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 5523:     if ($argsymb) { $symb=$argsymb; }
 5524:     my ($map,$id,$res)=&decode_symb($symb);
 5525:     if ($argmap) { $map = $argmap; }
 5526:     if ($type eq 'course') {
 5527: 	$res='course';
 5528:     } elsif ($type eq 'map') {
 5529: 	$res=&symbread($map);
 5530:     } else {
 5531: 	$res=$symb;
 5532:     }
 5533:     &load_all_first_access($uname,$udom,$ignorecache);
 5534:     return $cachedtimes{"$courseid\0$res"};
 5535: }
 5536: 
 5537: sub set_first_access {
 5538:     my ($type,$interval)=@_;
 5539:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 5540:     my ($map,$id,$res)=&decode_symb($symb);
 5541:     if ($type eq 'course') {
 5542: 	$res='course';
 5543:     } elsif ($type eq 'map') {
 5544: 	$res=&symbread($map);
 5545:     } else {
 5546: 	$res=$symb;
 5547:     }
 5548:     $cachedkey='';
 5549:     my $firstaccess=&get_first_access($type,$symb,$map);
 5550:     if ($firstaccess) {
 5551:         &logthis("First access time already set ($firstaccess) when attempting ".
 5552:                  "to set new value (type: $type, extent: $res) for $uname:$udom ".
 5553:                  "in $courseid");
 5554:         return 'already_set';
 5555:     } else {
 5556:         my $start = time;
 5557: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
 5558:                           $udom,$uname);
 5559:         if ($putres eq 'ok') {
 5560:             &put('timerinterval',{"$courseid\0$res"=>$interval},
 5561:                  $udom,$uname); 
 5562:             &appenv(
 5563:                      {
 5564:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
 5565:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
 5566:                      }
 5567:                   );
 5568:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
 5569:                 $cachedtimes{"$courseid\0$res"} = $start;
 5570:             }
 5571:         } elsif ($putres ne 'refused') {
 5572:             &logthis("Result: $putres when attempting to set first access time ".
 5573:                      "(type: $type, extent: $res) for $uname:$udom in $courseid");
 5574:         }
 5575:         return $putres;
 5576:     }
 5577:     return 'already_set';
 5578: }
 5579: }
 5580: 
 5581: sub checkout {
 5582:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
 5583:     my $now=time;
 5584:     my $lonhost=$perlvar{'lonHostID'};
 5585:     my $ip = &get_requestor_ip();
 5586:     my $infostr=&escape(
 5587:                  'CHECKOUTTOKEN&'.
 5588:                  $tuname.'&'.
 5589:                  $tudom.'&'.
 5590:                  $tcrsid.'&'.
 5591:                  $symb.'&'.
 5592:                  $now.'&'.$ip);
 5593:     my $token=&reply('tmpput:'.$infostr,$lonhost);
 5594:     if ($token=~/^error\:/) {
 5595:         &logthis("<font color=\"blue\">WARNING: ".
 5596:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
 5597:                  "</font>");
 5598:         return '';
 5599:     }
 5600: 
 5601:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
 5602:     $token=~tr/a-z/A-Z/;
 5603: 
 5604:     my %infohash=('resource.0.outtoken' => $token,
 5605:                   'resource.0.checkouttime' => $now,
 5606:                   'resource.0.outremote' => $ip);
 5607: 
 5608:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 5609:        return '';
 5610:     } else {
 5611:         &logthis("<font color=\"blue\">WARNING: ".
 5612:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
 5613:                  "</font>");
 5614:     }
 5615: 
 5616:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 5617:                          &escape('Checkout '.$infostr.' - '.
 5618:                                                  $token)) ne 'ok') {
 5619:         return '';
 5620:     } else {
 5621:         &logthis("<font color=\"blue\">WARNING: ".
 5622:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
 5623:                  "</font>");
 5624:     }
 5625:     return $token;
 5626: }
 5627: 
 5628: # ------------------------------------------------------------ Check in an item
 5629: 
 5630: sub checkin {
 5631:     my $token=shift;
 5632:     my $now=time;
 5633:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
 5634:     $lonhost=~tr/A-Z/a-z/;
 5635:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
 5636:     $dtoken=~s/\W/\_/g;
 5637:     my $ip = &get_requestor_ip();
 5638:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
 5639:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
 5640: 
 5641:     unless (($tuname) && ($tudom)) {
 5642:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
 5643:         return '';
 5644:     }
 5645: 
 5646:     unless (&allowed('mgr',$tcrsid)) {
 5647:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
 5648:                  $env{'user.name'}.' - '.$env{'user.domain'});
 5649:         return '';
 5650:     }
 5651: 
 5652:     my %infohash=('resource.0.intoken' => $token,
 5653:                   'resource.0.checkintime' => $now,
 5654:                   'resource.0.inremote' => $ip);
 5655: 
 5656:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 5657:        return '';
 5658:     }
 5659: 
 5660:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 5661:                          &escape('Checkin - '.$token)) ne 'ok') {
 5662:         return '';
 5663:     }
 5664: 
 5665:     return ($symb,$tuname,$tudom,$tcrsid);
 5666: }
 5667: 
 5668: # --------------------------------------------- Set Expire Date for Spreadsheet
 5669: 
 5670: sub expirespread {
 5671:     my ($uname,$udom,$stype,$usymb)=@_;
 5672:     my $cid=$env{'request.course.id'}; 
 5673:     if ($cid) {
 5674:        my $now=time;
 5675:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 5676:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 5677:                             $env{'course.'.$cid.'.num'}.
 5678: 	        	    ':nohist_expirationdates:'.
 5679:                             &escape($key).'='.$now,
 5680:                             $env{'course.'.$cid.'.home'})
 5681:     }
 5682:     return 'ok';
 5683: }
 5684: 
 5685: # ----------------------------------------------------- Devalidate Spreadsheets
 5686: 
 5687: sub devalidate {
 5688:     my ($symb,$uname,$udom)=@_;
 5689:     my $cid=$env{'request.course.id'}; 
 5690:     if ($cid) {
 5691:         # delete the stored spreadsheets for
 5692:         # - the student level sheet of this user in course's homespace
 5693:         # - the assessment level sheet for this resource 
 5694:         #   for this user in user's homespace
 5695: 	# - current conditional state info
 5696: 	my $key=$uname.':'.$udom.':';
 5697:         my $status=
 5698: 	    &del('nohist_calculatedsheets',
 5699: 		 [$key.'studentcalc:'],
 5700: 		 $env{'course.'.$cid.'.domain'},
 5701: 		 $env{'course.'.$cid.'.num'})
 5702: 		.' '.
 5703: 	    &del('nohist_calculatedsheets_'.$cid,
 5704: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 5705:         unless ($status eq 'ok ok') {
 5706:            &logthis('Could not devalidate spreadsheet '.
 5707:                     $uname.' at '.$udom.' for '.
 5708: 		    $symb.': '.$status);
 5709:         }
 5710: 	&delenv('user.state.'.$cid);
 5711:     }
 5712: }
 5713: 
 5714: sub get_scalar {
 5715:     my ($string,$end) = @_;
 5716:     my $value;
 5717:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 5718: 	$value = $1;
 5719:     } elsif ($$string =~ s/^([^&]*?)&//) {
 5720: 	$value = $1;
 5721:     }
 5722:     return &unescape($value);
 5723: }
 5724: 
 5725: sub array2str {
 5726:   my (@array) = @_;
 5727:   my $result=&arrayref2str(\@array);
 5728:   $result=~s/^__ARRAY_REF__//;
 5729:   $result=~s/__END_ARRAY_REF__$//;
 5730:   return $result;
 5731: }
 5732: 
 5733: sub arrayref2str {
 5734:   my ($arrayref) = @_;
 5735:   my $result='__ARRAY_REF__';
 5736:   foreach my $elem (@$arrayref) {
 5737:     if(ref($elem) eq 'ARRAY') {
 5738:       $result.=&arrayref2str($elem).'&';
 5739:     } elsif(ref($elem) eq 'HASH') {
 5740:       $result.=&hashref2str($elem).'&';
 5741:     } elsif(ref($elem)) {
 5742:       #print("Got a ref of ".(ref($elem))." skipping.");
 5743:     } else {
 5744:       $result.=&escape($elem).'&';
 5745:     }
 5746:   }
 5747:   $result=~s/\&$//;
 5748:   $result .= '__END_ARRAY_REF__';
 5749:   return $result;
 5750: }
 5751: 
 5752: sub hash2str {
 5753:   my (%hash) = @_;
 5754:   my $result=&hashref2str(\%hash);
 5755:   $result=~s/^__HASH_REF__//;
 5756:   $result=~s/__END_HASH_REF__$//;
 5757:   return $result;
 5758: }
 5759: 
 5760: sub hashref2str {
 5761:   my ($hashref)=@_;
 5762:   my $result='__HASH_REF__';
 5763:   foreach my $key (sort(keys(%$hashref))) {
 5764:     if (ref($key) eq 'ARRAY') {
 5765:       $result.=&arrayref2str($key).'=';
 5766:     } elsif (ref($key) eq 'HASH') {
 5767:       $result.=&hashref2str($key).'=';
 5768:     } elsif (ref($key)) {
 5769:       $result.='=';
 5770:       #print("Got a ref of ".(ref($key))." skipping.");
 5771:     } else {
 5772: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
 5773:     }
 5774: 
 5775:     if(ref($hashref->{$key}) eq 'ARRAY') {
 5776:       $result.=&arrayref2str($hashref->{$key}).'&';
 5777:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 5778:       $result.=&hashref2str($hashref->{$key}).'&';
 5779:     } elsif(ref($hashref->{$key})) {
 5780:        $result.='&';
 5781:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 5782:     } else {
 5783:       $result.=&escape($hashref->{$key}).'&';
 5784:     }
 5785:   }
 5786:   $result=~s/\&$//;
 5787:   $result .= '__END_HASH_REF__';
 5788:   return $result;
 5789: }
 5790: 
 5791: sub str2hash {
 5792:     my ($string)=@_;
 5793:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 5794:     return %$hash;
 5795: }
 5796: 
 5797: sub str2hashref {
 5798:   my ($string) = @_;
 5799: 
 5800:   my %hash;
 5801: 
 5802:   if($string !~ /^__HASH_REF__/) {
 5803:       if (! ($string eq '' || !defined($string))) {
 5804: 	  $hash{'error'}='Not hash reference';
 5805:       }
 5806:       return (\%hash, $string);
 5807:   }
 5808: 
 5809:   $string =~ s/^__HASH_REF__//;
 5810: 
 5811:   while($string !~ /^__END_HASH_REF__/) {
 5812:       #key
 5813:       my $key='';
 5814:       if($string =~ /^__HASH_REF__/) {
 5815:           ($key, $string)=&str2hashref($string);
 5816:           if(defined($key->{'error'})) {
 5817:               $hash{'error'}='Bad data';
 5818:               return (\%hash, $string);
 5819:           }
 5820:       } elsif($string =~ /^__ARRAY_REF__/) {
 5821:           ($key, $string)=&str2arrayref($string);
 5822:           if($key->[0] eq 'Array reference error') {
 5823:               $hash{'error'}='Bad data';
 5824:               return (\%hash, $string);
 5825:           }
 5826:       } else {
 5827:           $string =~ s/^(.*?)=//;
 5828: 	  $key=&unescape($1);
 5829:       }
 5830:       $string =~ s/^=//;
 5831: 
 5832:       #value
 5833:       my $value='';
 5834:       if($string =~ /^__HASH_REF__/) {
 5835:           ($value, $string)=&str2hashref($string);
 5836:           if(defined($value->{'error'})) {
 5837:               $hash{'error'}='Bad data';
 5838:               return (\%hash, $string);
 5839:           }
 5840:       } elsif($string =~ /^__ARRAY_REF__/) {
 5841:           ($value, $string)=&str2arrayref($string);
 5842:           if($value->[0] eq 'Array reference error') {
 5843:               $hash{'error'}='Bad data';
 5844:               return (\%hash, $string);
 5845:           }
 5846:       } else {
 5847: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 5848:       }
 5849:       $string =~ s/^&//;
 5850: 
 5851:       $hash{$key}=$value;
 5852:   }
 5853: 
 5854:   $string =~ s/^__END_HASH_REF__//;
 5855: 
 5856:   return (\%hash, $string);
 5857: }
 5858: 
 5859: sub str2array {
 5860:     my ($string)=@_;
 5861:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 5862:     return @$array;
 5863: }
 5864: 
 5865: sub str2arrayref {
 5866:   my ($string) = @_;
 5867:   my @array;
 5868: 
 5869:   if($string !~ /^__ARRAY_REF__/) {
 5870:       if (! ($string eq '' || !defined($string))) {
 5871: 	  $array[0]='Array reference error';
 5872:       }
 5873:       return (\@array, $string);
 5874:   }
 5875: 
 5876:   $string =~ s/^__ARRAY_REF__//;
 5877: 
 5878:   while($string !~ /^__END_ARRAY_REF__/) {
 5879:       my $value='';
 5880:       if($string =~ /^__HASH_REF__/) {
 5881:           ($value, $string)=&str2hashref($string);
 5882:           if(defined($value->{'error'})) {
 5883:               $array[0] ='Array reference error';
 5884:               return (\@array, $string);
 5885:           }
 5886:       } elsif($string =~ /^__ARRAY_REF__/) {
 5887:           ($value, $string)=&str2arrayref($string);
 5888:           if($value->[0] eq 'Array reference error') {
 5889:               $array[0] ='Array reference error';
 5890:               return (\@array, $string);
 5891:           }
 5892:       } else {
 5893: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 5894:       }
 5895:       $string =~ s/^&//;
 5896: 
 5897:       push(@array, $value);
 5898:   }
 5899: 
 5900:   $string =~ s/^__END_ARRAY_REF__//;
 5901: 
 5902:   return (\@array, $string);
 5903: }
 5904: 
 5905: # -------------------------------------------------------------------Temp Store
 5906: 
 5907: sub tmpreset {
 5908:   my ($symb,$namespace,$domain,$stuname) = @_;
 5909:   if (!$symb) {
 5910:     $symb=&symbread();
 5911:     if (!$symb) { $symb= $env{'request.url'}; }
 5912:   }
 5913:   $symb=escape($symb);
 5914: 
 5915:   if (!$namespace) { $namespace=$env{'request.state'}; }
 5916:   $namespace=~s/\//\_/g;
 5917:   $namespace=~s/\W//g;
 5918: 
 5919:   if (!$domain) { $domain=$env{'user.domain'}; }
 5920:   if (!$stuname) { $stuname=$env{'user.name'}; }
 5921:   if ($domain eq 'public' && $stuname eq 'public') {
 5922:       $stuname=$ENV{'REMOTE_ADDR'};
 5923:   }
 5924:   my $path=LONCAPA::tempdir();
 5925:   my %hash;
 5926:   if (tie(%hash,'GDBM_File',
 5927: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 5928: 	  &GDBM_WRCREAT(),0640)) {
 5929:     foreach my $key (keys(%hash)) {
 5930:       if ($key=~ /:$symb/) {
 5931: 	delete($hash{$key});
 5932:       }
 5933:     }
 5934:   }
 5935: }
 5936: 
 5937: sub tmpstore {
 5938:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 5939: 
 5940:   if (!$symb) {
 5941:     $symb=&symbread();
 5942:     if (!$symb) { $symb= $env{'request.url'}; }
 5943:   }
 5944:   $symb=escape($symb);
 5945: 
 5946:   if (!$namespace) {
 5947:     # I don't think we would ever want to store this for a course.
 5948:     # it seems this will only be used if we don't have a course.
 5949:     #$namespace=$env{'request.course.id'};
 5950:     #if (!$namespace) {
 5951:       $namespace=$env{'request.state'};
 5952:     #}
 5953:   }
 5954:   $namespace=~s/\//\_/g;
 5955:   $namespace=~s/\W//g;
 5956:   if (!$domain) { $domain=$env{'user.domain'}; }
 5957:   if (!$stuname) { $stuname=$env{'user.name'}; }
 5958:   if ($domain eq 'public' && $stuname eq 'public') {
 5959:       $stuname=$ENV{'REMOTE_ADDR'};
 5960:   }
 5961:   my $now=time;
 5962:   my %hash;
 5963:   my $path=LONCAPA::tempdir();
 5964:   if (tie(%hash,'GDBM_File',
 5965: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 5966: 	  &GDBM_WRCREAT(),0640)) {
 5967:     $hash{"version:$symb"}++;
 5968:     my $version=$hash{"version:$symb"};
 5969:     my $allkeys=''; 
 5970:     foreach my $key (keys(%$storehash)) {
 5971:       $allkeys.=$key.':';
 5972:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 5973:     }
 5974:     $hash{"$version:$symb:timestamp"}=$now;
 5975:     $allkeys.='timestamp';
 5976:     $hash{"$version:keys:$symb"}=$allkeys;
 5977:     if (untie(%hash)) {
 5978:       return 'ok';
 5979:     } else {
 5980:       return "error:$!";
 5981:     }
 5982:   } else {
 5983:     return "error:$!";
 5984:   }
 5985: }
 5986: 
 5987: # -----------------------------------------------------------------Temp Restore
 5988: 
 5989: sub tmprestore {
 5990:   my ($symb,$namespace,$domain,$stuname) = @_;
 5991: 
 5992:   if (!$symb) {
 5993:     $symb=&symbread();
 5994:     if (!$symb) { $symb= $env{'request.url'}; }
 5995:   }
 5996:   $symb=escape($symb);
 5997: 
 5998:   if (!$namespace) { $namespace=$env{'request.state'}; }
 5999: 
 6000:   if (!$domain) { $domain=$env{'user.domain'}; }
 6001:   if (!$stuname) { $stuname=$env{'user.name'}; }
 6002:   if ($domain eq 'public' && $stuname eq 'public') {
 6003:       $stuname=$ENV{'REMOTE_ADDR'};
 6004:   }
 6005:   my %returnhash;
 6006:   $namespace=~s/\//\_/g;
 6007:   $namespace=~s/\W//g;
 6008:   my %hash;
 6009:   my $path=LONCAPA::tempdir();
 6010:   if (tie(%hash,'GDBM_File',
 6011: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 6012: 	  &GDBM_READER(),0640)) {
 6013:     my $version=$hash{"version:$symb"};
 6014:     $returnhash{'version'}=$version;
 6015:     my $scope;
 6016:     for ($scope=1;$scope<=$version;$scope++) {
 6017:       my $vkeys=$hash{"$scope:keys:$symb"};
 6018:       my @keys=split(/:/,$vkeys);
 6019:       my $key;
 6020:       $returnhash{"$scope:keys"}=$vkeys;
 6021:       foreach $key (@keys) {
 6022: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 6023: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 6024:       }
 6025:     }
 6026:     if (!(untie(%hash))) {
 6027:       return "error:$!";
 6028:     }
 6029:   } else {
 6030:     return "error:$!";
 6031:   }
 6032:   return %returnhash;
 6033: }
 6034: 
 6035: # ----------------------------------------------------------------------- Store
 6036: 
 6037: sub store {
 6038:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 6039:     my $home='';
 6040: 
 6041:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 6042: 
 6043:     $symb=&symbclean($symb);
 6044:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 6045: 
 6046:     if (!$domain) { $domain=$env{'user.domain'}; }
 6047:     if (!$stuname) { $stuname=$env{'user.name'}; }
 6048: 
 6049:     &devalidate($symb,$stuname,$domain);
 6050: 
 6051:     $symb=escape($symb);
 6052:     if (!$namespace) { 
 6053:        unless ($namespace=$env{'request.course.id'}) { 
 6054:           return ''; 
 6055:        } 
 6056:     }
 6057:     if (!$home) { $home=$env{'user.home'}; }
 6058: 
 6059:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 6060:     $$storehash{'host'}=$perlvar{'lonHostID'};
 6061: 
 6062:     my $namevalue='';
 6063:     foreach my $key (keys(%$storehash)) {
 6064:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 6065:     }
 6066:     $namevalue=~s/\&$//;
 6067:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 6068:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 6069: }
 6070: 
 6071: # -------------------------------------------------------------- Critical Store
 6072: 
 6073: sub cstore {
 6074:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 6075:     my $home='';
 6076: 
 6077:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 6078: 
 6079:     $symb=&symbclean($symb);
 6080:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 6081: 
 6082:     if (!$domain) { $domain=$env{'user.domain'}; }
 6083:     if (!$stuname) { $stuname=$env{'user.name'}; }
 6084: 
 6085:     &devalidate($symb,$stuname,$domain);
 6086: 
 6087:     $symb=escape($symb);
 6088:     if (!$namespace) { 
 6089:        unless ($namespace=$env{'request.course.id'}) { 
 6090:           return ''; 
 6091:        } 
 6092:     }
 6093:     if (!$home) { $home=$env{'user.home'}; }
 6094: 
 6095:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 6096:     $$storehash{'host'}=$perlvar{'lonHostID'};
 6097: 
 6098:     my $namevalue='';
 6099:     foreach my $key (keys(%$storehash)) {
 6100:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 6101:     }
 6102:     $namevalue=~s/\&$//;
 6103:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 6104:     return critical
 6105:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 6106: }
 6107: 
 6108: # --------------------------------------------------------------------- Restore
 6109: 
 6110: sub restore {
 6111:     my ($symb,$namespace,$domain,$stuname) = @_;
 6112:     my $home='';
 6113: 
 6114:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 6115: 
 6116:     if (!$symb) {
 6117:         return if ($namespace eq 'courserequests');
 6118:         unless ($symb=escape(&symbread())) { return ''; }
 6119:     } else {
 6120:         unless ($namespace eq 'courserequests') {
 6121:             $symb=&escape(&symbclean($symb));
 6122:         }
 6123:     }
 6124:     if (!$namespace) { 
 6125:        unless ($namespace=$env{'request.course.id'}) { 
 6126:           return ''; 
 6127:        } 
 6128:     }
 6129:     if (!$domain) { $domain=$env{'user.domain'}; }
 6130:     if (!$stuname) { $stuname=$env{'user.name'}; }
 6131:     if (!$home) { $home=$env{'user.home'}; }
 6132:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 6133: 
 6134:     my %returnhash=();
 6135:     foreach my $line (split(/\&/,$answer)) {
 6136: 	my ($name,$value)=split(/\=/,$line);
 6137:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 6138:     }
 6139:     my $version;
 6140:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 6141:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 6142:           $returnhash{$item}=$returnhash{$version.':'.$item};
 6143:        }
 6144:     }
 6145:     return %returnhash;
 6146: }
 6147: 
 6148: # ---------------------------------------------------------- Course Description
 6149: #
 6150: #  
 6151: 
 6152: sub coursedescription {
 6153:     my ($courseid,$args)=@_;
 6154:     $courseid=~s/^\///;
 6155:     $courseid=~s/\_/\//g;
 6156:     my ($cdomain,$cnum)=split(/\//,$courseid);
 6157:     my $chome=&homeserver($cnum,$cdomain);
 6158:     my $normalid=$cdomain.'_'.$cnum;
 6159:     # need to always cache even if we get errors otherwise we keep 
 6160:     # trying and trying and trying to get the course description.
 6161:     my %envhash=();
 6162:     my %returnhash=();
 6163:     
 6164:     my $expiretime=600;
 6165:     if ($env{'request.course.id'} eq $normalid) {
 6166: 	$expiretime=120;
 6167:     }
 6168: 
 6169:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 6170:     if (!$args->{'freshen_cache'}
 6171: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 6172: 	foreach my $key (keys(%env)) {
 6173: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 6174: 	    my ($setting) = $1;
 6175: 	    $returnhash{$setting} = $env{$key};
 6176: 	}
 6177: 	return %returnhash;
 6178:     }
 6179: 
 6180:     # get the data again
 6181: 
 6182:     if (!$args->{'one_time'}) {
 6183: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 6184:     }
 6185: 
 6186:     if ($chome ne 'no_host') {
 6187:        %returnhash=&dump('environment',$cdomain,$cnum);
 6188:        if (!exists($returnhash{'con_lost'})) {
 6189: 	   my $username = $env{'user.name'}; # Defult username
 6190: 	   if(defined $args->{'user'}) {
 6191: 	       $username = $args->{'user'};
 6192: 	   }
 6193:            $returnhash{'home'}= $chome;
 6194: 	   $returnhash{'domain'} = $cdomain;
 6195: 	   $returnhash{'num'} = $cnum;
 6196:            if (!defined($returnhash{'type'})) {
 6197:                $returnhash{'type'} = 'Course';
 6198:            }
 6199:            while (my ($name,$value) = each %returnhash) {
 6200:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 6201:            }
 6202:            $returnhash{'url'}=&clutter($returnhash{'url'});
 6203:            $returnhash{'fn'}=LONCAPA::tempdir() .
 6204: 	       $username.'_'.$cdomain.'_'.$cnum;
 6205:            $envhash{'course.'.$normalid.'.home'}=$chome;
 6206:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 6207:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 6208:        }
 6209:     }
 6210:     if (!$args->{'one_time'}) {
 6211: 	&appenv(\%envhash);
 6212:     }
 6213:     return %returnhash;
 6214: }
 6215: 
 6216: sub update_released_required {
 6217:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
 6218:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
 6219:         $cid = $env{'request.course.id'};
 6220:         $cdom = $env{'course.'.$cid.'.domain'};
 6221:         $cnum = $env{'course.'.$cid.'.num'};
 6222:         $chome = $env{'course.'.$cid.'.home'};
 6223:     }
 6224:     if ($needsrelease) {
 6225:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
 6226:         my $needsupdate;
 6227:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
 6228:             $needsupdate = 1;
 6229:         } else {
 6230:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
 6231:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
 6232:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
 6233:                 $needsupdate = 1;
 6234:             }
 6235:         }
 6236:         if ($needsupdate) {
 6237:             my %needshash = (
 6238:                              'internal.releaserequired' => $needsrelease,
 6239:                             );
 6240:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
 6241:             if ($putresult eq 'ok') {
 6242:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
 6243:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 6244:                 if (ref($crsinfo{$cid}) eq 'HASH') {
 6245:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
 6246:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
 6247:                 }
 6248:             }
 6249:         }
 6250:     }
 6251:     return;
 6252: }
 6253: 
 6254: # -------------------------------------------------See if a user is privileged
 6255: 
 6256: sub privileged {
 6257:     my ($username,$domain,$possdomains,$possroles)=@_;
 6258:     my $now = time;
 6259:     my $roles;
 6260:     if (ref($possroles) eq 'ARRAY') {
 6261:         $roles = $possroles;
 6262:     } else {
 6263:         $roles = ['dc','su'];
 6264:     }
 6265:     if (ref($possdomains) eq 'ARRAY') {
 6266:         my %privileged = &privileged_by_domain($possdomains,$roles);
 6267:         foreach my $dom (@{$possdomains}) {
 6268:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
 6269:                 (ref($privileged{$dom}) eq 'HASH')) {
 6270:                 foreach my $role (@{$roles}) {
 6271:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 6272:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
 6273:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
 6274:                             return 1 unless (($end && $end < $now) ||
 6275:                                              ($start && $start > $now));
 6276:                         }
 6277:                     }
 6278:                 }
 6279:             }
 6280:         }
 6281:     } else {
 6282:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
 6283:         my $now = time;
 6284: 
 6285:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
 6286:             my ($trole, $tend, $tstart) = split(/_/, $role);
 6287:             if (grep(/^\Q$trole\E$/,@{$roles})) {
 6288:                 return 1 unless ($tend && $tend < $now)
 6289:                         or ($tstart && $tstart > $now);
 6290:             }
 6291:         }
 6292:     }
 6293:     return 0;
 6294: }
 6295: 
 6296: sub privileged_by_domain {
 6297:     my ($domains,$roles) = @_;
 6298:     my %privileged = ();
 6299:     my $cachetime = 60*60*24;
 6300:     my $now = time;
 6301:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
 6302:         return %privileged;
 6303:     }
 6304:     foreach my $dom (@{$domains}) {
 6305:         next if (ref($privileged{$dom}) eq 'HASH');
 6306:         my $needroles;
 6307:         foreach my $role (@{$roles}) {
 6308:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
 6309:             if (defined($cached)) {
 6310:                 if (ref($result) eq 'HASH') {
 6311:                     $privileged{$dom}{$role} = $result;
 6312:                 }
 6313:             } else {
 6314:                 $needroles = 1;
 6315:             }
 6316:         }
 6317:         if ($needroles) {
 6318:             my %dompersonnel = &get_domain_roles($dom,$roles);
 6319:             $privileged{$dom} = {};
 6320:             foreach my $server (keys(%dompersonnel)) {
 6321:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 6322:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
 6323:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
 6324:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
 6325:                         next if ($end && $end < $now);
 6326:                         $privileged{$dom}{$trole}{$uname.':'.$udom} =
 6327:                             $dompersonnel{$server}{$item};
 6328:                     }
 6329:                 }
 6330:             }
 6331:             if (ref($privileged{$dom}) eq 'HASH') {
 6332:                 foreach my $role (@{$roles}) {
 6333:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 6334:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
 6335:                     } else {
 6336:                         my %hash = ();
 6337:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
 6338:                     }
 6339:                 }
 6340:             }
 6341:         }
 6342:     }
 6343:     return %privileged;
 6344: }
 6345: 
 6346: # -------------------------------------------------------- Get user privileges
 6347: 
 6348: sub rolesinit {
 6349:     my ($domain, $username) = @_;
 6350:     my %userroles = ('user.login.time' => time);
 6351:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
 6352: 
 6353:     # firstaccess and timerinterval are related to timed maps/resources. 
 6354:     # also, blocking can be triggered by an activating timer
 6355:     # it's saved in the user's %env.
 6356:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
 6357:     my %timerinterval = &dump('timerinterval', $domain, $username);
 6358:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
 6359:         %timerintchk, %timerintenv);
 6360: 
 6361:     foreach my $key (keys(%firstaccess)) {
 6362:         my ($cid, $rest) = split(/\0/, $key);
 6363:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
 6364:     }
 6365: 
 6366:     foreach my $key (keys(%timerinterval)) {
 6367:         my ($cid,$rest) = split(/\0/,$key);
 6368:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
 6369:     }
 6370: 
 6371:     my %allroles=();
 6372:     my %allgroups=();
 6373: 
 6374:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
 6375:         my $role = $rolesdump{$area};
 6376:         $area =~ s/\_\w\w$//;
 6377: 
 6378:         my ($trole, $tend, $tstart, $group_privs);
 6379: 
 6380:         if ($role =~ /^cr/) {
 6381:         # Custom role, defined by a user 
 6382:         # e.g., user.role.cr/msu/smith/mynewrole
 6383:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 6384:                 $trole = $1;
 6385:                 ($tend, $tstart) = split('_', $2);
 6386:             } else {
 6387:                 $trole = $role;
 6388:             }
 6389:         } elsif ($role =~ m|^gr/|) {
 6390:         # Role of member in a group, defined within a course/community
 6391:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
 6392:             ($trole, $tend, $tstart) = split(/_/, $role);
 6393:             next if $tstart eq '-1';
 6394:             ($trole, $group_privs) = split(/\//, $trole);
 6395:             $group_privs = &unescape($group_privs);
 6396:         } else {
 6397:         # Just a normal role, defined in roles.tab
 6398:             ($trole, $tend, $tstart) = split(/_/,$role);
 6399:         }
 6400: 
 6401:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 6402:                  $username);
 6403:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 6404: 
 6405:         # role expired or not available yet?
 6406:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
 6407:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
 6408: 
 6409:         next if $area eq '' or $trole eq '';
 6410: 
 6411:         my $spec = "$trole.$area";
 6412:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
 6413: 
 6414:         if ($trole =~ /^cr\//) {
 6415:         # Custom role, defined by a user
 6416:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 6417:         } elsif ($trole eq 'gr') {
 6418:         # Role of a member in a group, defined within a course/community
 6419:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 6420:             next;
 6421:         } else {
 6422:         # Normal role, defined in roles.tab
 6423:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 6424:         }
 6425: 
 6426:         my $cid = $tdomain.'_'.$trest;
 6427:         unless ($firstaccchk{$cid}) {
 6428:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
 6429:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
 6430:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
 6431:                         $coursetimerstarts{$cid}{$item}; 
 6432:                 }
 6433:             }
 6434:             $firstaccchk{$cid} = 1;
 6435:         }
 6436:         unless ($timerintchk{$cid}) {
 6437:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
 6438:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
 6439:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
 6440:                        $coursetimerintervals{$cid}{$item};
 6441:                 }
 6442:             }
 6443:             $timerintchk{$cid} = 1;
 6444:         }
 6445:     }
 6446: 
 6447:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
 6448:                                                           \%allroles, \%allgroups);
 6449:     $env{'user.adv'} = $userroles{'user.adv'};
 6450:     $env{'user.rar'} = $userroles{'user.rar'};
 6451: 
 6452:     return (\%userroles,\%firstaccenv,\%timerintenv);
 6453: }
 6454: 
 6455: sub set_arearole {
 6456:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
 6457:     unless ($nolog) {
 6458: # log the associated role with the area
 6459:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 6460:     }
 6461:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 6462: }
 6463: 
 6464: sub custom_roleprivs {
 6465:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 6466:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 6467:     my $homsvr = &homeserver($rauthor,$rdomain);
 6468:     if (&hostname($homsvr) ne '') {
 6469:         my ($rdummy,$roledef)=
 6470:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 6471:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 6472:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 6473:             if (defined($syspriv)) {
 6474:                 if ($trest =~ /^$match_community$/) {
 6475:                     $syspriv =~ s/bre\&S//; 
 6476:                 }
 6477:                 $$allroles{'cm./'}.=':'.$syspriv;
 6478:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 6479:             }
 6480:             if ($tdomain ne '') {
 6481:                 if (defined($dompriv)) {
 6482:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 6483:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 6484:                 }
 6485:                 if (($trest ne '') && (defined($coursepriv))) {
 6486:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
 6487:                         my $rolename = $1;
 6488:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
 6489:                     }
 6490:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 6491:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 6492:                 }
 6493:             }
 6494:         }
 6495:     }
 6496: }
 6497: 
 6498: sub course_adhocrole_privs {
 6499:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
 6500:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
 6501:     if ($overrides{"internal.adhocpriv.$rolename"}) {
 6502:         my (%currprivs,%storeprivs);
 6503:         foreach my $item (split(/:/,$coursepriv)) {
 6504:             my ($priv,$restrict) = split(/\&/,$item);
 6505:             $currprivs{$priv} = $restrict;
 6506:         }
 6507:         my (%possadd,%possremove,%full);
 6508:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
 6509:             my ($priv,$restrict)=split(/\&/,$item);
 6510:             $full{$priv} = $restrict;
 6511:         }
 6512:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
 6513:              next if ($item eq '');
 6514:              my ($rule,$rest) = split(/=/,$item);
 6515:              next unless (($rule eq 'off') || ($rule eq 'on'));
 6516:              foreach my $priv (split(/:/,$rest)) {
 6517:                  if ($priv ne '') {
 6518:                      if ($rule eq 'off') {
 6519:                          $possremove{$priv} = 1;
 6520:                      } else {
 6521:                          $possadd{$priv} = 1;
 6522:                      }
 6523:                  }
 6524:              }
 6525:          }
 6526:          foreach my $priv (sort(keys(%full))) {
 6527:              if (exists($currprivs{$priv})) {
 6528:                  unless (exists($possremove{$priv})) {
 6529:                      $storeprivs{$priv} = $currprivs{$priv};
 6530:                  }
 6531:              } elsif (exists($possadd{$priv})) {
 6532:                  $storeprivs{$priv} = $full{$priv};
 6533:              }
 6534:          }
 6535:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
 6536:      }
 6537:      return $coursepriv;
 6538: }
 6539: 
 6540: sub group_roleprivs {
 6541:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 6542:     my $access = 1;
 6543:     my $now = time;
 6544:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 6545:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 6546:     if ($access) {
 6547:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 6548:         $$allgroups{$course}{$group} .=':'.$group_privs;
 6549:     }
 6550: }
 6551: 
 6552: sub standard_roleprivs {
 6553:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 6554:     if (defined($pr{$trole.':s'})) {
 6555:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 6556:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 6557:     }
 6558:     if ($tdomain ne '') {
 6559:         if (defined($pr{$trole.':d'})) {
 6560:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 6561:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 6562:         }
 6563:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 6564:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 6565:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 6566:         }
 6567:     }
 6568: }
 6569: 
 6570: sub set_userprivs {
 6571:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
 6572:     my $author=0;
 6573:     my $adv=0;
 6574:     my $rar=0;
 6575:     my %grouproles = ();
 6576:     if (keys(%{$allgroups}) > 0) {
 6577:         my @groupkeys; 
 6578:         foreach my $role (keys(%{$allroles})) {
 6579:             push(@groupkeys,$role);
 6580:         }
 6581:         if (ref($groups_roles) eq 'HASH') {
 6582:             foreach my $key (keys(%{$groups_roles})) {
 6583:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
 6584:                     push(@groupkeys,$key);
 6585:                 }
 6586:             }
 6587:         }
 6588:         if (@groupkeys > 0) {
 6589:             foreach my $role (@groupkeys) {
 6590:                 my ($trole,$area,$sec,$extendedarea);
 6591:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 6592:                     $trole = $1;
 6593:                     $area = $2;
 6594:                     $sec = $3;
 6595:                     $extendedarea = $area.$sec;
 6596:                     if (exists($$allgroups{$area})) {
 6597:                         foreach my $group (keys(%{$$allgroups{$area}})) {
 6598:                             my $spec = $trole.'.'.$extendedarea;
 6599:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
 6600:                                                 $$allgroups{$area}{$group};
 6601:                         }
 6602:                     }
 6603:                 }
 6604:             }
 6605:         }
 6606:     }
 6607:     foreach my $group (keys(%grouproles)) {
 6608:         $$allroles{$group} = $grouproles{$group};
 6609:     }
 6610:     foreach my $role (keys(%{$allroles})) {
 6611:         my %thesepriv;
 6612:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 6613:         foreach my $item (split(/:/,$$allroles{$role})) {
 6614:             if ($item ne '') {
 6615:                 my ($privilege,$restrictions)=split(/&/,$item);
 6616:                 if ($restrictions eq '') {
 6617:                     $thesepriv{$privilege}='F';
 6618:                 } elsif ($thesepriv{$privilege} ne 'F') {
 6619:                     $thesepriv{$privilege}.=$restrictions;
 6620:                 }
 6621:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 6622:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
 6623:             }
 6624:         }
 6625:         my $thesestr='';
 6626:         foreach my $priv (sort(keys(%thesepriv))) {
 6627: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 6628: 	}
 6629:         $userroles->{'user.priv.'.$role} = $thesestr;
 6630:     }
 6631:     return ($author,$adv,$rar);
 6632: }
 6633: 
 6634: sub role_status {
 6635:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 6636:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 6637:         my ($one,$two) = split(m{\./},$rolekey,2);
 6638:         (undef,undef,$$role) = split(/\./,$one,3);
 6639:         unless (!defined($$role) || $$role eq '') {
 6640:             $$where = '/'.$two;
 6641:             $$trolecode=$$role.'.'.$$where;
 6642:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 6643:             $$tstatus='is';
 6644:             if ($$tstart && $$tstart>$update) {
 6645:                 $$tstatus='future';
 6646:                 if ($$tstart<$now) {
 6647:                     if ($$tstart && $$tstart>$refresh) {
 6648:                         if (($$where ne '') && ($$role ne '')) {
 6649:                             my (%allroles,%allgroups,$group_privs,
 6650:                                 %groups_roles,@rolecodes);
 6651:                             my %userroles = (
 6652:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 6653:                             );
 6654:                             @rolecodes = ('cm'); 
 6655:                             my $spec=$$role.'.'.$$where;
 6656:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 6657:                             if ($$role =~ /^cr\//) {
 6658:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 6659:                                 push(@rolecodes,'cr');
 6660:                             } elsif ($$role eq 'gr') {
 6661:                                 push(@rolecodes,$$role);
 6662:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 6663:                                                     $env{'user.name'});
 6664:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
 6665:                                 (undef,my $group_privs) = split(/\//,$trole);
 6666:                                 $group_privs = &unescape($group_privs);
 6667:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 6668:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
 6669:                                 &get_groups_roles($tdomain,$trest,
 6670:                                                   \%course_roles,\@rolecodes,
 6671:                                                   \%groups_roles);
 6672:                             } else {
 6673:                                 push(@rolecodes,$$role);
 6674:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 6675:                             }
 6676:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
 6677:                                                                    \%groups_roles);
 6678:                             &appenv(\%userroles,\@rolecodes);
 6679:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
 6680:                         }
 6681:                     }
 6682:                     $$tstatus = 'is';
 6683:                 }
 6684:             }
 6685:             if ($$tend) {
 6686:                 if ($$tend<$update) {
 6687:                     $$tstatus='expired';
 6688:                 } elsif ($$tend<$now) {
 6689:                     $$tstatus='will_not';
 6690:                 }
 6691:             }
 6692:         }
 6693:     }
 6694: }
 6695: 
 6696: sub get_groups_roles {
 6697:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
 6698:     return unless((ref($cdom_courseroles) eq 'HASH') && 
 6699:                   (ref($rolecodes) eq 'ARRAY') && 
 6700:                   (ref($groups_roles) eq 'HASH')); 
 6701:     if (keys(%{$cdom_courseroles}) > 0) {
 6702:         my ($cnum) = ($rest =~ /^($match_courseid)/);
 6703:         if ($cdom ne '' && $cnum ne '') {
 6704:             foreach my $key (keys(%{$cdom_courseroles})) {
 6705:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
 6706:                     my $crsrole = $1;
 6707:                     my $crssec = $2;
 6708:                     if ($crsrole =~ /^cr/) {
 6709:                         unless (grep(/^cr$/,@{$rolecodes})) {
 6710:                             push(@{$rolecodes},'cr');
 6711:                         }
 6712:                     } else {
 6713:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
 6714:                             push(@{$rolecodes},$crsrole);
 6715:                         }
 6716:                     }
 6717:                     my $rolekey = "$crsrole./$cdom/$cnum";
 6718:                     if ($crssec ne '') {
 6719:                         $rolekey .= "/$crssec";
 6720:                     }
 6721:                     $rolekey .= './';
 6722:                     $groups_roles->{$rolekey} = $rolecodes;
 6723:                 }
 6724:             }
 6725:         }
 6726:     }
 6727:     return;
 6728: }
 6729: 
 6730: sub delete_env_groupprivs {
 6731:     my ($where,$courseroles,$possroles) = @_;
 6732:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
 6733:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
 6734:     unless (ref($courseroles->{$udom}) eq 'HASH') {
 6735:         %{$courseroles->{$udom}} =
 6736:             &get_my_roles('','','userroles',['active'],
 6737:                           $possroles,[$udom],1);
 6738:     }
 6739:     if (ref($courseroles->{$udom}) eq 'HASH') {
 6740:         foreach my $item (keys(%{$courseroles->{$udom}})) {
 6741:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
 6742:             my $area = '/'.$cdom.'/'.$cnum;
 6743:             my $privkey = "user.priv.$crsrole.$area";
 6744:             if ($crssec ne '') {
 6745:                 $privkey .= '/'.$crssec;
 6746:             }
 6747:             $privkey .= ".$area/$group";
 6748:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
 6749:         }
 6750:     }
 6751:     return;
 6752: }
 6753: 
 6754: sub check_adhoc_privs {
 6755:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
 6756:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 6757:     if ($sec) {
 6758:         $cckey .= '/'.$sec;
 6759:     }
 6760:     my $setprivs;
 6761:     if ($env{$cckey}) {
 6762:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 6763:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 6764:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 6765:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
 6766:             $setprivs = 1;
 6767:         }
 6768:     } else {
 6769:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
 6770:         $setprivs = 1;
 6771:     }
 6772:     return $setprivs;
 6773: }
 6774: 
 6775: sub set_adhoc_privileges {
 6776: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
 6777:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
 6778:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 6779:     if ($sec ne '') {
 6780:         $area .= '/'.$sec;
 6781:     }
 6782:     my $spec = $role.'.'.$area;
 6783:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 6784:                                   $env{'user.name'},1);
 6785:     my %rolehash = ();
 6786:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
 6787:         my $rolename = $1;
 6788:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
 6789:         my %domdef = &get_domain_defaults($dcdom);
 6790:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
 6791:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
 6792:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
 6793:             }
 6794:         }
 6795:     } else {
 6796:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
 6797:     }
 6798:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
 6799:     &appenv(\%userroles,[$role,'cm']);
 6800:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
 6801:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
 6802:         &appenv( {'request.role'        => $spec,
 6803:                   'request.role.domain' => $dcdom,
 6804:                   'request.course.sec'  => $sec, 
 6805:                  }
 6806:                );
 6807:         my $tadv=0;
 6808:         if (&allowed('adv') eq 'F') { $tadv=1; }
 6809:         &appenv({'request.role.adv'    => $tadv});
 6810:     }
 6811: }
 6812: 
 6813: # --------------------------------------------------------------- get interface
 6814: 
 6815: sub get {
 6816:    my ($namespace,$storearr,$udomain,$uname)=@_;
 6817:    my $items='';
 6818:    foreach my $item (@$storearr) {
 6819:        $items.=&escape($item).'&';
 6820:    }
 6821:    $items=~s/\&$//;
 6822:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6823:    if (!$uname) { $uname=$env{'user.name'}; }
 6824:    my $uhome=&homeserver($uname,$udomain);
 6825: 
 6826:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 6827:    my @pairs=split(/\&/,$rep);
 6828:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 6829:      return @pairs;
 6830:    }
 6831:    my %returnhash=();
 6832:    my $i=0;
 6833:    foreach my $item (@$storearr) {
 6834:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 6835:       $i++;
 6836:    }
 6837:    return %returnhash;
 6838: }
 6839: 
 6840: # --------------------------------------------------------------- del interface
 6841: 
 6842: sub del {
 6843:    my ($namespace,$storearr,$udomain,$uname)=@_;
 6844:    my $items='';
 6845:    foreach my $item (@$storearr) {
 6846:        $items.=&escape($item).'&';
 6847:    }
 6848: 
 6849:    $items=~s/\&$//;
 6850:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6851:    if (!$uname) { $uname=$env{'user.name'}; }
 6852:    my $uhome=&homeserver($uname,$udomain);
 6853:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 6854: }
 6855: 
 6856: # -------------------------------------------------------------- dump interface
 6857: 
 6858: sub unserialize {
 6859:     my ($rep, $escapedkeys) = @_;
 6860: 
 6861:     return {} if $rep =~ /^error/;
 6862: 
 6863:     my %returnhash=();
 6864:     foreach my $item (split(/\&/,$rep)) {
 6865:         my ($key, $value) = split(/=/, $item, 2);
 6866:         $key = unescape($key) unless $escapedkeys;
 6867:         next if $key =~ /^error: 2 /;
 6868:         $returnhash{$key} = &thaw_unescape($value);
 6869:     }
 6870:     return \%returnhash;
 6871: }
 6872: 
 6873: # see Lond::dump_with_regexp
 6874: # if $escapedkeys hash keys won't get unescaped.
 6875: sub dump {
 6876:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
 6877:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 6878:     if (!$uname) { $uname=$env{'user.name'}; }
 6879:     my $uhome=&homeserver($uname,$udomain);
 6880: 
 6881:     if ($regexp) {
 6882:         $regexp=&escape($regexp);
 6883:     } else {
 6884:         $regexp='.';
 6885:     }
 6886:     if (grep { $_ eq $uhome } &current_machine_ids()) {
 6887:         # user is hosted on this machine
 6888:         my $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
 6889:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
 6890:         return %{&unserialize($reply, $escapedkeys)};
 6891:     }
 6892:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 6893:     my @pairs=split(/\&/,$rep);
 6894:     my %returnhash=();
 6895:     if (!($rep =~ /^error/ )) {
 6896: 	foreach my $item (@pairs) {
 6897: 	    my ($key,$value)=split(/=/,$item,2);
 6898:             $key = &unescape($key) unless ($escapedkeys);
 6899: 	    next if ($key =~ /^error: 2 /);
 6900: 	    $returnhash{$key}=&thaw_unescape($value);
 6901: 	}
 6902:     }
 6903:     return %returnhash;
 6904: }
 6905: 
 6906: 
 6907: # --------------------------------------------------------- dumpstore interface
 6908: 
 6909: sub dumpstore {
 6910:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 6911:    # same as dump but keys must be escaped. They may contain colon separated
 6912:    # lists of values that may themself contain colons (e.g. symbs).
 6913:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
 6914: }
 6915: 
 6916: # -------------------------------------------------------------- keys interface
 6917: 
 6918: sub getkeys {
 6919:    my ($namespace,$udomain,$uname)=@_;
 6920:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6921:    if (!$uname) { $uname=$env{'user.name'}; }
 6922:    my $uhome=&homeserver($uname,$udomain);
 6923:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 6924:    my @keyarray=();
 6925:    foreach my $key (split(/\&/,$rep)) {
 6926:       next if ($key =~ /^error: 2 /);
 6927:       push(@keyarray,&unescape($key));
 6928:    }
 6929:    return @keyarray;
 6930: }
 6931: 
 6932: # --------------------------------------------------------------- currentdump
 6933: sub currentdump {
 6934:    my ($courseid,$sdom,$sname)=@_;
 6935:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 6936:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 6937:    $sname    = $env{'user.name'}         if (! defined($sname));
 6938:    my $uhome = &homeserver($sname,$sdom);
 6939:    my $rep;
 6940: 
 6941:    if (grep { $_ eq $uhome } current_machine_ids()) {
 6942:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
 6943:                    $courseid)));
 6944:    } else {
 6945:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 6946:    }
 6947: 
 6948:    return if ($rep =~ /^(error:|no_such_host)/);
 6949:    #
 6950:    my %returnhash=();
 6951:    #
 6952:    if ($rep eq 'unknown_cmd') {
 6953:        # an old lond will not know currentdump
 6954:        # Do a dump and make it look like a currentdump
 6955:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 6956:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 6957:        my %hash = @tmp;
 6958:        @tmp=();
 6959:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 6960:    } else {
 6961:        my @pairs=split(/\&/,$rep);
 6962:        foreach my $pair (@pairs) {
 6963:            my ($key,$value)=split(/=/,$pair,2);
 6964:            my ($symb,$param) = split(/:/,$key);
 6965:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 6966:                                                         &thaw_unescape($value);
 6967:        }
 6968:    }
 6969:    return %returnhash;
 6970: }
 6971: 
 6972: sub convert_dump_to_currentdump{
 6973:     my %hash = %{shift()};
 6974:     my %returnhash;
 6975:     # Code ripped from lond, essentially.  The only difference
 6976:     # here is the unescaping done by lonnet::dump().  Conceivably
 6977:     # we might run in to problems with parameter names =~ /^v\./
 6978:     while (my ($key,$value) = each(%hash)) {
 6979:         my ($v,$symb,$param) = split(/:/,$key);
 6980: 	$symb  = &unescape($symb);
 6981: 	$param = &unescape($param);
 6982:         next if ($v eq 'version' || $symb eq 'keys');
 6983:         next if (exists($returnhash{$symb}) &&
 6984:                  exists($returnhash{$symb}->{$param}) &&
 6985:                  $returnhash{$symb}->{'v.'.$param} > $v);
 6986:         $returnhash{$symb}->{$param}=$value;
 6987:         $returnhash{$symb}->{'v.'.$param}=$v;
 6988:     }
 6989:     #
 6990:     # Remove all of the keys in the hashes which keep track of
 6991:     # the version of the parameter.
 6992:     while (my ($symb,$param_hash) = each(%returnhash)) {
 6993:         # use a foreach because we are going to delete from the hash.
 6994:         foreach my $key (keys(%$param_hash)) {
 6995:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 6996:         }
 6997:     }
 6998:     return \%returnhash;
 6999: }
 7000: 
 7001: # ------------------------------------------------------ critical inc interface
 7002: 
 7003: sub cinc {
 7004:     return &inc(@_,'critical');
 7005: }
 7006: 
 7007: # --------------------------------------------------------------- inc interface
 7008: 
 7009: sub inc {
 7010:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 7011:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 7012:     if (!$uname) { $uname=$env{'user.name'}; }
 7013:     my $uhome=&homeserver($uname,$udomain);
 7014:     my $items='';
 7015:     if (! ref($store)) {
 7016:         # got a single value, so use that instead
 7017:         $items = &escape($store).'=&';
 7018:     } elsif (ref($store) eq 'SCALAR') {
 7019:         $items = &escape($$store).'=&';        
 7020:     } elsif (ref($store) eq 'ARRAY') {
 7021:         $items = join('=&',map {&escape($_);} @{$store});
 7022:     } elsif (ref($store) eq 'HASH') {
 7023:         while (my($key,$value) = each(%{$store})) {
 7024:             $items.= &escape($key).'='.&escape($value).'&';
 7025:         }
 7026:     }
 7027:     $items=~s/\&$//;
 7028:     if ($critical) {
 7029: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 7030:     } else {
 7031: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 7032:     }
 7033: }
 7034: 
 7035: # --------------------------------------------------------------- put interface
 7036: 
 7037: sub put {
 7038:    my ($namespace,$storehash,$udomain,$uname)=@_;
 7039:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7040:    if (!$uname) { $uname=$env{'user.name'}; }
 7041:    my $uhome=&homeserver($uname,$udomain);
 7042:    my $items='';
 7043:    foreach my $item (keys(%$storehash)) {
 7044:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 7045:    }
 7046:    $items=~s/\&$//;
 7047:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 7048: }
 7049: 
 7050: # ------------------------------------------------------------ newput interface
 7051: 
 7052: sub newput {
 7053:    my ($namespace,$storehash,$udomain,$uname)=@_;
 7054:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7055:    if (!$uname) { $uname=$env{'user.name'}; }
 7056:    my $uhome=&homeserver($uname,$udomain);
 7057:    my $items='';
 7058:    foreach my $key (keys(%$storehash)) {
 7059:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 7060:    }
 7061:    $items=~s/\&$//;
 7062:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 7063: }
 7064: 
 7065: # ---------------------------------------------------------  putstore interface
 7066: 
 7067: sub putstore {
 7068:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
 7069:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7070:    if (!$uname) { $uname=$env{'user.name'}; }
 7071:    my $uhome=&homeserver($uname,$udomain);
 7072:    my $items='';
 7073:    foreach my $key (keys(%$storehash)) {
 7074:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 7075:    }
 7076:    $items=~s/\&$//;
 7077:    my $esc_symb=&escape($symb);
 7078:    my $esc_v=&escape($version);
 7079:    my $reply =
 7080:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 7081: 	      $uhome);
 7082:    if (($tolog) && ($reply eq 'ok')) {
 7083:        my $namevalue='';
 7084:        foreach my $key (keys(%{$storehash})) {
 7085:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 7086:        }
 7087:        my $ip = &get_requestor_ip();
 7088:        $namevalue .= 'ip='.&escape($ip).
 7089:                      '&host='.&escape($perlvar{'lonHostID'}).
 7090:                      '&version='.$esc_v.
 7091:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
 7092:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
 7093:    }
 7094:    if ($reply eq 'unknown_cmd') {
 7095:        # gfall back to way things use to be done
 7096:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 7097: 			    $uname);
 7098:    }
 7099:    return $reply;
 7100: }
 7101: 
 7102: sub old_putstore {
 7103:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 7104:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 7105:     if (!$uname) { $uname=$env{'user.name'}; }
 7106:     my $uhome=&homeserver($uname,$udomain);
 7107:     my %newstorehash;
 7108:     foreach my $item (keys(%$storehash)) {
 7109: 	my $key = $version.':'.&escape($symb).':'.$item;
 7110: 	$newstorehash{$key} = $storehash->{$item};
 7111:     }
 7112:     my $items='';
 7113:     my %allitems = ();
 7114:     foreach my $item (keys(%newstorehash)) {
 7115: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 7116: 	    my $key = $1.':keys:'.$2;
 7117: 	    $allitems{$key} .= $3.':';
 7118: 	}
 7119: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 7120:     }
 7121:     foreach my $item (keys(%allitems)) {
 7122: 	$allitems{$item} =~ s/\:$//;
 7123: 	$items.= $item.'='.$allitems{$item}.'&';
 7124:     }
 7125:     $items=~s/\&$//;
 7126:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 7127: }
 7128: 
 7129: # ------------------------------------------------------ critical put interface
 7130: 
 7131: sub cput {
 7132:    my ($namespace,$storehash,$udomain,$uname)=@_;
 7133:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7134:    if (!$uname) { $uname=$env{'user.name'}; }
 7135:    my $uhome=&homeserver($uname,$udomain);
 7136:    my $items='';
 7137:    foreach my $item (keys(%$storehash)) {
 7138:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 7139:    }
 7140:    $items=~s/\&$//;
 7141:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 7142: }
 7143: 
 7144: # -------------------------------------------------------------- eget interface
 7145: 
 7146: sub eget {
 7147:    my ($namespace,$storearr,$udomain,$uname)=@_;
 7148:    my $items='';
 7149:    foreach my $item (@$storearr) {
 7150:        $items.=&escape($item).'&';
 7151:    }
 7152:    $items=~s/\&$//;
 7153:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7154:    if (!$uname) { $uname=$env{'user.name'}; }
 7155:    my $uhome=&homeserver($uname,$udomain);
 7156:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 7157:    my @pairs=split(/\&/,$rep);
 7158:    my %returnhash=();
 7159:    my $i=0;
 7160:    foreach my $item (@$storearr) {
 7161:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 7162:       $i++;
 7163:    }
 7164:    return %returnhash;
 7165: }
 7166: 
 7167: # ------------------------------------------------------------ tmpput interface
 7168: sub tmpput {
 7169:     my ($storehash,$server,$context)=@_;
 7170:     my $items='';
 7171:     foreach my $item (keys(%$storehash)) {
 7172: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 7173:     }
 7174:     $items=~s/\&$//;
 7175:     if (defined($context)) {
 7176:         $items .= ':'.&escape($context);
 7177:     }
 7178:     return &reply("tmpput:$items",$server);
 7179: }
 7180: 
 7181: # ------------------------------------------------------------ tmpget interface
 7182: sub tmpget {
 7183:     my ($token,$server)=@_;
 7184:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 7185:     my $rep=&reply("tmpget:$token",$server);
 7186:     my %returnhash;
 7187:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
 7188:         return %returnhash;
 7189:     }
 7190:     foreach my $item (split(/\&/,$rep)) {
 7191: 	my ($key,$value)=split(/=/,$item);
 7192: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 7193:     }
 7194:     return %returnhash;
 7195: }
 7196: 
 7197: # ------------------------------------------------------------ tmpdel interface
 7198: sub tmpdel {
 7199:     my ($token,$server)=@_;
 7200:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 7201:     return &reply("tmpdel:$token",$server);
 7202: }
 7203: 
 7204: # ------------------------------------------------------------ get_timebased_id
 7205: 
 7206: sub get_timebased_id {
 7207:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
 7208:         $maxtries) = @_;
 7209:     my ($newid,$error,$dellock);
 7210:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
 7211:         return ('','ok','invalid call to get suffix');
 7212:     }
 7213: 
 7214: # set defaults for any optional args for which values were not supplied
 7215:     if ($who eq '') {
 7216:         $who = $env{'user.name'}.':'.$env{'user.domain'};
 7217:     }
 7218:     if (!$locktries) {
 7219:         $locktries = 3;
 7220:     }
 7221:     if (!$maxtries) {
 7222:         $maxtries = 10;
 7223:     }
 7224: 
 7225:     if (($cdom eq '') || ($cnum eq '')) {
 7226:         if ($env{'request.course.id'}) {
 7227:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7228:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7229:         }
 7230:         if (($cdom eq '') || ($cnum eq '')) {
 7231:             return ('','ok','call to get suffix not in course context');
 7232:         }
 7233:     }
 7234: 
 7235: # construct locking item
 7236:     my $lockhash = {
 7237:                       $prefix."\0".'locked_'.$keyid => $who,
 7238:                    };
 7239:     my $tries = 0;
 7240: 
 7241: # attempt to get lock on nohist_$namespace file
 7242:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 7243:     while (($gotlock ne 'ok') && $tries <$locktries) {
 7244:         $tries ++;
 7245:         sleep 1;
 7246:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 7247:     }
 7248: 
 7249: # attempt to get unique identifier, based on current timestamp
 7250:     if ($gotlock eq 'ok') {
 7251:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
 7252:         my $id = time;
 7253:         $newid = $id;
 7254:         if ($idtype eq 'addcode') {
 7255:             $newid .= &sixnum_code();
 7256:         }
 7257:         my $idtries = 0;
 7258:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
 7259:             if ($idtype eq 'concat') {
 7260:                 $newid = $id.$idtries;
 7261:             } elsif ($idtype eq 'addcode') {
 7262:                 $newid = $newid.&sixnum_code();
 7263:             } else {
 7264:                 $newid ++;
 7265:             }
 7266:             $idtries ++;
 7267:         }
 7268:         if (!exists($inuse{$prefix."\0".$newid})) {
 7269:             my %new_item =  (
 7270:                               $prefix."\0".$newid => $who,
 7271:                             );
 7272:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
 7273:                                                  $cdom,$cnum);
 7274:             if ($putresult ne 'ok') {
 7275:                 undef($newid);
 7276:                 $error = 'error saving new item: '.$putresult;
 7277:             }
 7278:         } else {
 7279:              undef($newid);
 7280:              $error = ('error: no unique suffix available for the new item ');
 7281:         }
 7282: #  remove lock
 7283:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
 7284:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
 7285:     } else {
 7286:         $error = "error: could not obtain lockfile\n";
 7287:         $dellock = 'ok';
 7288:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
 7289:             $dellock = 'nolock';
 7290:         }
 7291:     }
 7292:     return ($newid,$dellock,$error);
 7293: }
 7294: 
 7295: sub sixnum_code {
 7296:     my $code;
 7297:     for (0..6) {
 7298:         $code .= int( rand(9) );
 7299:     }
 7300:     return $code;
 7301: }
 7302: 
 7303: # -------------------------------------------------- portfolio access checking
 7304: 
 7305: sub portfolio_access {
 7306:     my ($requrl,$clientip) = @_;
 7307:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 7308:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
 7309:     if ($result) {
 7310:         my %setters;
 7311:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 7312:             my ($startblock,$endblock) =
 7313:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 7314:             if ($startblock && $endblock) {
 7315:                 return 'B';
 7316:             }
 7317:         } else {
 7318:             my ($startblock,$endblock) =
 7319:                 &Apache::loncommon::blockcheck(\%setters,'port');
 7320:             if ($startblock && $endblock) {
 7321:                 return 'B';
 7322:             }
 7323:         }
 7324:     }
 7325:     if ($result eq 'ok') {
 7326:        return 'F';
 7327:     } elsif ($result =~ /^[^:]+:guest_/) {
 7328:        return 'A';
 7329:     }
 7330:     return '';
 7331: }
 7332: 
 7333: sub get_portfolio_access {
 7334:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
 7335: 
 7336:     if (!ref($access_hash)) {
 7337: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 7338: 	my %access_controls = &get_access_controls($current_perms,$group,
 7339: 						   $file_name);
 7340: 	$access_hash = $access_controls{$file_name};
 7341:     }
 7342: 
 7343:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
 7344:     my $now = time;
 7345:     if (ref($access_hash) eq 'HASH') {
 7346:         foreach my $key (keys(%{$access_hash})) {
 7347:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 7348:             if ($start > $now) {
 7349:                 next;
 7350:             }
 7351:             if ($end && $end<$now) {
 7352:                 next;
 7353:             }
 7354:             if ($scope eq 'public') {
 7355:                 $public = $key;
 7356:                 last;
 7357:             } elsif ($scope eq 'guest') {
 7358:                 $guest = $key;
 7359:             } elsif ($scope eq 'domains') {
 7360:                 push(@domains,$key);
 7361:             } elsif ($scope eq 'users') {
 7362:                 push(@users,$key);
 7363:             } elsif ($scope eq 'course') {
 7364:                 push(@courses,$key);
 7365:             } elsif ($scope eq 'group') {
 7366:                 push(@groups,$key);
 7367:             } elsif ($scope eq 'ip') {
 7368:                 push(@ips,$key);
 7369:             }
 7370:         }
 7371:         if ($public) {
 7372:             return 'ok';
 7373:         } elsif (@ips > 0) {
 7374:             my $allowed;
 7375:             foreach my $ipkey (@ips) {
 7376:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
 7377:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
 7378:                         $allowed = 1;
 7379:                         last;
 7380:                     }
 7381:                 }
 7382:             }
 7383:             if ($allowed) {
 7384:                 return 'ok';
 7385:             }
 7386:         }
 7387:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 7388:             if ($guest) {
 7389:                 return $guest;
 7390:             }
 7391:         } else {
 7392:             if (@domains > 0) {
 7393:                 foreach my $domkey (@domains) {
 7394:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 7395:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 7396:                             return 'ok';
 7397:                         }
 7398:                     }
 7399:                 }
 7400:             }
 7401:             if (@users > 0) {
 7402:                 foreach my $userkey (@users) {
 7403:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 7404:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 7405:                             if (ref($item) eq 'HASH') {
 7406:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 7407:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 7408:                                     return 'ok';
 7409:                                 }
 7410:                             }
 7411:                         }
 7412:                     } 
 7413:                 }
 7414:             }
 7415:             my %roleshash;
 7416:             my @courses_and_groups = @courses;
 7417:             push(@courses_and_groups,@groups); 
 7418:             if (@courses_and_groups > 0) {
 7419:                 my (%allgroups,%allroles); 
 7420:                 my ($start,$end,$role,$sec,$group);
 7421:                 foreach my $envkey (%env) {
 7422:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 7423:                         my $cid = $2.'_'.$3; 
 7424:                         if ($1 eq 'gr') {
 7425:                             $group = $4;
 7426:                             $allgroups{$cid}{$group} = $env{$envkey};
 7427:                         } else {
 7428:                             if ($4 eq '') {
 7429:                                 $sec = 'none';
 7430:                             } else {
 7431:                                 $sec = $4;
 7432:                             }
 7433:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 7434:                         }
 7435:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 7436:                         my $cid = $2.'_'.$3;
 7437:                         if ($4 eq '') {
 7438:                             $sec = 'none';
 7439:                         } else {
 7440:                             $sec = $4;
 7441:                         }
 7442:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 7443:                     }
 7444:                 }
 7445:                 if (keys(%allroles) == 0) {
 7446:                     return;
 7447:                 }
 7448:                 foreach my $key (@courses_and_groups) {
 7449:                     my %content = %{$$access_hash{$key}};
 7450:                     my $cnum = $content{'number'};
 7451:                     my $cdom = $content{'domain'};
 7452:                     my $cid = $cdom.'_'.$cnum;
 7453:                     if (!exists($allroles{$cid})) {
 7454:                         next;
 7455:                     }    
 7456:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 7457:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 7458:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 7459:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 7460:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 7461:                         foreach my $role (keys(%{$allroles{$cid}})) {
 7462:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 7463:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 7464:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 7465:                                         if (grep/^all$/,@sections) {
 7466:                                             return 'ok';
 7467:                                         } else {
 7468:                                             if (grep/^$sec$/,@sections) {
 7469:                                                 return 'ok';
 7470:                                             }
 7471:                                         }
 7472:                                     }
 7473:                                 }
 7474:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 7475:                                     if (grep/^none$/,@groups) {
 7476:                                         return 'ok';
 7477:                                     }
 7478:                                 } else {
 7479:                                     if (grep/^all$/,@groups) {
 7480:                                         return 'ok';
 7481:                                     } 
 7482:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 7483:                                         if (grep/^$group$/,@groups) {
 7484:                                             return 'ok';
 7485:                                         }
 7486:                                     }
 7487:                                 } 
 7488:                             }
 7489:                         }
 7490:                     }
 7491:                 }
 7492:             }
 7493:             if ($guest) {
 7494:                 return $guest;
 7495:             }
 7496:         }
 7497:     }
 7498:     return;
 7499: }
 7500: 
 7501: sub course_group_datechecker {
 7502:     my ($dates,$now,$status) = @_;
 7503:     my ($start,$end) = split(/\./,$dates);
 7504:     if (!$start && !$end) {
 7505:         return 'ok';
 7506:     }
 7507:     if (grep/^active$/,@{$status}) {
 7508:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 7509:             return 'ok';
 7510:         }
 7511:     }
 7512:     if (grep/^previous$/,@{$status}) {
 7513:         if ($end > $now ) {
 7514:             return 'ok';
 7515:         }
 7516:     }
 7517:     if (grep/^future$/,@{$status}) {
 7518:         if ($start > $now) {
 7519:             return 'ok';
 7520:         }
 7521:     }
 7522:     return; 
 7523: }
 7524: 
 7525: sub parse_portfolio_url {
 7526:     my ($url) = @_;
 7527: 
 7528:     my ($type,$udom,$unum,$group,$file_name);
 7529:     
 7530:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 7531: 	$type = 1;
 7532:         $udom = $1;
 7533:         $unum = $2;
 7534:         $file_name = $3;
 7535:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 7536: 	$type = 2;
 7537:         $udom = $1;
 7538:         $unum = $2;
 7539:         $group = $3;
 7540:         $file_name = $3.'/'.$4;
 7541:     }
 7542:     if (wantarray) {
 7543: 	return ($type,$udom,$unum,$file_name,$group);
 7544:     }
 7545:     return $type;
 7546: }
 7547: 
 7548: sub is_portfolio_url {
 7549:     my ($url) = @_;
 7550:     return scalar(&parse_portfolio_url($url));
 7551: }
 7552: 
 7553: sub is_portfolio_file {
 7554:     my ($file) = @_;
 7555:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 7556:         return 1;
 7557:     }
 7558:     return;
 7559: }
 7560: 
 7561: sub usertools_access {
 7562:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
 7563:     my ($access,%tools);
 7564:     if ($context eq '') {
 7565:         $context = 'tools';
 7566:     }
 7567:     if ($context eq 'requestcourses') {
 7568:         %tools = (
 7569:                       official   => 1,
 7570:                       unofficial => 1,
 7571:                       community  => 1,
 7572:                       textbook   => 1,
 7573:                  );
 7574:     } elsif ($context eq 'requestauthor') {
 7575:         %tools = (
 7576:                       requestauthor => 1,
 7577:                  );
 7578:     } else {
 7579:         %tools = (
 7580:                       aboutme   => 1,
 7581:                       blog      => 1,
 7582:                       webdav    => 1,
 7583:                       portfolio => 1,
 7584:                  );
 7585:     }
 7586:     return if (!defined($tools{$tool}));
 7587: 
 7588:     if (($udom eq '') || ($uname eq '')) {
 7589:         $udom = $env{'user.domain'};
 7590:         $uname = $env{'user.name'};
 7591:     }
 7592: 
 7593:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 7594:         if ($action ne 'reload') {
 7595:             if ($context eq 'requestcourses') {
 7596:                 return $env{'environment.canrequest.'.$tool};
 7597:             } elsif ($context eq 'requestauthor') {
 7598:                 return $env{'environment.canrequest.author'};
 7599:             } else {
 7600:                 return $env{'environment.availabletools.'.$tool};
 7601:             }
 7602:         }
 7603:     }
 7604: 
 7605:     my ($toolstatus,$inststatus,$envkey);
 7606:     if ($context eq 'requestauthor') {
 7607:         $envkey = $context;
 7608:     } else {
 7609:         $envkey = $context.'.'.$tool;
 7610:     }
 7611: 
 7612:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 7613:          ($action ne 'reload')) {
 7614:         $toolstatus = $env{'environment.'.$envkey};
 7615:         $inststatus = $env{'environment.inststatus'};
 7616:     } else {
 7617:         if (ref($userenvref) eq 'HASH') {
 7618:             $toolstatus = $userenvref->{$envkey};
 7619:             $inststatus = $userenvref->{'inststatus'};
 7620:         } else {
 7621:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
 7622:             $toolstatus = $userenv{$envkey};
 7623:             $inststatus = $userenv{'inststatus'};
 7624:         }
 7625:     }
 7626: 
 7627:     if ($toolstatus ne '') {
 7628:         if ($toolstatus) {
 7629:             $access = 1;
 7630:         } else {
 7631:             $access = 0;
 7632:         }
 7633:         return $access;
 7634:     }
 7635: 
 7636:     my ($is_adv,%domdef);
 7637:     if (ref($is_advref) eq 'HASH') {
 7638:         $is_adv = $is_advref->{'is_adv'};
 7639:     } else {
 7640:         $is_adv = &is_advanced_user($udom,$uname);
 7641:     }
 7642:     if (ref($domdefref) eq 'HASH') {
 7643:         %domdef = %{$domdefref};
 7644:     } else {
 7645:         %domdef = &get_domain_defaults($udom);
 7646:     }
 7647:     if (ref($domdef{$tool}) eq 'HASH') {
 7648:         if ($is_adv) {
 7649:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 7650:                 if ($domdef{$tool}{'_LC_adv'}) { 
 7651:                     $access = 1;
 7652:                 } else {
 7653:                     $access = 0;
 7654:                 }
 7655:                 return $access;
 7656:             }
 7657:         }
 7658:         if ($inststatus ne '') {
 7659:             my ($hasaccess,$hasnoaccess);
 7660:             foreach my $affiliation (split(/:/,$inststatus)) {
 7661:                 if ($domdef{$tool}{$affiliation} ne '') { 
 7662:                     if ($domdef{$tool}{$affiliation}) {
 7663:                         $hasaccess = 1;
 7664:                     } else {
 7665:                         $hasnoaccess = 1;
 7666:                     }
 7667:                 }
 7668:             }
 7669:             if ($hasaccess || $hasnoaccess) {
 7670:                 if ($hasaccess) {
 7671:                     $access = 1;
 7672:                 } elsif ($hasnoaccess) {
 7673:                     $access = 0; 
 7674:                 }
 7675:                 return $access;
 7676:             }
 7677:         } else {
 7678:             if ($domdef{$tool}{'default'} ne '') {
 7679:                 if ($domdef{$tool}{'default'}) {
 7680:                     $access = 1;
 7681:                 } elsif ($domdef{$tool}{'default'} == 0) {
 7682:                     $access = 0;
 7683:                 }
 7684:                 return $access;
 7685:             }
 7686:         }
 7687:     } else {
 7688:         if (($context eq 'tools') && ($tool ne 'webdav')) {
 7689:             $access = 1;
 7690:         } else {
 7691:             $access = 0;
 7692:         }
 7693:         return $access;
 7694:     }
 7695: }
 7696: 
 7697: sub is_course_owner {
 7698:     my ($cdom,$cnum,$udom,$uname) = @_;
 7699:     if (($udom eq '') || ($uname eq '')) {
 7700:         $udom = $env{'user.domain'};
 7701:         $uname = $env{'user.name'};
 7702:     }
 7703:     unless (($udom eq '') || ($uname eq '')) {
 7704:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
 7705:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
 7706:                 return 1;
 7707:             } else {
 7708:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
 7709:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
 7710:                     return 1;
 7711:                 }
 7712:             }
 7713:         }
 7714:     }
 7715:     return;
 7716: }
 7717: 
 7718: sub is_advanced_user {
 7719:     my ($udom,$uname) = @_;
 7720:     if ($udom ne '' && $uname ne '') {
 7721:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 7722:             if (wantarray) {
 7723:                 return ($env{'user.adv'},$env{'user.author'});
 7724:             } else {
 7725:                 return $env{'user.adv'};
 7726:             }
 7727:         }
 7728:     }
 7729:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 7730:     my %allroles;
 7731:     my ($is_adv,$is_author);
 7732:     foreach my $role (keys(%roleshash)) {
 7733:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 7734:         my $area = '/'.$tdomain.'/'.$trest;
 7735:         if ($sec ne '') {
 7736:             $area .= '/'.$sec;
 7737:         }
 7738:         if (($area ne '') && ($trole ne '')) {
 7739:             my $spec=$trole.'.'.$area;
 7740:             if ($trole =~ /^cr\//) {
 7741:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 7742:             } elsif ($trole ne 'gr') {
 7743:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 7744:             }
 7745:             if ($trole eq 'au') {
 7746:                 $is_author = 1;
 7747:             }
 7748:         }
 7749:     }
 7750:     foreach my $role (keys(%allroles)) {
 7751:         last if ($is_adv);
 7752:         foreach my $item (split(/:/,$allroles{$role})) {
 7753:             if ($item ne '') {
 7754:                 my ($privilege,$restrictions)=split(/&/,$item);
 7755:                 if ($privilege eq 'adv') {
 7756:                     $is_adv = 1;
 7757:                     last;
 7758:                 }
 7759:             }
 7760:         }
 7761:     }
 7762:     if (wantarray) {
 7763:         return ($is_adv,$is_author);
 7764:     }
 7765:     return $is_adv;
 7766: }
 7767: 
 7768: sub check_can_request {
 7769:     my ($dom,$can_request,$request_domains) = @_;
 7770:     my $canreq = 0;
 7771:     my ($types,$typename) = &Apache::loncommon::course_types();
 7772:     my @options = ('approval','validate','autolimit');
 7773:     my $optregex = join('|',@options);
 7774:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
 7775:         foreach my $type (@{$types}) {
 7776:             if (&usertools_access($env{'user.name'},
 7777:                                   $env{'user.domain'},
 7778:                                   $type,undef,'requestcourses')) {
 7779:                 $canreq ++;
 7780:                 if (ref($request_domains) eq 'HASH') {
 7781:                     push(@{$request_domains->{$type}},$env{'user.domain'});
 7782:                 }
 7783:                 if ($dom eq $env{'user.domain'}) {
 7784:                     $can_request->{$type} = 1;
 7785:                 }
 7786:             }
 7787:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
 7788:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
 7789:                 if (@curr > 0) {
 7790:                     foreach my $item (@curr) {
 7791:                         if (ref($request_domains) eq 'HASH') {
 7792:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
 7793:                             if ($otherdom ne '') {
 7794:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
 7795:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
 7796:                                         push(@{$request_domains->{$type}},$otherdom);
 7797:                                     }
 7798:                                 } else {
 7799:                                     push(@{$request_domains->{$type}},$otherdom);
 7800:                                 }
 7801:                             }
 7802:                         }
 7803:                     }
 7804:                     unless($dom eq $env{'user.domain'}) {
 7805:                         $canreq ++;
 7806:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
 7807:                             $can_request->{$type} = 1;
 7808:                         }
 7809:                     }
 7810:                 }
 7811:             }
 7812:         }
 7813:     }
 7814:     return $canreq;
 7815: }
 7816: 
 7817: # ---------------------------------------------- Custom access rule evaluation
 7818: 
 7819: sub customaccess {
 7820:     my ($priv,$uri)=@_;
 7821:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 7822:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 7823:     $udom = &LONCAPA::clean_domain($udom);
 7824:     $ucrs = &LONCAPA::clean_username($ucrs);
 7825:     my $access=0;
 7826:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 7827: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 7828: 	if ($type eq 'user') {
 7829: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 7830: 		my ($tdom,$tuname)=split(m{/},$scope);
 7831: 		if ($tdom) {
 7832: 		    if ($tdom ne $env{'user.domain'}) { next; }
 7833: 		}
 7834: 		if ($tuname) {
 7835: 		    if ($tuname ne $env{'user.name'}) { next; }
 7836: 		}
 7837: 		$access=($effect eq 'allow');
 7838: 		last;
 7839: 	    }
 7840: 	} else {
 7841: 	    if ($role) {
 7842: 		if ($role ne $urole) { next; }
 7843: 	    }
 7844: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 7845: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 7846: 		if ($tdom) {
 7847: 		    if ($tdom ne $udom) { next; }
 7848: 		}
 7849: 		if ($tcrs) {
 7850: 		    if ($tcrs ne $ucrs) { next; }
 7851: 		}
 7852: 		if ($tsec) {
 7853: 		    if ($tsec ne $usec) { next; }
 7854: 		}
 7855: 		$access=($effect eq 'allow');
 7856: 		last;
 7857: 	    }
 7858: 	    if ($realm eq '' && $role eq '') {
 7859: 		$access=($effect eq 'allow');
 7860: 	    }
 7861: 	}
 7862:     }
 7863:     return $access;
 7864: }
 7865: 
 7866: # ------------------------------------------------- Check for a user privilege
 7867: 
 7868: sub allowed {
 7869:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck,$ignorecache)=@_;
 7870:     my $ver_orguri=$uri;
 7871:     $uri=&deversion($uri);
 7872:     my $orguri=$uri;
 7873:     $uri=&declutter($uri);
 7874: 
 7875:     if ($priv eq 'evb') {
 7876: # Evade communication block restrictions for specified role in a course
 7877:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 7878:             return $1;
 7879:         } else {
 7880:             return;
 7881:         }
 7882:     }
 7883: 
 7884:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 7885: # Free bre access to adm and meta resources
 7886:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|viewclasslist|aboutme|ext\.tool)$})) 
 7887: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 7888: 	&& ($priv eq 'bre')) {
 7889: 	return 'F';
 7890:     }
 7891: 
 7892: # Free bre access to user's own portfolio contents
 7893:     my ($space,$domain,$name,@dir)=split('/',$uri);
 7894:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 7895: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 7896:         my %setters;
 7897:         my ($startblock,$endblock) = 
 7898:             &Apache::loncommon::blockcheck(\%setters,'port');
 7899:         if ($startblock && $endblock) {
 7900:             return 'B';
 7901:         } else {
 7902:             return 'F';
 7903:         }
 7904:     }
 7905: 
 7906: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 7907:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 7908:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 7909:         if (exists($env{'request.course.id'})) {
 7910:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7911:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7912:             if (($domain eq $cdom) && ($name eq $cnum)) {
 7913:                 my $courseprivid=$env{'request.course.id'};
 7914:                 $courseprivid=~s/\_/\//;
 7915:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 7916:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 7917:                     return $1; 
 7918:                 } else {
 7919:                     if ($env{'request.course.sec'}) {
 7920:                         $courseprivid.='/'.$env{'request.course.sec'};
 7921:                     }
 7922:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 7923:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 7924:                         return $2;
 7925:                     }
 7926:                 }
 7927:             }
 7928:         }
 7929:     }
 7930: 
 7931: # Free bre to public access
 7932: 
 7933:     if ($priv eq 'bre') {
 7934:         my $copyright=&metadata($uri,'copyright');
 7935: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 7936:            return 'F'; 
 7937:         }
 7938:         if ($copyright eq 'priv') {
 7939:             $uri=~/([^\/]+)\/([^\/]+)\//;
 7940: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 7941: 		return '';
 7942:             }
 7943:         }
 7944:         if ($copyright eq 'domain') {
 7945:             $uri=~/([^\/]+)\/([^\/]+)\//;
 7946: 	    unless (($env{'user.domain'} eq $1) ||
 7947:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 7948: 		return '';
 7949:             }
 7950:         }
 7951:         if ($env{'request.role'}=~ /li\.\//) {
 7952:             # Library role, so allow browsing of resources in this domain.
 7953:             return 'F';
 7954:         }
 7955:         if ($copyright eq 'custom') {
 7956: 	    unless (&customaccess($priv,$uri)) { return ''; }
 7957:         }
 7958:     }
 7959:     # Domain coordinator is trying to create a course
 7960:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 7961:         # uri is the requested domain in this case.
 7962:         # comparison to 'request.role.domain' shows if the user has selected
 7963:         # a role of dc for the domain in question.
 7964:         return 'F' if ($uri eq $env{'request.role.domain'});
 7965:     }
 7966: 
 7967:     my $thisallowed='';
 7968:     my $statecond=0;
 7969:     my $courseprivid='';
 7970: 
 7971:     my $ownaccess;
 7972:     # Community Coordinator or Assistant Co-author browsing resource space.
 7973:     if (($priv eq 'bro') && ($env{'user.author'})) {
 7974:         if ($uri eq '') {
 7975:             $ownaccess = 1;
 7976:         } else {
 7977:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
 7978:                 my $udom = $env{'user.domain'};
 7979:                 my $uname = $env{'user.name'};
 7980:                 if ($uri =~ m{^\Q$udom\E/?$}) {
 7981:                     $ownaccess = 1;
 7982:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
 7983:                     unless ($uri =~ m{\.\./}) {
 7984:                         $ownaccess = 1;
 7985:                     }
 7986:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
 7987:                     my $now = time;
 7988:                     if ($uri =~ m{^([^/]+)/?$}) {
 7989:                         my $adom = $1;
 7990:                         foreach my $key (keys(%env)) {
 7991:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
 7992:                                 my ($start,$end) = split('.',$env{$key});
 7993:                                 if (($now >= $start) && (!$end || $end < $now)) {
 7994:                                     $ownaccess = 1;
 7995:                                     last;
 7996:                                 }
 7997:                             }
 7998:                         }
 7999:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
 8000:                         my $adom = $1;
 8001:                         my $aname = $2;
 8002:                         foreach my $role ('ca','aa') { 
 8003:                             if ($env{"user.role.$role./$adom/$aname"}) {
 8004:                                 my ($start,$end) =
 8005:                                     split('.',$env{"user.role.$role./$adom/$aname"});
 8006:                                 if (($now >= $start) && (!$end || $end < $now)) {
 8007:                                     $ownaccess = 1;
 8008:                                     last;
 8009:                                 }
 8010:                             }
 8011:                         }
 8012:                     }
 8013:                 }
 8014:             }
 8015:         }
 8016:     }
 8017: 
 8018: # Course
 8019: 
 8020:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 8021:         unless (($priv eq 'bro') && (!$ownaccess)) {
 8022:             $thisallowed.=$1;
 8023:         }
 8024:     }
 8025: 
 8026: # Domain
 8027: 
 8028:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 8029:        =~/\Q$priv\E\&([^\:]*)/) {
 8030:         unless (($priv eq 'bro') && (!$ownaccess)) {
 8031:             $thisallowed.=$1;
 8032:         }
 8033:     }
 8034: 
 8035: # User who is not author or co-author might still be able to edit
 8036: # resource of an author in the domain (e.g., if Domain Coordinator).
 8037:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
 8038:         (&allowed('mdc',$env{'request.course.id'}))) {
 8039:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
 8040:             $thisallowed.=$1;
 8041:         }
 8042:     }
 8043: 
 8044: # Course: uri itself is a course
 8045:     my $courseuri=$uri;
 8046:     $courseuri=~s/\_(\d)/\/$1/;
 8047:     $courseuri=~s/^([^\/])/\/$1/;
 8048: 
 8049:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 8050:        =~/\Q$priv\E\&([^\:]*)/) {
 8051:         if ($priv eq 'mip') {
 8052:             my $rem = $1;
 8053:             if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
 8054:                 ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
 8055:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8056:                 if ($cdom ne '') {
 8057:                     my %passwdconf = &get_passwdconf($cdom);
 8058:                     if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
 8059:                         if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
 8060:                             if (@{$passwdconf{'crsownerchg'}{'by'}}) {
 8061:                                 my @inststatuses = split(':',$env{'environment.inststatus'});
 8062:                                 unless (@inststatuses) {
 8063:                                     @inststatuses = ('default');
 8064:                                 }
 8065:                                 foreach my $status (@inststatuses) {
 8066:                                     if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
 8067:                                         $thisallowed.=$rem;
 8068:                                     }
 8069:                                 }
 8070:                             }
 8071:                         }
 8072:                     }
 8073:                 }
 8074:             }
 8075:         } else {
 8076:             unless (($priv eq 'bro') && (!$ownaccess)) {
 8077:                 $thisallowed.=$1;
 8078:             }
 8079:         }
 8080:     }
 8081: 
 8082: # URI is an uploaded document for this course, default permissions don't matter
 8083: # not allowing 'edit' access (editupload) to uploaded course docs
 8084:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 8085: 	$thisallowed='';
 8086:         my ($match)=&is_on_map($uri);
 8087:         if ($match) {
 8088:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 8089:                   =~/\Q$priv\E\&([^\:]*)/) {
 8090:                 my $value = $1;
 8091:                 if ($noblockcheck) {
 8092:                     $thisallowed.=$value;
 8093:                 } else {
 8094:                     my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
 8095:                     if (@blockers > 0) {
 8096:                         $thisallowed = 'B';
 8097:                     } else {
 8098:                         $thisallowed.=$value;
 8099:                     }
 8100:                 }
 8101:             }
 8102:         } else {
 8103:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 8104:             if ($refuri) {
 8105:                 if ($refuri =~ m|^/adm/|) {
 8106:                     $thisallowed='F';
 8107:                 } else {
 8108:                     $refuri=&declutter($refuri);
 8109:                     my ($match) = &is_on_map($refuri);
 8110:                     if ($match) {
 8111:                         if ($noblockcheck) {
 8112:                             $thisallowed='F';
 8113:                         } else {
 8114:                             my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
 8115:                             if (@blockers > 0) {
 8116:                                 $thisallowed = 'B';
 8117:                             } else {
 8118:                                 $thisallowed='F';
 8119:                             }
 8120:                         }
 8121:                     }
 8122:                 }
 8123:             }
 8124:         }
 8125:     }
 8126: 
 8127:     if ($priv eq 'bre'
 8128: 	&& $thisallowed ne 'F' 
 8129: 	&& $thisallowed ne '2'
 8130: 	&& &is_portfolio_url($uri)) {
 8131: 	$thisallowed = &portfolio_access($uri,$clientip);
 8132:     }
 8133: 
 8134: # Full access at system, domain or course-wide level? Exit.
 8135:     if ($thisallowed=~/F/) {
 8136: 	return 'F';
 8137:     }
 8138: 
 8139: # If this is generating or modifying users, exit with special codes
 8140: 
 8141:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 8142: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 8143: 	    my ($audom,$auname)=split('/',$uri);
 8144: # no author name given, so this just checks on the general right to make a co-author in this domain
 8145: 	    unless ($auname) { return $thisallowed; }
 8146: # an author name is given, so we are about to actually make a co-author for a certain account
 8147: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 8148: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 8149: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 8150: 	}
 8151: 	return $thisallowed;
 8152:     }
 8153: #
 8154: # Gathered so far: system, domain and course wide privileges
 8155: #
 8156: # Course: See if uri or referer is an individual resource that is part of 
 8157: # the course
 8158: 
 8159:     if ($env{'request.course.id'}) {
 8160: 
 8161: # If this is modifying password (internal auth) domains must match for user and user's role.
 8162: 
 8163:         if ($priv eq 'mip') {
 8164:             if ($env{'user.domain'} eq $env{'request.role.domain'}) {
 8165:                 return $thisallowed;
 8166:             } else {
 8167:                 return '';
 8168:             }
 8169:         }
 8170: 
 8171:        $courseprivid=$env{'request.course.id'};
 8172:        if ($env{'request.course.sec'}) {
 8173:           $courseprivid.='/'.$env{'request.course.sec'};
 8174:        }
 8175:        $courseprivid=~s/\_/\//;
 8176:        my $checkreferer=1;
 8177:        my ($match,$cond)=&is_on_map($uri);
 8178:        if ($match) {
 8179:            $statecond=$cond;
 8180:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 8181:                =~/\Q$priv\E\&([^\:]*)/) {
 8182:                my $value = $1;
 8183:                if ($priv eq 'bre') {
 8184:                    if ($noblockcheck) {
 8185:                        $thisallowed.=$value;
 8186:                    } else {
 8187:                        my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
 8188:                        if (@blockers > 0) {
 8189:                            $thisallowed = 'B';
 8190:                        } else {
 8191:                            $thisallowed.=$value;
 8192:                        }
 8193:                    }
 8194:                } else {
 8195:                    $thisallowed.=$value;
 8196:                }
 8197:                $checkreferer=0;
 8198:            }
 8199:        }
 8200: 
 8201:        if ($checkreferer) {
 8202: 	  my $refuri=$env{'httpref.'.$orguri};
 8203:             unless ($refuri) {
 8204:                 foreach my $key (keys(%env)) {
 8205: 		    if ($key=~/^httpref\..*\*/) {
 8206: 			my $pattern=$key;
 8207:                         $pattern=~s/^httpref\.\/res\///;
 8208:                         $pattern=~s/\*/\[\^\/\]\+/g;
 8209:                         $pattern=~s/\//\\\//g;
 8210:                         if ($orguri=~/$pattern/) {
 8211: 			    $refuri=$env{$key};
 8212:                         }
 8213:                     }
 8214:                 }
 8215:             }
 8216: 
 8217:          if ($refuri) { 
 8218: 	  $refuri=&declutter($refuri);
 8219:           my ($match,$cond)=&is_on_map($refuri);
 8220:             if ($match) {
 8221:               my $refstatecond=$cond;
 8222:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 8223:                   =~/\Q$priv\E\&([^\:]*)/) {
 8224:                   my $value = $1;
 8225:                   if ($priv eq 'bre') {
 8226:                       if ($noblockcheck) {
 8227:                           $thisallowed.=$value;
 8228:                       } else {
 8229:                           my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
 8230:                           if (@blockers > 0) {
 8231:                               $thisallowed = 'B';
 8232:                           } else {
 8233:                               $thisallowed.=$value;
 8234:                           }
 8235:                       }
 8236:                   } else {
 8237:                       $thisallowed.=$value;
 8238:                   }
 8239:                   $uri=$refuri;
 8240:                   $statecond=$refstatecond;
 8241:               }
 8242:           }
 8243:         }
 8244:        }
 8245:    }
 8246: 
 8247: #
 8248: # Gathered now: all privileges that could apply, and condition number
 8249: # 
 8250: #
 8251: # Full or no access?
 8252: #
 8253: 
 8254:     if ($thisallowed=~/F/) {
 8255: 	return 'F';
 8256:     }
 8257: 
 8258:     unless ($thisallowed) {
 8259:         return '';
 8260:     }
 8261: 
 8262: # Restrictions exist, deal with them
 8263: #
 8264: #   C:according to course preferences
 8265: #   R:according to resource settings
 8266: #   L:unless locked
 8267: #   X:according to user session state
 8268: #
 8269: 
 8270: # Possibly locked functionality, check all courses
 8271: # Locks might take effect only after 10 minutes cache expiration for other
 8272: # courses, and 2 minutes for current course
 8273: 
 8274:     my $envkey;
 8275:     if ($thisallowed=~/L/) {
 8276:         foreach $envkey (keys(%env)) {
 8277:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 8278:                my $courseid=$2;
 8279:                my $roleid=$1.'.'.$2;
 8280:                $courseid=~s/^\///;
 8281:                my $expiretime=600;
 8282:                if ($env{'request.role'} eq $roleid) {
 8283: 		  $expiretime=120;
 8284:                }
 8285: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 8286:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 8287:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 8288: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 8289:                }
 8290:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 8291:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 8292: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 8293:                        &log($env{'user.domain'},$env{'user.name'},
 8294:                             $env{'user.home'},
 8295:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 8296:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 8297:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 8298: 		       return '';
 8299:                    }
 8300:                }
 8301:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 8302:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 8303: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 8304:                        &log($env{'user.domain'},$env{'user.name'},
 8305:                             $env{'user.home'},
 8306:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 8307:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 8308:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 8309: 		       return '';
 8310:                    }
 8311:                }
 8312: 	   }
 8313:        }
 8314:     }
 8315: 
 8316: #
 8317: # Rest of the restrictions depend on selected course
 8318: #
 8319: 
 8320:     unless ($env{'request.course.id'}) {
 8321: 	if ($thisallowed eq 'A') {
 8322: 	    return 'A';
 8323:         } elsif ($thisallowed eq 'B') {
 8324:             return 'B';
 8325: 	} else {
 8326: 	    return '1';
 8327: 	}
 8328:     }
 8329: 
 8330: #
 8331: # Now user is definitely in a course
 8332: #
 8333: 
 8334: 
 8335: # Course preferences
 8336: 
 8337:    if ($thisallowed=~/C/) {
 8338:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 8339:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 8340:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 8341: 	   =~/\Q$rolecode\E/) {
 8342: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 8343: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 8344: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 8345: 			$env{'request.course.id'});
 8346: 	   }
 8347:            return '';
 8348:        }
 8349: 
 8350:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 8351: 	   =~/\Q$unamedom\E/) {
 8352: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 8353: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 8354: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 8355: 			$env{'request.course.id'});
 8356: 	   }
 8357:            return '';
 8358:        }
 8359:    }
 8360: 
 8361: # Resource preferences
 8362: 
 8363:    if ($thisallowed=~/R/) {
 8364:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 8365:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 8366: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 8367: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 8368: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 8369: 	   }
 8370: 	   return '';
 8371:        }
 8372:    }
 8373: 
 8374: # Restricted by state or randomout?
 8375: 
 8376:    if ($thisallowed=~/X/) {
 8377:       if ($env{'acc.randomout'}) {
 8378: 	 if (!$symb) { $symb=&symbread($uri,1); }
 8379:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 8380:             return ''; 
 8381:          }
 8382:       }
 8383:       if (&condval($statecond)) {
 8384: 	 return '2';
 8385:       } else {
 8386:          return '';
 8387:       }
 8388:    }
 8389: 
 8390:     if ($thisallowed eq 'A') {
 8391: 	return 'A';
 8392:     } elsif ($thisallowed eq 'B') {
 8393:         return 'B';
 8394:     }
 8395:    return 'F';
 8396: }
 8397: 
 8398: # ------------------------------------------- Check construction space access
 8399: 
 8400: sub constructaccess {
 8401:     my ($url,$setpriv)=@_;
 8402: 
 8403: # We do not allow editing of previous versions of files
 8404:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
 8405: 
 8406: # Get username and domain from URL
 8407:     my ($ownername,$ownerdomain,$ownerhome);
 8408: 
 8409:     ($ownerdomain,$ownername) =
 8410:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)(?:/|$)});
 8411: 
 8412: # The URL does not really point to any authorspace, forget it
 8413:     unless (($ownername) && ($ownerdomain)) { return ''; }
 8414: 
 8415: # Now we need to see if the user has access to the authorspace of
 8416: # $ownername at $ownerdomain
 8417: 
 8418:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
 8419: # Real author for this?
 8420:        $ownerhome = $env{'user.home'};
 8421:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
 8422:           return ($ownername,$ownerdomain,$ownerhome);
 8423:        }
 8424:     } else {
 8425: # Co-author for this?
 8426:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
 8427:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
 8428:             $ownerhome = &homeserver($ownername,$ownerdomain);
 8429:             return ($ownername,$ownerdomain,$ownerhome);
 8430:         }
 8431:     }
 8432: 
 8433: # We don't have any access right now. If we are not possibly going to do anything about this,
 8434: # we might as well leave
 8435:    unless ($setpriv) { return ''; }
 8436: 
 8437: # Backdoor access?
 8438:     my $allowed=&allowed('eco',$ownerdomain);
 8439: # Nope
 8440:     unless ($allowed) { return ''; }
 8441: # Looks like we may have access, but could be locked by the owner of the construction space
 8442:     if ($allowed eq 'U') {
 8443:         my %blocked=&get('environment',['domcoord.author'],
 8444:                          $ownerdomain,$ownername);
 8445: # Is blocked by owner
 8446:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
 8447:     }
 8448:     if (($allowed eq 'F') || ($allowed eq 'U')) {
 8449: # Grant temporary access
 8450:         my $then=$env{'user.login.time'};
 8451:         my $update=$env{'user.update.time'};
 8452:         if (!$update) { $update = $then; }
 8453:         my $refresh=$env{'user.refresh.time'};
 8454:         if (!$refresh) { $refresh = $update; }
 8455:         my $now = time;
 8456:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
 8457:                            $now,'ca','constructaccess');
 8458:         $ownerhome = &homeserver($ownername,$ownerdomain);
 8459:         return($ownername,$ownerdomain,$ownerhome);
 8460:     }
 8461: # No business here
 8462:     return '';
 8463: }
 8464: 
 8465: # ----------------------------------------------------------- Content Blocking
 8466: 
 8467: {
 8468: # Caches for faster Course Contents display where content blocking
 8469: # is in operation (i.e., interval param set) for timed quiz.
 8470: #
 8471: # User for whom data are being temporarily cached.
 8472: my $cacheduser='';
 8473: # Course for which data are being temporarily cached.
 8474: my $cachedcid='';
 8475: # Cached blockers for this user (a hash of blocking items).
 8476: my %cachedblockers=();
 8477: # When the data were last cached.
 8478: my $cachedlast='';
 8479: 
 8480: sub load_all_blockers {
 8481:     my ($uname,$udom)=@_;
 8482:     if (($uname ne '') && ($udom ne '')) {
 8483:         if (($cacheduser eq $uname.':'.$udom) &&
 8484:             ($cachedcid eq $env{'request.course.id'}) &&
 8485:             (abs($cachedlast-time)<5)) {
 8486:             return;
 8487:         }
 8488:     }
 8489:     $cachedlast=time;
 8490:     $cacheduser=$uname.':'.$udom;
 8491:     $cachedcid=$env{'request.course.id'};
 8492:     %cachedblockers = &get_commblock_resources();
 8493:     return;
 8494: }
 8495: 
 8496: sub get_comm_blocks {
 8497:     my ($cdom,$cnum) = @_;
 8498:     if ($cdom eq '' || $cnum eq '') {
 8499:         return unless ($env{'request.course.id'});
 8500:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8501:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8502:     }
 8503:     my %commblocks;
 8504:     my $hashid=$cdom.'_'.$cnum;
 8505:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
 8506:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
 8507:         %commblocks = %{$blocksref};
 8508:     } else {
 8509:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
 8510:         my $cachetime = 600;
 8511:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
 8512:     }
 8513:     return %commblocks;
 8514: }
 8515: 
 8516: sub get_commblock_resources {
 8517:     my ($blocks) = @_;
 8518:     my %blockers = ();
 8519:     return %blockers unless ($env{'request.course.id'});
 8520:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 8521:     my %commblocks;
 8522:     if (ref($blocks) eq 'HASH') {
 8523:         %commblocks = %{$blocks};
 8524:     } else {
 8525:         %commblocks = &get_comm_blocks();
 8526:     }
 8527:     return %blockers unless (keys(%commblocks) > 0);
 8528:     my $navmap = Apache::lonnavmaps::navmap->new();
 8529:     return %blockers unless (ref($navmap));
 8530:     my $now = time;
 8531:     foreach my $block (keys(%commblocks)) {
 8532:         if ($block =~ /^(\d+)____(\d+)$/) {
 8533:             my ($start,$end) = ($1,$2);
 8534:             if ($start <= $now && $end >= $now) {
 8535:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 8536:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 8537:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 8538:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 8539:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
 8540:                             }
 8541:                         }
 8542:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 8543:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 8544:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 8545:                             }
 8546:                         }
 8547:                     }
 8548:                 }
 8549:             }
 8550:         } elsif ($block =~ /^firstaccess____(.+)$/) {
 8551:             my $item = $1;
 8552:             my @to_test;
 8553:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 8554:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 8555:                     my @interval;
 8556:                     my $type = 'map';
 8557:                     if ($item eq 'course') {
 8558:                         $type = 'course';
 8559:                         @interval=&EXT("resource.0.interval");
 8560:                     } else {
 8561:                         if ($item =~ /___\d+___/) {
 8562:                             $type = 'resource';
 8563:                             @interval=&EXT("resource.0.interval",$item);
 8564:                             if (ref($navmap)) {
 8565:                                 my $res = $navmap->getBySymb($item);
 8566:                                 push(@to_test,$res);
 8567:                             }
 8568:                         } else {
 8569:                             my $mapsymb = &symbread($item,1);
 8570:                             if ($mapsymb) {
 8571:                                 if (ref($navmap)) {
 8572:                                     my $mapres = $navmap->getBySymb($mapsymb);
 8573:                                     if (ref($mapres)) {
 8574:                                         my $first = $mapres->map_start();
 8575:                                         my $finish = $mapres->map_finish();
 8576:                                         my $it = $navmap->getIterator($first,$finish,undef,0,0);
 8577:                                         if (ref($it)) {
 8578:                                             my $res;
 8579:                                             while ($res = $it->next(undef,1)) {
 8580:                                                 next unless (ref($res));
 8581:                                                 my $symb = $res->symb();
 8582:                                                 next if (($symb eq $mapsymb) || ($symb eq ''));
 8583:                                                 @interval=&EXT("resource.0.interval",$symb);
 8584:                                                 if ($interval[1] eq 'map') {
 8585:                                                     if ($res->answerable()) {
 8586:                                                         push(@to_test,$res);
 8587:                                                         last;
 8588:                                                     }
 8589:                                                 }
 8590:                                             }
 8591:                                         }
 8592:                                     }
 8593:                                 }
 8594:                             }
 8595:                         }
 8596:                     }
 8597:                     if ($interval[0] =~ /^(\d+)/) {
 8598:                         my $timelimit = $1; 
 8599:                         my $first_access;
 8600:                         if ($type eq 'resource') {
 8601:                             $first_access=&get_first_access($interval[1],$item);
 8602:                         } elsif ($type eq 'map') {
 8603:                             $first_access=&get_first_access($interval[1],undef,$item);
 8604:                         } else {
 8605:                             $first_access=&get_first_access($interval[1]);
 8606:                         }
 8607:                         if ($first_access) {
 8608:                             my $timesup = $first_access+$timelimit;
 8609:                             if ($timesup > $now) {
 8610:                                 my $activeblock;
 8611:                                 foreach my $res (@to_test) {
 8612:                                     if ($res->answerable()) {
 8613:                                         $activeblock = 1;
 8614:                                         last;
 8615:                                     }
 8616:                                 }
 8617:                                 if ($activeblock) {
 8618:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 8619:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 8620:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
 8621:                                          }
 8622:                                     }
 8623:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 8624:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 8625:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 8626:                                         }
 8627:                                     }
 8628:                                 }
 8629:                             }
 8630:                         }
 8631:                     }
 8632:                 }
 8633:             }
 8634:         }
 8635:     }
 8636:     return %blockers;
 8637: }
 8638: 
 8639: sub has_comm_blocking {
 8640:     my ($priv,$symb,$uri,$ignoresymbdb,$noenccheck,$blocked,$blocks) = @_;
 8641:     my @blockers;
 8642:     return unless ($env{'request.course.id'});
 8643:     return unless ($priv eq 'bre');
 8644:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 8645:     return if ($env{'request.state'} eq 'construct');
 8646:     my %blockinfo;
 8647:     if (ref($blocks) eq 'HASH') {
 8648:         %blockinfo = &get_commblock_resources($blocks);
 8649:     } else {
 8650:         &load_all_blockers($env{'user.name'},$env{'user.domain'});
 8651:         %blockinfo = %cachedblockers;
 8652:     }
 8653:     return unless (keys(%blockinfo) > 0);
 8654:     my (%possibles,@symbs);
 8655:     if (!$symb) {
 8656:         $symb = &symbread($uri,1,1,1,\%possibles,$ignoresymbdb,$noenccheck);
 8657:     }
 8658:     if ($symb) {
 8659:         @symbs = ($symb);
 8660:     } elsif (keys(%possibles)) {
 8661:         @symbs = keys(%possibles);
 8662:     }
 8663:     my $noblock;
 8664:     foreach my $symb (@symbs) {
 8665:         last if ($noblock);
 8666:         my ($map,$resid,$resurl)=&decode_symb($symb);
 8667:         foreach my $block (keys(%blockinfo)) {
 8668:             if ($block =~ /^firstaccess____(.+)$/) {
 8669:                 my $item = $1;
 8670:                 unless ($blocked) {
 8671:                     if (($item eq $map) || ($item eq $symb)) {
 8672:                         $noblock = 1;
 8673:                         last;
 8674:                     }
 8675:                 }
 8676:             }
 8677:             if (ref($blockinfo{$block}) eq 'HASH') {
 8678:                 if (ref($blockinfo{$block}{'resources'}) eq 'HASH') {
 8679:                     if ($blockinfo{$block}{'resources'}{$symb}) {
 8680:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 8681:                             push(@blockers,$block);
 8682:                         }
 8683:                     }
 8684:                 }
 8685:                 if (ref($blockinfo{$block}{'maps'}) eq 'HASH') {
 8686:                     if ($blockinfo{$block}{'maps'}{$map}) {
 8687:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 8688:                             push(@blockers,$block);
 8689:                         }
 8690:                     }
 8691:                 }
 8692:             }
 8693:         }
 8694:     }
 8695:     unless ($noblock) {
 8696:         return @blockers;
 8697:     }
 8698:     return;
 8699: }
 8700: }
 8701: 
 8702: # -------------------------------- Deversion and split uri into path an filename
 8703: 
 8704: #
 8705: #   Removes the version from a URI and
 8706: #   splits it in to its filename and path to the filename.
 8707: #   Seems like File::Basename could have done this more clearly.
 8708: #   Parameters:
 8709: #      $uri   - input URI
 8710: #   Returns:
 8711: #     Two element list consisting of 
 8712: #     $pathname  - the URI up to and excluding the trailing /
 8713: #     $filename  - The part of the URI following the last /
 8714: #  NOTE:
 8715: #    Another realization of this is simply:
 8716: #    use File::Basename;
 8717: #    ...
 8718: #    $uri = shift;
 8719: #    $filename = basename($uri);
 8720: #    $path     = dirname($uri);
 8721: #    return ($filename, $path);
 8722: #
 8723: #     The implementation below is probably faster however.
 8724: #
 8725: sub split_uri_for_cond {
 8726:     my $uri=&deversion(&declutter(shift));
 8727:     my @uriparts=split(/\//,$uri);
 8728:     my $filename=pop(@uriparts);
 8729:     my $pathname=join('/',@uriparts);
 8730:     return ($pathname,$filename);
 8731: }
 8732: # --------------------------------------------------- Is a resource on the map?
 8733: 
 8734: sub is_on_map {
 8735:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 8736:     #Trying to find the conditional for the file
 8737:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 8738: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 8739:     if ($match) {
 8740: 	return (1,$1);
 8741:     } else {
 8742: 	return (0,0);
 8743:     }
 8744: }
 8745: 
 8746: # --------------------------------------------------------- Get symb from alias
 8747: 
 8748: sub get_symb_from_alias {
 8749:     my $symb=shift;
 8750:     my ($map,$resid,$url)=&decode_symb($symb);
 8751: # Already is a symb
 8752:     if ($url) { return $symb; }
 8753: # Must be an alias
 8754:     my $aliassymb='';
 8755:     my %bighash;
 8756:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 8757:                             &GDBM_READER(),0640)) {
 8758:         my $rid=$bighash{'mapalias_'.$symb};
 8759: 	if ($rid) {
 8760: 	    my ($mapid,$resid)=split(/\./,$rid);
 8761: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 8762: 				    $resid,$bighash{'src_'.$rid});
 8763: 	}
 8764:         untie %bighash;
 8765:     }
 8766:     return $aliassymb;
 8767: }
 8768: 
 8769: # ----------------------------------------------------------------- Define Role
 8770: 
 8771: sub definerole {
 8772:   if (allowed('mcr','/')) {
 8773:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
 8774:     foreach my $role (split(':',$sysrole)) {
 8775: 	my ($crole,$cqual)=split(/\&/,$role);
 8776:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 8777:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 8778: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 8779:                return "refused:s:$crole&$cqual"; 
 8780:             }
 8781:         }
 8782:     }
 8783:     foreach my $role (split(':',$domrole)) {
 8784: 	my ($crole,$cqual)=split(/\&/,$role);
 8785:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 8786:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 8787: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 8788:                return "refused:d:$crole&$cqual"; 
 8789:             }
 8790:         }
 8791:     }
 8792:     foreach my $role (split(':',$courole)) {
 8793: 	my ($crole,$cqual)=split(/\&/,$role);
 8794:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 8795:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 8796: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 8797:                return "refused:c:$crole&$cqual"; 
 8798:             }
 8799:         }
 8800:     }
 8801:     my $uhome;
 8802:     if (($uname ne '') && ($udom ne '')) {
 8803:         $uhome = &homeserver($uname,$udom);
 8804:         return $uhome if ($uhome eq 'no_host');
 8805:     } else {
 8806:         $uname = $env{'user.name'};
 8807:         $udom = $env{'user.domain'};
 8808:         $uhome = $env{'user.home'};
 8809:     }
 8810:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 8811:                 "$udom:$uname:rolesdef_$rolename=".
 8812:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 8813:     return reply($command,$uhome);
 8814:   } else {
 8815:     return 'refused';
 8816:   }
 8817: }
 8818: 
 8819: # ---------------- Make a metadata query against the network of library servers
 8820: 
 8821: sub metadata_query {
 8822:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
 8823:     my %rhash;
 8824:     my %libserv = &all_library();
 8825:     my @server_list = (defined($server_array) ? @$server_array
 8826:                                               : keys(%libserv) );
 8827:     for my $server (@server_list) {
 8828:         my $domains = '';
 8829:         if (ref($domains_hash) eq 'HASH') {
 8830:             $domains = $domains_hash->{$server};    
 8831:         }
 8832: 	unless ($custom or $customshow) {
 8833: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
 8834: 	    $rhash{$server}=$reply;
 8835: 	}
 8836: 	else {
 8837: 	    my $reply=&reply("querysend:".&escape($query).':'.
 8838: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
 8839: 			     $server);
 8840: 	    $rhash{$server}=$reply;
 8841: 	}
 8842:     }
 8843:     return \%rhash;
 8844: }
 8845: 
 8846: # ----------------------------------------- Send log queries and wait for reply
 8847: 
 8848: sub log_query {
 8849:     my ($uname,$udom,$query,%filters)=@_;
 8850:     my $uhome=&homeserver($uname,$udom);
 8851:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 8852:     my $uhost=&hostname($uhome);
 8853:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 8854:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 8855:                        $uhome);
 8856:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 8857:     return get_query_reply($queryid);
 8858: }
 8859: 
 8860: # -------------------------- Update MySQL table for portfolio file
 8861: 
 8862: sub update_portfolio_table {
 8863:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 8864:     if ($group ne '') {
 8865:         $file_name =~s /^\Q$group\E//;
 8866:     }
 8867:     my $homeserver = &homeserver($uname,$udom);
 8868:     my $queryid=
 8869:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 8870:                ':'.&escape($file_name).':'.$action,$homeserver);
 8871:     my $reply = &get_query_reply($queryid);
 8872:     return $reply;
 8873: }
 8874: 
 8875: # -------------------------- Update MySQL allusers table
 8876: 
 8877: sub update_allusers_table {
 8878:     my ($uname,$udom,$names) = @_;
 8879:     my $homeserver = &homeserver($uname,$udom);
 8880:     my $queryid=
 8881:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 8882:                'lastname='.&escape($names->{'lastname'}).'%%'.
 8883:                'firstname='.&escape($names->{'firstname'}).'%%'.
 8884:                'middlename='.&escape($names->{'middlename'}).'%%'.
 8885:                'generation='.&escape($names->{'generation'}).'%%'.
 8886:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 8887:                'id='.&escape($names->{'id'}),$homeserver);
 8888:     return;
 8889: }
 8890: 
 8891: # ------- Request retrieval of institutional classlists for course(s)
 8892: 
 8893: sub fetch_enrollment_query {
 8894:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 8895:     my ($homeserver,$sleep,$loopmax);
 8896:     my $maxtries = 1;
 8897:     if ($context eq 'automated') {
 8898:         $homeserver = $perlvar{'lonHostID'};
 8899:         $sleep = 2;
 8900:         $loopmax = 100;
 8901:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 8902:     } else {
 8903:         $homeserver = &homeserver($cnum,$dom);
 8904:     }
 8905:     my $host=&hostname($homeserver);
 8906:     my $cmd = '';
 8907:     foreach my $affiliate (keys(%{$affiliatesref})) {
 8908:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 8909:     }
 8910:     $cmd =~ s/%%$//;
 8911:     $cmd = &escape($cmd);
 8912:     my $query = 'fetchenrollment';
 8913:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 8914:     unless ($queryid=~/^\Q$host\E\_/) { 
 8915:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 8916:         return 'error: '.$queryid;
 8917:     }
 8918:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
 8919:     my $tries = 1;
 8920:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 8921:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
 8922:         $tries ++;
 8923:     }
 8924:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 8925:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 8926:     } else {
 8927:         my @responses = split(/:/,$reply);
 8928:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
 8929:             foreach my $line (@responses) {
 8930:                 my ($key,$value) = split(/=/,$line,2);
 8931:                 $$replyref{$key} = $value;
 8932:             }
 8933:         } else {
 8934:             my $pathname = LONCAPA::tempdir();
 8935:             foreach my $line (@responses) {
 8936:                 my ($key,$value) = split(/=/,$line);
 8937:                 $$replyref{$key} = $value;
 8938:                 if ($value > 0) {
 8939:                     foreach my $item (@{$$affiliatesref{$key}}) {
 8940:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 8941:                         my $destname = $pathname.'/'.$filename;
 8942:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 8943:                         if ($xml_classlist =~ /^error/) {
 8944:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 8945:                         } else {
 8946:                             if ( open(FILE,">",$destname) ) {
 8947:                                 print FILE &unescape($xml_classlist);
 8948:                                 close(FILE);
 8949:                             } else {
 8950:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 8951:                             }
 8952:                         }
 8953:                     }
 8954:                 }
 8955:             }
 8956:         }
 8957:         return 'ok';
 8958:     }
 8959:     return 'error';
 8960: }
 8961: 
 8962: sub get_query_reply {
 8963:     my ($queryid,$sleep,$loopmax) = @_;
 8964:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
 8965:         $sleep = 0.2;
 8966:     }
 8967:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
 8968:         $loopmax = 100;
 8969:     }
 8970:     my $replyfile=LONCAPA::tempdir().$queryid;
 8971:     my $reply='';
 8972:     for (1..$loopmax) {
 8973: 	sleep($sleep);
 8974:         if (-e $replyfile.'.end') {
 8975: 	    if (open(my $fh,"<",$replyfile)) {
 8976: 		$reply = join('',<$fh>);
 8977: 		close($fh);
 8978: 	   } else { return 'error: reply_file_error'; }
 8979:            return &unescape($reply);
 8980: 	}
 8981:     }
 8982:     return 'timeout:'.$queryid;
 8983: }
 8984: 
 8985: sub courselog_query {
 8986: #
 8987: # possible filters:
 8988: # url: url or symb
 8989: # username
 8990: # domain
 8991: # action: view, submit, grade
 8992: # start: timestamp
 8993: # end: timestamp
 8994: #
 8995:     my (%filters)=@_;
 8996:     unless ($env{'request.course.id'}) { return 'no_course'; }
 8997:     if ($filters{'url'}) {
 8998: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 8999:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 9000:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 9001:     }
 9002:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 9003:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 9004:     return &log_query($cname,$cdom,'courselog',%filters);
 9005: }
 9006: 
 9007: sub userlog_query {
 9008: #
 9009: # possible filters:
 9010: # action: log check role
 9011: # start: timestamp
 9012: # end: timestamp
 9013: #
 9014:     my ($uname,$udom,%filters)=@_;
 9015:     return &log_query($uname,$udom,'userlog',%filters);
 9016: }
 9017: 
 9018: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 9019: 
 9020: sub auto_run {
 9021:     my ($cnum,$cdom) = @_;
 9022:     my $response = 0;
 9023:     my $settings;
 9024:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 9025:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 9026:         $settings = $domconfig{'autoenroll'};
 9027:         if ($settings->{'run'} eq '1') {
 9028:             $response = 1;
 9029:         }
 9030:     } else {
 9031:         my $homeserver;
 9032:         if (&is_course($cdom,$cnum)) {
 9033:             $homeserver = &homeserver($cnum,$cdom);
 9034:         } else {
 9035:             $homeserver = &domain($cdom,'primary');
 9036:         }
 9037:         if ($homeserver ne 'no_host') {
 9038:             $response = &reply('autorun:'.$cdom,$homeserver);
 9039:         }
 9040:     }
 9041:     return $response;
 9042: }
 9043: 
 9044: sub auto_get_sections {
 9045:     my ($cnum,$cdom,$inst_coursecode) = @_;
 9046:     my $homeserver;
 9047:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
 9048:         $homeserver = &homeserver($cnum,$cdom);
 9049:     }
 9050:     if (!defined($homeserver)) { 
 9051:         if ($cdom =~ /^$match_domain$/) {
 9052:             $homeserver = &domain($cdom,'primary');
 9053:         }
 9054:     }
 9055:     my @secs;
 9056:     if (defined($homeserver)) {
 9057:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 9058:         unless ($response eq 'refused') {
 9059:             @secs = split(/:/,$response);
 9060:         }
 9061:     }
 9062:     return @secs;
 9063: }
 9064: 
 9065: sub auto_new_course {
 9066:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
 9067:     my $homeserver = &homeserver($cnum,$cdom);
 9068:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
 9069:     return $response;
 9070: }
 9071: 
 9072: sub auto_validate_courseID {
 9073:     my ($cnum,$cdom,$inst_course_id) = @_;
 9074:     my $homeserver = &homeserver($cnum,$cdom);
 9075:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 9076:     return $response;
 9077: }
 9078: 
 9079: sub auto_validate_instcode {
 9080:     my ($cnum,$cdom,$instcode,$owner) = @_;
 9081:     my ($homeserver,$response);
 9082:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 9083:         $homeserver = &homeserver($cnum,$cdom);
 9084:     }
 9085:     if (!defined($homeserver)) {
 9086:         if ($cdom =~ /^$match_domain$/) {
 9087:             $homeserver = &domain($cdom,'primary');
 9088:         }
 9089:     }
 9090:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
 9091:                         &escape($instcode).':'.&escape($owner),$homeserver));
 9092:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
 9093:     return ($outcome,$description,$defaultcredits);
 9094: }
 9095: 
 9096: sub auto_create_password {
 9097:     my ($cnum,$cdom,$authparam,$udom) = @_;
 9098:     my ($homeserver,$response);
 9099:     my $create_passwd = 0;
 9100:     my $authchk = '';
 9101:     if ($udom =~ /^$match_domain$/) {
 9102:         $homeserver = &domain($udom,'primary');
 9103:     }
 9104:     if ($homeserver eq '') {
 9105:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 9106:             $homeserver = &homeserver($cnum,$cdom);
 9107:         }
 9108:     }
 9109:     if ($homeserver eq '') {
 9110:         $authchk = 'nodomain';
 9111:     } else {
 9112:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 9113:         if ($response eq 'refused') {
 9114:             $authchk = 'refused';
 9115:         } else {
 9116:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 9117:         }
 9118:     }
 9119:     return ($authparam,$create_passwd,$authchk);
 9120: }
 9121: 
 9122: sub auto_photo_permission {
 9123:     my ($cnum,$cdom,$students) = @_;
 9124:     my $homeserver = &homeserver($cnum,$cdom);
 9125:     my ($outcome,$perm_reqd,$conditions) = 
 9126: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 9127:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 9128: 	return (undef,undef);
 9129:     }
 9130:     return ($outcome,$perm_reqd,$conditions);
 9131: }
 9132: 
 9133: sub auto_checkphotos {
 9134:     my ($uname,$udom,$pid) = @_;
 9135:     my $homeserver = &homeserver($uname,$udom);
 9136:     my ($result,$resulttype);
 9137:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 9138: 				   &escape($uname).':'.&escape($pid),
 9139: 				   $homeserver));
 9140:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 9141: 	return (undef,undef);
 9142:     }
 9143:     if ($outcome) {
 9144:         ($result,$resulttype) = split(/:/,$outcome);
 9145:     } 
 9146:     return ($result,$resulttype);
 9147: }
 9148: 
 9149: sub auto_photochoice {
 9150:     my ($cnum,$cdom) = @_;
 9151:     my $homeserver = &homeserver($cnum,$cdom);
 9152:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 9153: 						       &escape($cdom),
 9154: 						       $homeserver)));
 9155:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 9156: 	return (undef,undef);
 9157:     }
 9158:     return ($update,$comment);
 9159: }
 9160: 
 9161: sub auto_photoupdate {
 9162:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 9163:     my $homeserver = &homeserver($cnum,$dom);
 9164:     my $host=&hostname($homeserver);
 9165:     my $cmd = '';
 9166:     my $maxtries = 1;
 9167:     foreach my $affiliate (keys(%{$affiliatesref})) {
 9168:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 9169:     }
 9170:     $cmd =~ s/%%$//;
 9171:     $cmd = &escape($cmd);
 9172:     my $query = 'institutionalphotos';
 9173:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 9174:     unless ($queryid=~/^\Q$host\E\_/) {
 9175:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 9176:         return 'error: '.$queryid;
 9177:     }
 9178:     my $reply = &get_query_reply($queryid);
 9179:     my $tries = 1;
 9180:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 9181:         $reply = &get_query_reply($queryid);
 9182:         $tries ++;
 9183:     }
 9184:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 9185:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 9186:     } else {
 9187:         my @responses = split(/:/,$reply);
 9188:         my $outcome = shift(@responses); 
 9189:         foreach my $item (@responses) {
 9190:             my ($key,$value) = split(/=/,$item);
 9191:             $$photo{$key} = $value;
 9192:         }
 9193:         return $outcome;
 9194:     }
 9195:     return 'error';
 9196: }
 9197: 
 9198: sub auto_instcode_format {
 9199:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 9200: 	$cat_order) = @_;
 9201:     my $courses = '';
 9202:     my @homeservers;
 9203:     if ($caller eq 'global') {
 9204: 	my %servers = &get_servers($codedom,'library');
 9205: 	foreach my $tryserver (keys(%servers)) {
 9206: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 9207: 		push(@homeservers,$tryserver);
 9208: 	    }
 9209:         }
 9210:     } elsif ($caller eq 'requests') {
 9211:         if ($codedom =~ /^$match_domain$/) {
 9212:             my $chome = &domain($codedom,'primary');
 9213:             unless ($chome eq 'no_host') {
 9214:                 push(@homeservers,$chome);
 9215:             }
 9216:         }
 9217:     } else {
 9218:         push(@homeservers,&homeserver($caller,$codedom));
 9219:     }
 9220:     foreach my $code (keys(%{$instcodes})) {
 9221:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 9222:     }
 9223:     chop($courses);
 9224:     my $ok_response = 0;
 9225:     my $response;
 9226:     while (@homeservers > 0 && $ok_response == 0) {
 9227:         my $server = shift(@homeservers); 
 9228:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 9229:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 9230:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 9231: 		split(/:/,$response);
 9232:             %{$codes} = (%{$codes},&str2hash($codes_str));
 9233:             push(@{$codetitles},&str2array($codetitles_str));
 9234:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 9235:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 9236:             $ok_response = 1;
 9237:         }
 9238:     }
 9239:     if ($ok_response) {
 9240:         return 'ok';
 9241:     } else {
 9242:         return $response;
 9243:     }
 9244: }
 9245: 
 9246: sub auto_instcode_defaults {
 9247:     my ($domain,$returnhash,$code_order) = @_;
 9248:     my @homeservers;
 9249: 
 9250:     my %servers = &get_servers($domain,'library');
 9251:     foreach my $tryserver (keys(%servers)) {
 9252: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 9253: 	    push(@homeservers,$tryserver);
 9254: 	}
 9255:     }
 9256: 
 9257:     my $response;
 9258:     foreach my $server (@homeservers) {
 9259:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 9260:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 9261: 	
 9262: 	foreach my $pair (split(/\&/,$response)) {
 9263: 	    my ($name,$value)=split(/\=/,$pair);
 9264: 	    if ($name eq 'code_order') {
 9265: 		@{$code_order} = split(/\&/,&unescape($value));
 9266: 	    } else {
 9267: 		$returnhash->{&unescape($name)}=&unescape($value);
 9268: 	    }
 9269: 	}
 9270: 	return 'ok';
 9271:     }
 9272: 
 9273:     return $response;
 9274: }
 9275: 
 9276: sub auto_possible_instcodes {
 9277:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
 9278:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
 9279:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 9280:         return;
 9281:     }
 9282:     my (@homeservers,$uhome);
 9283:     if (defined(&domain($domain,'primary'))) {
 9284:         $uhome=&domain($domain,'primary');
 9285:         push(@homeservers,&domain($domain,'primary'));
 9286:     } else {
 9287:         my %servers = &get_servers($domain,'library');
 9288:         foreach my $tryserver (keys(%servers)) {
 9289:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 9290:                 push(@homeservers,$tryserver);
 9291:             }
 9292:         }
 9293:     }
 9294:     my $response;
 9295:     foreach my $server (@homeservers) {
 9296:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
 9297:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 9298:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
 9299:             split(':',$response);
 9300:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
 9301:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
 9302:         foreach my $item (split('&',$cat_title)) {   
 9303:             my ($name,$value)=split('=',$item);
 9304:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
 9305:         }
 9306:         foreach my $item (split('&',$cat_order)) {
 9307:             my ($name,$value)=split('=',$item);
 9308:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
 9309:         }
 9310:         return 'ok';
 9311:     }
 9312:     return $response;
 9313: }
 9314: 
 9315: sub auto_courserequest_checks {
 9316:     my ($dom) = @_;
 9317:     my ($homeserver,%validations);
 9318:     if ($dom =~ /^$match_domain$/) {
 9319:         $homeserver = &domain($dom,'primary');
 9320:     }
 9321:     unless ($homeserver eq 'no_host') {
 9322:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
 9323:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 9324:             my @items = split(/&/,$response);
 9325:             foreach my $item (@items) {
 9326:                 my ($key,$value) = split('=',$item);
 9327:                 $validations{&unescape($key)} = &thaw_unescape($value);
 9328:             }
 9329:         }
 9330:     }
 9331:     return %validations; 
 9332: }
 9333: 
 9334: sub auto_courserequest_validation {
 9335:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
 9336:     my ($homeserver,$response);
 9337:     if ($dom =~ /^$match_domain$/) {
 9338:         $homeserver = &domain($dom,'primary');
 9339:     }
 9340:     unless ($homeserver eq 'no_host') {
 9341:         my $customdata;
 9342:         if (ref($custominfo) eq 'HASH') {
 9343:             $customdata = &freeze_escape($custominfo);
 9344:         }
 9345:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
 9346:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
 9347:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
 9348:                                     $customdata,$homeserver));
 9349:     }
 9350:     return $response;
 9351: }
 9352: 
 9353: sub auto_validate_class_sec {
 9354:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 9355:     my $homeserver = &homeserver($cnum,$cdom);
 9356:     my $ownerlist;
 9357:     if (ref($owners) eq 'ARRAY') {
 9358:         $ownerlist = join(',',@{$owners});
 9359:     } else {
 9360:         $ownerlist = $owners;
 9361:     }
 9362:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 9363:                         &escape($ownerlist).':'.$cdom,$homeserver);
 9364:     return $response;
 9365: }
 9366: 
 9367: sub auto_validate_instclasses {
 9368:     my ($cdom,$cnum,$owners,$classesref) = @_;
 9369:     my ($homeserver,%validations);
 9370:     $homeserver = &homeserver($cnum,$cdom);
 9371:     unless ($homeserver eq 'no_host') {
 9372:         my $ownerlist;
 9373:         if (ref($owners) eq 'ARRAY') {
 9374:             $ownerlist = join(',',@{$owners});
 9375:         } else {
 9376:             $ownerlist = $owners;
 9377:         }
 9378:         if (ref($classesref) eq 'HASH') {
 9379:             my $classes = &freeze_escape($classesref);
 9380:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
 9381:                                 ':'.$cdom.':'.$classes,$homeserver);
 9382:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 9383:                 my @items = split(/&/,$response);
 9384:                 foreach my $item (@items) {
 9385:                     my ($key,$value) = split('=',$item);
 9386:                     $validations{&unescape($key)} = &thaw_unescape($value);
 9387:                 }
 9388:             }
 9389:         }
 9390:     }
 9391:     return %validations;
 9392: }
 9393: 
 9394: sub auto_crsreq_update {
 9395:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
 9396:         $code,$accessstart,$accessend,$inbound) = @_;
 9397:     my ($homeserver,%crsreqresponse);
 9398:     if ($cdom =~ /^$match_domain$/) {
 9399:         $homeserver = &domain($cdom,'primary');
 9400:     }
 9401:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
 9402:         my $info;
 9403:         if (ref($inbound) eq 'HASH') {
 9404:             $info = &freeze_escape($inbound);
 9405:         }
 9406:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
 9407:                             ':'.&escape($action).':'.&escape($ownername).':'.
 9408:                             &escape($ownerdomain).':'.&escape($fullname).':'.
 9409:                             &escape($title).':'.&escape($code).':'.
 9410:                             &escape($accessstart).':'.&escape($accessend).':'.$info,$homeserver);
 9411:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 9412:             my @items = split(/&/,$response);
 9413:             foreach my $item (@items) {
 9414:                 my ($key,$value) = split('=',$item);
 9415:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
 9416:             }
 9417:         }
 9418:     }
 9419:     return \%crsreqresponse;
 9420: }
 9421: 
 9422: sub auto_export_grades {
 9423:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
 9424:     my ($homeserver,%exportresponse);
 9425:     if ($cdom =~ /^$match_domain$/) {
 9426:         $homeserver = &domain($cdom,'primary');
 9427:     }
 9428:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
 9429:         my $info;
 9430:         if (ref($inforef) eq 'HASH') {
 9431:             $info = &freeze_escape($inforef);
 9432:         }
 9433:         if (ref($gradesref) eq 'HASH') {
 9434:             my $grades = &freeze_escape($gradesref);
 9435:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
 9436:                                 $info.':'.$grades,$homeserver);
 9437:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
 9438:                 my @items = split(/&/,$response);
 9439:                 foreach my $item (@items) {
 9440:                     my ($key,$value) = split('=',$item);
 9441:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
 9442:                 }
 9443:             }
 9444:         }
 9445:     }
 9446:     return \%exportresponse;
 9447: }
 9448: 
 9449: sub check_instcode_cloning {
 9450:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
 9451:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 9452:         return;
 9453:     }
 9454:     my $canclone;
 9455:     if (@{$code_order} > 0) {
 9456:         my $instcoderegexp ='^';
 9457:         my @clonecodes = split(/\&/,$cloner);
 9458:         foreach my $item (@{$code_order}) {
 9459:             if (grep(/^\Q$item\E=/,@clonecodes)) {
 9460:                 foreach my $pair (@clonecodes) {
 9461:                     my ($key,$val) = split(/\=/,$pair,2);
 9462:                     $val = &unescape($val);
 9463:                     if ($key eq $item) {
 9464:                         $instcoderegexp .= '('.$val.')';
 9465:                         last;
 9466:                     }
 9467:                 }
 9468:             } else {
 9469:                 $instcoderegexp .= $codedefaults->{$item};
 9470:             }
 9471:         }
 9472:         $instcoderegexp .= '$';
 9473:         my (@from,@to);
 9474:         eval {
 9475:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
 9476:                (@to) = ($clonetocode =~ /$instcoderegexp/);
 9477:         };
 9478:         if ((@from > 0) && (@to > 0)) {
 9479:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
 9480:             if (!@diffs) {
 9481:                 $canclone = 1;
 9482:             }
 9483:         }
 9484:     }
 9485:     return $canclone;
 9486: }
 9487: 
 9488: sub default_instcode_cloning {
 9489:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
 9490:     my (%codedefaults,@code_order,$canclone);
 9491:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
 9492:         %codedefaults = %{$codedefaultsref};
 9493:         @code_order = @{$codeorderref};
 9494:     } elsif ($clonedom) {
 9495:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
 9496:     }
 9497:     if (($domdefclone) && (@code_order)) {
 9498:         my @clonecodes = split(/\+/,$domdefclone);
 9499:         my $instcoderegexp ='^';
 9500:         foreach my $item (@code_order) {
 9501:             if (grep(/^\Q$item\E$/,@clonecodes)) {
 9502:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
 9503:             } else {
 9504:                 $instcoderegexp .= $codedefaults{$item};
 9505:             }
 9506:         }
 9507:         $instcoderegexp .= '$';
 9508:         my (@from,@to);
 9509:         eval {
 9510:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
 9511:             (@to) = ($clonetocode =~ /$instcoderegexp/);
 9512:         };
 9513:         if ((@from > 0) && (@to > 0)) {
 9514:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
 9515:             if (!@diffs) {
 9516:                 $canclone = 1;
 9517:             }
 9518:         }
 9519:     }
 9520:     return $canclone;
 9521: }
 9522: 
 9523: # ------------------------------------------------------- Course Group routines
 9524: 
 9525: sub get_coursegroups {
 9526:     my ($cdom,$cnum,$group,$namespace) = @_;
 9527:     return(&dump($namespace,$cdom,$cnum,$group));
 9528: }
 9529: 
 9530: sub modify_coursegroup {
 9531:     my ($cdom,$cnum,$groupsettings) = @_;
 9532:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 9533: }
 9534: 
 9535: sub toggle_coursegroup_status {
 9536:     my ($cdom,$cnum,$group,$action) = @_;
 9537:     my ($from_namespace,$to_namespace);
 9538:     if ($action eq 'delete') {
 9539:         $from_namespace = 'coursegroups';
 9540:         $to_namespace = 'deleted_groups';
 9541:     } else {
 9542:         $from_namespace = 'deleted_groups';
 9543:         $to_namespace = 'coursegroups';
 9544:     }
 9545:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 9546:     if (my $tmp = &error(%curr_group)) {
 9547:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 9548:         return ('read error',$tmp);
 9549:     } else {
 9550:         my %savedsettings = %curr_group; 
 9551:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 9552:         my $deloutcome;
 9553:         if ($result eq 'ok') {
 9554:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 9555:         } else {
 9556:             return ('write error',$result);
 9557:         }
 9558:         if ($deloutcome eq 'ok') {
 9559:             return 'ok';
 9560:         } else {
 9561:             return ('delete error',$deloutcome);
 9562:         }
 9563:     }
 9564: }
 9565: 
 9566: sub modify_group_roles {
 9567:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 9568:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 9569:     my $role = 'gr/'.&escape($userprivs);
 9570:     my ($uname,$udom) = split(/:/,$user);
 9571:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 9572:     if ($result eq 'ok') {
 9573:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 9574:     }
 9575:     return $result;
 9576: }
 9577: 
 9578: sub modify_coursegroup_membership {
 9579:     my ($cdom,$cnum,$membership) = @_;
 9580:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 9581:     return $result;
 9582: }
 9583: 
 9584: sub get_active_groups {
 9585:     my ($udom,$uname,$cdom,$cnum) = @_;
 9586:     my $now = time;
 9587:     my %groups = ();
 9588:     foreach my $key (keys(%env)) {
 9589:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 9590:             my ($start,$end) = split(/\./,$env{$key});
 9591:             if (($end!=0) && ($end<$now)) { next; }
 9592:             if (($start!=0) && ($start>$now)) { next; }
 9593:             if ($1 eq $cdom && $2 eq $cnum) {
 9594:                 $groups{$3} = $env{$key} ;
 9595:             }
 9596:         }
 9597:     }
 9598:     return %groups;
 9599: }
 9600: 
 9601: sub get_group_membership {
 9602:     my ($cdom,$cnum,$group) = @_;
 9603:     return(&dump('groupmembership',$cdom,$cnum,$group));
 9604: }
 9605: 
 9606: sub get_users_groups {
 9607:     my ($udom,$uname,$courseid) = @_;
 9608:     my @usersgroups;
 9609:     my $cachetime=1800;
 9610: 
 9611:     my $hashid="$udom:$uname:$courseid";
 9612:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 9613:     if (defined($cached)) {
 9614:         @usersgroups = split(/:/,$grouplist);
 9615:     } else {  
 9616:         $grouplist = '';
 9617:         my $courseurl = &courseid_to_courseurl($courseid);
 9618:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 9619:         my $access_end = $env{'course.'.$courseid.
 9620:                               '.default_enrollment_end_date'};
 9621:         my $now = time;
 9622:         foreach my $key (keys(%roleshash)) {
 9623:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 9624:                 my $group = $1;
 9625:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 9626:                     my $start = $2;
 9627:                     my $end = $1;
 9628:                     if ($start == -1) { next; } # deleted from group
 9629:                     if (($start!=0) && ($start>$now)) { next; }
 9630:                     if (($end!=0) && ($end<$now)) {
 9631:                         if ($access_end && $access_end < $now) {
 9632:                             if ($access_end - $end < 86400) {
 9633:                                 push(@usersgroups,$group);
 9634:                             }
 9635:                         }
 9636:                         next;
 9637:                     }
 9638:                     push(@usersgroups,$group);
 9639:                 }
 9640:             }
 9641:         }
 9642:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 9643:         $grouplist = join(':',@usersgroups);
 9644:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 9645:     }
 9646:     return @usersgroups;
 9647: }
 9648: 
 9649: sub devalidate_getgroups_cache {
 9650:     my ($udom,$uname,$cdom,$cnum)=@_;
 9651:     my $courseid = $cdom.'_'.$cnum;
 9652: 
 9653:     my $hashid="$udom:$uname:$courseid";
 9654:     &devalidate_cache_new('getgroups',$hashid);
 9655: }
 9656: 
 9657: # ------------------------------------------------------------------ Plain Text
 9658: 
 9659: sub plaintext {
 9660:     my ($short,$type,$cid,$forcedefault) = @_;
 9661:     if ($short =~ m{^cr/}) {
 9662: 	return (split('/',$short))[-1];
 9663:     }
 9664:     if (!defined($cid)) {
 9665:         $cid = $env{'request.course.id'};
 9666:     }
 9667:     my %rolenames = (
 9668:                       Course    => 'std',
 9669:                       Community => 'alt1',
 9670:                     );
 9671:     if ($cid ne '') {
 9672:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
 9673:             unless ($forcedefault) {
 9674:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
 9675:                 &Apache::lonlocal::mt_escape(\$roletext);
 9676:                 return &Apache::lonlocal::mt($roletext);
 9677:             }
 9678:         }
 9679:     }
 9680:     if ((defined($type)) && (defined($rolenames{$type})) &&
 9681:         (defined($rolenames{$type})) && 
 9682:         (defined($prp{$short}{$rolenames{$type}}))) {
 9683:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 9684:     } elsif ($cid ne '') {
 9685:         my $crstype = $env{'course.'.$cid.'.type'};
 9686:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
 9687:             (defined($prp{$short}{$rolenames{$crstype}}))) {
 9688:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
 9689:         }
 9690:     }
 9691:     return &Apache::lonlocal::mt($prp{$short}{'std'});
 9692: }
 9693: 
 9694: # ----------------------------------------------------------------- Assign Role
 9695: 
 9696: sub assignrole {
 9697:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
 9698:         $context)=@_;
 9699:     my $mrole;
 9700:     if ($role =~ /^cr\//) {
 9701:         my $cwosec=$url;
 9702:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 9703: 	unless (&allowed('ccr',$cwosec)) {
 9704:            my $refused = 1;
 9705:            if ($context eq 'requestcourses') {
 9706:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 9707:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
 9708:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
 9709:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 9710:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 9711:                            if ($crsenv{'internal.courseowner'} eq
 9712:                                $env{'user.name'}.':'.$env{'user.domain'}) {
 9713:                                $refused = '';
 9714:                            }
 9715:                        }
 9716:                    }
 9717:                }
 9718:            }
 9719:            if ($refused) {
 9720:                &logthis('Refused custom assignrole: '.
 9721:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
 9722:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
 9723:                return 'refused';
 9724:            }
 9725:         }
 9726:         $mrole='cr';
 9727:     } elsif ($role =~ /^gr\//) {
 9728:         my $cwogrp=$url;
 9729:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 9730:         unless (&allowed('mdg',$cwogrp)) {
 9731:             &logthis('Refused group assignrole: '.
 9732:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 9733:                     $env{'user.name'}.' at '.$env{'user.domain'});
 9734:             return 'refused';
 9735:         }
 9736:         $mrole='gr';
 9737:     } else {
 9738:         my $cwosec=$url;
 9739:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 9740:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 9741:             my $refused;
 9742:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 9743:                 if (!(&allowed('c'.$role,$url))) {
 9744:                     $refused = 1;
 9745:                 }
 9746:             } else {
 9747:                 $refused = 1;
 9748:             }
 9749:             if ($refused) {
 9750:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 9751:                 if (!$selfenroll && $context eq 'course') {
 9752:                     my %crsenv;
 9753:                     if ($role eq 'cc' || $role eq 'co') {
 9754:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 9755:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
 9756:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
 9757:                                 if ($crsenv{'internal.courseowner'} eq 
 9758:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 9759:                                     $refused = '';
 9760:                                 }
 9761:                             }
 9762:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
 9763:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
 9764:                                 if ($crsenv{'internal.courseowner'} eq 
 9765:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 9766:                                     $refused = '';
 9767:                                 }
 9768:                             }
 9769:                         }
 9770:                     }
 9771:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 9772:                     $refused = '';
 9773:                 } elsif ($context eq 'requestcourses') {
 9774:                     my @possroles = ('st','ta','ep','in','cc','co');
 9775:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
 9776:                         my $wrongcc;
 9777:                         if ($cnum =~ /^$match_community$/) {
 9778:                             $wrongcc = 1 if ($role eq 'cc');
 9779:                         } else {
 9780:                             $wrongcc = 1 if ($role eq 'co');
 9781:                         }
 9782:                         unless ($wrongcc) {
 9783:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 9784:                             if ($crsenv{'internal.courseowner'} eq 
 9785:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
 9786:                                 $refused = '';
 9787:                             }
 9788:                         }
 9789:                     }
 9790:                 } elsif ($context eq 'requestauthor') {
 9791:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 9792:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
 9793:                         if ($env{'environment.requestauthor'} eq 'automatic') {
 9794:                             $refused = '';
 9795:                         } else {
 9796:                             my %domdefaults = &get_domain_defaults($udom);
 9797:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
 9798:                                 my $checkbystatus;
 9799:                                 if ($env{'user.adv'}) {
 9800:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
 9801:                                     if ($disposition eq 'automatic') {
 9802:                                         $refused = '';
 9803:                                     } elsif ($disposition eq '') {
 9804:                                         $checkbystatus = 1;
 9805:                                     }
 9806:                                 } else {
 9807:                                     $checkbystatus = 1;
 9808:                                 }
 9809:                                 if ($checkbystatus) {
 9810:                                     if ($env{'environment.inststatus'}) {
 9811:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
 9812:                                         foreach my $type (@inststatuses) {
 9813:                                             if (($type ne '') &&
 9814:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
 9815:                                                 $refused = '';
 9816:                                             }
 9817:                                         }
 9818:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
 9819:                                         $refused = '';
 9820:                                     }
 9821:                                 }
 9822:                             }
 9823:                         }
 9824:                     }
 9825:                 }
 9826:                 if ($refused) {
 9827:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 9828:                              ' '.$role.' '.$end.' '.$start.' by '.
 9829: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
 9830:                     return 'refused';
 9831:                 }
 9832:             }
 9833:         } elsif ($role eq 'au') {
 9834:             if ($url ne '/'.$udom.'/') {
 9835:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
 9836:                          ' to assign author role for '.$uname.':'.$udom.
 9837:                          ' in domain: '.$url.' refused (wrong domain).');
 9838:                 return 'refused';
 9839:             }
 9840:         }
 9841:         $mrole=$role;
 9842:     }
 9843:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 9844:                 "$udom:$uname:$url".'_'."$mrole=$role";
 9845:     if ($end) { $command.='_'.$end; }
 9846:     if ($start) {
 9847: 	if ($end) { 
 9848:            $command.='_'.$start; 
 9849:         } else {
 9850:            $command.='_0_'.$start;
 9851:         }
 9852:     }
 9853:     my $origstart = $start;
 9854:     my $origend = $end;
 9855:     my $delflag;
 9856: # actually delete
 9857:     if ($deleteflag) {
 9858: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 9859: # modify command to delete the role
 9860:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 9861:                 "$udom:$uname:$url".'_'."$mrole";
 9862: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 9863: # set start and finish to negative values for userrolelog
 9864:            $start=-1;
 9865:            $end=-1;
 9866:            $delflag = 1;
 9867:         }
 9868:     }
 9869: # send command
 9870:     my $answer=&reply($command,&homeserver($uname,$udom));
 9871: # log new user role if status is ok
 9872:     if ($answer eq 'ok') {
 9873: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 9874:         if (($role eq 'cc') || ($role eq 'in') ||
 9875:             ($role eq 'ep') || ($role eq 'ad') ||
 9876:             ($role eq 'ta') || ($role eq 'st') ||
 9877:             ($role=~/^cr/) || ($role eq 'gr') ||
 9878:             ($role eq 'co')) {
 9879: # for course roles, perform group memberships changes triggered by role change.
 9880:             unless ($role =~ /^gr/) {
 9881:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 9882:                                                  $origstart,$selfenroll,$context);
 9883:             }
 9884:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 9885:                            $selfenroll,$context);
 9886:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
 9887:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
 9888:                  ($role eq 'da')) {
 9889:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 9890:                            $context);
 9891:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
 9892:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 9893:                              $context);
 9894:         }
 9895:         if ($role eq 'cc') {
 9896:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
 9897:         }
 9898:     }
 9899:     return $answer;
 9900: }
 9901: 
 9902: sub autoupdate_coowners {
 9903:     my ($url,$end,$start,$uname,$udom) = @_;
 9904:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
 9905:     if (($cdom ne '') && ($cnum ne '')) {
 9906:         my $now = time;
 9907:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
 9908:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
 9909:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
 9910:             my $instcode = $coursehash{'internal.coursecode'};
 9911:             if ($instcode ne '') {
 9912:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
 9913:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
 9914:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
 9915:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
 9916:                         if ($result eq 'valid') {
 9917:                             if ($coursehash{'internal.co-owners'}) {
 9918:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 9919:                                     push(@newcoowners,$coowner);
 9920:                                 }
 9921:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
 9922:                                     push(@newcoowners,$uname.':'.$udom);
 9923:                                 }
 9924:                                 @newcoowners = sort(@newcoowners);
 9925:                             } else {
 9926:                                 push(@newcoowners,$uname.':'.$udom);
 9927:                             }
 9928:                         } else {
 9929:                             if ($coursehash{'internal.co-owners'}) {
 9930:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 9931:                                     unless ($coowner eq $uname.':'.$udom) {
 9932:                                         push(@newcoowners,$coowner);
 9933:                                     }
 9934:                                 }
 9935:                                 unless (@newcoowners > 0) {
 9936:                                     $delcoowners = 1;
 9937:                                     $coowners = '';
 9938:                                 }
 9939:                             }
 9940:                         }
 9941:                         if (@newcoowners || $delcoowners) {
 9942:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
 9943:                                             $delcoowners,@newcoowners);
 9944:                         }
 9945:                     }
 9946:                 }
 9947:             }
 9948:         }
 9949:     }
 9950: }
 9951: 
 9952: sub store_coowners {
 9953:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
 9954:     my $cid = $cdom.'_'.$cnum;
 9955:     my ($coowners,$delresult,$putresult);
 9956:     if (@newcoowners) {
 9957:         $coowners = join(',',@newcoowners);
 9958:         my %coownershash = (
 9959:                             'internal.co-owners' => $coowners,
 9960:                            );
 9961:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
 9962:         if ($putresult eq 'ok') {
 9963:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
 9964:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
 9965:             }
 9966:         }
 9967:     }
 9968:     if ($delcoowners) {
 9969:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
 9970:         if ($delresult eq 'ok') {
 9971:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
 9972:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
 9973:             }
 9974:         }
 9975:     }
 9976:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
 9977:         my %crsinfo =
 9978:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 9979:         if (ref($crsinfo{$cid}) eq 'HASH') {
 9980:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
 9981:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
 9982:         }
 9983:     }
 9984: }
 9985: 
 9986: # -------------------------------------------------- Modify user authentication
 9987: # Overrides without validation
 9988: 
 9989: sub modifyuserauth {
 9990:     my ($udom,$uname,$umode,$upass)=@_;
 9991:     my $uhome=&homeserver($uname,$udom);
 9992:     my $allowed;
 9993:     if (&allowed('mau',$udom)) {
 9994:         $allowed = 1;
 9995:     } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
 9996:              ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
 9997:              (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
 9998:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 9999:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10000:         if (($cdom ne '') && ($cnum ne '')) {
10001:             my $is_owner = &is_course_owner($cdom,$cnum);
10002:             if ($is_owner) {
10003:                 $allowed = 1;
10004:             }
10005:         }
10006:     }
10007:     unless ($allowed) { return 'refused'; }
10008:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
10009:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
10010:              ' in domain '.$env{'request.role.domain'});  
10011:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
10012: 		     &escape($upass),$uhome);
10013:     my $ip = &get_requestor_ip();
10014:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
10015:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
10016:          '(Remote '.$ip.'): '.$reply);
10017:     &log($udom,,$uname,$uhome,
10018:         'Authentication changed by '.$env{'user.domain'}.', '.
10019:                                      $env{'user.name'}.', '.$umode.
10020:          '(Remote '.$ip.'): '.$reply);
10021:     unless ($reply eq 'ok') {
10022:         &logthis('Authentication mode error: '.$reply);
10023: 	return 'error: '.$reply;
10024:     }   
10025:     return 'ok';
10026: }
10027: 
10028: # --------------------------------------------------------------- Modify a user
10029: 
10030: sub modifyuser {
10031:     my ($udom,    $uname, $uid,
10032:         $umode,   $upass, $first,
10033:         $middle,  $last,  $gene,
10034:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
10035:     $udom= &LONCAPA::clean_domain($udom);
10036:     $uname=&LONCAPA::clean_username($uname);
10037:     my $showcandelete = 'none';
10038:     if (ref($candelete) eq 'ARRAY') {
10039:         if (@{$candelete} > 0) {
10040:             $showcandelete = join(', ',@{$candelete});
10041:         }
10042:     }
10043:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
10044:              $umode.', '.$first.', '.$middle.', '.
10045: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
10046:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
10047:                                      ' desiredhome not specified'). 
10048:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
10049:              ' in domain '.$env{'request.role.domain'});
10050:     my $uhome=&homeserver($uname,$udom,'true');
10051:     my $newuser;
10052:     if ($uhome eq 'no_host') {
10053:         $newuser = 1;
10054:     }
10055: # ----------------------------------------------------------------- Create User
10056:     if (($uhome eq 'no_host') && 
10057: 	(($umode && $upass) || ($umode eq 'localauth'))) {
10058:         my $unhome='';
10059:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
10060:             $unhome = $desiredhome;
10061: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
10062: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
10063:         } else { # load balancing routine for determining $unhome
10064:             my $loadm=10000000;
10065: 	    my %servers = &get_servers($udom,'library');
10066: 	    foreach my $tryserver (keys(%servers)) {
10067: 		my $answer=reply('load',$tryserver);
10068: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
10069: 		    $loadm=$answer;
10070: 		    $unhome=$tryserver;
10071: 		}
10072: 	    }
10073:         }
10074:         if (($unhome eq '') || ($unhome eq 'no_host')) {
10075: 	    return 'error: unable to find a home server for '.$uname.
10076:                    ' in domain '.$udom;
10077:         }
10078:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
10079:                          &escape($upass),$unhome);
10080: 	unless ($reply eq 'ok') {
10081:             return 'error: '.$reply;
10082:         }   
10083:         $uhome=&homeserver($uname,$udom,'true');
10084:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
10085: 	    return 'error: unable verify users home machine.';
10086:         }
10087:     }   # End of creation of new user
10088: # ---------------------------------------------------------------------- Add ID
10089:     if ($uid) {
10090:        $uid=~tr/A-Z/a-z/;
10091:        my %uidhash=&idrget($udom,$uname);
10092:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
10093:          && (!$forceid)) {
10094: 	  unless ($uid eq $uidhash{$uname}) {
10095: 	      return 'error: user id "'.$uid.'" does not match '.
10096:                   'current user id "'.$uidhash{$uname}.'".';
10097:           }
10098:        } else {
10099: 	  &idput($udom,($uname => $uid));
10100:        }
10101:     }
10102: # -------------------------------------------------------------- Add names, etc
10103:     my @tmp=&get('environment',
10104: 		   ['firstname','middlename','lastname','generation','id',
10105:                     'permanentemail','inststatus'],
10106: 		   $udom,$uname);
10107:     my (%names,%oldnames);
10108:     if ($tmp[0] =~ m/^error:.*/) { 
10109:         %names=(); 
10110:     } else {
10111:         %names = @tmp;
10112:         %oldnames = %names;
10113:     }
10114: #
10115: # If name, email and/or uid are blank (e.g., because an uploaded file
10116: # of users did not contain them), do not overwrite existing values
10117: # unless field is in $candelete array ref.  
10118: #
10119: 
10120:     my @fields = ('firstname','middlename','lastname','generation',
10121:                   'permanentemail','id');
10122:     my %newvalues;
10123:     if (ref($candelete) eq 'ARRAY') {
10124:         foreach my $field (@fields) {
10125:             if (grep(/^\Q$field\E$/,@{$candelete})) {
10126:                 if ($field eq 'firstname') {
10127:                     $names{$field} = $first;
10128:                 } elsif ($field eq 'middlename') {
10129:                     $names{$field} = $middle;
10130:                 } elsif ($field eq 'lastname') {
10131:                     $names{$field} = $last;
10132:                 } elsif ($field eq 'generation') { 
10133:                     $names{$field} = $gene;
10134:                 } elsif ($field eq 'permanentemail') {
10135:                     $names{$field} = $email;
10136:                 } elsif ($field eq 'id') {
10137:                     $names{$field}  = $uid;
10138:                 }
10139:             }
10140:         }
10141:     }
10142:     if ($first)  { $names{'firstname'}  = $first; }
10143:     if (defined($middle)) { $names{'middlename'} = $middle; }
10144:     if ($last)   { $names{'lastname'}   = $last; }
10145:     if (defined($gene))   { $names{'generation'} = $gene; }
10146:     if ($email) {
10147:        $email=~s/[^\w\@\.\-\,]//gs;
10148:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
10149:     }
10150:     if ($uid) { $names{'id'}  = $uid; }
10151:     if (defined($inststatus)) {
10152:         $names{'inststatus'} = '';
10153:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
10154:         if (ref($usertypes) eq 'HASH') {
10155:             my @okstatuses; 
10156:             foreach my $item (split(/:/,$inststatus)) {
10157:                 if (defined($usertypes->{$item})) {
10158:                     push(@okstatuses,$item);  
10159:                 }
10160:             }
10161:             if (@okstatuses) {
10162:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
10163:             }
10164:         }
10165:     }
10166:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
10167:                  $umode.', '.$first.', '.$middle.', '.
10168:                  $last.', '.$gene.', '.$email.', '.$inststatus;
10169:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
10170:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
10171:     } else {
10172:         $logmsg .= ' during self creation';
10173:     }
10174:     my $changed;
10175:     if ($newuser) {
10176:         $changed = 1;
10177:     } else {
10178:         foreach my $field (@fields) {
10179:             if ($names{$field} ne $oldnames{$field}) {
10180:                 $changed = 1;
10181:                 last;
10182:             }
10183:         }
10184:     }
10185:     unless ($changed) {
10186:         $logmsg = 'No changes in user information needed for: '.$logmsg;
10187:         &logthis($logmsg);
10188:         return 'ok';
10189:     }
10190:     my $reply = &put('environment', \%names, $udom,$uname);
10191:     if ($reply ne 'ok') { 
10192:         return 'error: '.$reply;
10193:     }
10194:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
10195:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
10196:     }
10197:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
10198:     &devalidate_cache_new('namescache',$uname.':'.$udom);
10199:     $logmsg = 'Success modifying user '.$logmsg;
10200:     &logthis($logmsg);
10201:     return 'ok';
10202: }
10203: 
10204: # -------------------------------------------------------------- Modify student
10205: 
10206: sub modifystudent {
10207:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
10208:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
10209:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
10210:     if (!$cid) {
10211: 	unless ($cid=$env{'request.course.id'}) {
10212: 	    return 'not_in_class';
10213: 	}
10214:     }
10215: # --------------------------------------------------------------- Make the user
10216:     my $reply=&modifyuser
10217: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
10218:          $desiredhome,$email,$inststatus);
10219:     unless ($reply eq 'ok') { return $reply; }
10220:     # This will cause &modify_student_enrollment to get the uid from the
10221:     # student's environment
10222:     $uid = undef if (!$forceid);
10223:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
10224: 					$gene,$usec,$end,$start,$type,$locktype,
10225:                                         $cid,$selfenroll,$context,$credits,$instsec);
10226:     return $reply;
10227: }
10228: 
10229: sub modify_student_enrollment {
10230:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
10231:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
10232:     my ($cdom,$cnum,$chome);
10233:     if (!$cid) {
10234: 	unless ($cid=$env{'request.course.id'}) {
10235: 	    return 'not_in_class';
10236: 	}
10237: 	$cdom=$env{'course.'.$cid.'.domain'};
10238: 	$cnum=$env{'course.'.$cid.'.num'};
10239:     } else {
10240: 	($cdom,$cnum)=split(/_/,$cid);
10241:     }
10242:     $chome=$env{'course.'.$cid.'.home'};
10243:     if (!$chome) {
10244: 	$chome=&homeserver($cnum,$cdom);
10245:     }
10246:     if (!$chome) { return 'unknown_course'; }
10247:     # Make sure the user exists
10248:     my $uhome=&homeserver($uname,$udom);
10249:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
10250: 	return 'error: no such user';
10251:     }
10252:     # Get student data if we were not given enough information
10253:     if (!defined($first)  || $first  eq '' || 
10254:         !defined($last)   || $last   eq '' || 
10255:         !defined($uid)    || $uid    eq '' || 
10256:         !defined($middle) || $middle eq '' || 
10257:         !defined($gene)   || $gene   eq '') {
10258:         # They did not supply us with enough data to enroll the student, so
10259:         # we need to pick up more information.
10260:         my %tmp = &get('environment',
10261:                        ['firstname','middlename','lastname', 'generation','id']
10262:                        ,$udom,$uname);
10263: 
10264:         #foreach my $key (keys(%tmp)) {
10265:         #    &logthis("key $key = ".$tmp{$key});
10266:         #}
10267:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
10268:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
10269:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
10270:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
10271:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
10272:     }
10273:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
10274:     my $user = "$uname:$udom";
10275:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
10276:     my $reply=cput('classlist',
10277: 		   {$user => 
10278: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
10279: 		   $cdom,$cnum);
10280:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
10281:         &devalidate_getsection_cache($udom,$uname,$cid);
10282:     } else { 
10283: 	return 'error: '.$reply;
10284:     }
10285:     # Add student role to user
10286:     my $uurl='/'.$cid;
10287:     $uurl=~s/\_/\//g;
10288:     if ($usec) {
10289: 	$uurl.='/'.$usec;
10290:     }
10291:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
10292:                              $selfenroll,$context);
10293:     if ($result ne 'ok') {
10294:         if ($old_entry{$user} ne '') {
10295:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
10296:         } else {
10297:             $reply = &del('classlist',[$user],$cdom,$cnum);
10298:         }
10299:     }
10300:     return $result; 
10301: }
10302: 
10303: sub format_name {
10304:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
10305:     my $name;
10306:     if ($first ne 'lastname') {
10307: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
10308:     } else {
10309: 	if ($lastname=~/\S/) {
10310: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
10311: 	    $name=~s/\s+,/,/;
10312: 	} else {
10313: 	    $name.= $firstname.' '.$middlename.' '.$generation;
10314: 	}
10315:     }
10316:     $name=~s/^\s+//;
10317:     $name=~s/\s+$//;
10318:     $name=~s/\s+/ /g;
10319:     return $name;
10320: }
10321: 
10322: # ------------------------------------------------- Write to course preferences
10323: 
10324: sub writecoursepref {
10325:     my ($courseid,%prefs)=@_;
10326:     $courseid=~s/^\///;
10327:     $courseid=~s/\_/\//g;
10328:     my ($cdomain,$cnum)=split(/\//,$courseid);
10329:     my $chome=homeserver($cnum,$cdomain);
10330:     if (($chome eq '') || ($chome eq 'no_host')) { 
10331: 	return 'error: no such course';
10332:     }
10333:     my $cstring='';
10334:     foreach my $pref (keys(%prefs)) {
10335: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
10336:     }
10337:     $cstring=~s/\&$//;
10338:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
10339: }
10340: 
10341: # ---------------------------------------------------------- Make/modify course
10342: 
10343: sub createcourse {
10344:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
10345:         $course_owner,$crstype,$cnum,$context,$category,$callercontext)=@_;
10346:     $url=&declutter($url);
10347:     my $cid='';
10348:     if ($context eq 'requestcourses') {
10349:         my $can_create = 0;
10350:         my ($ownername,$ownerdom) = split(':',$course_owner);
10351:         if ($udom eq $ownerdom) {
10352:             my $reload;
10353:             if (($callercontext eq 'auto') &&
10354:                ($ownerdom eq $env{'user.domain'}) && ($ownername eq $env{'user.name'})) {
10355:                 $reload = 'reload';
10356:             }
10357:             if (&usertools_access($ownername,$ownerdom,$category,$reload,
10358:                                   $context)) {
10359:                 $can_create = 1;
10360:             }
10361:         } else {
10362:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
10363:                                            $category);
10364:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
10365:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
10366:                 if (@curr > 0) {
10367:                     my @options = qw(approval validate autolimit);
10368:                     my $optregex = join('|',@options);
10369:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
10370:                         $can_create = 1;
10371:                     }
10372:                 }
10373:             }
10374:         }
10375:         if ($can_create) {
10376:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
10377:                 unless (&allowed('ccc',$udom)) {
10378:                     return 'refused'; 
10379:                 }
10380:             }
10381:         } else {
10382:             return 'refused';
10383:         }
10384:     } elsif (!&allowed('ccc',$udom)) {
10385:         return 'refused';
10386:     }
10387: # --------------------------------------------------------------- Get Unique ID
10388:     my $uname;
10389:     if ($cnum =~ /^$match_courseid$/) {
10390:         my $chome=&homeserver($cnum,$udom,'true');
10391:         if (($chome eq '') || ($chome eq 'no_host')) {
10392:             $uname = $cnum;
10393:         } else {
10394:             $uname = &generate_coursenum($udom,$crstype);
10395:         }
10396:     } else {
10397:         $uname = &generate_coursenum($udom,$crstype);
10398:     }
10399:     return $uname if ($uname =~ /^error/);
10400: # -------------------------------------------------- Check supplied server name
10401:     if (!defined($course_server)) {
10402:         if (defined(&domain($udom,'primary'))) {
10403:             $course_server = &domain($udom,'primary');
10404:         } else {
10405:             $course_server = $env{'user.home'}; 
10406:         }
10407:     }
10408:     my %host_servers =
10409:         &Apache::lonnet::get_servers($udom,'library');
10410:     unless ($host_servers{$course_server}) {
10411:         return 'error: invalid home server for course: '.$course_server;
10412:     }
10413: # ------------------------------------------------------------- Make the course
10414:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
10415:                       $course_server);
10416:     unless ($reply eq 'ok') { return 'error: '.$reply; }
10417:     my $uhome=&homeserver($uname,$udom,'true');
10418:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
10419: 	return 'error: no such course';
10420:     }
10421: # ----------------------------------------------------------------- Course made
10422: # log existence
10423:     my $now = time;
10424:     my $newcourse = {
10425:                     $udom.'_'.$uname => {
10426:                                      description => $description,
10427:                                      inst_code   => $inst_code,
10428:                                      owner       => $course_owner,
10429:                                      type        => $crstype,
10430:                                      creator     => $env{'user.name'}.':'.
10431:                                                     $env{'user.domain'},
10432:                                      created     => $now,
10433:                                      context     => $context,
10434:                                                 },
10435:                     };
10436:     &courseidput($udom,$newcourse,$uhome,'notime');
10437: # set toplevel url
10438:     my $topurl=$url;
10439:     unless ($nonstandard) {
10440: # ------------------------------------------ For standard courses, make top url
10441:         my $mapurl=&clutter($url);
10442:         if ($mapurl eq '/res/') { $mapurl=''; }
10443:         $env{'form.initmap'}=(<<ENDINITMAP);
10444: <map>
10445: <resource id="1" type="start"></resource>
10446: <resource id="2" src="$mapurl"></resource>
10447: <resource id="3" type="finish"></resource>
10448: <link index="1" from="1" to="2"></link>
10449: <link index="2" from="2" to="3"></link>
10450: </map>
10451: ENDINITMAP
10452:         $topurl=&declutter(
10453:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
10454:                           );
10455:     }
10456: # ----------------------------------------------------------- Write preferences
10457:     &writecoursepref($udom.'_'.$uname,
10458:                      ('description'              => $description,
10459:                       'url'                      => $topurl,
10460:                       'internal.creator'         => $env{'user.name'}.':'.
10461:                                                     $env{'user.domain'},
10462:                       'internal.created'         => $now,
10463:                       'internal.creationcontext' => $context)
10464:                     );
10465:     return '/'.$udom.'/'.$uname;
10466: }
10467: 
10468: # ------------------------------------------------------------------- Create ID
10469: sub generate_coursenum {
10470:     my ($udom,$crstype) = @_;
10471:     my $domdesc = &domain($udom);
10472:     return 'error: invalid domain' if ($domdesc eq '');
10473:     my $first;
10474:     if ($crstype eq 'Community') {
10475:         $first = '0';
10476:     } else {
10477:         $first = int(1+rand(9)); 
10478:     } 
10479:     my $uname=$first.
10480:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
10481:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
10482:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
10483: # ----------------------------------------------- Make sure that does not exist
10484:     my $uhome=&homeserver($uname,$udom,'true');
10485:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
10486:         if ($crstype eq 'Community') {
10487:             $first = '0';
10488:         } else {
10489:             $first = int(1+rand(9));
10490:         }
10491:         $uname=$first.
10492:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
10493:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
10494:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
10495:         $uhome=&homeserver($uname,$udom,'true');
10496:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
10497:             return 'error: unable to generate unique course-ID';
10498:         }
10499:     }
10500:     return $uname;
10501: }
10502: 
10503: sub is_course {
10504:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
10505:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
10506:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
10507:     my $uhome=&homeserver($cnum,$cdom);
10508:     my $iscourse;
10509:     if (grep { $_ eq $uhome } current_machine_ids()) {
10510:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
10511:     } else {
10512:         my $hashid = $cdom.':'.$cnum;
10513:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
10514:         unless (defined($cached)) {
10515:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
10516:                                         $cnum,undef,undef,'.');
10517:             $iscourse = 0;
10518:             if (exists($courses{$cdom.'_'.$cnum})) {
10519:                 $iscourse = 1;
10520:             }
10521:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
10522:         }
10523:     }
10524:     return unless($iscourse);
10525:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
10526: }
10527: 
10528: sub store_userdata {
10529:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
10530:     my $result;
10531:     if ($datakey ne '') {
10532:         if (ref($storehash) eq 'HASH') {
10533:             if ($udom eq '' || $uname eq '') {
10534:                 $udom = $env{'user.domain'};
10535:                 $uname = $env{'user.name'};
10536:             }
10537:             my $uhome=&homeserver($uname,$udom);
10538:             if (($uhome eq '') || ($uhome eq 'no_host')) {
10539:                 $result = 'error: no_host';
10540:             } else {
10541:                 $storehash->{'ip'} = &get_requestor_ip();
10542:                 $storehash->{'host'} = $perlvar{'lonHostID'};
10543: 
10544:                 my $namevalue='';
10545:                 foreach my $key (keys(%{$storehash})) {
10546:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
10547:                 }
10548:                 $namevalue=~s/\&$//;
10549:                 unless ($namespace eq 'courserequests') {
10550:                     $datakey = &escape($datakey);
10551:                 }
10552:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
10553:                                   $namevalue,$uhome);
10554:             }
10555:         } else {
10556:             $result = 'error: data to store was not a hash reference'; 
10557:         }
10558:     } else {
10559:         $result= 'error: invalid requestkey'; 
10560:     }
10561:     return $result;
10562: }
10563: 
10564: # ---------------------------------------------------------- Assign Custom Role
10565: 
10566: sub assigncustomrole {
10567:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
10568:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
10569:                        $end,$start,$deleteflag,$selfenroll,$context);
10570: }
10571: 
10572: # ----------------------------------------------------------------- Revoke Role
10573: 
10574: sub revokerole {
10575:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
10576:     my $now=time;
10577:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
10578: }
10579: 
10580: # ---------------------------------------------------------- Revoke Custom Role
10581: 
10582: sub revokecustomrole {
10583:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
10584:     my $now=time;
10585:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
10586:            $deleteflag,$selfenroll,$context);
10587: }
10588: 
10589: # ------------------------------------------------------------ Disk usage
10590: sub diskusage {
10591:     my ($udom,$uname,$directorypath,$getpropath)=@_;
10592:     $directorypath =~ s/\/$//;
10593:     my $listing=&reply('du2:'.&escape($directorypath).':'
10594:                        .&escape($getpropath).':'.&escape($uname).':'
10595:                        .&escape($udom),homeserver($uname,$udom));
10596:     if ($listing eq 'unknown_cmd') {
10597:         if ($getpropath) {
10598:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
10599:         }
10600:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
10601:     }
10602:     return $listing;
10603: }
10604: 
10605: sub is_locked {
10606:     my ($file_name, $domain, $user, $which) = @_;
10607:     my @check;
10608:     my $is_locked;
10609:     push (@check,$file_name);
10610:     my %locked = &get('file_permissions',\@check,
10611: 		      $env{'user.domain'},$env{'user.name'});
10612:     my ($tmp)=keys(%locked);
10613:     if ($tmp=~/^error:/) { undef(%locked); }
10614:     
10615:     if (ref($locked{$file_name}) eq 'ARRAY') {
10616:         $is_locked = 'false';
10617:         foreach my $entry (@{$locked{$file_name}}) {
10618:            if (ref($entry) eq 'ARRAY') {
10619:                $is_locked = 'true';
10620:                if (ref($which) eq 'ARRAY') {
10621:                    push(@{$which},$entry);
10622:                } else {
10623:                    last;
10624:                }
10625:            }
10626:        }
10627:     } else {
10628:         $is_locked = 'false';
10629:     }
10630:     return $is_locked;
10631: }
10632: 
10633: sub declutter_portfile {
10634:     my ($file) = @_;
10635:     $file =~ s{^(/portfolio/|portfolio/)}{/};
10636:     return $file;
10637: }
10638: 
10639: # ------------------------------------------------------------- Mark as Read Only
10640: 
10641: sub mark_as_readonly {
10642:     my ($domain,$user,$files,$what) = @_;
10643:     my %current_permissions = &dump('file_permissions',$domain,$user);
10644:     my ($tmp)=keys(%current_permissions);
10645:     if ($tmp=~/^error:/) { undef(%current_permissions); }
10646:     foreach my $file (@{$files}) {
10647: 	$file = &declutter_portfile($file);
10648:         push(@{$current_permissions{$file}},$what);
10649:     }
10650:     &put('file_permissions',\%current_permissions,$domain,$user);
10651:     return;
10652: }
10653: 
10654: # ------------------------------------------------------------Save Selected Files
10655: 
10656: sub save_selected_files {
10657:     my ($user, $path, @files) = @_;
10658:     my $filename = $user."savedfiles";
10659:     my @other_files = &files_not_in_path($user, $path);
10660:     open (OUT,'>',LONCAPA::tempdir().$filename);
10661:     foreach my $file (@files) {
10662:         print (OUT $env{'form.currentpath'}.$file."\n");
10663:     }
10664:     foreach my $file (@other_files) {
10665:         print (OUT $file."\n");
10666:     }
10667:     close (OUT);
10668:     return 'ok';
10669: }
10670: 
10671: sub clear_selected_files {
10672:     my ($user) = @_;
10673:     my $filename = $user."savedfiles";
10674:     open (OUT,'>',LONCAPA::tempdir().$filename);
10675:     print (OUT undef);
10676:     close (OUT);
10677:     return ("ok");    
10678: }
10679: 
10680: sub files_in_path {
10681:     my ($user, $path) = @_;
10682:     my $filename = $user."savedfiles";
10683:     my %return_files;
10684:     open (IN,'<',LONCAPA::tempdir().$filename);
10685:     while (my $line_in = <IN>) {
10686:         chomp ($line_in);
10687:         my @paths_and_file = split (m!/!, $line_in);
10688:         my $file_part = pop (@paths_and_file);
10689:         my $path_part = join ('/', @paths_and_file);
10690:         $path_part.='/';
10691:         my $path_and_file = $path_part.$file_part;
10692:         if ($path_part eq $path) {
10693:             $return_files{$file_part}= 'selected';
10694:         }
10695:     }
10696:     close (IN);
10697:     return (\%return_files);
10698: }
10699: 
10700: # called in portfolio select mode, to show files selected NOT in current directory
10701: sub files_not_in_path {
10702:     my ($user, $path) = @_;
10703:     my $filename = $user."savedfiles";
10704:     my @return_files;
10705:     my $path_part;
10706:     open(IN, '<',LONCAPA::tempdir().$filename);
10707:     while (my $line = <IN>) {
10708:         #ok, I know it's clunky, but I want it to work
10709:         my @paths_and_file = split(m|/|, $line);
10710:         my $file_part = pop(@paths_and_file);
10711:         chomp($file_part);
10712:         my $path_part = join('/', @paths_and_file);
10713:         $path_part .= '/';
10714:         my $path_and_file = $path_part.$file_part;
10715:         if ($path_part ne $path) {
10716:             push(@return_files, ($path_and_file));
10717:         }
10718:     }
10719:     close(OUT);
10720:     return (@return_files);
10721: }
10722: 
10723: #----------------------------------------------Get portfolio file permissions
10724: 
10725: sub get_portfile_permissions {
10726:     my ($domain,$user) = @_;
10727:     my %current_permissions = &dump('file_permissions',$domain,$user);
10728:     my ($tmp)=keys(%current_permissions);
10729:     if ($tmp=~/^error:/) { undef(%current_permissions); }
10730:     return \%current_permissions;
10731: }
10732: 
10733: #---------------------------------------------Get portfolio file access controls
10734: 
10735: sub get_access_controls {
10736:     my ($current_permissions,$group,$file) = @_;
10737:     my %access;
10738:     my $real_file = $file;
10739:     $file =~ s/\.meta$//;
10740:     if (defined($file)) {
10741:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
10742:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
10743:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
10744:             }
10745:         }
10746:     } else {
10747:         foreach my $key (keys(%{$current_permissions})) {
10748:             if ($key =~ /\0accesscontrol$/) {
10749:                 if (defined($group)) {
10750:                     if ($key !~ m-^\Q$group\E/-) {
10751:                         next;
10752:                     }
10753:                 }
10754:                 my ($fullpath) = split(/\0/,$key);
10755:                 if (ref($$current_permissions{$key}) eq 'HASH') {
10756:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
10757:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
10758:                     }
10759:                 }
10760:             }
10761:         }
10762:     }
10763:     return %access;
10764: }
10765: 
10766: sub modify_access_controls {
10767:     my ($file_name,$changes,$domain,$user)=@_;
10768:     my ($outcome,$deloutcome);
10769:     my %store_permissions;
10770:     my %new_values;
10771:     my %new_control;
10772:     my %translation;
10773:     my @deletions = ();
10774:     my $now = time;
10775:     if (exists($$changes{'activate'})) {
10776:         if (ref($$changes{'activate'}) eq 'HASH') {
10777:             my @newitems = sort(keys(%{$$changes{'activate'}}));
10778:             my $numnew = scalar(@newitems);
10779:             for (my $i=0; $i<$numnew; $i++) {
10780:                 my $newkey = $newitems[$i];
10781:                 my $newid = &Apache::loncommon::get_cgi_id();
10782:                 if ($newkey =~ /^\d+:/) { 
10783:                     $newkey =~ s/^(\d+)/$newid/;
10784:                     $translation{$1} = $newid;
10785:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
10786:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
10787:                     $translation{$1} = $newid;
10788:                 }
10789:                 $new_values{$file_name."\0".$newkey} = 
10790:                                           $$changes{'activate'}{$newitems[$i]};
10791:                 $new_control{$newkey} = $now;
10792:             }
10793:         }
10794:     }
10795:     my %todelete;
10796:     my %changed_items;
10797:     foreach my $action ('delete','update') {
10798:         if (exists($$changes{$action})) {
10799:             if (ref($$changes{$action}) eq 'HASH') {
10800:                 foreach my $key (keys(%{$$changes{$action}})) {
10801:                     my ($itemnum) = ($key =~ /^([^:]+):/);
10802:                     if ($action eq 'delete') { 
10803:                         $todelete{$itemnum} = 1;
10804:                     } else {
10805:                         $changed_items{$itemnum} = $key;
10806:                     }
10807:                 }
10808:             }
10809:         }
10810:     }
10811:     # get lock on access controls for file.
10812:     my $lockhash = {
10813:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
10814:                                                        ':'.$env{'user.domain'},
10815:                    }; 
10816:     my $tries = 0;
10817:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
10818:    
10819:     while (($gotlock ne 'ok') && $tries < 10) {
10820:         $tries ++;
10821:         sleep(0.1);
10822:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
10823:     }
10824:     if ($gotlock eq 'ok') {
10825:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
10826:         my ($tmp)=keys(%curr_permissions);
10827:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
10828:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
10829:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
10830:             if (ref($curr_controls) eq 'HASH') {
10831:                 foreach my $control_item (keys(%{$curr_controls})) {
10832:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
10833:                     if (defined($todelete{$itemnum})) {
10834:                         push(@deletions,$file_name."\0".$control_item);
10835:                     } else {
10836:                         if (defined($changed_items{$itemnum})) {
10837:                             $new_control{$changed_items{$itemnum}} = $now;
10838:                             push(@deletions,$file_name."\0".$control_item);
10839:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
10840:                         } else {
10841:                             $new_control{$control_item} = $$curr_controls{$control_item};
10842:                         }
10843:                     }
10844:                 }
10845:             }
10846:         }
10847:         my ($group);
10848:         if (&is_course($domain,$user)) {
10849:             ($group,my $file) = split(/\//,$file_name,2);
10850:         }
10851:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
10852:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
10853:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
10854:         #  remove lock
10855:         my @del_lock = ($file_name."\0".'locked_access_records');
10856:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
10857:         my $sqlresult =
10858:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
10859:                                     $group);
10860:     } else {
10861:         $outcome = "error: could not obtain lockfile\n";  
10862:     }
10863:     return ($outcome,$deloutcome,\%new_values,\%translation);
10864: }
10865: 
10866: sub make_public_indefinitely {
10867:     my ($requrl) = @_;
10868:     my $now = time;
10869:     my $action = 'activate';
10870:     my $aclnum = 0;
10871:     if (&is_portfolio_url($requrl)) {
10872:         my (undef,$udom,$unum,$file_name,$group) =
10873:             &parse_portfolio_url($requrl);
10874:         my $current_perms = &get_portfile_permissions($udom,$unum);
10875:         my %access_controls = &get_access_controls($current_perms,
10876:                                                    $group,$file_name);
10877:         foreach my $key (keys(%{$access_controls{$file_name}})) {
10878:             my ($num,$scope,$end,$start) = 
10879:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
10880:             if ($scope eq 'public') {
10881:                 if ($start <= $now && $end == 0) {
10882:                     $action = 'none';
10883:                 } else {
10884:                     $action = 'update';
10885:                     $aclnum = $num;
10886:                 }
10887:                 last;
10888:             }
10889:         }
10890:         if ($action eq 'none') {
10891:              return 'ok';
10892:         } else {
10893:             my %changes;
10894:             my $newend = 0;
10895:             my $newstart = $now;
10896:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
10897:             $changes{$action}{$newkey} = {
10898:                 type => 'public',
10899:                 time => {
10900:                     start => $newstart,
10901:                     end   => $newend,
10902:                 },
10903:             };
10904:             my ($outcome,$deloutcome,$new_values,$translation) =
10905:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
10906:             return $outcome;
10907:         }
10908:     } else {
10909:         return 'invalid';
10910:     }
10911: }
10912: 
10913: #------------------------------------------------------Get Marked as Read Only
10914: 
10915: sub get_marked_as_readonly {
10916:     my ($domain,$user,$what,$group) = @_;
10917:     my $current_permissions = &get_portfile_permissions($domain,$user);
10918:     my @readonly_files;
10919:     my $cmp1=$what;
10920:     if (ref($what)) { $cmp1=join('',@{$what}) };
10921:     while (my ($file_name,$value) = each(%{$current_permissions})) {
10922:         if (defined($group)) {
10923:             if ($file_name !~ m-^\Q$group\E/-) {
10924:                 next;
10925:             }
10926:         }
10927:         if (ref($value) eq "ARRAY"){
10928:             foreach my $stored_what (@{$value}) {
10929:                 my $cmp2=$stored_what;
10930:                 if (ref($stored_what) eq 'ARRAY') {
10931:                     $cmp2=join('',@{$stored_what});
10932:                 }
10933:                 if ($cmp1 eq $cmp2) {
10934:                     push(@readonly_files, $file_name);
10935:                     last;
10936:                 } elsif (!defined($what)) {
10937:                     push(@readonly_files, $file_name);
10938:                     last;
10939:                 }
10940:             }
10941:         }
10942:     }
10943:     return @readonly_files;
10944: }
10945: #-----------------------------------------------------------Get Marked as Read Only Hash
10946: 
10947: sub get_marked_as_readonly_hash {
10948:     my ($current_permissions,$group,$what) = @_;
10949:     my %readonly_files;
10950:     while (my ($file_name,$value) = each(%{$current_permissions})) {
10951:         if (defined($group)) {
10952:             if ($file_name !~ m-^\Q$group\E/-) {
10953:                 next;
10954:             }
10955:         }
10956:         if (ref($value) eq "ARRAY"){
10957:             foreach my $stored_what (@{$value}) {
10958:                 if (ref($stored_what) eq 'ARRAY') {
10959:                     foreach my $lock_descriptor(@{$stored_what}) {
10960:                         if ($lock_descriptor eq 'graded') {
10961:                             $readonly_files{$file_name} = 'graded';
10962:                         } elsif ($lock_descriptor eq 'handback') {
10963:                             $readonly_files{$file_name} = 'handback';
10964:                         } else {
10965:                             if (!exists($readonly_files{$file_name})) {
10966:                                 $readonly_files{$file_name} = 'locked';
10967:                             }
10968:                         }
10969:                     }
10970:                 } 
10971:             }
10972:         } 
10973:     }
10974:     return %readonly_files;
10975: }
10976: # ------------------------------------------------------------ Unmark as Read Only
10977: 
10978: sub unmark_as_readonly {
10979:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
10980:     # for portfolio submissions, $what contains [$symb,$crsid] 
10981:     my ($domain,$user,$what,$file_name,$group) = @_;
10982:     $file_name = &declutter_portfile($file_name);
10983:     my $symb_crs = $what;
10984:     if (ref($what)) { $symb_crs=join('',@$what); }
10985:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
10986:     my ($tmp)=keys(%current_permissions);
10987:     if ($tmp=~/^error:/) { undef(%current_permissions); }
10988:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
10989:     foreach my $file (@readonly_files) {
10990: 	my $clean_file = &declutter_portfile($file);
10991: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
10992: 	my $current_locks = $current_permissions{$file};
10993:         my @new_locks;
10994:         my @del_keys;
10995:         if (ref($current_locks) eq "ARRAY"){
10996:             foreach my $locker (@{$current_locks}) {
10997:                 my $compare=$locker;
10998:                 if (ref($locker) eq 'ARRAY') {
10999:                     $compare=join('',@{$locker});
11000:                     if ($compare ne $symb_crs) {
11001:                         push(@new_locks, $locker);
11002:                     }
11003:                 }
11004:             }
11005:             if (scalar(@new_locks) > 0) {
11006:                 $current_permissions{$file} = \@new_locks;
11007:             } else {
11008:                 push(@del_keys, $file);
11009:                 &del('file_permissions',\@del_keys, $domain, $user);
11010:                 delete($current_permissions{$file});
11011:             }
11012:         }
11013:     }
11014:     &put('file_permissions',\%current_permissions,$domain,$user);
11015:     return;
11016: }
11017: 
11018: # ------------------------------------------------------------ Directory lister
11019: 
11020: sub dirlist {
11021:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
11022:     $uri=~s/^\///;
11023:     $uri=~s/\/$//;
11024:     my ($udom, $uname);
11025:     if ($getuserdir) {
11026:         $udom = $userdomain;
11027:         $uname = $username;
11028:     } else {
11029:         (undef,$udom,$uname)=split(/\//,$uri);
11030:         if(defined($userdomain)) {
11031:             $udom = $userdomain;
11032:         }
11033:         if(defined($username)) {
11034:             $uname = $username;
11035:         }
11036:     }
11037:     my ($dirRoot,$listing,@listing_results);
11038: 
11039:     $dirRoot = $perlvar{'lonDocRoot'};
11040:     if (defined($getpropath)) {
11041:         $dirRoot = &propath($udom,$uname);
11042:         $dirRoot =~ s/\/$//;
11043:     } elsif (defined($getuserdir)) {
11044:         my $subdir=$uname.'__';
11045:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
11046:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
11047:                    ."/$udom/$subdir/$uname";
11048:     } elsif (defined($alternateRoot)) {
11049:         $dirRoot = $alternateRoot;
11050:     }
11051: 
11052:     if($udom) {
11053:         if($uname) {
11054:             my $uhome = &homeserver($uname,$udom);
11055:             if ($uhome eq 'no_host') {
11056:                 return ([],'no_host');
11057:             }
11058:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
11059:                               .$getuserdir.':'.&escape($dirRoot)
11060:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
11061:             if ($listing eq 'unknown_cmd') {
11062:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
11063:             } else {
11064:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
11065:             }
11066:             if ($listing eq 'unknown_cmd') {
11067:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
11068:                 @listing_results = split(/:/,$listing);
11069:             } else {
11070:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
11071:             }
11072:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
11073:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
11074:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11075:                 return ([],$listing);
11076:             } else {
11077:                 return (\@listing_results);
11078:             }
11079:         } elsif(!$alternateRoot) {
11080:             my (%allusers,%listerror);
11081: 	    my %servers = &get_servers($udom,'library');
11082:  	    foreach my $tryserver (keys(%servers)) {
11083:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
11084:                                   &escape($udom),$tryserver);
11085:                 if ($listing eq 'unknown_cmd') {
11086: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
11087: 				      $udom, $tryserver);
11088:                 } else {
11089:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
11090:                 }
11091: 		if ($listing eq 'unknown_cmd') {
11092: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
11093: 				      $udom, $tryserver);
11094: 		    @listing_results = split(/:/,$listing);
11095: 		} else {
11096: 		    @listing_results =
11097: 			map { &unescape($_); } split(/:/,$listing);
11098: 		}
11099:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
11100:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
11101:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11102:                     $listerror{$tryserver} = $listing;
11103:                 } else {
11104: 		    foreach my $line (@listing_results) {
11105: 			my ($entry) = split(/&/,$line,2);
11106: 			$allusers{$entry} = 1;
11107: 		    }
11108: 		}
11109:             }
11110:             my @alluserslist=();
11111:             foreach my $user (sort(keys(%allusers))) {
11112:                 push(@alluserslist,$user.'&user');
11113:             }
11114:             if (!%listerror) {
11115:                 # no errors
11116:                 return (\@alluserslist);
11117:             } elsif (scalar(keys(%servers)) == 1) {
11118:                 # one library server, one error
11119:                 my ($key) = keys(%listerror);
11120:                 return (\@alluserslist, $listerror{$key});
11121:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
11122:                 # con_lost indicates that we might miss data from at least one
11123:                 # library server
11124:                 return (\@alluserslist, 'con_lost');
11125:             } else {
11126:                 # multiple library servers and no con_lost -> data should be
11127:                 # complete.
11128:                 return (\@alluserslist);
11129:             }
11130: 
11131:         } else {
11132:             return ([],'missing username');
11133:         }
11134:     } elsif(!defined($getpropath)) {
11135:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
11136:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
11137:         return (\@all_domains);
11138:     } else {
11139:         return ([],'missing domain');
11140:     }
11141: }
11142: 
11143: # --------------------------------------------- GetFileTimestamp
11144: # This function utilizes dirlist and returns the date stamp for
11145: # when it was last modified.  It will also return an error of -1
11146: # if an error occurs
11147: 
11148: sub GetFileTimestamp {
11149:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
11150:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
11151:     $studentName   = &LONCAPA::clean_username($studentName);
11152:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
11153:                                     undef,$getuserdir);
11154:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11155:         return -1;
11156:     }
11157:     if (ref($fileref) eq 'ARRAY') {
11158:         my @stats = split('&',$fileref->[0]);
11159:         # @stats contains first the filename, then the stat output
11160:         return $stats[10]; # so this is 10 instead of 9.
11161:     } else {
11162:         return -1;
11163:     }
11164: }
11165: 
11166: sub stat_file {
11167:     my ($uri) = @_;
11168:     $uri = &clutter_with_no_wrapper($uri);
11169: 
11170:     my ($udom,$uname,$file);
11171:     if ($uri =~ m-^/(uploaded|editupload)/-) {
11172: 	($udom,$uname,$file) =
11173: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
11174: 	$file = 'userfiles/'.$file;
11175:     }
11176:     if ($uri =~ m-^/res/-) {
11177: 	($udom,$uname) = 
11178: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
11179: 	$file = $uri;
11180:     }
11181: 
11182:     if (!$udom || !$uname || !$file) {
11183: 	# unable to handle the uri
11184: 	return ();
11185:     }
11186:     my $getpropath;
11187:     if ($file =~ /^userfiles\//) {
11188:         $getpropath = 1;
11189:     }
11190:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
11191:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11192:         return ();
11193:     } else {
11194:         if (ref($listref) eq 'ARRAY') {
11195:             my @stats = split('&',$listref->[0]);
11196: 	    shift(@stats); #filename is first
11197: 	    return @stats;
11198:         }
11199:     }
11200:     return ();
11201: }
11202: 
11203: # -------------------------------------------------------- Value of a Condition
11204: 
11205: # gets the value of a specific preevaluated condition
11206: #    stored in the string  $env{user.state.<cid>}
11207: # or looks up a condition reference in the bighash and if if hasn't
11208: # already been evaluated recurses into docondval to get the value of
11209: # the condition, then memoizing it to 
11210: #   $env{user.state.<cid>.<condition>}
11211: sub directcondval {
11212:     my $number=shift;
11213:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
11214: 	&Apache::lonuserstate::evalstate();
11215:     }
11216:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
11217: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
11218:     } elsif ($number =~ /^_/) {
11219: 	my $sub_condition;
11220: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
11221: 		&GDBM_READER(),0640)) {
11222: 	    $sub_condition=$bighash{'conditions'.$number};
11223: 	    untie(%bighash);
11224: 	}
11225: 	my $value = &docondval($sub_condition);
11226: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
11227: 	return $value;
11228:     }
11229:     if ($env{'user.state.'.$env{'request.course.id'}}) {
11230:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
11231:     } else {
11232:        return 2;
11233:     }
11234: }
11235: 
11236: # get the collection of conditions for this resource
11237: sub condval {
11238:     my $condidx=shift;
11239:     my $allpathcond='';
11240:     foreach my $cond (split(/\|/,$condidx)) {
11241: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
11242: 	    $allpathcond.=
11243: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
11244: 	}
11245:     }
11246:     $allpathcond=~s/\|$//;
11247:     return &docondval($allpathcond);
11248: }
11249: 
11250: #evaluates an expression of conditions
11251: sub docondval {
11252:     my ($allpathcond) = @_;
11253:     my $result=0;
11254:     if ($env{'request.course.id'}
11255: 	&& defined($allpathcond)) {
11256: 	my $operand='|';
11257: 	my @stack;
11258: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
11259: 	    if ($chunk eq '(') {
11260: 		push @stack,($operand,$result);
11261: 	    } elsif ($chunk eq ')') {
11262: 		my $before=pop @stack;
11263: 		if (pop @stack eq '&') {
11264: 		    $result=$result>$before?$before:$result;
11265: 		} else {
11266: 		    $result=$result>$before?$result:$before;
11267: 		}
11268: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
11269: 		$operand=$chunk;
11270: 	    } else {
11271: 		my $new=directcondval($chunk);
11272: 		if ($operand eq '&') {
11273: 		    $result=$result>$new?$new:$result;
11274: 		} else {
11275: 		    $result=$result>$new?$result:$new;
11276: 		}
11277: 	    }
11278: 	}
11279:     }
11280:     return $result;
11281: }
11282: 
11283: # ---------------------------------------------------- Devalidate courseresdata
11284: 
11285: sub devalidatecourseresdata {
11286:     my ($coursenum,$coursedomain)=@_;
11287:     my $hashid=$coursenum.':'.$coursedomain;
11288:     &devalidate_cache_new('courseres',$hashid);
11289: }
11290: 
11291: 
11292: # --------------------------------------------------- Course Resourcedata Query
11293: #
11294: #  Parameters:
11295: #      $coursenum    - Number of the course.
11296: #      $coursedomain - Domain at which the course was created.
11297: #  Returns:
11298: #     A hash of the course parameters along (I think) with timestamps
11299: #     and version info.
11300: 
11301: sub get_courseresdata {
11302:     my ($coursenum,$coursedomain)=@_;
11303:     my $coursehom=&homeserver($coursenum,$coursedomain);
11304:     my $hashid=$coursenum.':'.$coursedomain;
11305:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
11306:     my %dumpreply;
11307:     unless (defined($cached)) {
11308: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
11309: 	$result=\%dumpreply;
11310: 	my ($tmp) = keys(%dumpreply);
11311: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
11312: 	    &do_cache_new('courseres',$hashid,$result,600);
11313: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
11314: 	    return $tmp;
11315: 	} elsif ($tmp =~ /^(error)/) {
11316: 	    $result=undef;
11317: 	    &do_cache_new('courseres',$hashid,$result,600);
11318: 	}
11319:     }
11320:     return $result;
11321: }
11322: 
11323: sub devalidateuserresdata {
11324:     my ($uname,$udom)=@_;
11325:     my $hashid="$udom:$uname";
11326:     &devalidate_cache_new('userres',$hashid);
11327: }
11328: 
11329: sub get_userresdata {
11330:     my ($uname,$udom)=@_;
11331:     #most student don\'t have any data set, check if there is some data
11332:     if (&EXT_cache_status($udom,$uname)) { return undef; }
11333: 
11334:     my $hashid="$udom:$uname";
11335:     my ($result,$cached)=&is_cached_new('userres',$hashid);
11336:     if (!defined($cached)) {
11337: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
11338: 	$result=\%resourcedata;
11339: 	&do_cache_new('userres',$hashid,$result,600);
11340:     }
11341:     my ($tmp)=keys(%$result);
11342:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
11343: 	return $result;
11344:     }
11345:     #error 2 occurs when the .db doesn't exist
11346:     if ($tmp!~/error: 2 /) {
11347:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
11348: 	    &logthis("<font color=\"blue\">WARNING:".
11349: 		     " Trying to get resource data for ".
11350: 		     $uname." at ".$udom.": ".
11351: 		     $tmp."</font>");
11352:         }
11353:     } elsif ($tmp=~/error: 2 /) {
11354: 	#&EXT_cache_set($udom,$uname);
11355: 	&do_cache_new('userres',$hashid,undef,600);
11356: 	undef($tmp); # not really an error so don't send it back
11357:     }
11358:     return $tmp;
11359: }
11360: #----------------------------------------------- resdata - return resource data
11361: #  Purpose:
11362: #    Return resource data for either users or for a course.
11363: #  Parameters:
11364: #     $name      - Course/user name.
11365: #     $domain    - Name of the domain the user/course is registered on.
11366: #     $type      - Type of thing $name is (must be 'course' or 'user')
11367: #     @which     - Array of names of resources desired.
11368: #  Returns:
11369: #     The value of the first reasource in @which that is found in the
11370: #     resource hash.
11371: #  Exceptional Conditions:
11372: #     If the $type passed in is not valid (not the string 'course' or 
11373: #     'user', an undefined  reference is returned.
11374: #     If none of the resources are found, an undef is returned
11375: sub resdata {
11376:     my ($name,$domain,$type,@which)=@_;
11377:     my $result;
11378:     if ($type eq 'course') {
11379: 	$result=&get_courseresdata($name,$domain);
11380:     } elsif ($type eq 'user') {
11381: 	$result=&get_userresdata($name,$domain);
11382:     }
11383:     if (!ref($result)) { return $result; }    
11384:     foreach my $item (@which) {
11385: 	if (defined($result->{$item->[0]})) {
11386: 	    return [$result->{$item->[0]},$item->[1]];
11387:         }
11388:     }
11389:     return undef;
11390: }
11391: 
11392: sub get_domain_lti {
11393:     my ($cdom,$context) = @_;
11394:     my ($name,%lti);
11395:     if ($context eq 'consumer') {
11396:         $name = 'ltitools';
11397:     } elsif ($context eq 'provider') {
11398:         $name = 'lti';
11399:     } else {
11400:         return %lti;
11401:     }
11402:     my ($result,$cached)=&is_cached_new($name,$cdom);
11403:     if (defined($cached)) {
11404:         if (ref($result) eq 'HASH') {
11405:             %lti = %{$result};
11406:         }
11407:     } else {
11408:         my %domconfig = &get_dom('configuration',[$name],$cdom);
11409:         if (ref($domconfig{$name}) eq 'HASH') {
11410:             %lti = %{$domconfig{$name}};
11411:             my %encdomconfig = &get_dom('encconfig',[$name],$cdom);
11412:             if (ref($encdomconfig{$name}) eq 'HASH') {
11413:                 foreach my $id (keys(%lti)) {
11414:                     if (ref($encdomconfig{$name}{$id}) eq 'HASH') {
11415:                         foreach my $item ('key','secret') {
11416:                             $lti{$id}{$item} = $encdomconfig{$name}{$id}{$item};
11417:                         }
11418:                     }
11419:                 }
11420:             }
11421:         }
11422:         my $cachetime = 24*60*60;
11423:         &do_cache_new($name,$cdom,\%lti,$cachetime);
11424:     }
11425:     return %lti;
11426: }
11427: 
11428: sub get_numsuppfiles {
11429:     my ($cnum,$cdom,$ignorecache)=@_;
11430:     my $hashid=$cnum.':'.$cdom;
11431:     my ($suppcount,$cached);
11432:     unless ($ignorecache) {
11433:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
11434:     }
11435:     unless (defined($cached)) {
11436:         my $chome=&homeserver($cnum,$cdom);
11437:         unless ($chome eq 'no_host') {
11438:             ($suppcount,my $errors) = (0,0);
11439:             my $suppmap = 'supplemental.sequence';
11440:             ($suppcount,$errors) =
11441:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
11442:         }
11443:         &do_cache_new('suppcount',$hashid,$suppcount,600);
11444:     }
11445:     return $suppcount;
11446: }
11447: 
11448: #
11449: # EXT resource caching routines
11450: #
11451: 
11452: sub clear_EXT_cache_status {
11453:     &delenv('cache.EXT.');
11454: }
11455: 
11456: sub EXT_cache_status {
11457:     my ($target_domain,$target_user) = @_;
11458:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
11459:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
11460:         # We know already the user has no data
11461:         return 1;
11462:     } else {
11463:         return 0;
11464:     }
11465: }
11466: 
11467: sub EXT_cache_set {
11468:     my ($target_domain,$target_user) = @_;
11469:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
11470:     #&appenv({$cachename => time});
11471: }
11472: 
11473: # --------------------------------------------------------- Value of a Variable
11474: sub EXT {
11475: 
11476:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
11477:     unless ($varname) { return ''; }
11478:     #get real user name/domain, courseid and symb
11479:     my $courseid;
11480:     my $publicuser;
11481:     if ($symbparm) {
11482: 	$symbparm=&get_symb_from_alias($symbparm);
11483:     }
11484:     if (!($uname && $udom)) {
11485:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
11486:       if (!$symbparm) {	$symbparm=$cursymb; }
11487:     } else {
11488: 	$courseid=$env{'request.course.id'};
11489:     }
11490:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
11491:     my $rest;
11492:     if (defined($therest[0])) {
11493:        $rest=join('.',@therest);
11494:     } else {
11495:        $rest='';
11496:     }
11497: 
11498:     my $qualifierrest=$qualifier;
11499:     if ($rest) { $qualifierrest.='.'.$rest; }
11500:     my $spacequalifierrest=$space;
11501:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
11502:     if ($realm eq 'user') {
11503: # --------------------------------------------------------------- user.resource
11504: 	if ($space eq 'resource') {
11505: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
11506: 		  || defined($Apache::lonhomework::parsing_a_task))
11507: 		 &&
11508: 		 ($symbparm eq &symbread()) ) {	
11509: 		# if we are in the middle of processing the resource the
11510: 		# get the value we are planning on committing
11511:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
11512:                     return $Apache::lonhomework::results{$qualifierrest};
11513:                 } else {
11514:                     return $Apache::lonhomework::history{$qualifierrest};
11515:                 }
11516: 	    } else {
11517: 		my %restored;
11518: 		if ($publicuser || $env{'request.state'} eq 'construct') {
11519: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
11520: 		} else {
11521: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
11522: 		}
11523: 		return $restored{$qualifierrest};
11524: 	    }
11525: # ----------------------------------------------------------------- user.access
11526:         } elsif ($space eq 'access') {
11527: 	    # FIXME - not supporting calls for a specific user
11528:             return &allowed($qualifier,$rest);
11529: # ------------------------------------------ user.preferences, user.environment
11530:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
11531: 	    if (($uname eq $env{'user.name'}) &&
11532: 		($udom eq $env{'user.domain'})) {
11533: 		return $env{join('.',('environment',$qualifierrest))};
11534: 	    } else {
11535: 		my %returnhash;
11536: 		if (!$publicuser) {
11537: 		    %returnhash=&userenvironment($udom,$uname,
11538: 						 $qualifierrest);
11539: 		}
11540: 		return $returnhash{$qualifierrest};
11541: 	    }
11542: # ----------------------------------------------------------------- user.course
11543:         } elsif ($space eq 'course') {
11544: 	    # FIXME - not supporting calls for a specific user
11545:             return $env{join('.',('request.course',$qualifier))};
11546: # ------------------------------------------------------------------- user.role
11547:         } elsif ($space eq 'role') {
11548: 	    # FIXME - not supporting calls for a specific user
11549:             my ($role,$where)=split(/\./,$env{'request.role'});
11550:             if ($qualifier eq 'value') {
11551: 		return $role;
11552:             } elsif ($qualifier eq 'extent') {
11553:                 return $where;
11554:             }
11555: # ----------------------------------------------------------------- user.domain
11556:         } elsif ($space eq 'domain') {
11557:             return $udom;
11558: # ------------------------------------------------------------------- user.name
11559:         } elsif ($space eq 'name') {
11560:             return $uname;
11561: # ---------------------------------------------------- Any other user namespace
11562:         } else {
11563: 	    my %reply;
11564: 	    if (!$publicuser) {
11565: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
11566: 	    }
11567: 	    return $reply{$qualifierrest};
11568:         }
11569:     } elsif ($realm eq 'query') {
11570: # ---------------------------------------------- pull stuff out of query string
11571:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
11572: 						[$spacequalifierrest]);
11573: 	return $env{'form.'.$spacequalifierrest}; 
11574:    } elsif ($realm eq 'request') {
11575: # ------------------------------------------------------------- request.browser
11576:         if ($space eq 'browser') {
11577:             return $env{'browser.'.$qualifier};
11578: # ------------------------------------------------------------ request.filename
11579:         } else {
11580:             return $env{'request.'.$spacequalifierrest};
11581:         }
11582:     } elsif ($realm eq 'course') {
11583: # ---------------------------------------------------------- course.description
11584:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
11585:     } elsif ($realm eq 'resource') {
11586: 
11587: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
11588: 	    if (!$symbparm) { $symbparm=&symbread(); }
11589: 	}
11590: 
11591:         if ($qualifier eq '') {
11592: 	    if ($space eq 'title') {
11593: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
11594: 	        return &gettitle($symbparm);
11595: 	    }
11596: 	
11597: 	    if ($space eq 'map') {
11598: 	        my ($map) = &decode_symb($symbparm);
11599: 	        return &symbread($map);
11600: 	    }
11601:             if ($space eq 'maptitle') {
11602:                 my ($map) = &decode_symb($symbparm);
11603:                 return &gettitle($map);
11604:             }
11605: 	    if ($space eq 'filename') {
11606: 	        if ($symbparm) {
11607: 		    return &clutter((&decode_symb($symbparm))[2]);
11608: 	        }
11609: 	        return &hreflocation('',$env{'request.filename'});
11610: 	    }
11611: 
11612:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
11613:                 if ($space eq 'visibleparts') {
11614:                     my $navmap = Apache::lonnavmaps::navmap->new();
11615:                     my $item;
11616:                     if (ref($navmap)) {
11617:                         my $res = $navmap->getBySymb($symbparm);
11618:                         my $parts = $res->parts();
11619:                         if (ref($parts) eq 'ARRAY') {
11620:                             $item = join(',',@{$parts});
11621:                         }
11622:                         undef($navmap);
11623:                     }
11624:                     return $item;
11625:                 }
11626:             }
11627:         }
11628: 
11629: 	my ($section, $group, @groups);
11630: 	my ($courselevelm,$courselevel);
11631:         if (($courseid eq '') && ($cid)) {
11632:             $courseid = $cid;
11633:         }
11634: 	if (($symbparm && $courseid) && 
11635: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
11636: 
11637: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
11638: 
11639: # ----------------------------------------------------- Cascading lookup scheme
11640: 	    my $symbp=$symbparm;
11641: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
11642: 
11643: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
11644: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
11645: 
11646: 	    if (($env{'user.name'} eq $uname) &&
11647: 		($env{'user.domain'} eq $udom)) {
11648: 		$section=$env{'request.course.sec'};
11649:                 @groups = split(/:/,$env{'request.course.groups'});  
11650:                 @groups=&sort_course_groups($courseid,@groups); 
11651: 	    } else {
11652: 		if (! defined($usection)) {
11653: 		    $section=&getsection($udom,$uname,$courseid);
11654: 		} else {
11655: 		    $section = $usection;
11656: 		}
11657:                 @groups = &get_users_groups($udom,$uname,$courseid);
11658: 	    }
11659: 
11660: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
11661: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
11662: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
11663: 
11664: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
11665: 	    my $courselevelr=$courseid.'.'.$symbparm;
11666: 	    $courselevelm=$courseid.'.'.$mapparm;
11667: 
11668: # ----------------------------------------------------------- first, check user
11669: 
11670: 	    my $userreply=&resdata($uname,$udom,'user',
11671: 				       ([$courselevelr,'resource'],
11672: 					[$courselevelm,'map'     ],
11673: 					[$courselevel, 'course'  ]));
11674: 	    if (defined($userreply)) { return &get_reply($userreply); }
11675: 
11676: # ------------------------------------------------ second, check some of course
11677:             my $coursereply;
11678:             if (@groups > 0) {
11679:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
11680:                                        $mapparm,$spacequalifierrest);
11681:                 if (defined($coursereply)) { return &get_reply($coursereply); }
11682:             }
11683: 
11684: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
11685: 				  $env{'course.'.$courseid.'.domain'},
11686: 				  'course',
11687: 				  ([$seclevelr,   'resource'],
11688: 				   [$seclevelm,   'map'     ],
11689: 				   [$seclevel,    'course'  ],
11690: 				   [$courselevelr,'resource']));
11691: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
11692: 
11693: # ------------------------------------------------------ third, check map parms
11694: 	    my %parmhash=();
11695: 	    my $thisparm='';
11696: 	    if (tie(%parmhash,'GDBM_File',
11697: 		    $env{'request.course.fn'}.'_parms.db',
11698: 		    &GDBM_READER(),0640)) {
11699: 		$thisparm=$parmhash{$symbparm};
11700: 		untie(%parmhash);
11701: 	    }
11702: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
11703: 	}
11704: # ------------------------------------------ fourth, look in resource metadata
11705: 
11706: 	$spacequalifierrest=~s/\./\_/;
11707: 	my $filename;
11708: 	if (!$symbparm) { $symbparm=&symbread(); }
11709: 	if ($symbparm) {
11710: 	    $filename=(&decode_symb($symbparm))[2];
11711: 	} else {
11712: 	    $filename=$env{'request.filename'};
11713: 	}
11714: 	my $metadata=&metadata($filename,$spacequalifierrest);
11715: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
11716: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
11717: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
11718: 
11719: # ---------------------------------------------- fourth, look in rest of course
11720: 	if ($symbparm && defined($courseid) && 
11721: 	    $courseid eq $env{'request.course.id'}) {
11722: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
11723: 				     $env{'course.'.$courseid.'.domain'},
11724: 				     'course',
11725: 				     ([$courselevelm,'map'   ],
11726: 				      [$courselevel, 'course']));
11727: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
11728: 	}
11729: # ------------------------------------------------------------------ Cascade up
11730: 	unless ($space eq '0') {
11731: 	    my @parts=split(/_/,$space);
11732: 	    my $id=pop(@parts);
11733: 	    my $part=join('_',@parts);
11734: 	    if ($part eq '') { $part='0'; }
11735: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
11736: 				 $symbparm,$udom,$uname,$section,1);
11737: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
11738: 	}
11739: 	if ($recurse) { return undef; }
11740: 	my $pack_def=&packages_tab_default($filename,$varname);
11741: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
11742: # ---------------------------------------------------- Any other user namespace
11743:     } elsif ($realm eq 'environment') {
11744: # ----------------------------------------------------------------- environment
11745: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
11746: 	    return $env{'environment.'.$spacequalifierrest};
11747: 	} else {
11748: 	    if ($uname eq 'anonymous' && $udom eq '') {
11749: 		return '';
11750: 	    }
11751: 	    my %returnhash=&userenvironment($udom,$uname,
11752: 					    $spacequalifierrest);
11753: 	    return $returnhash{$spacequalifierrest};
11754: 	}
11755:     } elsif ($realm eq 'system') {
11756: # ----------------------------------------------------------------- system.time
11757: 	if ($space eq 'time') {
11758: 	    return time;
11759:         }
11760:     } elsif ($realm eq 'server') {
11761: # ----------------------------------------------------------------- system.time
11762: 	if ($space eq 'name') {
11763: 	    return $ENV{'SERVER_NAME'};
11764:         }
11765:     }
11766:     return '';
11767: }
11768: 
11769: sub get_reply {
11770:     my ($reply_value) = @_;
11771:     if (ref($reply_value) eq 'ARRAY') {
11772:         if (wantarray) {
11773: 	    return @$reply_value;
11774:         }
11775:         return $reply_value->[0];
11776:     } else {
11777:         return $reply_value;
11778:     }
11779: }
11780: 
11781: sub check_group_parms {
11782:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
11783:     my @groupitems = ();
11784:     my $resultitem;
11785:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
11786:     foreach my $group (@{$groups}) {
11787:         foreach my $level (@levels) {
11788:              my $item = $courseid.'.['.$group.'].'.$level->[0];
11789:              push(@groupitems,[$item,$level->[1]]);
11790:         }
11791:     }
11792:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
11793:                             $env{'course.'.$courseid.'.domain'},
11794:                                      'course',@groupitems);
11795:     return $coursereply;
11796: }
11797: 
11798: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
11799:     my ($courseid,@groups) = @_;
11800:     @groups = sort(@groups);
11801:     return @groups;
11802: }
11803: 
11804: sub packages_tab_default {
11805:     my ($uri,$varname)=@_;
11806:     my (undef,$part,$name)=split(/\./,$varname);
11807: 
11808:     my (@extension,@specifics,$do_default);
11809:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
11810: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
11811: 	if ($pack_type eq 'default') {
11812: 	    $do_default=1;
11813: 	} elsif ($pack_type eq 'extension') {
11814: 	    push(@extension,[$package,$pack_type,$pack_part]);
11815: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
11816: 	    # only look at packages defaults for packages that this id is
11817: 	    push(@specifics,[$package,$pack_type,$pack_part]);
11818: 	}
11819:     }
11820:     # first look for a package that matches the requested part id
11821:     foreach my $package (@specifics) {
11822: 	my (undef,$pack_type,$pack_part)=@{$package};
11823: 	next if ($pack_part ne $part);
11824: 	if (defined($packagetab{"$pack_type&$name&default"})) {
11825: 	    return $packagetab{"$pack_type&$name&default"};
11826: 	}
11827:     }
11828:     # look for any possible matching non extension_ package
11829:     foreach my $package (@specifics) {
11830: 	my (undef,$pack_type,$pack_part)=@{$package};
11831: 	if (defined($packagetab{"$pack_type&$name&default"})) {
11832: 	    return $packagetab{"$pack_type&$name&default"};
11833: 	}
11834: 	if ($pack_type eq 'part') { $pack_part='0'; }
11835: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
11836: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
11837: 	}
11838:     }
11839:     # look for any posible extension_ match
11840:     foreach my $package (@extension) {
11841: 	my ($package,$pack_type)=@{$package};
11842: 	if (defined($packagetab{"$pack_type&$name&default"})) {
11843: 	    return $packagetab{"$pack_type&$name&default"};
11844: 	}
11845: 	if (defined($packagetab{$package."&$name&default"})) {
11846: 	    return $packagetab{$package."&$name&default"};
11847: 	}
11848:     }
11849:     # look for a global default setting
11850:     if ($do_default && defined($packagetab{"default&$name&default"})) {
11851: 	return $packagetab{"default&$name&default"};
11852:     }
11853:     return undef;
11854: }
11855: 
11856: sub add_prefix_and_part {
11857:     my ($prefix,$part)=@_;
11858:     my $keyroot;
11859:     if (defined($prefix) && $prefix !~ /^__/) {
11860: 	# prefix that has a part already
11861: 	$keyroot=$prefix;
11862:     } elsif (defined($prefix)) {
11863: 	# prefix that is missing a part
11864: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
11865:     } else {
11866: 	# no prefix at all
11867: 	if (defined($part)) { $keyroot='_'.$part; }
11868:     }
11869:     return $keyroot;
11870: }
11871: 
11872: # ---------------------------------------------------------------- Get metadata
11873: 
11874: my %metaentry;
11875: my %importedpartids;
11876: my %importedrespids;
11877: sub metadata {
11878:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
11879:     $uri=&declutter($uri);
11880:     # if it is a non metadata possible uri return quickly
11881:     if (($uri eq '') || 
11882: 	(($uri =~ m|^/*adm/|) && 
11883: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
11884:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
11885: 	return undef;
11886:     }
11887:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
11888: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
11889: 	return undef;
11890:     }
11891:     my $filename=$uri;
11892:     $uri=~s/\.meta$//;
11893: #
11894: # Is the metadata already cached?
11895: # Look at timestamp of caching
11896: # Everything is cached by the main uri, libraries are never directly cached
11897: #
11898:     if (!defined($liburi)) {
11899: 	my ($result,$cached)=&is_cached_new('meta',$uri);
11900: 	if (defined($cached)) { return $result->{':'.$what}; }
11901:     }
11902:     {
11903: # Imported parts would go here
11904:         my @origfiletagids=();
11905:         my $importedparts=0;
11906: 
11907: # Imported responseids would go here
11908:         my $importedresponses=0;
11909: #
11910: # Is this a recursive call for a library?
11911: #
11912: #	if (! exists($metacache{$uri})) {
11913: #	    $metacache{$uri}={};
11914: #	}
11915: 	my $cachetime = 60*60;
11916:         if ($liburi) {
11917: 	    $liburi=&declutter($liburi);
11918:             $filename=$liburi;
11919:         } else {
11920: 	    &devalidate_cache_new('meta',$uri);
11921: 	    undef(%metaentry);
11922: 	}
11923:         my %metathesekeys=();
11924:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
11925: 	my $metastring;
11926: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
11927: 	    my $which = &hreflocation('','/'.($liburi || $uri));
11928: 	    $metastring = 
11929: 		&Apache::lonnet::ssi_body($which,
11930: 					  ('grade_target' => 'meta'));
11931: 	    $cachetime = 1; # only want this cached in the child not long term
11932: 	} elsif (($uri !~ m -^(editupload)/-) && 
11933:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
11934: 	    my $file=&filelocation('',&clutter($filename));
11935: 	    #push(@{$metaentry{$uri.'.file'}},$file);
11936: 	    $metastring=&getfile($file);
11937: 	}
11938:         my $parser=HTML::LCParser->new(\$metastring);
11939:         my $token;
11940:         undef %metathesekeys;
11941:         while ($token=$parser->get_token) {
11942: 	    if ($token->[0] eq 'S') {
11943: 		if (defined($token->[2]->{'package'})) {
11944: #
11945: # This is a package - get package info
11946: #
11947: 		    my $package=$token->[2]->{'package'};
11948: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11949: 		    if (defined($token->[2]->{'id'})) { 
11950: 			$keyroot.='_'.$token->[2]->{'id'}; 
11951: 		    }
11952: 		    if ($metaentry{':packages'}) {
11953: 			$metaentry{':packages'}.=','.$package.$keyroot;
11954: 		    } else {
11955: 			$metaentry{':packages'}=$package.$keyroot;
11956: 		    }
11957: 		    foreach my $pack_entry (keys(%packagetab)) {
11958: 			my $part=$keyroot;
11959: 			$part=~s/^\_//;
11960: 			if ($pack_entry=~/^\Q$package\E\&/ || 
11961: 			    $pack_entry=~/^\Q$package\E_0\&/) {
11962: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
11963: 			    # ignore package.tab specified default values
11964:                             # here &package_tab_default() will fetch those
11965: 			    if ($subp eq 'default') { next; }
11966: 			    my $value=$packagetab{$pack_entry};
11967: 			    my $unikey;
11968: 			    if ($pack =~ /_0$/) {
11969: 				$unikey='parameter_0_'.$name;
11970: 				$part=0;
11971: 			    } else {
11972: 				$unikey='parameter'.$keyroot.'_'.$name;
11973: 			    }
11974: 			    if ($subp eq 'display') {
11975: 				$value.=' [Part: '.$part.']';
11976: 			    }
11977: 			    $metaentry{':'.$unikey.'.part'}=$part;
11978: 			    $metathesekeys{$unikey}=1;
11979: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
11980: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
11981: 			    }
11982: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
11983: 				$metaentry{':'.$unikey}=
11984: 				    $metaentry{':'.$unikey.'.default'};
11985: 			    }
11986: 			}
11987: 		    }
11988: 		} else {
11989: #
11990: # This is not a package - some other kind of start tag
11991: #
11992: 		    my $entry=$token->[1];
11993: 		    my $unikey='';
11994: 
11995: 		    if ($entry eq 'import') {
11996: #
11997: # Importing a library here
11998: #
11999:                         my $location=$parser->get_text('/import');
12000:                         my $dir=$filename;
12001:                         $dir=~s|[^/]*$||;
12002:                         $location=&filelocation($dir,$location);
12003: 
12004:                         my $importid=$token->[2]->{'id'};
12005:                         my $importmode=$token->[2]->{'importmode'};
12006: #
12007: # Check metadata for imported file to
12008: # see if it contained response items
12009: #
12010:                         my %currmetaentry = %metaentry;
12011:                         my $libresponseorder = &metadata($location,'responseorder');
12012:                         my $origfile;
12013:                         if ($libresponseorder ne '') {
12014:                             if ($#origfiletagids<0) {
12015:                                 undef(%importedrespids);
12016:                                 undef(%importedpartids);
12017:                             }
12018:                             @{$importedrespids{$importid}} = split(/\s*,\s*/,$libresponseorder);
12019:                             if (@{$importedrespids{$importid}} > 0) {
12020:                                 $importedresponses = 1;
12021: # We need to get the original file and the imported file to get the response order correct
12022: # Load and inspect original file
12023:                                 if ($#origfiletagids<0) {
12024:                                     my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
12025:                                     $origfile=&getfile($origfilelocation);
12026:                                     @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12027:                                 }
12028:                             }
12029:                         }
12030: # Do not overwrite contents of %metaentry hash for resource itself with 
12031: # hash populated for imported library file
12032:                         %metaentry = %currmetaentry;
12033:                         undef(%currmetaentry);
12034:                         if ($importmode eq 'problem') {
12035: # Import as problem/response
12036:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
12037:                         } elsif ($importmode eq 'part') {
12038: # Import as part(s)
12039:                            $importedparts=1;
12040: # We need to get the original file and the imported file to get the part order correct
12041: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
12042: # Load and inspect original file if we didn't do that already
12043:                            if ($#origfiletagids<0) {
12044:                                undef(%importedrespids);
12045:                                undef(%importedpartids);
12046:                                if ($origfile eq '') {
12047:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
12048:                                    $origfile=&getfile($origfilelocation);
12049:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12050:                                }
12051:                            }
12052: 
12053: # Load and inspect imported file
12054:                            my $impfile=&getfile($location);
12055:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12056:                            if ($#impfilepartids>=0) {
12057: # This problem had parts
12058:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
12059:                            } else {
12060: # Importing by turning a single problem into a problem part
12061: # It gets the import-tags ID as part-ID
12062:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
12063:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
12064:                            }
12065:                         } else {
12066: # Normal import
12067:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
12068:                            if (defined($token->[2]->{'id'})) {
12069:                               $unikey.='_'.$token->[2]->{'id'};
12070:                            }
12071:                         }
12072: 
12073: 			if ($depthcount<20) {
12074: 			    my $metadata = 
12075: 				&metadata($uri,'keys', $location,$unikey,
12076: 					  $depthcount+1);
12077: 			    foreach my $meta (split(',',$metadata)) {
12078: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
12079: 				$metathesekeys{$meta}=1;
12080: 			    }
12081: 			
12082:                         }
12083: 		    } else {
12084: #
12085: # Not importing, some other kind of non-package, non-library start tag
12086: # 
12087:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
12088:                         if (defined($token->[2]->{'id'})) {
12089:                             $unikey.='_'.$token->[2]->{'id'};
12090:                         }
12091: 			if (defined($token->[2]->{'name'})) { 
12092: 			    $unikey.='_'.$token->[2]->{'name'}; 
12093: 			}
12094: 			$metathesekeys{$unikey}=1;
12095: 			foreach my $param (@{$token->[3]}) {
12096: 			    $metaentry{':'.$unikey.'.'.$param} =
12097: 				$token->[2]->{$param};
12098: 			}
12099: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
12100: 			my $default=$metaentry{':'.$unikey.'.default'};
12101: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
12102: 		 # only ws inside the tag, and not in default, so use default
12103: 		 # as value
12104: 			    $metaentry{':'.$unikey}=$default;
12105: 			} elsif ( $internaltext =~ /\S/ ) {
12106: 		  # something interesting inside the tag
12107: 			    $metaentry{':'.$unikey}=$internaltext;
12108: 			} else {
12109: 		  # no interesting values, don't set a default
12110: 			}
12111: # end of not-a-package not-a-library import
12112: 		    }
12113: # end of not-a-package start tag
12114: 		}
12115: # the next is the end of "start tag"
12116: 	    }
12117: 	}
12118: 	my ($extension) = ($uri =~ /\.(\w+)$/);
12119: 	$extension = lc($extension);
12120: 	if ($extension eq 'htm') { $extension='html'; }
12121: 
12122: 	foreach my $key (keys(%packagetab)) {
12123: 	    #no specific packages #how's our extension
12124: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
12125: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
12126: 					 \%metathesekeys);
12127: 	}
12128: 
12129: 	if (!exists($metaentry{':packages'})
12130: 	    || $packagetab{"import_defaults&extension_$extension"}) {
12131: 	    foreach my $key (keys(%packagetab)) {
12132: 		#no specific packages well let's get default then
12133: 		if ($key!~/^default&/) { next; }
12134: 		&metadata_create_package_def($uri,$key,'default',
12135: 					     \%metathesekeys);
12136: 	    }
12137: 	}
12138: # are there custom rights to evaluate
12139: 	if ($metaentry{':copyright'} eq 'custom') {
12140: 
12141:     #
12142:     # Importing a rights file here
12143:     #
12144: 	    unless ($depthcount) {
12145: 		my $location=$metaentry{':customdistributionfile'};
12146: 		my $dir=$filename;
12147: 		$dir=~s|[^/]*$||;
12148: 		$location=&filelocation($dir,$location);
12149: 		my $rights_metadata =
12150: 		    &metadata($uri,'keys',$location,'_rights',
12151: 			      $depthcount+1);
12152: 		foreach my $rights (split(',',$rights_metadata)) {
12153: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
12154: 		    $metathesekeys{$rights}=1;
12155: 		}
12156: 	    }
12157: 	}
12158: 	# uniqifiy package listing
12159: 	my %seen;
12160: 	my @uniq_packages =
12161: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
12162: 	$metaentry{':packages'} = join(',',@uniq_packages);
12163: 
12164:         if (($importedresponses) || ($importedparts)) {
12165:             if ($importedparts) {
12166: # We had imported parts and need to rebuild partorder
12167:                 $metaentry{':partorder'}='';
12168:                 $metathesekeys{'partorder'}=1;
12169:             }
12170:             if ($importedresponses) {
12171: # We had imported responses and need to rebuild responseorder
12172:                 $metaentry{':responseorder'}='';
12173:                 $metathesekeys{'responseorder'}=1;
12174:             }
12175:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
12176:                 my $origid = $origfiletagids[$index+1];
12177:                 if ($origfiletagids[$index] eq 'part') {
12178: # Original part, part of the problem
12179:                     if ($importedparts) {
12180:                         $metaentry{':partorder'}.=','.$origid;
12181:                     }
12182:                 } elsif ($origfiletagids[$index] eq 'import') {
12183:                     if ($importedparts) {
12184: # We have imported parts at this position
12185:                         $metaentry{':partorder'}.=','.$importedpartids{$origid};
12186:                     }
12187:                     if ($importedresponses) {
12188: # We have imported responses at this position
12189:                         if (ref($importedrespids{$origid}) eq 'ARRAY') {
12190:                             $metaentry{':responseorder'}.=','.join(',',map { $origid.'_'.$_ } @{$importedrespids{$origid}});
12191:                         }
12192:                     }
12193:                 } else {
12194: # Original response item, part of the problem
12195:                     if ($importedresponses) {
12196:                         $metaentry{':responseorder'}.=','.$origid;
12197:                     }
12198:                 }
12199:             }
12200:             if ($importedparts) {
12201:                 $metaentry{':partorder'}=~s/^\,//;
12202:             }
12203:             if ($importedresponses) {
12204:                 $metaentry{':responseorder'}=~s/^\,//;
12205:             }
12206:         }
12207: 
12208: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
12209: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
12210: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
12211: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
12212: # this is the end of "was not already recently cached
12213:     }
12214:     return $metaentry{':'.$what};
12215: }
12216: 
12217: sub metadata_create_package_def {
12218:     my ($uri,$key,$package,$metathesekeys)=@_;
12219:     my ($pack,$name,$subp)=split(/\&/,$key);
12220:     if ($subp eq 'default') { next; }
12221:     
12222:     if (defined($metaentry{':packages'})) {
12223: 	$metaentry{':packages'}.=','.$package;
12224:     } else {
12225: 	$metaentry{':packages'}=$package;
12226:     }
12227:     my $value=$packagetab{$key};
12228:     my $unikey;
12229:     $unikey='parameter_0_'.$name;
12230:     $metaentry{':'.$unikey.'.part'}=0;
12231:     $$metathesekeys{$unikey}=1;
12232:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
12233: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
12234:     }
12235:     if (defined($metaentry{':'.$unikey.'.default'})) {
12236: 	$metaentry{':'.$unikey}=
12237: 	    $metaentry{':'.$unikey.'.default'};
12238:     }
12239: }
12240: 
12241: sub metadata_generate_part0 {
12242:     my ($metadata,$metacache,$uri) = @_;
12243:     my %allnames;
12244:     foreach my $metakey (keys(%$metadata)) {
12245: 	if ($metakey=~/^parameter\_(.*)/) {
12246: 	  my $part=$$metacache{':'.$metakey.'.part'};
12247: 	  my $name=$$metacache{':'.$metakey.'.name'};
12248: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
12249: 	    $allnames{$name}=$part;
12250: 	  }
12251: 	}
12252:     }
12253:     foreach my $name (keys(%allnames)) {
12254:       $$metadata{"parameter_0_$name"}=1;
12255:       my $key=":parameter_0_$name";
12256:       $$metacache{"$key.part"}='0';
12257:       $$metacache{"$key.name"}=$name;
12258:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
12259: 					   $allnames{$name}.'_'.$name.
12260: 					   '.type'};
12261:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
12262: 			     '.display'};
12263:       my $expr='[Part: '.$allnames{$name}.']';
12264:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
12265:       $$metacache{"$key.display"}=$olddis;
12266:     }
12267: }
12268: 
12269: # ------------------------------------------------------ Devalidate title cache
12270: 
12271: sub devalidate_title_cache {
12272:     my ($url)=@_;
12273:     if (!$env{'request.course.id'}) { return; }
12274:     my $symb=&symbread($url);
12275:     if (!$symb) { return; }
12276:     my $key=$env{'request.course.id'}."\0".$symb;
12277:     &devalidate_cache_new('title',$key);
12278: }
12279: 
12280: # ------------------------------------------------- Get the title of a course
12281: 
12282: sub current_course_title {
12283:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
12284: }
12285: # ------------------------------------------------- Get the title of a resource
12286: 
12287: sub gettitle {
12288:     my $urlsymb=shift;
12289:     my $symb=&symbread($urlsymb);
12290:     if ($symb) {
12291: 	my $key=$env{'request.course.id'}."\0".$symb;
12292: 	my ($result,$cached)=&is_cached_new('title',$key);
12293: 	if (defined($cached)) { 
12294: 	    return $result;
12295: 	}
12296: 	my ($map,$resid,$url)=&decode_symb($symb);
12297: 	my $title='';
12298: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
12299: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
12300: 	} else {
12301: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12302: 		    &GDBM_READER(),0640)) {
12303: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
12304: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
12305: 		untie(%bighash);
12306: 	    }
12307: 	}
12308: 	$title=~s/\&colon\;/\:/gs;
12309: 	if ($title) {
12310: # Remember both $symb and $title for dynamic metadata
12311:             $accesshash{$symb.'___crstitle'}=$title;
12312:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
12313: # Cache this title and then return it
12314: 	    return &do_cache_new('title',$key,$title,600);
12315: 	}
12316: 	$urlsymb=$url;
12317:     }
12318:     my $title=&metadata($urlsymb,'title');
12319:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
12320:     return $title;
12321: }
12322: 
12323: sub get_slot {
12324:     my ($which,$cnum,$cdom)=@_;
12325:     if (!$cnum || !$cdom) {
12326: 	(undef,my $courseid)=&whichuser();
12327: 	$cdom=$env{'course.'.$courseid.'.domain'};
12328: 	$cnum=$env{'course.'.$courseid.'.num'};
12329:     }
12330:     my $key=join("\0",'slots',$cdom,$cnum,$which);
12331:     my %slotinfo;
12332:     if (exists($remembered{$key})) {
12333: 	$slotinfo{$which} = $remembered{$key};
12334:     } else {
12335: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
12336: 	&Apache::lonhomework::showhash(%slotinfo);
12337: 	my ($tmp)=keys(%slotinfo);
12338: 	if ($tmp=~/^error:/) { return (); }
12339: 	$remembered{$key} = $slotinfo{$which};
12340:     }
12341:     if (ref($slotinfo{$which}) eq 'HASH') {
12342: 	return %{$slotinfo{$which}};
12343:     }
12344:     return $slotinfo{$which};
12345: }
12346: 
12347: sub get_reservable_slots {
12348:     my ($cnum,$cdom,$uname,$udom) = @_;
12349:     my $now = time;
12350:     my $reservable_info;
12351:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
12352:     if (exists($remembered{$key})) {
12353:         $reservable_info = $remembered{$key};
12354:     } else {
12355:         my %resv;
12356:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
12357:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
12358:         $reservable_info = \%resv;
12359:         $remembered{$key} = $reservable_info;
12360:     }
12361:     return $reservable_info;
12362: }
12363: 
12364: sub get_course_slots {
12365:     my ($cnum,$cdom) = @_;
12366:     my $hashid=$cnum.':'.$cdom;
12367:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
12368:     if (defined($cached)) {
12369:         if (ref($result) eq 'HASH') {
12370:             return %{$result};
12371:         }
12372:     } else {
12373:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
12374:         my ($tmp) = keys(%slots);
12375:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
12376:             &do_cache_new('allslots',$hashid,\%slots,600);
12377:             return %slots;
12378:         }
12379:     }
12380:     return;
12381: }
12382: 
12383: sub devalidate_slots_cache {
12384:     my ($cnum,$cdom)=@_;
12385:     my $hashid=$cnum.':'.$cdom;
12386:     &devalidate_cache_new('allslots',$hashid);
12387: }
12388: 
12389: sub get_coursechange {
12390:     my ($cdom,$cnum) = @_;
12391:     if ($cdom eq '' || $cnum eq '') {
12392:         return unless ($env{'request.course.id'});
12393:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
12394:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
12395:     }
12396:     my $hashid=$cdom.'_'.$cnum;
12397:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
12398:     if ((defined($cached)) && ($change ne '')) {
12399:         return $change;
12400:     } else {
12401:         my %crshash;
12402:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
12403:         if ($crshash{'internal.contentchange'} eq '') {
12404:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
12405:             if ($change eq '') {
12406:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
12407:                 $change = $crshash{'internal.created'};
12408:             }
12409:         } else {
12410:             $change = $crshash{'internal.contentchange'};
12411:         }
12412:         my $cachetime = 600;
12413:         &do_cache_new('crschange',$hashid,$change,$cachetime);
12414:     }
12415:     return $change;
12416: }
12417: 
12418: sub devalidate_coursechange_cache {
12419:     my ($cnum,$cdom)=@_;
12420:     my $hashid=$cnum.':'.$cdom;
12421:     &devalidate_cache_new('crschange',$hashid);
12422: }
12423: 
12424: # ------------------------------------------------- Update symbolic store links
12425: 
12426: sub symblist {
12427:     my ($mapname,%newhash)=@_;
12428:     $mapname=&deversion(&declutter($mapname));
12429:     my %hash;
12430:     if (($env{'request.course.fn'}) && (%newhash)) {
12431:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
12432:                       &GDBM_WRCREAT(),0640)) {
12433: 	    foreach my $url (keys(%newhash)) {
12434: 		next if ($url eq 'last_known'
12435: 			 && $env{'form.no_update_last_known'});
12436: 		$hash{declutter($url)}=&encode_symb($mapname,
12437: 						    $newhash{$url}->[1],
12438: 						    $newhash{$url}->[0]);
12439:             }
12440:             if (untie(%hash)) {
12441: 		return 'ok';
12442:             }
12443:         }
12444:     }
12445:     return 'error';
12446: }
12447: 
12448: # --------------------------------------------------------------- Verify a symb
12449: 
12450: sub symbverify {
12451:     my ($symb,$thisurl,$encstate)=@_;
12452:     my $thisfn=$thisurl;
12453:     $thisfn=&declutter($thisfn);
12454: # direct jump to resource in page or to a sequence - will construct own symbs
12455:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
12456: # check URL part
12457:     my ($map,$resid,$url)=&decode_symb($symb);
12458: 
12459:     unless ($url eq $thisfn) { return 0; }
12460: 
12461:     $symb=&symbclean($symb);
12462:     $thisurl=&deversion($thisurl);
12463:     $thisfn=&deversion($thisfn);
12464: 
12465:     my %bighash;
12466:     my $okay=0;
12467: 
12468:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12469:                             &GDBM_READER(),0640)) {
12470:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
12471:             $thisurl =~ s/\?.+$//;
12472:             if ($map =~ m{^uploaded/.+\.page$}) {
12473:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
12474:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
12475:             }
12476:         }
12477:         my $ids;
12478:         if ($map =~ m{^uploaded/.+\.page$}) {
12479:             $ids=$bighash{'ids_'.&clutter_with_no_wrapper($thisurl)};
12480:         } else {
12481:             $ids=$bighash{'ids_'.&clutter($thisurl)};
12482:         }
12483:         unless ($ids) {
12484:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
12485:             $ids=$bighash{$idkey};
12486:         }
12487:         if ($ids) {
12488: # ------------------------------------------------------------------- Has ID(s)
12489:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
12490:                 $symb =~ s/\?.+$//;
12491:             }
12492: 	    foreach my $id (split(/\,/,$ids)) {
12493: 	       my ($mapid,$resid)=split(/\./,$id);
12494:                if (
12495:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
12496:    eq $symb) {
12497:                    if (ref($encstate)) {
12498:                        $$encstate = $bighash{'encrypted_'.$id};
12499:                    }
12500:                    if (($env{'request.role.adv'}) ||
12501:                        ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
12502:                        ($thisurl eq '/adm/navmaps')) {
12503:                        $okay=1;
12504:                        last;
12505:                    }
12506:                }
12507:            }
12508:         }
12509: 	untie(%bighash);
12510:     }
12511:     return $okay;
12512: }
12513: 
12514: # --------------------------------------------------------------- Clean-up symb
12515: 
12516: sub symbclean {
12517:     my $symb=shift;
12518:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
12519: # remove version from map
12520:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
12521: 
12522: # remove version from URL
12523:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
12524: 
12525: # remove wrapper
12526: 
12527:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
12528:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
12529:     return $symb;
12530: }
12531: 
12532: # ---------------------------------------------- Split symb to find map and url
12533: 
12534: sub encode_symb {
12535:     my ($map,$resid,$url)=@_;
12536:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
12537: }
12538: 
12539: sub decode_symb {
12540:     my $symb=shift;
12541:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
12542:     my ($map,$resid,$url)=split(/___/,$symb);
12543:     return (&fixversion($map),$resid,&fixversion($url));
12544: }
12545: 
12546: sub fixversion {
12547:     my $fn=shift;
12548:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
12549:     my %bighash;
12550:     my $uri=&clutter($fn);
12551:     my $key=$env{'request.course.id'}.'_'.$uri;
12552: # is this cached?
12553:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
12554:     if (defined($cached)) { return $result; }
12555: # unfortunately not cached, or expired
12556:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12557: 	    &GDBM_READER(),0640)) {
12558:  	if ($bighash{'version_'.$uri}) {
12559:  	    my $version=$bighash{'version_'.$uri};
12560:  	    unless (($version eq 'mostrecent') || 
12561: 		    ($version==&getversion($uri))) {
12562:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
12563:  	    }
12564:  	}
12565:  	untie %bighash;
12566:     }
12567:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
12568: }
12569: 
12570: sub deversion {
12571:     my $url=shift;
12572:     $url=~s/\.\d+\.(\w+)$/\.$1/;
12573:     return $url;
12574: }
12575: 
12576: # ------------------------------------------------------ Return symb list entry
12577: 
12578: sub symbread {
12579:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles,
12580:         $ignoresymbdb,$noenccheck)=@_;
12581:     my $cache_str='request.symbread.cached.'.$thisfn;
12582:     if (defined($env{$cache_str})) {
12583:         unless (ref($possibles) eq 'HASH') {
12584:             if ($ignorecachednull) {
12585:                 return $env{$cache_str} unless ($env{$cache_str} eq '');
12586:             } else {
12587:                 return $env{$cache_str};
12588:             }
12589:         }
12590:     }
12591: # no filename provided? try from environment
12592:     unless ($thisfn) {
12593:         if ($env{'request.symb'}) {
12594:             return $env{$cache_str}=&symbclean($env{'request.symb'});
12595:         }
12596:         $thisfn=$env{'request.filename'};
12597:     }
12598:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
12599: # is that filename actually a symb? Verify, clean, and return
12600:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
12601: 	if (&symbverify($thisfn,$1)) {
12602: 	    return $env{$cache_str}=&symbclean($thisfn);
12603: 	}
12604:     }
12605:     $thisfn=declutter($thisfn);
12606:     my %hash;
12607:     my %bighash;
12608:     my $syval='';
12609:     if (($env{'request.course.fn'}) && ($thisfn)) {
12610:         my $targetfn = $thisfn;
12611:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
12612:             $targetfn = 'adm/wrapper/'.$thisfn;
12613:         }
12614: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
12615: 	    $targetfn=$1;
12616: 	}
12617:         unless ($ignoresymbdb) {
12618:             if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
12619:                           &GDBM_READER(),0640)) {
12620: 	        $syval=$hash{$targetfn};
12621:                 untie(%hash);
12622:             }
12623:             if ($syval && $checkforblock) {
12624:                 my @blockers = &has_comm_blocking('bre',$syval,$thisfn,$ignoresymbdb,$noenccheck);
12625:                 if (@blockers) {
12626:                     $syval='';
12627:                 }
12628:             }
12629:         }
12630: # ---------------------------------------------------------- There was an entry
12631:         if ($syval) {
12632: 	    #unless ($syval=~/\_\d+$/) {
12633: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
12634: 		    #&appenv({'request.ambiguous' => $thisfn});
12635: 		    #return $env{$cache_str}='';
12636: 		#}    
12637: 		#$syval.=$1;
12638: 	    #}
12639:         } else {
12640: # ------------------------------------------------------- Was not in symb table
12641:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12642:                             &GDBM_READER(),0640)) {
12643: # ---------------------------------------------- Get ID(s) for current resource
12644:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
12645:               unless ($ids) { 
12646:                  $ids=$bighash{'ids_/'.$thisfn};
12647:               }
12648:               unless ($ids) {
12649: # alias?
12650: 		  $ids=$bighash{'mapalias_'.$thisfn};
12651:               }
12652:               if ($ids) {
12653: # ------------------------------------------------------------------- Has ID(s)
12654:                  my @possibilities=split(/\,/,$ids);
12655:                  if ($#possibilities==0) {
12656: # ----------------------------------------------- There is only one possibility
12657: 		     my ($mapid,$resid)=split(/\./,$ids);
12658: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
12659: 						    $resid,$thisfn);
12660:                      if (ref($possibles) eq 'HASH') {
12661:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
12662:                              $possibles->{$syval} = 1;
12663:                          }
12664:                      }
12665:                      if ($checkforblock) {
12666:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
12667:                              my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids},'',$noenccheck);
12668:                              if (@blockers) {
12669:                                  $syval = '';
12670:                                  untie(%bighash);
12671:                                  return $env{$cache_str}='';
12672:                              }
12673:                          }
12674:                      }
12675:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
12676: # ------------------------------------------ There is more than one possibility
12677:                      my $realpossible=0;
12678:                      foreach my $id (@possibilities) {
12679: 			 my $file=$bighash{'src_'.$id};
12680:                          my $canaccess;
12681:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
12682:                              $canaccess = 1;
12683:                          } else {
12684:                              $canaccess = &allowed('bre',$file);
12685:                          }
12686:                          if ($canaccess) {
12687:          		     my ($mapid,$resid)=split(/\./,$id);
12688:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
12689:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
12690:                                                              $resid,$thisfn);
12691:                                  next if ($bighash{'randomout_'.$id} && !$env{'request.role.adv'});
12692:                                  next unless (($noenccheck) || ($bighash{'encrypted_'.$id} eq $env{'request.enc'}));
12693:                                  if ($checkforblock) {
12694:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file,'',$noenccheck);
12695:                                      if (@blockers > 0) {
12696:                                          $syval = '';
12697:                                      } else {
12698:                                          $syval = $poss_syval;
12699:                                          $realpossible++;
12700:                                      }
12701:                                  } else {
12702:                                      $syval = $poss_syval;
12703:                                      $realpossible++;
12704:                                  }
12705:                                  if ($syval) {
12706:                                      if (ref($possibles) eq 'HASH') {
12707:                                          $possibles->{$syval} = 1;
12708:                                      }
12709:                                  }
12710:                              }
12711: 			 }
12712:                      }
12713: 		     if ($realpossible!=1) { $syval=''; }
12714:                  } else {
12715:                      $syval='';
12716:                  }
12717: 	      }
12718:               untie(%bighash);
12719:            }
12720:         }
12721:         if ($syval) {
12722: 	    return $env{$cache_str}=$syval;
12723:         }
12724:     }
12725:     &appenv({'request.ambiguous' => $thisfn});
12726:     return $env{$cache_str}='';
12727: }
12728: 
12729: # ---------------------------------------------------------- Return random seed
12730: 
12731: sub numval {
12732:     my $txt=shift;
12733:     $txt=~tr/A-J/0-9/;
12734:     $txt=~tr/a-j/0-9/;
12735:     $txt=~tr/K-T/0-9/;
12736:     $txt=~tr/k-t/0-9/;
12737:     $txt=~tr/U-Z/0-5/;
12738:     $txt=~tr/u-z/0-5/;
12739:     $txt=~s/\D//g;
12740:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
12741:     return int($txt);
12742: }
12743: 
12744: sub numval2 {
12745:     my $txt=shift;
12746:     $txt=~tr/A-J/0-9/;
12747:     $txt=~tr/a-j/0-9/;
12748:     $txt=~tr/K-T/0-9/;
12749:     $txt=~tr/k-t/0-9/;
12750:     $txt=~tr/U-Z/0-5/;
12751:     $txt=~tr/u-z/0-5/;
12752:     $txt=~s/\D//g;
12753:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
12754:     my $total;
12755:     foreach my $val (@txts) { $total+=$val; }
12756:     if ($_64bit) { if ($total > 2**32) { return -1; } }
12757:     return int($total);
12758: }
12759: 
12760: sub numval3 {
12761:     use integer;
12762:     my $txt=shift;
12763:     $txt=~tr/A-J/0-9/;
12764:     $txt=~tr/a-j/0-9/;
12765:     $txt=~tr/K-T/0-9/;
12766:     $txt=~tr/k-t/0-9/;
12767:     $txt=~tr/U-Z/0-5/;
12768:     $txt=~tr/u-z/0-5/;
12769:     $txt=~s/\D//g;
12770:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
12771:     my $total;
12772:     foreach my $val (@txts) { $total+=$val; }
12773:     if ($_64bit) { $total=(($total<<32)>>32); }
12774:     return $total;
12775: }
12776: 
12777: sub digest {
12778:     my ($data)=@_;
12779:     my $digest=&Digest::MD5::md5($data);
12780:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
12781:     my ($e,$f);
12782:     {
12783:         use integer;
12784:         $e=($a+$b);
12785:         $f=($c+$d);
12786:         if ($_64bit) {
12787:             $e=(($e<<32)>>32);
12788:             $f=(($f<<32)>>32);
12789:         }
12790:     }
12791:     if (wantarray) {
12792: 	return ($e,$f);
12793:     } else {
12794: 	my $g;
12795: 	{
12796: 	    use integer;
12797: 	    $g=($e+$f);
12798: 	    if ($_64bit) {
12799: 		$g=(($g<<32)>>32);
12800: 	    }
12801: 	}
12802: 	return $g;
12803:     }
12804: }
12805: 
12806: sub latest_rnd_algorithm_id {
12807:     return '64bit5';
12808: }
12809: 
12810: sub get_rand_alg {
12811:     my ($courseid)=@_;
12812:     if (!$courseid) { $courseid=(&whichuser())[1]; }
12813:     if ($courseid) {
12814: 	return $env{"course.$courseid.rndseed"};
12815:     }
12816:     return &latest_rnd_algorithm_id();
12817: }
12818: 
12819: sub validCODE {
12820:     my ($CODE)=@_;
12821:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
12822:     return 0;
12823: }
12824: 
12825: sub getCODE {
12826:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
12827:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
12828: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
12829: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
12830: 	return $Apache::lonhomework::history{'resource.CODE'};
12831:     }
12832:     return undef;
12833: }
12834: #
12835: #  Determines the random seed for a specific context:
12836: #
12837: # parameters:
12838: #   symb      - in course context the symb for the seed.
12839: #   course_id - The course id of the form domain_coursenum.
12840: #   domain    - Domain for the user.
12841: #   course    - Course for the user.
12842: #   cenv      - environment of the course.
12843: #
12844: # NOTE:
12845: #   All parameters are picked out of the environment if missing
12846: #   or not defined.
12847: #   If a symb cannot be determined the current time is used instead.
12848: #
12849: #  For a given well defined symb, courside, domain, username,
12850: #  and course environment, the seed is reproducible.
12851: #
12852: sub rndseed {
12853:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
12854:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
12855:     if (!defined($symb)) {
12856: 	unless ($symb=$wsymb) { return time; }
12857:     }
12858:     if (!defined $courseid) { 
12859: 	$courseid=$wcourseid; 
12860:     }
12861:     if (!defined $domain) { $domain=$wdomain; }
12862:     if (!defined $username) { $username=$wusername }
12863: 
12864:     my $which;
12865:     if (defined($cenv->{'rndseed'})) {
12866: 	$which = $cenv->{'rndseed'};
12867:     } else {
12868: 	$which =&get_rand_alg($courseid);
12869:     }
12870:     if (defined(&getCODE())) {
12871: 	if ($which eq '64bit5') {
12872: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
12873: 	} elsif ($which eq '64bit4') {
12874: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
12875: 	} else {
12876: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
12877: 	}
12878:     } elsif ($which eq '64bit5') {
12879: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
12880:     } elsif ($which eq '64bit4') {
12881: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
12882:     } elsif ($which eq '64bit3') {
12883: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
12884:     } elsif ($which eq '64bit2') {
12885: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
12886:     } elsif ($which eq '64bit') {
12887: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
12888:     }
12889:     return &rndseed_32bit($symb,$courseid,$domain,$username);
12890: }
12891: 
12892: sub rndseed_32bit {
12893:     my ($symb,$courseid,$domain,$username)=@_;
12894:     {
12895: 	use integer;
12896: 	my $symbchck=unpack("%32C*",$symb) << 27;
12897: 	my $symbseed=numval($symb) << 22;
12898: 	my $namechck=unpack("%32C*",$username) << 17;
12899: 	my $nameseed=numval($username) << 12;
12900: 	my $domainseed=unpack("%32C*",$domain) << 7;
12901: 	my $courseseed=unpack("%32C*",$courseid);
12902: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
12903: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12904: 	#&logthis("rndseed :$num:$symb");
12905: 	if ($_64bit) { $num=(($num<<32)>>32); }
12906: 	return $num;
12907:     }
12908: }
12909: 
12910: sub rndseed_64bit {
12911:     my ($symb,$courseid,$domain,$username)=@_;
12912:     {
12913: 	use integer;
12914: 	my $symbchck=unpack("%32S*",$symb) << 21;
12915: 	my $symbseed=numval($symb) << 10;
12916: 	my $namechck=unpack("%32S*",$username);
12917: 	
12918: 	my $nameseed=numval($username) << 21;
12919: 	my $domainseed=unpack("%32S*",$domain) << 10;
12920: 	my $courseseed=unpack("%32S*",$courseid);
12921: 	
12922: 	my $num1=$symbchck+$symbseed+$namechck;
12923: 	my $num2=$nameseed+$domainseed+$courseseed;
12924: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12925: 	#&logthis("rndseed :$num:$symb");
12926: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
12927: 	return "$num1,$num2";
12928:     }
12929: }
12930: 
12931: sub rndseed_64bit2 {
12932:     my ($symb,$courseid,$domain,$username)=@_;
12933:     {
12934: 	use integer;
12935: 	# strings need to be an even # of cahracters long, it it is odd the
12936:         # last characters gets thrown away
12937: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
12938: 	my $symbseed=numval($symb) << 10;
12939: 	my $namechck=unpack("%32S*",$username.' ');
12940: 	
12941: 	my $nameseed=numval($username) << 21;
12942: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
12943: 	my $courseseed=unpack("%32S*",$courseid.' ');
12944: 	
12945: 	my $num1=$symbchck+$symbseed+$namechck;
12946: 	my $num2=$nameseed+$domainseed+$courseseed;
12947: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12948: 	#&logthis("rndseed :$num:$symb");
12949: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
12950: 	return "$num1,$num2";
12951:     }
12952: }
12953: 
12954: sub rndseed_64bit3 {
12955:     my ($symb,$courseid,$domain,$username)=@_;
12956:     {
12957: 	use integer;
12958: 	# strings need to be an even # of cahracters long, it it is odd the
12959:         # last characters gets thrown away
12960: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
12961: 	my $symbseed=numval2($symb) << 10;
12962: 	my $namechck=unpack("%32S*",$username.' ');
12963: 	
12964: 	my $nameseed=numval2($username) << 21;
12965: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
12966: 	my $courseseed=unpack("%32S*",$courseid.' ');
12967: 	
12968: 	my $num1=$symbchck+$symbseed+$namechck;
12969: 	my $num2=$nameseed+$domainseed+$courseseed;
12970: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12971: 	#&logthis("rndseed :$num1:$num2:$_64bit");
12972: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
12973: 	
12974: 	return "$num1:$num2";
12975:     }
12976: }
12977: 
12978: sub rndseed_64bit4 {
12979:     my ($symb,$courseid,$domain,$username)=@_;
12980:     {
12981: 	use integer;
12982: 	# strings need to be an even # of cahracters long, it it is odd the
12983:         # last characters gets thrown away
12984: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
12985: 	my $symbseed=numval3($symb) << 10;
12986: 	my $namechck=unpack("%32S*",$username.' ');
12987: 	
12988: 	my $nameseed=numval3($username) << 21;
12989: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
12990: 	my $courseseed=unpack("%32S*",$courseid.' ');
12991: 	
12992: 	my $num1=$symbchck+$symbseed+$namechck;
12993: 	my $num2=$nameseed+$domainseed+$courseseed;
12994: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12995: 	#&logthis("rndseed :$num1:$num2:$_64bit");
12996: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
12997: 	
12998: 	return "$num1:$num2";
12999:     }
13000: }
13001: 
13002: sub rndseed_64bit5 {
13003:     my ($symb,$courseid,$domain,$username)=@_;
13004:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
13005:     return "$num1:$num2";
13006: }
13007: 
13008: sub rndseed_CODE_64bit {
13009:     my ($symb,$courseid,$domain,$username)=@_;
13010:     {
13011: 	use integer;
13012: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
13013: 	my $symbseed=numval2($symb);
13014: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
13015: 	my $CODEseed=numval(&getCODE());
13016: 	my $courseseed=unpack("%32S*",$courseid.' ');
13017: 	my $num1=$symbseed+$CODEchck;
13018: 	my $num2=$CODEseed+$courseseed+$symbchck;
13019: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
13020: 	#&logthis("rndseed :$num1:$num2:$symb");
13021: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
13022: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
13023: 	return "$num1:$num2";
13024:     }
13025: }
13026: 
13027: sub rndseed_CODE_64bit4 {
13028:     my ($symb,$courseid,$domain,$username)=@_;
13029:     {
13030: 	use integer;
13031: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
13032: 	my $symbseed=numval3($symb);
13033: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
13034: 	my $CODEseed=numval3(&getCODE());
13035: 	my $courseseed=unpack("%32S*",$courseid.' ');
13036: 	my $num1=$symbseed+$CODEchck;
13037: 	my $num2=$CODEseed+$courseseed+$symbchck;
13038: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
13039: 	#&logthis("rndseed :$num1:$num2:$symb");
13040: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
13041: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
13042: 	return "$num1:$num2";
13043:     }
13044: }
13045: 
13046: sub rndseed_CODE_64bit5 {
13047:     my ($symb,$courseid,$domain,$username)=@_;
13048:     my $code = &getCODE();
13049:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
13050:     return "$num1:$num2";
13051: }
13052: 
13053: sub setup_random_from_rndseed {
13054:     my ($rndseed)=@_;
13055:     if ($rndseed =~/([,:])/) {
13056: 	my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
13057:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
13058:             &Math::Random::random_set_seed_from_phrase($rndseed);
13059:         } else {
13060:             &Math::Random::random_set_seed($num1,$num2);
13061:         }
13062:     } else {
13063: 	&Math::Random::random_set_seed_from_phrase($rndseed);
13064:     }
13065: }
13066: 
13067: sub latest_receipt_algorithm_id {
13068:     return 'receipt3';
13069: }
13070: 
13071: sub recunique {
13072:     my $fucourseid=shift;
13073:     my $unique;
13074:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
13075: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
13076: 	$unique=$env{"course.$fucourseid.internal.encseed"};
13077:     } else {
13078: 	$unique=$perlvar{'lonReceipt'};
13079:     }
13080:     return unpack("%32C*",$unique);
13081: }
13082: 
13083: sub recprefix {
13084:     my $fucourseid=shift;
13085:     my $prefix;
13086:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
13087: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
13088: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
13089:     } else {
13090: 	$prefix=$perlvar{'lonHostID'};
13091:     }
13092:     return unpack("%32C*",$prefix);
13093: }
13094: 
13095: sub ireceipt {
13096:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
13097: 
13098:     my $return =&recprefix($fucourseid).'-';
13099: 
13100:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
13101: 	$env{'request.state'} eq 'construct') {
13102: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
13103: 	return $return;
13104:     }
13105: 
13106:     my $cuname=unpack("%32C*",$funame);
13107:     my $cudom=unpack("%32C*",$fudom);
13108:     my $cucourseid=unpack("%32C*",$fucourseid);
13109:     my $cusymb=unpack("%32C*",$fusymb);
13110:     my $cunique=&recunique($fucourseid);
13111:     my $cpart=unpack("%32S*",$part);
13112:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
13113: 
13114: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
13115: 			       
13116: 	$return.= ($cunique%$cuname+
13117: 		   $cunique%$cudom+
13118: 		   $cusymb%$cuname+
13119: 		   $cusymb%$cudom+
13120: 		   $cucourseid%$cuname+
13121: 		   $cucourseid%$cudom+
13122: 		   $cpart%$cuname+
13123: 		   $cpart%$cudom);
13124:     } else {
13125: 	$return.= ($cunique%$cuname+
13126: 		   $cunique%$cudom+
13127: 		   $cusymb%$cuname+
13128: 		   $cusymb%$cudom+
13129: 		   $cucourseid%$cuname+
13130: 		   $cucourseid%$cudom);
13131:     }
13132:     return $return;
13133: }
13134: 
13135: sub receipt {
13136:     my ($part)=@_;
13137:     my ($symb,$courseid,$domain,$name) = &whichuser();
13138:     return &ireceipt($name,$domain,$courseid,$symb,$part);
13139: }
13140: 
13141: sub whichuser {
13142:     my ($passedsymb)=@_;
13143:     my ($symb,$courseid,$domain,$name,$publicuser);
13144:     if (defined($env{'form.grade_symb'})) {
13145: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
13146: 	my $allowed=&allowed('vgr',$tmp_courseid);
13147: 	if (!$allowed &&
13148: 	    exists($env{'request.course.sec'}) &&
13149: 	    $env{'request.course.sec'} !~ /^\s*$/) {
13150: 	    $allowed=&allowed('vgr',$tmp_courseid.
13151: 			      '/'.$env{'request.course.sec'});
13152: 	}
13153: 	if ($allowed) {
13154: 	    ($symb)=&get_env_multiple('form.grade_symb');
13155: 	    $courseid=$tmp_courseid;
13156: 	    ($domain)=&get_env_multiple('form.grade_domain');
13157: 	    ($name)=&get_env_multiple('form.grade_username');
13158: 	    return ($symb,$courseid,$domain,$name,$publicuser);
13159: 	}
13160:     }
13161:     if (!$passedsymb) {
13162: 	$symb=&symbread();
13163:     } else {
13164: 	$symb=$passedsymb;
13165:     }
13166:     $courseid=$env{'request.course.id'};
13167:     $domain=$env{'user.domain'};
13168:     $name=$env{'user.name'};
13169:     if ($name eq 'public' && $domain eq 'public') {
13170: 	if (!defined($env{'form.username'})) {
13171: 	    $env{'form.username'}.=time.rand(10000000);
13172: 	}
13173: 	$name.=$env{'form.username'};
13174:     }
13175:     return ($symb,$courseid,$domain,$name,$publicuser);
13176: 
13177: }
13178: 
13179: # ------------------------------------------------------------ Serves up a file
13180: # returns either the contents of the file or 
13181: # -1 if the file doesn't exist
13182: #
13183: # if the target is a file that was uploaded via DOCS, 
13184: # a check will be made to see if a current copy exists on the local server,
13185: # if it does this will be served, otherwise a copy will be retrieved from
13186: # the home server for the course and stored in /home/httpd/html/userfiles on
13187: # the local server.   
13188: 
13189: sub getfile {
13190:     my ($file) = @_;
13191:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
13192:     &repcopy($file);
13193:     return &readfile($file);
13194: }
13195: 
13196: sub repcopy_userfile {
13197:     my ($file)=@_;
13198:     my $londocroot = $perlvar{'lonDocRoot'};
13199:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
13200:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
13201:     my ($cdom,$cnum,$filename) = 
13202: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
13203:     my $uri="/uploaded/$cdom/$cnum/$filename";
13204:     if (-e "$file") {
13205: # we already have a local copy, check it out
13206: 	my @fileinfo = stat($file);
13207: 	my $rtncode;
13208: 	my $info;
13209: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
13210: 	if ($lwpresp ne 'ok') {
13211: # there is no such file anymore, even though we had a local copy
13212: 	    if ($rtncode eq '404') {
13213: 		unlink($file);
13214: 	    }
13215: 	    return -1;
13216: 	}
13217: 	if ($info < $fileinfo[9]) {
13218: # nice, the file we have is up-to-date, just say okay
13219: 	    return 'ok';
13220: 	} else {
13221: # the file is outdated, get rid of it
13222: 	    unlink($file);
13223: 	}
13224:     }
13225: # one way or the other, at this point, we don't have the file
13226: # construct the correct path for the file
13227:     my @parts = ($cdom,$cnum); 
13228:     if ($filename =~ m|^(.+)/[^/]+$|) {
13229: 	push @parts, split(/\//,$1);
13230:     }
13231:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
13232:     foreach my $part (@parts) {
13233: 	$path .= '/'.$part;
13234: 	if (!-e $path) {
13235: 	    mkdir($path,0770);
13236: 	}
13237:     }
13238: # now the path exists for sure
13239: # get a user agent
13240:     my $ua=new LWP::UserAgent;
13241:     my $transferfile=$file.'.in.transfer';
13242: # FIXME: this should flock
13243:     if (-e $transferfile) { return 'ok'; }
13244:     my $request;
13245:     $uri=~s/^\///;
13246:     my $homeserver = &homeserver($cnum,$cdom);
13247:     my $hostname = &hostname($homeserver);
13248:     my $protocol = $protocol{$homeserver};
13249:     $protocol = 'http' if ($protocol ne 'https');
13250:     $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
13251:     my $response=$ua->request($request,$transferfile);
13252: # did it work?
13253:     if ($response->is_error()) {
13254: 	unlink($transferfile);
13255: 	&logthis("Userfile repcopy failed for $uri");
13256: 	return -1;
13257:     }
13258: # worked, rename the transfer file
13259:     rename($transferfile,$file);
13260:     return 'ok';
13261: }
13262: 
13263: sub tokenwrapper {
13264:     my $uri=shift;
13265:     $uri=~s|^https?\://([^/]+)||;
13266:     $uri=~s|^/||;
13267:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
13268:     my $token=$1;
13269:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
13270:     if ($udom && $uname && $file) {
13271: 	$file=~s|(\?\.*)*$||;
13272:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
13273:         my $homeserver = &homeserver($uname,$udom);
13274:         my $hostname = &hostname($homeserver);
13275:         my $protocol = $protocol{$homeserver};
13276:         $protocol = 'http' if ($protocol ne 'https');
13277:         return $protocol.'://'.$hostname.'/'.$uri.
13278:                (($uri=~/\?/)?'&':'?').'token='.$token.
13279:                                '&tokenissued='.$perlvar{'lonHostID'};
13280:     } else {
13281:         return '/adm/notfound.html';
13282:     }
13283: }
13284: 
13285: # call with reqtype HEAD: get last modification time
13286: # call with reqtype GET: get the file contents
13287: # Do not call this with reqtype GET for large files! It loads everything into memory
13288: #
13289: sub getuploaded {
13290:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
13291:     $uri=~s/^\///;
13292:     my $homeserver = &homeserver($cnum,$cdom);
13293:     my $hostname = &hostname($homeserver);
13294:     my $protocol = $protocol{$homeserver};
13295:     $protocol = 'http' if ($protocol ne 'https');
13296:     $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
13297:     my $ua=new LWP::UserAgent;
13298:     my $request=new HTTP::Request($reqtype,$uri);
13299:     my $response=$ua->request($request);
13300:     $$rtncode = $response->code;
13301:     if (! $response->is_success()) {
13302: 	return 'failed';
13303:     }      
13304:     if ($reqtype eq 'HEAD') {
13305: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
13306:     } elsif ($reqtype eq 'GET') {
13307: 	$$info = $response->content;
13308:     }
13309:     return 'ok';
13310: }
13311: 
13312: sub readfile {
13313:     my $file = shift;
13314:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
13315:     my $fh;
13316:     open($fh,"<",$file);
13317:     my $a='';
13318:     while (my $line = <$fh>) { $a .= $line; }
13319:     return $a;
13320: }
13321: 
13322: sub filelocation {
13323:     my ($dir,$file) = @_;
13324:     my $location;
13325:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
13326: 
13327:     if ($file =~ m-^/adm/-) {
13328: 	$file=~s-^/adm/wrapper/-/-;
13329: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
13330:     }
13331: 
13332:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
13333:         $location = $file;
13334:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
13335:         my ($udom,$uname,$filename)=
13336:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
13337:         my $home=&homeserver($uname,$udom);
13338:         my $is_me=0;
13339:         my @ids=&current_machine_ids();
13340:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
13341:         if ($is_me) {
13342:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
13343:         } else {
13344:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
13345:   	      $udom.'/'.$uname.'/'.$filename;
13346:         }
13347:     } elsif ($file =~ m-^/adm/-) {
13348: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
13349:     } else {
13350:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
13351:         $file=~s:^/(res|priv)/:/:;
13352:         my $space=$1;
13353:         if ( !( $file =~ m:^/:) ) {
13354:             $location = $dir. '/'.$file;
13355:         } else {
13356:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
13357:         }
13358:     }
13359:     $location=~s://+:/:g; # remove duplicate /
13360:     while ($location=~m{/\.\./}) {
13361: 	if ($location =~ m{/[^/]+/\.\./}) {
13362: 	    $location=~ s{/[^/]+/\.\./}{/}g;
13363: 	} else {
13364: 	    $location=~ s{/\.\./}{/}g;
13365: 	}
13366:     } #remove dir/..
13367:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
13368:     return $location;
13369: }
13370: 
13371: sub hreflocation {
13372:     my ($dir,$file)=@_;
13373:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
13374: 	$file=filelocation($dir,$file);
13375:     } elsif ($file=~m-^/adm/-) {
13376: 	$file=~s-^/adm/wrapper/-/-;
13377: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
13378:     }
13379:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
13380: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
13381:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
13382: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
13383: 	        {/uploaded/$1/$2/}x;
13384:     }
13385:     if ($file=~ m{^/userfiles/}) {
13386: 	$file =~ s{^/userfiles/}{/uploaded/};
13387:     }
13388:     return $file;
13389: }
13390: 
13391: 
13392: 
13393: 
13394: 
13395: sub current_machine_domains {
13396:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
13397: }
13398: 
13399: sub machine_domains {
13400:     my ($hostname) = @_;
13401:     my @domains;
13402:     my %hostname = &all_hostnames();
13403:     while( my($id, $name) = each(%hostname)) {
13404: #	&logthis("-$id-$name-$hostname-");
13405: 	if ($hostname eq $name) {
13406: 	    push(@domains,&host_domain($id));
13407: 	}
13408:     }
13409:     return @domains;
13410: }
13411: 
13412: sub current_machine_ids {
13413:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
13414: }
13415: 
13416: sub machine_ids {
13417:     my ($hostname) = @_;
13418:     $hostname ||= &hostname($perlvar{'lonHostID'});
13419:     my @ids;
13420:     my %name_to_host = &all_names();
13421:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
13422: 	return @{ $name_to_host{$hostname} };
13423:     }
13424:     return;
13425: }
13426: 
13427: sub additional_machine_domains {
13428:     my @domains;
13429:     open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab");
13430:     while( my $line = <$fh>) {
13431:         $line =~ s/\s//g;
13432:         push(@domains,$line);
13433:     }
13434:     return @domains;
13435: }
13436: 
13437: sub default_login_domain {
13438:     my $domain = $perlvar{'lonDefDomain'};
13439:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
13440:     foreach my $posdom (&current_machine_domains(),
13441:                         &additional_machine_domains()) {
13442:         if (lc($posdom) eq lc($testdomain)) {
13443:             $domain=$posdom;
13444:             last;
13445:         }
13446:     }
13447:     return $domain;
13448: }
13449: 
13450: sub shared_institution {
13451:     my ($dom,$lonhost) = @_;
13452:     if ($lonhost eq '') {
13453:         $lonhost = $perlvar{'lonHostID'};
13454:     }
13455:     my $same_intdom;
13456:     my $hostintdom = &internet_dom($lonhost);
13457:     if ($hostintdom ne '') {
13458:         my %iphost = &get_iphost();
13459:         my $primary_id = &domain($dom,'primary');
13460:         my $primary_ip = &get_host_ip($primary_id);
13461:         if (ref($iphost{$primary_ip}) eq 'ARRAY') {
13462:             foreach my $id (@{$iphost{$primary_ip}}) {
13463:                 my $intdom = &internet_dom($id);
13464:                 if ($intdom eq $hostintdom) {
13465:                     $same_intdom = 1;
13466:                     last;
13467:                 }
13468:             }
13469:         }
13470:     }
13471:     return $same_intdom;
13472: }
13473: 
13474: sub uses_sts {
13475:     my ($ignore_cache) = @_;
13476:     my $lonhost = $perlvar{'lonHostID'};
13477:     my $hostname = &hostname($lonhost);
13478:     my $sts_on;
13479:     if ($protocol{$lonhost} eq 'https') {
13480:         my $cachetime = 12*3600;
13481:         if (!$ignore_cache) {
13482:             ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
13483:             if (defined($cached)) {
13484:                 return $sts_on;
13485:             }
13486:         }
13487:         my $ua=new LWP::UserAgent;
13488:         my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
13489:         my $request=new HTTP::Request('HEAD',$url);
13490:         my $response=$ua->request($request);
13491:         if ($response->is_success) {
13492:             my $has_sts = $response->header('Strict-Transport-Security');
13493:             if ($has_sts eq '') {
13494:                 $sts_on = 0;
13495:             } else {
13496:                 if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
13497:                     my $maxage = $1;
13498:                     if ($maxage) {
13499:                         $sts_on = 1;
13500:                     } else {
13501:                         $sts_on = 0;
13502:                     }
13503:                 } else {
13504:                     $sts_on = 0;
13505:                 }
13506:             }
13507:             return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
13508:         }
13509:     }
13510:     return;
13511: }
13512: 
13513: sub get_requestor_ip {
13514:     my ($r,$nolookup,$noproxy) = @_;
13515:     my $from_ip;
13516:     if (ref($r)) {
13517:         $from_ip = $r->get_remote_host($nolookup);
13518:     } else {
13519:         $from_ip = $ENV{'REMOTE_ADDR'};
13520:     }
13521:     return $from_ip;
13522: }
13523: 
13524: # ------------------------------------------------------------- Declutters URLs
13525: 
13526: sub declutter {
13527:     my $thisfn=shift;
13528:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
13529:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
13530:         $thisfn=~s{^/home/httpd/html}{};
13531:     }
13532:     $thisfn=~s/^\///;
13533:     $thisfn=~s|^adm/wrapper/||;
13534:     $thisfn=~s|^adm/coursedocs/showdoc/||;
13535:     $thisfn=~s/^res\///;
13536:     $thisfn=~s/^priv\///;
13537:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
13538:         $thisfn=~s/\?.+$//;
13539:     }
13540:     return $thisfn;
13541: }
13542: 
13543: # ------------------------------------------------------------- Clutter up URLs
13544: 
13545: sub clutter {
13546:     my $thisfn='/'.&declutter(shift);
13547:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
13548: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
13549:        $thisfn='/res'.$thisfn; 
13550:     }
13551:     if ($thisfn !~m|^/adm|) {
13552: 	if ($thisfn =~ m|^/ext/|) {
13553: 	    $thisfn='/adm/wrapper'.$thisfn;
13554: 	} else {
13555: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
13556: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
13557: 	    if ($embstyle eq 'ssi'
13558: 		|| ($embstyle eq 'hdn')
13559: 		|| ($embstyle eq 'rat')
13560: 		|| ($embstyle eq 'prv')
13561: 		|| ($embstyle eq 'ign')) {
13562: 		#do nothing with these
13563: 	    } elsif (($embstyle eq 'img') 
13564: 		|| ($embstyle eq 'emb')
13565: 		|| ($embstyle eq 'wrp')) {
13566: 		$thisfn='/adm/wrapper'.$thisfn;
13567: 	    } elsif ($embstyle eq 'unk'
13568: 		     && $thisfn!~/\.(sequence|page)$/) {
13569: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
13570: 	    } else {
13571: #		&logthis("Got a blank emb style");
13572: 	    }
13573: 	}
13574:     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
13575:         $thisfn='/adm/wrapper'.$thisfn;
13576:     }
13577:     return $thisfn;
13578: }
13579: 
13580: sub clutter_with_no_wrapper {
13581:     my $uri = &clutter(shift);
13582:     if ($uri =~ m-^/adm/-) {
13583: 	$uri =~ s-^/adm/wrapper/-/-;
13584: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
13585:     }
13586:     return $uri;
13587: }
13588: 
13589: sub freeze_escape {
13590:     my ($value)=@_;
13591:     if (ref($value)) {
13592: 	$value=&nfreeze($value);
13593: 	return '__FROZEN__'.&escape($value);
13594:     }
13595:     return &escape($value);
13596: }
13597: 
13598: 
13599: sub thaw_unescape {
13600:     my ($value)=@_;
13601:     if ($value =~ /^__FROZEN__/) {
13602: 	substr($value,0,10,undef);
13603: 	$value=&unescape($value);
13604: 	return &thaw($value);
13605:     }
13606:     return &unescape($value);
13607: }
13608: 
13609: sub correct_line_ends {
13610:     my ($result)=@_;
13611:     $$result =~s/\r\n/\n/mg;
13612:     $$result =~s/\r/\n/mg;
13613: }
13614: # ================================================================ Main Program
13615: 
13616: sub goodbye {
13617:    &logthis("Starting Shut down");
13618: #not converted to using infrastruture and probably shouldn't be
13619:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
13620: #converted
13621: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
13622:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
13623: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
13624: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
13625: #1.1 only
13626: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
13627: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
13628: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
13629: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
13630:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
13631:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
13632:    &logthis(sprintf("%-20s is %s",'hits',$hits));
13633:    &flushcourselogs();
13634:    &logthis("Shutting down");
13635: }
13636: 
13637: sub get_dns {
13638:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
13639:     if (!$ignore_cache) {
13640: 	my ($content,$cached)=
13641: 	    &Apache::lonnet::is_cached_new('dns',$url);
13642: 	if ($cached) {
13643: 	    &$func($content,$hashref);
13644: 	    return;
13645: 	}
13646:     }
13647: 
13648:     my %alldns;
13649:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
13650:         foreach my $dns (<$config>) {
13651: 	    next if ($dns !~ /^\^(\S*)/x);
13652:             my $line = $1;
13653:             my ($host,$protocol) = split(/:/,$line);
13654:             if ($protocol ne 'https') {
13655:                 $protocol = 'http';
13656:             }
13657: 	    $alldns{$host} = $protocol;
13658:         }
13659:         close($config);
13660:     }
13661:     while (%alldns) {
13662: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
13663: 	my $ua=new LWP::UserAgent;
13664:         $ua->timeout(30);
13665: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
13666: 	my $response=$ua->request($request);
13667:         delete($alldns{$dns});
13668: 	next if ($response->is_error());
13669: 	my @content = split("\n",$response->content);
13670:         unless ($nocache) {
13671: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
13672:         }
13673: 	&$func(\@content,$hashref);
13674: 	return;
13675:     }
13676:     my $which = (split('/',$url))[3];
13677:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
13678:     if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
13679:         my @content = <$config>;
13680:         &$func(\@content,$hashref);
13681:     }
13682:     return;
13683: }
13684: 
13685: # ------------------------------------------------------Get DNS checksums file
13686: sub parse_dns_checksums_tab {
13687:     my ($lines,$hashref) = @_;
13688:     my $lonhost = $perlvar{'lonHostID'};
13689:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
13690:     my $loncaparev = &get_server_loncaparev($machine_dom);
13691:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
13692:     my $webconfdir = '/etc/httpd/conf';
13693:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
13694:         $webconfdir = '/etc/apache2';
13695:     } elsif ($distro =~ /^sles(\d+)$/) {
13696:         if ($1 >= 10) {
13697:             $webconfdir = '/etc/apache2';
13698:         }
13699:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
13700:         if ($1 >= 10.0) {
13701:             $webconfdir = '/etc/apache2';
13702:         }
13703:     }
13704:     my ($release,$timestamp) = split(/\-/,$loncaparev);
13705:     my (%chksum,%revnum);
13706:     if (ref($lines) eq 'ARRAY') {
13707:         chomp(@{$lines});
13708:         my $version = shift(@{$lines});
13709:         if ($version eq $release) {
13710:             foreach my $line (@{$lines}) {
13711:                 my ($file,$version,$shasum) = split(/,/,$line);
13712:                 if ($file =~ m{^/etc/httpd/conf}) {
13713:                     if ($webconfdir eq '/etc/apache2') {
13714:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
13715:                     }
13716:                 }
13717:                 $chksum{$file} = $shasum;
13718:                 $revnum{$file} = $version;
13719:             }
13720:             if (ref($hashref) eq 'HASH') {
13721:                 %{$hashref} = (
13722:                                 sums     => \%chksum,
13723:                                 versions => \%revnum,
13724:                               );
13725:             }
13726:         }
13727:     }
13728:     return;
13729: }
13730: 
13731: sub fetch_dns_checksums {
13732:     my %checksums;
13733:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
13734:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
13735:     my ($release,$timestamp) = split(/\-/,$loncaparev);
13736:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
13737:              \%checksums);
13738:     return \%checksums;
13739: }
13740: 
13741: # ------------------------------------------------------------ Read domain file
13742: {
13743:     my $loaded;
13744:     my %domain;
13745: 
13746:     sub parse_domain_tab {
13747: 	my ($lines) = @_;
13748: 	foreach my $line (@$lines) {
13749: 	    next if ($line =~ /^(\#|\s*$ )/x);
13750: 
13751: 	    chomp($line);
13752: 	    my ($name,@elements) = split(/:/,$line,9);
13753: 	    my %this_domain;
13754: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
13755: 			       'lang_def', 'city', 'longi', 'lati',
13756: 			       'primary') {
13757: 		$this_domain{$field} = shift(@elements);
13758: 	    }
13759: 	    $domain{$name} = \%this_domain;
13760: 	}
13761:     }
13762: 
13763:     sub reset_domain_info {
13764: 	undef($loaded);
13765: 	undef(%domain);
13766:     }
13767: 
13768:     sub load_domain_tab {
13769: 	my ($ignore_cache,$nocache) = @_;
13770: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
13771: 	my $fh;
13772: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
13773: 	    my @lines = <$fh>;
13774: 	    &parse_domain_tab(\@lines);
13775: 	}
13776: 	close($fh);
13777: 	$loaded = 1;
13778:     }
13779: 
13780:     sub domain {
13781: 	&load_domain_tab() if (!$loaded);
13782: 
13783: 	my ($name,$what) = @_;
13784: 	return if ( !exists($domain{$name}) );
13785: 
13786: 	if (!$what) {
13787: 	    return $domain{$name}{'description'};
13788: 	}
13789: 	return $domain{$name}{$what};
13790:     }
13791: 
13792:     sub domain_info {
13793:         &load_domain_tab() if (!$loaded);
13794:         return %domain;
13795:     }
13796: 
13797: }
13798: 
13799: 
13800: # ------------------------------------------------------------- Read hosts file
13801: {
13802:     my %hostname;
13803:     my %hostdom;
13804:     my %libserv;
13805:     my $loaded;
13806:     my %name_to_host;
13807:     my %internetdom;
13808:     my %LC_dns_serv;
13809: 
13810:     sub parse_hosts_tab {
13811: 	my ($file) = @_;
13812: 	foreach my $configline (@$file) {
13813: 	    next if ($configline =~ /^(\#|\s*$ )/x);
13814:             chomp($configline);
13815: 	    if ($configline =~ /^\^/) {
13816:                 if ($configline =~ /^\^([\w.\-]+)/) {
13817:                     $LC_dns_serv{$1} = 1;
13818:                 }
13819:                 next;
13820:             }
13821: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
13822: 	    $name=~s/\s//g;
13823: 	    if ($id && $domain && $role && $name) {
13824:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
13825:                     my $curr = $hostname{$id};
13826:                     my $skip;
13827:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
13828:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
13829:                             $skip = 1;
13830:                         } else {
13831:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
13832:                         }
13833:                     }
13834:                     unless ($skip) {
13835:                         push(@{$name_to_host{$name}},$id);
13836:                     }
13837:                 } else {
13838:                     push(@{$name_to_host{$name}},$id);
13839:                 }
13840: 		$hostname{$id}=$name;
13841: 		$hostdom{$id}=$domain;
13842: 		if ($role eq 'library') { $libserv{$id}=$name; }
13843:                 if (defined($protocol)) {
13844:                     if ($protocol eq 'https') {
13845:                         $protocol{$id} = $protocol;
13846:                     } else {
13847:                         $protocol{$id} = 'http'; 
13848:                     }
13849:                 } else {
13850:                     $protocol{$id} = 'http';
13851:                 }
13852:                 if (defined($intdom)) {
13853:                     $internetdom{$id} = $intdom;
13854:                 }
13855: 	    }
13856: 	}
13857:     }
13858:     
13859:     sub reset_hosts_info {
13860: 	&purge_remembered();
13861: 	&reset_domain_info();
13862: 	&reset_hosts_ip_info();
13863: 	undef(%name_to_host);
13864: 	undef(%hostname);
13865: 	undef(%hostdom);
13866: 	undef(%libserv);
13867: 	undef($loaded);
13868:     }
13869: 
13870:     sub load_hosts_tab {
13871: 	my ($ignore_cache,$nocache) = @_;
13872: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
13873: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
13874: 	my @config = <$config>;
13875: 	&parse_hosts_tab(\@config);
13876: 	close($config);
13877: 	$loaded=1;
13878:     }
13879: 
13880:     sub hostname {
13881: 	&load_hosts_tab() if (!$loaded);
13882: 
13883: 	my ($lonid) = @_;
13884: 	return $hostname{$lonid};
13885:     }
13886: 
13887:     sub all_hostnames {
13888: 	&load_hosts_tab() if (!$loaded);
13889: 
13890: 	return %hostname;
13891:     }
13892: 
13893:     sub all_names {
13894:         my ($ignore_cache,$nocache) = @_;
13895: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
13896: 
13897: 	return %name_to_host;
13898:     }
13899: 
13900:     sub all_host_domain {
13901:         &load_hosts_tab() if (!$loaded);
13902:         return %hostdom;
13903:     }
13904: 
13905:     sub is_library {
13906: 	&load_hosts_tab() if (!$loaded);
13907: 
13908: 	return exists($libserv{$_[0]});
13909:     }
13910: 
13911:     sub all_library {
13912: 	&load_hosts_tab() if (!$loaded);
13913: 
13914: 	return %libserv;
13915:     }
13916: 
13917:     sub unique_library {
13918: 	#2x reverse removes all hostnames that appear more than once
13919:         my %unique = reverse &all_library();
13920:         return reverse %unique;
13921:     }
13922: 
13923:     sub get_servers {
13924: 	&load_hosts_tab() if (!$loaded);
13925: 
13926: 	my ($domain,$type) = @_;
13927: 	my %possible_hosts = ($type eq 'library') ? %libserv
13928: 	                                          : %hostname;
13929: 	my %result;
13930: 	if (ref($domain) eq 'ARRAY') {
13931: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
13932: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
13933: 		    $result{$host} = $hostname;
13934: 		}
13935: 	    }
13936: 	} else {
13937: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
13938: 		if ($hostdom{$host} eq $domain) {
13939: 		    $result{$host} = $hostname;
13940: 		}
13941: 	    }
13942: 	}
13943: 	return %result;
13944:     }
13945: 
13946:     sub get_unique_servers {
13947:         my %unique = reverse &get_servers(@_);
13948: 	return reverse %unique;
13949:     }
13950: 
13951:     sub host_domain {
13952: 	&load_hosts_tab() if (!$loaded);
13953: 
13954: 	my ($lonid) = @_;
13955: 	return $hostdom{$lonid};
13956:     }
13957: 
13958:     sub all_domains {
13959: 	&load_hosts_tab() if (!$loaded);
13960: 
13961: 	my %seen;
13962: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
13963: 	return @uniq;
13964:     }
13965: 
13966:     sub internet_dom {
13967:         &load_hosts_tab() if (!$loaded);
13968: 
13969:         my ($lonid) = @_;
13970:         return $internetdom{$lonid};
13971:     }
13972: 
13973:     sub is_LC_dns {
13974:         &load_hosts_tab() if (!$loaded);
13975: 
13976:         my ($hostname) = @_;
13977:         return exists($LC_dns_serv{$hostname});
13978:     }
13979: 
13980: }
13981: 
13982: { 
13983:     my %iphost;
13984:     my %name_to_ip;
13985:     my %lonid_to_ip;
13986: 
13987:     sub get_hosts_from_ip {
13988: 	my ($ip) = @_;
13989: 	my %iphosts = &get_iphost();
13990: 	if (ref($iphosts{$ip})) {
13991: 	    return @{$iphosts{$ip}};
13992: 	}
13993: 	return;
13994:     }
13995:     
13996:     sub reset_hosts_ip_info {
13997: 	undef(%iphost);
13998: 	undef(%name_to_ip);
13999: 	undef(%lonid_to_ip);
14000:     }
14001: 
14002:     sub get_host_ip {
14003: 	my ($lonid) = @_;
14004: 	if (exists($lonid_to_ip{$lonid})) {
14005: 	    return $lonid_to_ip{$lonid};
14006: 	}
14007: 	my $name=&hostname($lonid);
14008:    	my $ip = gethostbyname($name);
14009: 	return if (!$ip || length($ip) ne 4);
14010: 	$ip=inet_ntoa($ip);
14011: 	$name_to_ip{$name}   = $ip;
14012: 	$lonid_to_ip{$lonid} = $ip;
14013: 	return $ip;
14014:     }
14015:     
14016:     sub get_iphost {
14017: 	my ($ignore_cache,$nocache) = @_;
14018: 
14019: 	if (!$ignore_cache) {
14020: 	    if (%iphost) {
14021: 		return %iphost;
14022: 	    }
14023: 	    my ($ip_info,$cached)=
14024: 		&Apache::lonnet::is_cached_new('iphost','iphost');
14025: 	    if ($cached) {
14026: 		%iphost      = %{$ip_info->[0]};
14027: 		%name_to_ip  = %{$ip_info->[1]};
14028: 		%lonid_to_ip = %{$ip_info->[2]};
14029: 		return %iphost;
14030: 	    }
14031: 	}
14032: 
14033: 	# get yesterday's info for fallback
14034: 	my %old_name_to_ip;
14035: 	my ($ip_info,$cached)=
14036: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
14037: 	if ($cached) {
14038: 	    %old_name_to_ip = %{$ip_info->[1]};
14039: 	}
14040: 
14041: 	my %name_to_host = &all_names($ignore_cache,$nocache);
14042: 	foreach my $name (keys(%name_to_host)) {
14043: 	    my $ip;
14044: 	    if (!exists($name_to_ip{$name})) {
14045: 		$ip = gethostbyname($name);
14046: 		if (!$ip || length($ip) ne 4) {
14047: 		    if (defined($old_name_to_ip{$name})) {
14048: 			$ip = $old_name_to_ip{$name};
14049: 			&logthis("Can't find $name defaulting to old $ip");
14050: 		    } else {
14051: 			&logthis("Name $name no IP found");
14052: 			next;
14053: 		    }
14054: 		} else {
14055: 		    $ip=inet_ntoa($ip);
14056: 		}
14057: 		$name_to_ip{$name} = $ip;
14058: 	    } else {
14059: 		$ip = $name_to_ip{$name};
14060: 	    }
14061: 	    foreach my $id (@{ $name_to_host{$name} }) {
14062: 		$lonid_to_ip{$id} = $ip;
14063: 	    }
14064: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
14065: 	}
14066:         unless ($nocache) {
14067: 	    &do_cache_new('iphost','iphost',
14068: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
14069: 		          48*60*60);
14070:         }
14071: 
14072: 	return %iphost;
14073:     }
14074: 
14075:     #
14076:     #  Given a DNS returns the loncapa host name for that DNS 
14077:     # 
14078:     sub host_from_dns {
14079:         my ($dns) = @_;
14080:         my @hosts;
14081:         my $ip;
14082: 
14083:         if (exists($name_to_ip{$dns})) {
14084:             $ip = $name_to_ip{$dns};
14085:         }
14086:         if (!$ip) {
14087:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
14088:             if (length($ip) == 4) { 
14089: 	        $ip   = &IO::Socket::inet_ntoa($ip);
14090:             }
14091:         }
14092:         if ($ip) {
14093: 	    @hosts = get_hosts_from_ip($ip);
14094: 	    return $hosts[0];
14095:         }
14096:         return undef;
14097:     }
14098: 
14099:     sub get_internet_names {
14100:         my ($lonid) = @_;
14101:         return if ($lonid eq '');
14102:         my ($idnref,$cached)=
14103:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
14104:         if ($cached) {
14105:             return $idnref;
14106:         }
14107:         my $ip = &get_host_ip($lonid);
14108:         my @hosts = &get_hosts_from_ip($ip);
14109:         my %iphost = &get_iphost();
14110:         my (@idns,%seen);
14111:         foreach my $id (@hosts) {
14112:             my $dom = &host_domain($id);
14113:             my $prim_id = &domain($dom,'primary');
14114:             my $prim_ip = &get_host_ip($prim_id);
14115:             next if ($seen{$prim_ip});
14116:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
14117:                 foreach my $id (@{$iphost{$prim_ip}}) {
14118:                     my $intdom = &internet_dom($id);
14119:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
14120:                         push(@idns,$intdom);
14121:                     }
14122:                 }
14123:             }
14124:             $seen{$prim_ip} = 1;
14125:         }
14126:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
14127:     }
14128: 
14129: }
14130: 
14131: sub all_loncaparevs {
14132:     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);
14133: }
14134: 
14135: # ------------------------------------------------------- Read loncaparev table
14136: {
14137:     sub load_loncaparevs {
14138:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
14139:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
14140:                 while (my $configline=<$config>) {
14141:                     chomp($configline);
14142:                     my ($hostid,$loncaparev)=split(/:/,$configline);
14143:                     $loncaparevs{$hostid}=$loncaparev;
14144:                 }
14145:                 close($config);
14146:             }
14147:         }
14148:     }
14149: }
14150: 
14151: # ----------------------------------------------------- Read serverhostID table
14152: {
14153:     sub load_serverhomeIDs {
14154:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
14155:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
14156:                 while (my $configline=<$config>) {
14157:                     chomp($configline);
14158:                     my ($name,$id)=split(/:/,$configline);
14159:                     $serverhomeIDs{$name}=$id;
14160:                 }
14161:                 close($config);
14162:             }
14163:         }
14164:     }
14165: }
14166: 
14167: 
14168: BEGIN {
14169: 
14170: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
14171:     unless ($readit) {
14172: {
14173:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
14174:     %perlvar = (%perlvar,%{$configvars});
14175: }
14176: 
14177: 
14178: # ------------------------------------------------------ Read spare server file
14179: {
14180:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
14181: 
14182:     while (my $configline=<$config>) {
14183:        chomp($configline);
14184:        if ($configline) {
14185: 	   my ($host,$type) = split(':',$configline,2);
14186: 	   if (!defined($type) || $type eq '') { $type = 'default' };
14187: 	   push(@{ $spareid{$type} }, $host);
14188:        }
14189:     }
14190:     close($config);
14191: }
14192: # ------------------------------------------------------------ Read permissions
14193: {
14194:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
14195: 
14196:     while (my $configline=<$config>) {
14197: 	chomp($configline);
14198: 	if ($configline) {
14199: 	    my ($role,$perm)=split(/ /,$configline);
14200: 	    if ($perm ne '') { $pr{$role}=$perm; }
14201: 	}
14202:     }
14203:     close($config);
14204: }
14205: 
14206: # -------------------------------------------- Read plain texts for permissions
14207: {
14208:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
14209: 
14210:     while (my $configline=<$config>) {
14211: 	chomp($configline);
14212: 	if ($configline) {
14213: 	    my ($short,@plain)=split(/:/,$configline);
14214:             %{$prp{$short}} = ();
14215: 	    if (@plain > 0) {
14216:                 $prp{$short}{'std'} = $plain[0];
14217:                 for (my $i=1; $i<@plain; $i++) {
14218:                     $prp{$short}{'alt'.$i} = $plain[$i];  
14219:                 }
14220:             }
14221: 	}
14222:     }
14223:     close($config);
14224: }
14225: 
14226: # ---------------------------------------------------------- Read package table
14227: {
14228:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
14229: 
14230:     while (my $configline=<$config>) {
14231: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
14232: 	chomp($configline);
14233: 	my ($short,$plain)=split(/:/,$configline);
14234: 	my ($pack,$name)=split(/\&/,$short);
14235: 	if ($plain ne '') {
14236: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
14237: 	    $packagetab{$short}=$plain; 
14238: 	}
14239:     }
14240:     close($config);
14241: }
14242: 
14243: # --------------------------------------------------------- Read loncaparev table
14244: 
14245: &load_loncaparevs();
14246: 
14247: # ------------------------------------------------------- Read serverhostID table
14248: 
14249: &load_serverhomeIDs();
14250: 
14251: # ---------------------------------------------------------- Read releaseslist XML
14252: {
14253:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
14254:     if (-e $file) {
14255:         my $parser = HTML::LCParser->new($file);
14256:         while (my $token = $parser->get_token()) {
14257:             if ($token->[0] eq 'S') {
14258:                 my $item = $token->[1];
14259:                 my $name = $token->[2]{'name'};
14260:                 my $value = $token->[2]{'value'};
14261:                 if ($item ne '' && $name ne '' && $value ne '') {
14262:                     my $release = $parser->get_text();
14263:                     $release =~ s/(^\s*|\s*$ )//gx;
14264:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
14265:                 }
14266:             }
14267:         }
14268:     }
14269: }
14270: 
14271: # ---------------------------------------------------------- Read managers table
14272: {
14273:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
14274:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
14275:             while (my $configline=<$config>) {
14276:                 chomp($configline);
14277:                 next if ($configline =~ /^\#/);
14278:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
14279:                     $managerstab{$configline} = 1;
14280:                 }
14281:             }
14282:             close($config);
14283:         }
14284:     }
14285: }
14286: 
14287: # ------------- set up temporary directory
14288: {
14289:     $tmpdir = LONCAPA::tempdir();
14290: 
14291: }
14292: 
14293: # ------------- set default texengine (domain default overrides this)
14294: {
14295:     $deftex = LONCAPA::texengine();
14296: }
14297: 
14298: # ------------- set default minimum length for passwords for internal auth users
14299: {
14300:     $passwdmin = LONCAPA::passwd_min();
14301: }
14302: 
14303: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
14304: 				'compress_threshold'=> 20_000,
14305:  			        });
14306: 
14307: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
14308: $dumpcount=0;
14309: $locknum=0;
14310: 
14311: &logtouch();
14312: &logthis('<font color="yellow">INFO: Read configuration</font>');
14313: $readit=1;
14314:     {
14315: 	use integer;
14316: 	my $test=(2**32)+1;
14317: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
14318: 	&logthis(" Detected 64bit platform ($_64bit)");
14319:     }
14320: }
14321: }
14322: 
14323: 1;
14324: __END__
14325: 
14326: =pod
14327: 
14328: =head1 NAME
14329: 
14330: Apache::lonnet - Subroutines to ask questions about things in the network.
14331: 
14332: =head1 SYNOPSIS
14333: 
14334: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
14335: 
14336:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
14337: 
14338: Common parameters:
14339: 
14340: =over 4
14341: 
14342: =item *
14343: 
14344: $uname : an internal username (if $cname expecting a course Id specifically)
14345: 
14346: =item *
14347: 
14348: $udom : a domain (if $cdom expecting a course's domain specifically)
14349: 
14350: =item *
14351: 
14352: $symb : a resource instance identifier
14353: 
14354: =item *
14355: 
14356: $namespace : the name of a .db file that contains the data needed or
14357: being set.
14358: 
14359: =back
14360: 
14361: =head1 OVERVIEW
14362: 
14363: lonnet provides subroutines which interact with the
14364: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
14365: about classes, users, and resources.
14366: 
14367: For many of these objects you can also use this to store data about
14368: them or modify them in various ways.
14369: 
14370: =head2 Symbs
14371: 
14372: To identify a specific instance of a resource, LON-CAPA uses symbols
14373: or "symbs"X<symb>. These identifiers are built from the URL of the
14374: map, the resource number of the resource in the map, and the URL of
14375: the resource itself. The latter is somewhat redundant, but might help
14376: if maps change.
14377: 
14378: An example is
14379: 
14380:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
14381: 
14382: The respective map entry is
14383: 
14384:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
14385:   title="Problem 2">
14386:  </resource>
14387: 
14388: Symbs are used by the random number generator, as well as to store and
14389: restore data specific to a certain instance of for example a problem.
14390: 
14391: =head2 Storing And Retrieving Data
14392: 
14393: X<store()>X<cstore()>X<restore()>Three of the most important functions
14394: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
14395: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
14396: is is the non-critical message twin of cstore. These functions are for
14397: handlers to store a perl hash to a user's permanent data space in an
14398: easy manner, and to retrieve it again on another call. It is expected
14399: that a handler would use this once at the beginning to retrieve data,
14400: and then again once at the end to send only the new data back.
14401: 
14402: The data is stored in the user's data directory on the user's
14403: homeserver under the ID of the course.
14404: 
14405: The hash that is returned by restore will have all of the previous
14406: value for all of the elements of the hash.
14407: 
14408: Example:
14409: 
14410:  #creating a hash
14411:  my %hash;
14412:  $hash{'foo'}='bar';
14413: 
14414:  #storing it
14415:  &Apache::lonnet::cstore(\%hash);
14416: 
14417:  #changing a value
14418:  $hash{'foo'}='notbar';
14419: 
14420:  #adding a new value
14421:  $hash{'bar'}='foo';
14422:  &Apache::lonnet::cstore(\%hash);
14423: 
14424:  #retrieving the hash
14425:  my %history=&Apache::lonnet::restore();
14426: 
14427:  #print the hash
14428:  foreach my $key (sort(keys(%history))) {
14429:    print("\%history{$key} = $history{$key}");
14430:  }
14431: 
14432: Will print out:
14433: 
14434:  %history{1:foo} = bar
14435:  %history{1:keys} = foo:timestamp
14436:  %history{1:timestamp} = 990455579
14437:  %history{2:bar} = foo
14438:  %history{2:foo} = notbar
14439:  %history{2:keys} = foo:bar:timestamp
14440:  %history{2:timestamp} = 990455580
14441:  %history{bar} = foo
14442:  %history{foo} = notbar
14443:  %history{timestamp} = 990455580
14444:  %history{version} = 2
14445: 
14446: Note that the special hash entries C<keys>, C<version> and
14447: C<timestamp> were added to the hash. C<version> will be equal to the
14448: total number of versions of the data that have been stored. The
14449: C<timestamp> attribute will be the UNIX time the hash was
14450: stored. C<keys> is available in every historical section to list which
14451: keys were added or changed at a specific historical revision of a
14452: hash.
14453: 
14454: B<Warning>: do not store the hash that restore returns directly. This
14455: will cause a mess since it will restore the historical keys as if the
14456: were new keys. I.E. 1:foo will become 1:1:foo etc.
14457: 
14458: Calling convention:
14459: 
14460:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
14461:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
14462: 
14463: For more detailed information, see lonnet specific documentation.
14464: 
14465: =head1 RETURN MESSAGES
14466: 
14467: =over 4
14468: 
14469: =item * B<con_lost>: unable to contact remote host
14470: 
14471: =item * B<con_delayed>: unable to contact remote host, message will be delivered
14472: when the connection is brought back up
14473: 
14474: =item * B<con_failed>: unable to contact remote host and unable to save message
14475: for later delivery
14476: 
14477: =item * B<error:>: an error a occurred, a description of the error follows the :
14478: 
14479: =item * B<no_such_host>: unable to fund a host associated with the user/domain
14480: that was requested
14481: 
14482: =back
14483: 
14484: =head1 PUBLIC SUBROUTINES
14485: 
14486: =head2 Session Environment Functions
14487: 
14488: =over 4
14489: 
14490: =item * 
14491: X<appenv()>
14492: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
14493: the user envirnoment file, and will be restored for each access this
14494: user makes during this session, also modifies the %env for the current
14495: process. Optional rolesarrayref - if defined contains a reference to an array
14496: of roles which are exempt from the restriction on modifying user.role entries 
14497: in the user's environment.db and in %env.    
14498: 
14499: =item *
14500: X<delenv()>
14501: B<delenv($delthis,$regexp)>: removes all items from the session
14502: environment file that begin with $delthis. If the 
14503: optional second arg - $regexp - is true, $delthis is treated as a 
14504: regular expression, otherwise \Q$delthis\E is used. 
14505: The values are also deleted from the current processes %env.
14506: 
14507: =item * get_env_multiple($name) 
14508: 
14509: gets $name from the %env hash, it seemlessly handles the cases where multiple
14510: values may be defined and end up as an array ref.
14511: 
14512: returns an array of values
14513: 
14514: =back
14515: 
14516: =head2 User Information
14517: 
14518: =over 4
14519: 
14520: =item *
14521: X<queryauthenticate()>
14522: B<queryauthenticate($uname,$udom)>: try to determine user's current 
14523: authentication scheme
14524: 
14525: =item *
14526: X<authenticate()>
14527: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
14528: authenticate user from domain's lib servers (first use the current
14529: one). C<$upass> should be the users password.
14530: $checkdefauth is optional (value is 1 if a check should be made to
14531:    authenticate user using default authentication method, and allow
14532:    account creation if username does not have account in the domain).
14533: $clientcancheckhost is optional (value is 1 if checking whether the
14534:    server can host will occur on the client side in lonauth.pm).   
14535: 
14536: =item *
14537: X<homeserver()>
14538: B<homeserver($uname,$udom)>: find the server which has
14539: the user's directory and files (there must be only one), this caches
14540: the answer, and also caches if there is a borken connection.
14541: 
14542: =item *
14543: X<idget()>
14544: B<idget($udom,@ids)>: find the usernames behind a list of IDs
14545: (IDs are a unique resource in a domain, there must be only 1 ID per
14546: username, and only 1 username per ID in a specific domain) (returns
14547: hash: id=>name,id=>name)
14548: 
14549: =item *
14550: X<idrget()>
14551: B<idrget($udom,@unames)>: find the IDs behind a list of
14552: usernames (returns hash: name=>id,name=>id)
14553: 
14554: =item *
14555: X<idput()>
14556: B<idput($udom,%ids)>: store away a list of names and associated IDs
14557: 
14558: =item *
14559: X<rolesinit()>
14560: B<rolesinit($udom,$username)>: get user privileges.
14561: returns user role, first access and timer interval hashes
14562: 
14563: =item *
14564: X<privileged()>
14565: B<privileged($username,$domain)>: returns a true if user has a
14566: privileged and active role (i.e. su or dc), false otherwise.
14567: 
14568: =item *
14569: X<getsection()>
14570: B<getsection($udom,$uname,$cname)>: finds the section of student in the
14571: course $cname, return section name/number or '' for "not in course"
14572: and '-1' for "no section"
14573: 
14574: =item *
14575: X<userenvironment()>
14576: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
14577: passed in @what from the requested user's environment, returns a hash
14578: 
14579: =item * 
14580: X<userlog_query()>
14581: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
14582: activity.log file. %filters defines filters applied when parsing the
14583: log file. These can be start or end timestamps, or the type of action
14584: - log to look for Login or Logout events, check for Checkin or
14585: Checkout, role for role selection. The response is in the form
14586: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
14587: escaped strings of the action recorded in the activity.log file.
14588: 
14589: =back
14590: 
14591: =head2 User Roles
14592: 
14593: =over 4
14594: 
14595: =item *
14596: 
14597: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
14598: returns codes for allowed actions.
14599: 
14600: The first argument is required, all others are optional.
14601: 
14602: $priv is the privilege being checked.
14603: $uri contains additional information about what is being checked for access (e.g.,
14604: URL, course ID etc.).
14605: $symb is the unique resource instance identifier in a course; if needed,
14606: but not provided, it will be retrieved via a call to &symbread().
14607: $role is the role for which a priv is being checked (only used if priv is evb).
14608: $clientip is the user's IP address (only used when checking for access to portfolio
14609: files).
14610: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
14611: prevents recursive calls to &allowed.
14612: 
14613:  F: full access
14614:  U,I,K: authentication modes (cxx only)
14615:  '': forbidden
14616:  1: user needs to choose course
14617:  2: browse allowed
14618:  A: passphrase authentication needed
14619:  B: access temporarily blocked because of a blocking event in a course.
14620: 
14621: =item *
14622: 
14623: constructaccess($url,$setpriv) : check for access to construction space URL
14624: 
14625: See if the owner domain and name in the URL match those in the
14626: expected environment.  If so, return three element list
14627: ($ownername,$ownerdomain,$ownerhome).
14628: 
14629: Otherwise return the null string.
14630: 
14631: If second argument 'setpriv' is true, it assigns the privileges,
14632: and returns the same three element list, unless the owner has
14633: blocked "ad hoc" Domain Coordinator access to the Author Space,
14634: in which case the null string is returned.
14635: 
14636: =item *
14637: 
14638: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
14639: define a custom role rolename set privileges in format of lonTabs/roles.tab
14640: for system, domain, and course level. $uname and $udom are optional (current
14641: user's username and domain will be used when either of $uname or $udom are absent.
14642: 
14643: =item *
14644: 
14645: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
14646: (rolesplain.tab); plain text explanation of a user role term.
14647: $type is Course (default) or Community.
14648: If $forcedefault evaluates to true, text returned will be default 
14649: text for $type. Otherwise, if this is a course, the text returned 
14650: will be a custom name for the role (if defined in the course's 
14651: environment).  If no custom name is defined the default is returned.
14652:    
14653: =item *
14654: 
14655: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
14656: All arguments are optional. Returns a hash of a roles, either for
14657: co-author/assistant author roles for a user's Construction Space
14658: (default), or if $context is 'userroles', roles for the user himself,
14659: In the hash, keys are set to colon-separated $uname,$udom,$role, and
14660: (optionally) if $withsec is true, a fourth colon-separated item - $section.
14661: For each key, value is set to colon-separated start and end times for
14662: the role.  If no username and domain are specified, will default to
14663: current user/domain. Types, roles, and roledoms are references to arrays
14664: of role statuses (active, future or previous), roles 
14665: (e.g., cc,in, st etc.) and domains of the roles which can be used
14666: to restrict the list of roles reported. If no array ref is 
14667: provided for types, will default to return only active roles.
14668: 
14669: =item *
14670: 
14671: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
14672: user: $uname:$udom has a role in the course: $cdom_$cnum.
14673: 
14674: Additional optional arguments are: $type (if role checking is to be restricted
14675: to certain user status types -- previous (expired roles), active (currently
14676: available roles) or future (roles available in the future), and
14677: $hideprivileged -- if true will not report course roles for users who
14678: have active Domain Coordinator role in course's domain or in additional
14679: domains (specified in 'Domains to check for privileged users' in course
14680: environment -- set via:  Course Settings -> Classlists and staff listing).
14681: 
14682: =item *
14683: 
14684: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
14685: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
14686: $possdomains and $possroles are optional array refs -- to domains to check and
14687: roles to check.  If $possdomains is not specified, a dump will be done of the
14688: users' roles.db to check for a dc or su role in any domain. This can be
14689: time consuming if &privileged is called repeatedly (e.g., when displaying a
14690: classlist), so in such cases, supplying a $possdomains array is preferred, as
14691: this then allows &privileged_by_domain() to be used, which caches the identity
14692: of privileged users, eliminating the need for repeated calls to &dump().
14693: 
14694: =item *
14695: 
14696: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
14697: where the outer hash keys are domains specified in the $possdomains array ref,
14698: next inner hash keys are privileged roles specified in the $roles array ref,
14699: and the innermost hash contains key = value pairs for username:domain = end:start
14700: for active or future "privileged" users with that role in that domain. To avoid
14701: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
14702: innerhash are cached using priv_$role and $dom as the identifiers.
14703: 
14704: =back
14705: 
14706: =head2 User Modification
14707: 
14708: =over 4
14709: 
14710: =item *
14711: 
14712: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
14713: user for the level given by URL.  Optional start and end dates (leave empty
14714: string or zero for "no date")
14715: 
14716: =item *
14717: 
14718: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
14719: change a users, password, possible return values are: ok,
14720: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
14721: refused
14722: 
14723: =item *
14724: 
14725: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
14726: 
14727: =item *
14728: 
14729: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
14730:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
14731: 
14732: will update user information (firstname,middlename,lastname,generation,
14733: permanentemail), and if forceid is true, student/employee ID also.
14734: A user's institutional affiliation(s) can also be updated.
14735: User information fields will not be overwritten with empty entries 
14736: unless the field is included in the $candelete array reference.
14737: This array is included when a single user is modified via "Manage Users",
14738: or when Autoupdate.pl is run by cron in a domain.
14739: 
14740: =item *
14741: 
14742: modifystudent
14743: 
14744: modify a student's enrollment and identification information.
14745: The course id is resolved based on the current user's environment.  
14746: This means the invoking user must be a course coordinator or otherwise
14747: associated with a course.
14748: 
14749: This call is essentially a wrapper for lonnet::modifyuser and
14750: lonnet::modify_student_enrollment
14751: 
14752: Inputs: 
14753: 
14754: =over 4
14755: 
14756: =item B<$udom> Student's loncapa domain
14757: 
14758: =item B<$uname> Student's loncapa login name
14759: 
14760: =item B<$uid> Student/Employee ID
14761: 
14762: =item B<$umode> Student's authentication mode
14763: 
14764: =item B<$upass> Student's password
14765: 
14766: =item B<$first> Student's first name
14767: 
14768: =item B<$middle> Student's middle name
14769: 
14770: =item B<$last> Student's last name
14771: 
14772: =item B<$gene> Student's generation
14773: 
14774: =item B<$usec> Student's section in course
14775: 
14776: =item B<$end> Unix time of the roles expiration
14777: 
14778: =item B<$start> Unix time of the roles start date
14779: 
14780: =item B<$forceid> If defined, allow $uid to be changed
14781: 
14782: =item B<$desiredhome> server to use as home server for student
14783: 
14784: =item B<$email> Student's permanent e-mail address
14785: 
14786: =item B<$type> Type of enrollment (auto or manual)
14787: 
14788: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
14789: 
14790: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
14791: 
14792: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
14793: 
14794: =item B<$context> role change context (shown in User Management Logs display in a course)
14795: 
14796: =item B<$inststatus> institutional status of user - : separated string of escaped status types
14797: 
14798: =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.
14799: 
14800: =back
14801: 
14802: =item *
14803: 
14804: modify_student_enrollment
14805: 
14806: Change a student's enrollment status in a class.  The environment variable
14807: 'role.request.course' must be defined for this function to proceed.
14808: 
14809: Inputs:
14810: 
14811: =over 4
14812: 
14813: =item $udom, student's domain
14814: 
14815: =item $uname, student's name
14816: 
14817: =item $uid, student's user id
14818: 
14819: =item $first, student's first name
14820: 
14821: =item $middle
14822: 
14823: =item $last
14824: 
14825: =item $gene
14826: 
14827: =item $usec
14828: 
14829: =item $end
14830: 
14831: =item $start
14832: 
14833: =item $type
14834: 
14835: =item $locktype
14836: 
14837: =item $cid
14838: 
14839: =item $selfenroll
14840: 
14841: =item $context
14842: 
14843: =item $credits, number of credits student will earn from this class
14844: 
14845: =item $instsec, institutional course section code for student
14846: 
14847: =back
14848: 
14849: 
14850: =item *
14851: 
14852: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
14853: custom role; give a custom role to a user for the level given by URL.  Specify
14854: name and domain of role author, and role name
14855: 
14856: =item *
14857: 
14858: revokerole($udom,$uname,$url,$role) : revoke a role for url
14859: 
14860: =item *
14861: 
14862: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
14863: 
14864: =back
14865: 
14866: =head2 Course Infomation
14867: 
14868: =over 4
14869: 
14870: =item *
14871: 
14872: coursedescription($courseid,$options) : returns a hash of information about the
14873: specified course id, including all environment settings for the
14874: course, the description of the course will be in the hash under the
14875: key 'description'
14876: 
14877: $options is an optional parameter that if supplied is a hash reference that controls
14878: what how this function works.  It has the following key/values:
14879: 
14880: =over 4
14881: 
14882: =item freshen_cache
14883: 
14884: If defined, and the environment cache for the course is valid, it is 
14885: returned in the returned hash.
14886: 
14887: =item one_time
14888: 
14889: If defined, the last cache time is set to _now_
14890: 
14891: =item user
14892: 
14893: If defined, the supplied username is used instead of the current user.
14894: 
14895: 
14896: =back
14897: 
14898: =item *
14899: 
14900: resdata($name,$domain,$type,@which) : request for current parameter
14901: setting for a specific $type, where $type is either 'course' or 'user',
14902: @what should be a list of parameters to ask about. This routine caches
14903: answers for 10 minutes.
14904: 
14905: =item *
14906: 
14907: get_courseresdata($courseid, $domain) : dump the entire course resource
14908: data base, returning a hash that is keyed by the resource name and has
14909: values that are the resource value.  I believe that the timestamps and
14910: versions are also returned.
14911: 
14912: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
14913: supplemental content area. This routine caches the number of files for
14914: 10 minutes.
14915: 
14916: =back
14917: 
14918: =head2 Course Modification
14919: 
14920: =over 4
14921: 
14922: =item *
14923: 
14924: writecoursepref($courseid,%prefs) : write preferences (environment
14925: database) for a course
14926: 
14927: =item *
14928: 
14929: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
14930: 
14931: =item *
14932: 
14933: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
14934: 
14935: =item *
14936: 
14937: is_course($courseid), is_course($cdom, $cnum)
14938: 
14939: Accepts either a combined $courseid (in the form of domain_courseid) or the
14940: two component version $cdom, $cnum. It checks if the specified course exists.
14941: 
14942: Returns:
14943:     undef if the course doesn't exist, otherwise
14944:     in scalar context the combined courseid.
14945:     in list context the two components of the course identifier, domain and 
14946:     courseid.    
14947: 
14948: =back
14949: 
14950: =head2 Bubblesheet Configuration
14951: 
14952: =over 4
14953: 
14954: =item *
14955: 
14956: get_scantron_config($which)
14957: 
14958: $which - the name of the configuration to parse from the file.
14959: 
14960: Parses and returns the bubblesheet configuration line selected as a
14961: hash of configuration file fields.
14962: 
14963: 
14964: Returns:
14965:     If the named configuration is not in the file, an empty
14966:     hash is returned.
14967: 
14968:     a hash with the fields
14969:       name         - internal name for the this configuration setup
14970:       description  - text to display to operator that describes this config
14971:       CODElocation - if 0 or the string 'none'
14972:                           - no CODE exists for this config
14973:                      if -1 || the string 'letter'
14974:                           - a CODE exists for this config and is
14975:                             a string of letters
14976:                      Unsupported value (but planned for future support)
14977:                           if a positive integer
14978:                                - The CODE exists as the first n items from
14979:                                  the question section of the form
14980:                           if the string 'number'
14981:                                - The CODE exists for this config and is
14982:                                  a string of numbers
14983:       CODEstart   - (only matter if a CODE exists) column in the line where
14984:                      the CODE starts
14985:       CODElength  - length of the CODE
14986:       IDstart     - column where the student/employee ID starts
14987:       IDlength    - length of the student/employee ID info
14988:       Qstart      - column where the information from the bubbled
14989:                     'questions' start
14990:       Qlength     - number of columns comprising a single bubble line from
14991:                     the sheet. (usually either 1 or 10)
14992:       Qon         - either a single character representing the character used
14993:                     to signal a bubble was chosen in the positional setup, or
14994:                     the string 'letter' if the letter of the chosen bubble is
14995:                     in the final, or 'number' if a number representing the
14996:                     chosen bubble is in the file (1->A 0->J)
14997:       Qoff        - the character used to represent that a bubble was
14998:                     left blank
14999:       PaperID     - if the scanning process generates a unique number for each
15000:                     sheet scanned the column that this ID number starts in
15001:       PaperIDlength - number of columns that comprise the unique ID number
15002:                       for the sheet of paper
15003:       FirstName   - column that the first name starts in
15004:       FirstNameLength - number of columns that the first name spans
15005:       LastName    - column that the last name starts in
15006:       LastNameLength - number of columns that the last name spans
15007:       BubblesPerRow - number of bubbles available in each row used to
15008:                       bubble an answer. (If not specified, 10 assumed).
15009: 
15010: 
15011: =item *
15012: 
15013: get_scantronformat_file($cdom)
15014: 
15015: $cdom - the course's domain (optional); if not supplied, uses
15016: domain for current $env{'request.course.id'}.
15017: 
15018: Returns an array containing lines from the scantron format file for
15019: the domain of the course.
15020: 
15021: If a url for a custom.tab file is listed in domain's configuration.db,
15022: lines are from this file.
15023: 
15024: Otherwise, if a default.tab has been published in RES space by the
15025: domainconfig user, lines are from this file.
15026: 
15027: Otherwise, fall back to getting lines from the legacy file on the
15028: local server:  /home/httpd/lonTabs/default_scantronformat.tab
15029: 
15030: =back
15031: 
15032: =head2 Resource Subroutines
15033: 
15034: =over 4
15035: 
15036: =item *
15037: 
15038: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
15039: 
15040: =item *
15041: 
15042: repcopy($filename) : subscribes to the requested file, and attempts to
15043: replicate from the owning library server, Might return
15044: 'unavailable', 'not_found', 'forbidden', 'ok', or
15045: 'bad_request', also attempts to grab the metadata for the
15046: resource. Expects the local filesystem pathname
15047: (/home/httpd/html/res/....)
15048: 
15049: =back
15050: 
15051: =head2 Resource Information
15052: 
15053: =over 4
15054: 
15055: =item *
15056: 
15057: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
15058: and returns the value of a variety of different possible values,
15059: $varname should be a request string, and the other parameters can be
15060: used to specify who and what one is asking about. Ordinarily, $cid 
15061: does not need to be specified, as it is retrived from 
15062: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
15063: within lonuserstate::loadmap() when initializing a course, before
15064: $env{'request.course.id'} has been set, so it needs to be provided
15065: in that one case.
15066: 
15067: Possible values for $varname are environment.lastname (or other item
15068: from the envirnment hash), user.name (or someother aspect about the
15069: user), resource.0.maxtries (or some other part and parameter of a
15070: resource)
15071: 
15072: =item *
15073: 
15074: directcondval($number) : get current value of a condition; reads from a state
15075: string
15076: 
15077: =item *
15078: 
15079: condval($condidx) : value of condition index based on state
15080: 
15081: =item *
15082: 
15083: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
15084: resource's metadata, $what should be either a specific key, or either
15085: 'keys' (to get a list of possible keys) or 'packages' to get a list of
15086: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
15087: 
15088: this function automatically caches all requests
15089: 
15090: =item *
15091: 
15092: metadata_query($query,$custom,$customshow) : make a metadata query against the
15093: network of library servers; returns file handle of where SQL and regex results
15094: will be stored for query
15095: 
15096: =item *
15097: 
15098: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
15099: return symbolic list entry (all arguments optional).
15100: 
15101: Args: filename is the filename (including path) for the file for which a symb
15102: is required; donotrecurse, if true will prevent calls to allowed() being made
15103: to check access status if more than one resource was found in the bighash
15104: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
15105: a randompick); ignorecachednull, if true will prevent a symb of '' being
15106: returned if $env{$cache_str} is defined as ''; checkforblock if true will
15107: cause possible symbs to be checked to determine if they are subject to content
15108: blocking, if so they will not be included as possible symbs; possibles is a
15109: ref to a hash, which, as a side effect, will be populated with all possible
15110: symbs (content blocking not tested).
15111: 
15112: returns the data handle
15113: 
15114: =item *
15115: 
15116: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
15117: and is a possible symb for the URL in $thisfn, and if is an encrypted
15118: resource that the user accessed using /enc/ returns a 1 on success, 0
15119: on failure, user must be in a course, as it assumes the existence of
15120: the course initial hash, and uses $env('request.course.id'}.  The third
15121: arg is an optional reference to a scalar.  If this arg is passed in the
15122: call to symbverify, it will be set to 1 if the symb has been set to be 
15123: encrypted; otherwise it will be null.
15124: 
15125: =item *
15126: 
15127: symbclean($symb) : removes versions numbers from a symb, returns the
15128: cleaned symb
15129: 
15130: =item *
15131: 
15132: is_on_map($uri) : checks if the $uri is somewhere on the current
15133: course map, user must be in a course for it to work.
15134: 
15135: =item *
15136: 
15137: numval($salt) : return random seed value (addend for rndseed)
15138: 
15139: =item *
15140: 
15141: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
15142: a random seed, all arguments are optional, if they aren't sent it uses the
15143: environment to derive them. Note: if symb isn't sent and it can't get one
15144: from &symbread it will use the current time as its return value
15145: 
15146: =item *
15147: 
15148: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
15149: unfakeable, receipt
15150: 
15151: =item *
15152: 
15153: receipt() : API to ireceipt working off of env values; given out to users
15154: 
15155: =item *
15156: 
15157: countacc($url) : count the number of accesses to a given URL
15158: 
15159: =item *
15160: 
15161: 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
15162: 
15163: =item *
15164: 
15165: 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)
15166: 
15167: =item *
15168: 
15169: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
15170: 
15171: =item *
15172: 
15173: devalidate($symb) : devalidate temporary spreadsheet calculations,
15174: forcing spreadsheet to reevaluate the resource scores next time.
15175: 
15176: =item *
15177: 
15178: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
15179: when viewing in course context.
15180: 
15181:  input: six args -- filename (decluttered), course number, course domain,
15182:                     url, symb (if registered) and group (if this is a
15183:                     group item -- e.g., bulletin board, group page etc.).
15184: 
15185:  output: array of five scalars --
15186:          $cfile -- url for file editing if editable on current server
15187:          $home -- homeserver of resource (i.e., for author if published,
15188:                                           or course if uploaded.).
15189:          $switchserver --  1 if server switch will be needed.
15190:          $forceedit -- 1 if icon/link should be to go to edit mode
15191:          $forceview -- 1 if icon/link should be to go to view mode
15192: 
15193: =item *
15194: 
15195: is_course_upload($file,$cnum,$cdom)
15196: 
15197: Used in course context to determine if current file was uploaded to
15198: the course (i.e., would be found in /userfiles/docs on the course's
15199: homeserver.
15200: 
15201:   input: 3 args -- filename (decluttered), course number and course domain.
15202:   output: boolean -- 1 if file was uploaded.
15203: 
15204: =back
15205: 
15206: =head2 Storing/Retreiving Data
15207: 
15208: =over 4
15209: 
15210: =item *
15211: 
15212: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash 
15213: permanently for this url; hashref needs to be given and should be a \%hashname;
15214: the remaining args aren't required and if they aren't passed or are '' they will
15215: be derived from the env (with the exception of $laststore, which is an
15216: optional arg used when a user's submission is stored in grading).
15217: $laststore is $version=$timestamp, where $version is the most recent version
15218: number retrieved for the corresponding $symb in the $namespace db file, and
15219: $timestamp is the timestamp for that transaction (UNIX time).
15220: $laststore is currently only passed when cstore() is called by
15221: structuretags::finalize_storage().
15222: 
15223: =item *
15224: 
15225: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store 
15226: but uses critical subroutine
15227: 
15228: =item *
15229: 
15230: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
15231: all args are optional
15232: 
15233: =item *
15234: 
15235: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
15236: dumps the complete (or key matching regexp) namespace into a hash
15237: ($udom, $uname, $regexp, $range are optional) for a namespace that is
15238: normally &store()ed into
15239: 
15240: $range should be either an integer '100' (give me the first 100
15241:                                            matching records)
15242:               or be  two integers sperated by a - with no spaces
15243:                  '30-50' (give me the 30th through the 50th matching
15244:                           records)
15245: 
15246: 
15247: =item *
15248: 
15249: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
15250: replaces a &store() version of data with a replacement set of data
15251: for a particular resource in a namespace passed in the $storehash hash 
15252: reference. If $tolog is true, the transaction is logged in the courselog
15253: with an action=PUTSTORE.
15254: 
15255: =item *
15256: 
15257: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
15258: works very similar to store/cstore, but all data is stored in a
15259: temporary location and can be reset using tmpreset, $storehash should
15260: be a hash reference, returns nothing on success
15261: 
15262: =item *
15263: 
15264: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
15265: similar to restore, but all data is stored in a temporary location and
15266: can be reset using tmpreset. Returns a hash of values on success,
15267: error string otherwise.
15268: 
15269: =item *
15270: 
15271: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
15272: deltes all keys for $symb form the temporary storage hash.
15273: 
15274: =item *
15275: 
15276: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
15277: reference filled in from namesp ($udom and $uname are optional)
15278: 
15279: =item *
15280: 
15281: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
15282: namesp ($udom and $uname are optional)
15283: 
15284: =item *
15285: 
15286: dump($namespace,$udom,$uname,$regexp,$range) : 
15287: dumps the complete (or key matching regexp) namespace into a hash
15288: ($udom, $uname, $regexp, $range are optional)
15289: 
15290: $range should be either an integer '100' (give me the first 100
15291:                                            matching records)
15292:               or be  two integers sperated by a - with no spaces
15293:                  '30-50' (give me the 30th through the 50th matching
15294:                           records)
15295: =item *
15296: 
15297: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
15298: $store can be a scalar, an array reference, or if the amount to be 
15299: incremented is > 1, a hash reference.
15300: 
15301: ($udom and $uname are optional)
15302: 
15303: =item *
15304: 
15305: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
15306: ($udom and $uname are optional)
15307: 
15308: =item *
15309: 
15310: cput($namespace,$storehash,$udom,$uname) : critical put
15311: ($udom and $uname are optional)
15312: 
15313: =item *
15314: 
15315: newput($namespace,$storehash,$udom,$uname) :
15316: 
15317: Attempts to store the items in the $storehash, but only if they don't
15318: currently exist, if this succeeds you can be certain that you have 
15319: successfully created a new key value pair in the $namespace db.
15320: 
15321: 
15322: Args:
15323:  $namespace: name of database to store values to
15324:  $storehash: hashref to store to the db
15325:  $udom: (optional) domain of user containing the db
15326:  $uname: (optional) name of user caontaining the db
15327: 
15328: Returns:
15329:  'ok' -> succeeded in storing all keys of $storehash
15330:  'key_exists: <key>' -> failed to anything out of $storehash, as at
15331:                         least <key> already existed in the db (other
15332:                         requested keys may also already exist)
15333:  'error: <msg>' -> unable to tie the DB or other error occurred
15334:  'con_lost' -> unable to contact request server
15335:  'refused' -> action was not allowed by remote machine
15336: 
15337: 
15338: =item *
15339: 
15340: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
15341: reference filled in from namesp (encrypts the return communication)
15342: ($udom and $uname are optional)
15343: 
15344: =item *
15345: 
15346: log($udom,$name,$home,$message) : write to permanent log for user; use
15347: critical subroutine
15348: 
15349: =item *
15350: 
15351: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
15352: array reference filled in from namespace found in domain level on either
15353: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
15354: 
15355: =item *
15356: 
15357: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
15358: domain level either on specified domain server ($uhome) or primary domain 
15359: server ($udom and $uhome are optional)
15360: 
15361: =item * 
15362: 
15363: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
15364: for: authentication, language, quotas, timezone, date locale, and portal URL in
15365: the target domain.
15366: 
15367: May also include additional key => value pairs for the following groups:
15368: 
15369: =over
15370: 
15371: =item
15372: disk quotas (MB allocated by default to portfolios and authoring spaces).
15373: 
15374: =over
15375: 
15376: =item defaultquota, authorquota
15377: 
15378: =back
15379: 
15380: =item
15381: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
15382: portfolio for users).
15383: 
15384: =over
15385: 
15386: =item
15387: aboutme, blog, webdav, portfolio
15388: 
15389: =back
15390: 
15391: =item
15392: requestcourses: ability to request courses, and how requests are processed.
15393: 
15394: =over
15395: 
15396: =item
15397: official, unofficial, community, textbook
15398: 
15399: =back
15400: 
15401: =item
15402: inststatus: types of institutional affiliation, and order in which they are displayed.
15403: 
15404: =over
15405: 
15406: =item
15407: inststatustypes, inststatusorder, inststatusguest
15408: 
15409: =back
15410: 
15411: =item
15412: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
15413: for course's uploaded content.
15414: 
15415: =over
15416: 
15417: =item
15418: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
15419: communityquota, textbookquota
15420: 
15421: =back
15422: 
15423: =item
15424: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
15425: on your servers.
15426: 
15427: =over
15428: 
15429: =item
15430: remotesessions, hostedsessions
15431: 
15432: =back
15433: 
15434: =back
15435: 
15436: In cases where a domain coordinator has never used the "Set Domain Configuration"
15437: utility to create a configuration.db file on a domain's primary library server
15438: only the following domain defaults: auth_def, auth_arg_def, lang_def
15439: -- corresponding values are authentication type (internal, krb4, krb5,
15440: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
15441: will be available. Values are retrieved from cache (if current), unless the
15442: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
15443: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
15444: 
15445: Typical usage:
15446: 
15447: %domdefaults = &get_domain_defaults($target_domain);
15448: 
15449: =back
15450: 
15451: =head2 Network Status Functions
15452: 
15453: =over 4
15454: 
15455: =item *
15456: 
15457: dirlist() : return directory list based on URI (first arg).
15458: 
15459: Inputs: 1 required, 5 optional.
15460: 
15461: =over
15462: 
15463: =item 
15464: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
15465: 
15466: =item
15467: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
15468: 
15469: =item
15470: $username -  username of user/course to be listed. Extracted from $uri if absent. 
15471: 
15472: =item
15473: $getpropath - boolean: 1 if prepend path using &propath(). 
15474: 
15475: =item
15476: $getuserdir - boolean: 1 if prepend path for "userfiles".
15477: 
15478: =item 
15479: $alternateRoot - path to prepend in place of path from $uri.
15480: 
15481: =back
15482: 
15483: Returns: Array of up to two items.
15484: 
15485: =over
15486: 
15487: a reference to an array of files/subdirectories
15488: 
15489: =over
15490: 
15491: Each element in the array of files/subdirectories is a & separated list of
15492: item name and the result of running stat on the item.  If dirlist was requested
15493: for a file instead of a directory, the item name will be ''. For a directory 
15494: listing, if the item is a metadata file, the element will end &N&M 
15495: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
15496: default copyright set (1).  
15497: 
15498: =back
15499: 
15500: a scalar containing error condition (if encountered).
15501: 
15502: =over
15503: 
15504: =item 
15505: no_host (no homeserver identified for $username:$domain).
15506: 
15507: =item 
15508: no_such_host (server contacted for listing not identified as valid host).
15509: 
15510: =item 
15511: con_lost (connection to remote server failed).
15512: 
15513: =item 
15514: refused (invalid $username:$domain received on lond side).
15515: 
15516: =item 
15517: no_such_dir (directory at specified path on lond side does not exist). 
15518: 
15519: =item 
15520: empty (directory at specified path on lond side is empty).
15521: 
15522: =over
15523: 
15524: This is currently not encountered because the &ls3, &ls2, 
15525: &ls (_handler) routines on the lond side do not filter out
15526: . and .. from a directory listing. 
15527: 
15528: =back
15529: 
15530: =back
15531: 
15532: =back
15533: 
15534: =item *
15535: 
15536: spareserver() : find server with least workload from spare.tab
15537: 
15538: 
15539: =item *
15540: 
15541: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
15542: if there is no corresponding loncapa host.
15543: 
15544: =back
15545: 
15546: 
15547: =head2 Apache Request
15548: 
15549: =over 4
15550: 
15551: =item *
15552: 
15553: ssi($url,%hash) : server side include, does a complete request cycle on url to
15554: localhost, posts hash
15555: 
15556: =back
15557: 
15558: =head2 Data to String to Data
15559: 
15560: =over 4
15561: 
15562: =item *
15563: 
15564: hash2str(%hash) : convert a hash into a string complete with escaping and '='
15565: and '&' separators, supports elements that are arrayrefs and hashrefs
15566: 
15567: =item *
15568: 
15569: hashref2str($hashref) : convert a hashref into a string complete with
15570: escaping and '=' and '&' separators, supports elements that are
15571: arrayrefs and hashrefs
15572: 
15573: =item *
15574: 
15575: arrayref2str($arrayref) : convert an arrayref into a string complete
15576: with escaping and '&' separators, supports elements that are arrayrefs
15577: and hashrefs
15578: 
15579: =item *
15580: 
15581: str2hash($string) : convert string to hash using unescaping and
15582: splitting on '=' and '&', supports elements that are arrayrefs and
15583: hashrefs
15584: 
15585: =item *
15586: 
15587: str2array($string) : convert string to hash using unescaping and
15588: splitting on '&', supports elements that are arrayrefs and hashrefs
15589: 
15590: =back
15591: 
15592: =head2 Logging Routines
15593: 
15594: 
15595: These routines allow one to make log messages in the lonnet.log and
15596: lonnet.perm logfiles.
15597: 
15598: =over 4
15599: 
15600: =item *
15601: 
15602: logtouch() : make sure the logfile, lonnet.log, exists
15603: 
15604: =item *
15605: 
15606: logthis() : append message to the normal lonnet.log file, it gets
15607: preiodically rolled over and deleted.
15608: 
15609: =item *
15610: 
15611: logperm() : append a permanent message to lonnet.perm.log, this log
15612: file never gets deleted by any automated portion of the system, only
15613: messages of critical importance should go in here.
15614: 
15615: 
15616: =back
15617: 
15618: =head2 General File Helper Routines
15619: 
15620: =over 4
15621: 
15622: =item *
15623: 
15624: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
15625: (a) files in /uploaded
15626:   (i) If a local copy of the file exists - 
15627:       compares modification date of local copy with last-modified date for 
15628:       definitive version stored on home server for course. If local copy is 
15629:       stale, requests a new version from the home server and stores it. 
15630:       If the original has been removed from the home server, then local copy 
15631:       is unlinked.
15632:   (ii) If local copy does not exist -
15633:       requests the file from the home server and stores it. 
15634:   
15635:   If $caller is 'uploadrep':  
15636:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
15637:     for request for files originally uploaded via DOCS. 
15638:      - returns 'ok' if fresh local copy now available, -1 otherwise.
15639:   
15640:   Otherwise:
15641:      This indicates a call from the content generation phase of the request.
15642:      -  returns the entire contents of the file or -1.
15643:      
15644: (b) files in /res
15645:    - returns the entire contents of a file or -1; 
15646:    it properly subscribes to and replicates the file if neccessary.
15647: 
15648: 
15649: =item *
15650: 
15651: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
15652:                   reference
15653: 
15654: returns either a stat() list of data about the file or an empty list
15655: if the file doesn't exist or couldn't find out about it (connection
15656: problems or user unknown)
15657: 
15658: =item *
15659: 
15660: filelocation($dir,$file) : returns file system location of a file
15661: based on URI; meant to be "fairly clean" absolute reference, $dir is a
15662: directory that relative $file lookups are to looked in ($dir of /a/dir
15663: and a file of ../bob will become /a/bob)
15664: 
15665: =item *
15666: 
15667: hreflocation($dir,$file) : returns file system location or a URL; same as
15668: filelocation except for hrefs
15669: 
15670: =item *
15671: 
15672: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
15673: also removes beginning /home/httpd/html unless /priv/ follows it.
15674: 
15675: =back
15676: 
15677: =head2 Usererfile file routines (/uploaded*)
15678: 
15679: =over 4
15680: 
15681: =item *
15682: 
15683: userfileupload(): main rotine for putting a file in a user or course's
15684:                   filespace, arguments are,
15685: 
15686:  formname - required - this is the name of the element in $env where the
15687:            filename, and the contents of the file to create/modifed exist
15688:            the filename is in $env{'form.'.$formname.'.filename'} and the
15689:            contents of the file is located in $env{'form.'.$formname}
15690:  context - if coursedoc, store the file in the course of the active role
15691:              of the current user; 
15692:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
15693:            if 'canceloverwrite': delete file in tmp/overwrites directory
15694:  subdir - required - subdirectory to put the file in under ../userfiles/
15695:          if undefined, it will be placed in "unknown"
15696: 
15697:  (This routine calls clean_filename() to remove any dangerous
15698:  characters from the filename, and then calls finuserfileupload() to
15699:  complete the transaction)
15700: 
15701:  returns either the url of the uploaded file (/uploaded/....) if successful
15702:  and /adm/notfound.html if unsuccessful
15703: 
15704: =item *
15705: 
15706: clean_filename(): routine for cleaing a filename up for storage in
15707:                  userfile space, argument is:
15708: 
15709:  filename - proposed filename
15710: 
15711: returns: the new clean filename
15712: 
15713: =item *
15714: 
15715: finishuserfileupload(): routine that creates and sends the file to
15716: userspace, probably shouldn't be called directly
15717: 
15718:   docuname: username or courseid of destination for the file
15719:   docudom: domain of user/course of destination for the file
15720:   formname: same as for userfileupload()
15721:   fname: filename (including subdirectories) for the file
15722:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
15723:           if hashref, and context is scantron, will convert csv format to standard format
15724:   allfiles: reference to hash used to store objects found by parser
15725:   codebase: reference to hash used for codebases of java objects found by parser
15726:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
15727:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
15728:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
15729:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
15730:   context: if 'overwrite', will move the uploaded file from its temporary location to
15731:             userfiles to facilitate overwriting a previously uploaded file with same name.
15732:   mimetype: reference to scalar to accommodate mime type determined
15733:             from File::MMagic if $parser = parse.
15734: 
15735:  returns either the url of the uploaded file (/uploaded/....) if successful
15736:  and /adm/notfound.html if unsuccessful (or an error message if context 
15737:  was 'overwrite').
15738:  
15739: 
15740: =item *
15741: 
15742: renameuserfile(): renames an existing userfile to a new name
15743: 
15744:   Args:
15745:    docuname: username or courseid of destination for the file
15746:    docudom: domain of user/course of destination for the file
15747:    old: current file name (including any subdirs under userfiles)
15748:    new: desired file name (including any subdirs under userfiles)
15749: 
15750: =item *
15751: 
15752: mkdiruserfile(): creates a directory is a userfiles dir
15753: 
15754:   Args:
15755:    docuname: username or courseid of destination for the file
15756:    docudom: domain of user/course of destination for the file
15757:    dir: dir to create (including any subdirs under userfiles)
15758: 
15759: =item *
15760: 
15761: removeuserfile(): removes a file that exists in userfiles
15762: 
15763:   Args:
15764:    docuname: username or courseid of destination for the file
15765:    docudom: domain of user/course of destination for the file
15766:    fname: filname to delete (including any subdirs under userfiles)
15767: 
15768: =item *
15769: 
15770: removeuploadedurl(): convience function for removeuserfile()
15771: 
15772:   Args:
15773:    url:  a full /uploaded/... url to delete
15774: 
15775: =item * 
15776: 
15777: get_portfile_permissions():
15778:   Args:
15779:     domain: domain of user or course contain the portfolio files
15780:     user: name of user or num of course contain the portfolio files
15781:   Returns:
15782:     hashref of a dump of the proper file_permissions.db
15783:    
15784: 
15785: =item * 
15786: 
15787: get_access_controls():
15788: 
15789: Args:
15790:   current_permissions: the hash ref returned from get_portfile_permissions()
15791:   group: (optional) the group you want the files associated with
15792:   file: (optional) the file you want access info on
15793: 
15794: Returns:
15795:     a hash (keys are file names) of hashes containing
15796:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
15797:         values are XML containing access control settings (see below) 
15798: 
15799: Internal notes:
15800: 
15801:  access controls are stored in file_permissions.db as key=value pairs.
15802:     key -> path to file/file_name\0uniqueID:scope_end_start
15803:         where scope -> public,guest,course,group,domains or users.
15804:               end -> UNIX time for end of access (0 -> no end date)
15805:               start -> UNIX time for start of access
15806: 
15807:     value -> XML description of access control
15808:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
15809:             <start></start>
15810:             <end></end>
15811: 
15812:             <password></password>  for scope type = guest
15813: 
15814:             <domain></domain>     for scope type = course or group
15815:             <number></number>
15816:             <roles id="">
15817:              <role></role>
15818:              <access></access>
15819:              <section></section>
15820:              <group></group>
15821:             </roles>
15822: 
15823:             <dom></dom>         for scope type = domains
15824: 
15825:             <users>             for scope type = users
15826:              <user>
15827:               <uname></uname>
15828:               <udom></udom>
15829:              </user>
15830:             </users>
15831:            </scope> 
15832:               
15833:  Access data is also aggregated for each file in an additional key=value pair:
15834:  key -> path to file/file_name\0accesscontrol 
15835:  value -> reference to hash
15836:           hash contains key = value pairs
15837:           where key = uniqueID:scope_end_start
15838:                 value = UNIX time record was last updated
15839: 
15840:           Used to improve speed of look-ups of access controls for each file.  
15841:  
15842:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
15843: 
15844: =item *
15845: 
15846: modify_access_controls():
15847: 
15848: Modifies access controls for a portfolio file
15849: Args
15850: 1. file name
15851: 2. reference to hash of required changes,
15852: 3. domain
15853: 4. username
15854:   where domain,username are the domain of the portfolio owner 
15855:   (either a user or a course) 
15856: 
15857: Returns:
15858: 1. result of additions or updates ('ok' or 'error', with error message). 
15859: 2. result of deletions ('ok' or 'error', with error message).
15860: 3. reference to hash of any new or updated access controls.
15861: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
15862:    key = integer (inbound ID)
15863:    value = uniqueID
15864: 
15865: =item *
15866: 
15867: get_timebased_id():
15868: 
15869: Attempts to get a unique timestamp-based suffix for use with items added to a
15870: course via the Course Editor (e.g., folders, composite pages,
15871: group bulletin boards).
15872: 
15873: Args: (first three required; six others optional)
15874: 
15875: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
15876:    docssequence, or name of group
15877: 
15878: 2. keyid (alphanumeric): name of temporary locking key in hash,
15879:    e.g., num, boardids
15880: 
15881: 3. namespace: name of gdbm file used to store suffixes already assigned;
15882:    file will be named nohist_namespace.db
15883: 
15884: 4. cdom: domain of course; default is current course domain from %env
15885: 
15886: 5. cnum: course number; default is current course number from %env
15887: 
15888: 6. idtype: set to concat if an additional digit is to be appended to the
15889:    unix timestamp to form the suffix, if the plain timestamp is already
15890:    in use.  Default is to not do this, but simply increment the unix
15891:    timestamp by 1 until a unique key is obtained.
15892: 
15893: 7. who: holder of locking key; defaults to user:domain for user.
15894: 
15895: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
15896:    retrying); default is 3.
15897: 
15898: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
15899: 
15900: Returns:
15901: 
15902: 1. suffix obtained (numeric)
15903: 
15904: 2. result of deleting locking key (ok if deleted, or lock never obtained)
15905: 
15906: 3. error: contains (localized) error message if an error occurred.
15907: 
15908: 
15909: =back
15910: 
15911: =head2 HTTP Helper Routines
15912: 
15913: =over 4
15914: 
15915: =item *
15916: 
15917: escape() : unpack non-word characters into CGI-compatible hex codes
15918: 
15919: =item *
15920: 
15921: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
15922: 
15923: =back
15924: 
15925: =head1 PRIVATE SUBROUTINES
15926: 
15927: =head2 Underlying communication routines (Shouldn't call)
15928: 
15929: =over 4
15930: 
15931: =item *
15932: 
15933: subreply() : tries to pass a message to lonc, returns con_lost if incapable
15934: 
15935: =item *
15936: 
15937: reply() : uses subreply to send a message to remote machine, logs all failures
15938: 
15939: =item *
15940: 
15941: critical() : passes a critical message to another server; if cannot
15942: get through then place message in connection buffer directory and
15943: returns con_delayed, if incapable of saving message, returns
15944: con_failed
15945: 
15946: =item *
15947: 
15948: reconlonc() : tries to reconnect lonc client processes.
15949: 
15950: =back
15951: 
15952: =head2 Resource Access Logging
15953: 
15954: =over 4
15955: 
15956: =item *
15957: 
15958: flushcourselogs() : flush (save) buffer logs and access logs
15959: 
15960: =item *
15961: 
15962: courselog($what) : save message for course in hash
15963: 
15964: =item *
15965: 
15966: courseacclog($what) : save message for course using &courselog().  Perform
15967: special processing for specific resource types (problems, exams, quizzes, etc).
15968: 
15969: =item *
15970: 
15971: goodbye() : flush course logs and log shutting down; it is called in srm.conf
15972: as a PerlChildExitHandler
15973: 
15974: =back
15975: 
15976: =head2 Other
15977: 
15978: =over 4
15979: 
15980: =item *
15981: 
15982: symblist($mapname,%newhash) : update symbolic storage links
15983: 
15984: =back
15985: 
15986: =cut
15987: 

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