File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1172.2.140.2.3: download - view: text, annotated - select for diffs
Tue Nov 9 21:04:30 2021 UTC (2 years, 7 months ago) by raeburn
Branches: version_2_11_3_uiuc
Diff to branchpoint 1.1172.2.140: preferred, unified
- For 2.11.3 (modified)
  Include changes in rev. 1.1471

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1172.2.140.2.3 2021/11/09 21:04:30 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: ###
   29: 
   30: =pod
   31: 
   32: =head1 NAME
   33: 
   34: Apache::lonnet.pm
   35: 
   36: =head1 SYNOPSIS
   37: 
   38: This file is an interface to the lonc processes of
   39: the LON-CAPA network as well as set of elaborated functions for handling information
   40: necessary for navigating through a given cluster of LON-CAPA machines within a
   41: domain. There are over 40 specialized functions in this module which handle the
   42: reading and transmission of metadata, user information (ids, names, environments, roles,
   43: logs), file information (storage, reading, directories, extensions, replication, embedded
   44: styles and descriptors), educational resources (course descriptions, section names and
   45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
   46: and from more descriptive phrases or explanations.
   47: 
   48: This is part of the LearningOnline Network with CAPA project
   49: described at http://www.lon-capa.org.
   50: 
   51: =head1 Package Variables
   52: 
   53: These are largely undocumented, so if you decipher one please note it here.
   54: 
   55: =over 4
   56: 
   57: =item $processmarker
   58: 
   59: Contains the time this process was started and this servers host id.
   60: 
   61: =item $dumpcount
   62: 
   63: Counts the number of times a message log flush has been attempted (regardless
   64: of success) by this process.  Used as part of the filename when messages are
   65: delayed.
   66: 
   67: =back
   68: 
   69: =cut
   70: 
   71: package Apache::lonnet;
   72: 
   73: use strict;
   74: use LWP::UserAgent();
   75: use HTTP::Date;
   76: use Image::Magick;
   77: use CGI::Cookie;
   78: 
   79: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir $deftex
   80:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
   81:             %managerstab $passwdmin);
   82: 
   83: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
   84:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
   85:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
   86:     %courseownerbuf, %coursetypebuf,$locknum);
   87: 
   88: use IO::Socket;
   89: use GDBM_File;
   90: use HTML::LCParser;
   91: use Fcntl qw(:flock);
   92: use Storable qw(thaw nfreeze);
   93: use Time::HiRes qw( sleep gettimeofday tv_interval );
   94: use Cache::Memcached;
   95: use Digest::MD5;
   96: use Math::Random;
   97: use File::MMagic;
   98: use LONCAPA qw(:DEFAULT :match);
   99: use LONCAPA::Configuration;
  100: use LONCAPA::lonmetadata;
  101: use LONCAPA::Lond;
  102: use LONCAPA::transliterate;
  103: 
  104: use File::Copy;
  105: 
  106: my $readit;
  107: my $max_connection_retries = 20;     # Or some such value.
  108: 
  109: require Exporter;
  110: 
  111: our @ISA = qw (Exporter);
  112: our @EXPORT = qw(%env);
  113: 
  114: # ------------------------------------ Logging (parameters, docs, slots, roles)
  115: {
  116:     my $logid;
  117:     sub write_log {
  118: 	my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
  119:         if ($context eq 'course') {
  120:             if (($cnum eq '') || ($cdom eq '')) {
  121:                 $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
  122:                 $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
  123:             }
  124:         }
  125: 	$logid ++;
  126:         my $now = time();
  127: 	my $id=$now.'00000'.$$.'00000'.$logid;
  128:         my $ip = &get_requestor_ip();  
  129:         my $logentry = {
  130:                          $id => {
  131:                                   'exe_uname' => $env{'user.name'},
  132:                                   'exe_udom'  => $env{'user.domain'},
  133:                                   'exe_time'  => $now,
  134:                                   'exe_ip'    => $ip,
  135:                                   'delflag'   => $delflag,
  136:                                   'logentry'  => $storehash,
  137:                                   'uname'     => $uname,
  138:                                   'udom'      => $udom,
  139:                                 }
  140:                        };
  141:         return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
  142:     }
  143: }
  144: 
  145: sub logtouch {
  146:     my $execdir=$perlvar{'lonDaemons'};
  147:     unless (-e "$execdir/logs/lonnet.log") {	
  148: 	open(my $fh,">>","$execdir/logs/lonnet.log");
  149: 	close $fh;
  150:     }
  151:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
  152:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
  153: }
  154: 
  155: sub logthis {
  156:     my $message=shift;
  157:     my $execdir=$perlvar{'lonDaemons'};
  158:     my $now=time;
  159:     my $local=localtime($now);
  160:     if (open(my $fh,">>","$execdir/logs/lonnet.log")) {
  161: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
  162: 	print $fh $logstring;
  163: 	close($fh);
  164:     }
  165:     return 1;
  166: }
  167: 
  168: sub logperm {
  169:     my $message=shift;
  170:     my $execdir=$perlvar{'lonDaemons'};
  171:     my $now=time;
  172:     my $local=localtime($now);
  173:     if (open(my $fh,">>","$execdir/logs/lonnet.perm.log")) {
  174: 	print $fh "$now:$message:$local\n";
  175: 	close($fh);
  176:     }
  177:     return 1;
  178: }
  179: 
  180: sub create_connection {
  181:     my ($hostname,$lonid) = @_;
  182:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
  183: 				     Type    => SOCK_STREAM,
  184: 				     Timeout => 10);
  185:     return 0 if (!$client);
  186:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
  187:     my $result = <$client>;
  188:     chomp($result);
  189:     return 1 if ($result eq 'done');
  190:     return 0;
  191: }
  192: 
  193: sub get_server_timezone {
  194:     my ($cnum,$cdom) = @_;
  195:     my $home=&homeserver($cnum,$cdom);
  196:     if ($home ne 'no_host') {
  197:         my $cachetime = 24*3600;
  198:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
  199:         if (defined($cached)) {
  200:             return $timezone;
  201:         } else {
  202:             my $timezone = &reply('servertimezone',$home);
  203:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
  204:         }
  205:     }
  206: }
  207: 
  208: sub get_server_distarch {
  209:     my ($lonhost,$ignore_cache) = @_;
  210:     if (defined($lonhost)) {
  211:         if (!defined(&hostname($lonhost))) {
  212:             return;
  213:         }
  214:         my $cachetime = 12*3600;
  215:         if (!$ignore_cache) {
  216:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
  217:             if (defined($cached)) {
  218:                 return $distarch;
  219:             }
  220:         }
  221:         my $rep = &reply('serverdistarch',$lonhost);
  222:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
  223:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
  224:                 $rep eq '') {
  225:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
  226:         }
  227:     }
  228:     return;
  229: }
  230: 
  231: sub get_server_loncaparev {
  232:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
  233:     if (defined($lonhost)) {
  234:         if (!defined(&hostname($lonhost))) {
  235:             undef($lonhost);
  236:         }
  237:     }
  238:     if (!defined($lonhost)) {
  239:         if (defined(&domain($dom,'primary'))) {
  240:             $lonhost=&domain($dom,'primary');
  241:             if ($lonhost eq 'no_host') {
  242:                 undef($lonhost);
  243:             }
  244:         }
  245:     }
  246:     if (defined($lonhost)) {
  247:         my $cachetime = 12*3600;
  248:         if (!$ignore_cache) {
  249:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
  250:             if (defined($cached)) {
  251:                 return $loncaparev;
  252:             }
  253:         }
  254:         my ($answer,$loncaparev);
  255:         my @ids=&current_machine_ids();
  256:         if (grep(/^\Q$lonhost\E$/,@ids)) {
  257:             $answer = $perlvar{'lonVersion'};
  258:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  259:                 $loncaparev = $1;
  260:             }
  261:         } else {
  262:             $answer = &reply('serverloncaparev',$lonhost);
  263:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
  264:                 if ($caller eq 'loncron') {
  265:                     my $ua=new LWP::UserAgent;
  266:                     $ua->timeout(4);
  267:                     my $hostname = &hostname($lonhost);
  268:                     my $protocol = $protocol{$lonhost};
  269:                     $protocol = 'http' if ($protocol ne 'https');
  270:                     my $url = $protocol.'://'.$hostname.'/adm/about.html';
  271:                     my $request=new HTTP::Request('GET',$url);
  272:                     my $response=$ua->request($request);
  273:                     unless ($response->is_error()) {
  274:                         my $content = $response->content;
  275:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
  276:                             $loncaparev = $1;
  277:                         }
  278:                     }
  279:                 } else {
  280:                     $loncaparev = $loncaparevs{$lonhost};
  281:                 }
  282:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  283:                 $loncaparev = $1;
  284:             }
  285:         }
  286:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
  287:     }
  288: }
  289: 
  290: sub get_server_homeID {
  291:     my ($hostname,$ignore_cache,$caller) = @_;
  292:     unless ($ignore_cache) {
  293:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
  294:         if (defined($cached)) {
  295:             return $serverhomeID;
  296:         }
  297:     }
  298:     my $cachetime = 12*3600;
  299:     my $serverhomeID;
  300:     if ($caller eq 'loncron') { 
  301:         my @machine_ids = &machine_ids($hostname);
  302:         foreach my $id (@machine_ids) {
  303:             my $response = &reply('serverhomeID',$id);
  304:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
  305:                 $serverhomeID = $response;
  306:                 last;
  307:             }
  308:         }
  309:         if ($serverhomeID eq '') {
  310:             $serverhomeID = $machine_ids[-1];
  311:         }
  312:     } else {
  313:         $serverhomeID = $serverhomeIDs{$hostname};
  314:     }
  315:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
  316: }
  317: 
  318: sub get_remote_globals {
  319:     my ($lonhost,$whathash,$ignore_cache) = @_;
  320:     my ($result,%returnhash,%whatneeded);
  321:     if (ref($whathash) eq 'HASH') {
  322:         foreach my $what (sort(keys(%{$whathash}))) {
  323:             my $hashid = $lonhost.'-'.$what;
  324:             my ($response,$cached);
  325:             unless ($ignore_cache) {
  326:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
  327:             }
  328:             if (defined($cached)) {
  329:                 $returnhash{$what} = $response;
  330:             } else {
  331:                 $whatneeded{$what} = 1;
  332:             }
  333:         }
  334:         if (keys(%whatneeded) == 0) {
  335:             $result = 'ok';
  336:         } else {
  337:             my $requested = &freeze_escape(\%whatneeded);
  338:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
  339:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
  340:                 ($rep eq 'unknown_cmd')) {
  341:                 $result = $rep;
  342:             } else {
  343:                 $result = 'ok';
  344:                 my @pairs=split(/\&/,$rep);
  345:                 foreach my $item (@pairs) {
  346:                     my ($key,$value)=split(/=/,$item,2);
  347:                     my $what = &unescape($key);
  348:                     my $hashid = $lonhost.'-'.$what;
  349:                     $returnhash{$what}=&thaw_unescape($value);
  350:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
  351:                 }
  352:             }
  353:         }
  354:     }
  355:     return ($result,\%returnhash);
  356: }
  357: 
  358: sub remote_devalidate_cache {
  359:     my ($lonhost,$cachekeys) = @_;
  360:     my $items;
  361:     return unless (ref($cachekeys) eq 'ARRAY');
  362:     my $cachestr = join('&',@{$cachekeys});
  363:     return &reply('devalidatecache:'.&escape($cachestr),$lonhost);
  364: }
  365: 
  366: # -------------------------------------------------- Non-critical communication
  367: sub subreply {
  368:     my ($cmd,$server)=@_;
  369:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
  370:     #
  371:     #  With loncnew process trimming, there's a timing hole between lonc server
  372:     #  process exit and the master server picking up the listen on the AF_UNIX
  373:     #  socket.  In that time interval, a lock file will exist:
  374: 
  375:     my $lockfile=$peerfile.".lock";
  376:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
  377: 	sleep(0.1);
  378:     }
  379:     # At this point, either a loncnew parent is listening or an old lonc
  380:     # or loncnew child is listening so we can connect or everything's dead.
  381:     #
  382:     #   We'll give the connection a few tries before abandoning it.  If
  383:     #   connection is not possible, we'll con_lost back to the client.
  384:     #   
  385:     my $client;
  386:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
  387: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  388: 				      Type    => SOCK_STREAM,
  389: 				      Timeout => 10);
  390: 	if ($client) {
  391: 	    last;		# Connected!
  392: 	} else {
  393: 	    &create_connection(&hostname($server),$server);
  394: 	}
  395:         sleep(0.1);		# Try again later if failed connection.
  396:     }
  397:     my $answer;
  398:     if ($client) {
  399: 	print $client "sethost:$server:$cmd\n";
  400: 	$answer=<$client>;
  401: 	if (!$answer) { $answer="con_lost"; }
  402: 	chomp($answer);
  403:     } else {
  404: 	$answer = 'con_lost';	# Failed connection.
  405:     }
  406:     return $answer;
  407: }
  408: 
  409: sub reply {
  410:     my ($cmd,$server)=@_;
  411:     unless (defined(&hostname($server))) { return 'no_such_host'; }
  412:     my $answer=subreply($cmd,$server);
  413:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
  414:         my $logged = $cmd;
  415:         if ($cmd =~ /^encrypt:([^:]+):/) {
  416:             my $subcmd = $1;
  417:             if (($subcmd eq 'auth') || ($subcmd eq 'passwd') ||
  418:                 ($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
  419:                 ($subcmd eq 'putdom') || ($subcmd eq 'autoexportgrades')) {
  420:                 (undef,undef,my @rest) = split(/:/,$cmd);
  421:                 if (($subcmd eq 'auth') || ($subcmd eq 'putdom')) {
  422:                     splice(@rest,2,1,'Hidden');
  423:                 } elsif ($subcmd eq 'passwd') {
  424:                     splice(@rest,2,2,('Hidden','Hidden'));
  425:                 } elsif (($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
  426:                          ($subcmd eq 'autoexportgrades')) {
  427:                     splice(@rest,3,1,'Hidden');
  428:                 }
  429:                 $logged = join(':',('encrypt:'.$subcmd,@rest));
  430:             }
  431:         }
  432:         &logthis("<font color=\"blue\">WARNING:".
  433:                  " $logged to $server returned $answer</font>");
  434:     }
  435:     return $answer;
  436: }
  437: 
  438: # ----------------------------------------------------------- Send USR1 to lonc
  439: 
  440: sub reconlonc {
  441:     my ($lonid) = @_;
  442:     if ($lonid) {
  443:         my $hostname = &hostname($lonid);
  444: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
  445: 	if ($hostname && -e $peerfile) {
  446: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
  447: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
  448: 					     Type    => SOCK_STREAM,
  449: 					     Timeout => 10);
  450: 	    if ($client) {
  451: 		print $client ("reset_retries\n");
  452: 		my $answer=<$client>;
  453: 		#reset just this one.
  454: 	    }
  455: 	}
  456: 	return;
  457:     }
  458: 
  459:     &logthis("Trying to reconnect lonc");
  460:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  461:     if (open(my $fh,"<",$loncfile)) {
  462: 	my $loncpid=<$fh>;
  463:         chomp($loncpid);
  464:         if (kill 0 => $loncpid) {
  465: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  466:             kill USR1 => $loncpid;
  467:             sleep 1;
  468:          } else {
  469: 	    &logthis(
  470:                "<font color=\"blue\">WARNING:".
  471:                " lonc at pid $loncpid not responding, giving up</font>");
  472:         }
  473:     } else {
  474: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
  475:     }
  476: }
  477: 
  478: # ------------------------------------------------------ Critical communication
  479: 
  480: sub critical {
  481:     my ($cmd,$server)=@_;
  482:     unless (&hostname($server)) {
  483:         &logthis("<font color=\"blue\">WARNING:".
  484:                " Critical message to unknown server ($server)</font>");
  485:         return 'no_such_host';
  486:     }
  487:     my $answer=reply($cmd,$server);
  488:     if ($answer eq 'con_lost') {
  489: 	&reconlonc($server);
  490: 	my $answer=reply($cmd,$server);
  491:         if ($answer eq 'con_lost') {
  492:             my $now=time;
  493:             my $middlename=$cmd;
  494:             $middlename=substr($middlename,0,16);
  495:             $middlename=~s/\W//g;
  496:             my $dfilename=
  497:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
  498:             $dumpcount++;
  499:             {
  500: 		my $dfh;
  501: 		if (open($dfh,">",$dfilename)) {
  502: 		    print $dfh "$cmd\n"; 
  503: 		    close($dfh);
  504: 		}
  505:             }
  506:             sleep 1;
  507:             my $wcmd='';
  508:             {
  509: 		my $dfh;
  510: 		if (open($dfh,"<",$dfilename)) {
  511: 		    $wcmd=<$dfh>; 
  512: 		    close($dfh);
  513: 		}
  514:             }
  515:             chomp($wcmd);
  516:             if ($wcmd eq $cmd) {
  517: 		&logthis("<font color=\"blue\">WARNING: ".
  518:                          "Connection buffer $dfilename: $cmd</font>");
  519:                 &logperm("D:$server:$cmd");
  520: 	        return 'con_delayed';
  521:             } else {
  522:                 &logthis("<font color=\"red\">CRITICAL:"
  523:                         ." Critical connection failed: $server $cmd</font>");
  524:                 &logperm("F:$server:$cmd");
  525:                 return 'con_failed';
  526:             }
  527:         }
  528:     }
  529:     return $answer;
  530: }
  531: 
  532: # ------------------------------------------- check if return value is an error
  533: 
  534: sub error {
  535:     my ($result) = @_;
  536:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
  537: 	if ($2 == 2) { return undef; }
  538: 	return $1;
  539:     }
  540:     return undef;
  541: }
  542: 
  543: sub convert_and_load_session_env {
  544:     my ($lonidsdir,$handle)=@_;
  545:     my @profile;
  546:     {
  547: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  548: 	if (!$opened) {
  549: 	    return 0;
  550: 	}
  551: 	flock($idf,LOCK_SH);
  552: 	@profile=<$idf>;
  553: 	close($idf);
  554:     }
  555:     my %temp_env;
  556:     foreach my $line (@profile) {
  557: 	if ($line !~ m/=/) {
  558: 	    return 0;
  559: 	}
  560: 	chomp($line);
  561: 	my ($envname,$envvalue)=split(/=/,$line,2);
  562: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
  563:     }
  564:     unlink("$lonidsdir/$handle.id");
  565:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
  566: 	    0640)) {
  567: 	%disk_env = %temp_env;
  568: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
  569: 	untie(%disk_env);
  570:     }
  571:     return 1;
  572: }
  573: 
  574: # ------------------------------------------- Transfer profile into environment
  575: my $env_loaded;
  576: sub transfer_profile_to_env {
  577:     my ($lonidsdir,$handle,$force_transfer) = @_;
  578:     if (!$force_transfer && $env_loaded) { return; } 
  579: 
  580:     if (!defined($lonidsdir)) {
  581: 	$lonidsdir = $perlvar{'lonIDsDir'};
  582:     }
  583:     if (!defined($handle)) {
  584:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
  585:     }
  586: 
  587:     my $convert;
  588:     {
  589:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  590: 	if (!$opened) {
  591: 	    return;
  592: 	}
  593: 	flock($idf,LOCK_SH);
  594: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  595: 		&GDBM_READER(),0640)) {
  596: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
  597: 	    untie(%disk_env);
  598: 	} else {
  599: 	    $convert = 1;
  600: 	}
  601:     }
  602:     if ($convert) {
  603: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
  604: 	    &logthis("Failed to load session, or convert session.");
  605: 	}
  606:     }
  607: 
  608:     my %remove;
  609:     while ( my $envname = each(%env) ) {
  610:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  611:             if ($time < time-300) {
  612:                 $remove{$key}++;
  613:             }
  614:         }
  615:     }
  616: 
  617:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  618:     $env_loaded=1;
  619:     foreach my $expired_key (keys(%remove)) {
  620:         &delenv($expired_key);
  621:     }
  622: }
  623: 
  624: # ---------------------------------------------------- Check for valid session 
  625: sub check_for_valid_session {
  626:     my ($r,$name,$userhashref,$domref) = @_;
  627:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
  628:     my ($lonidsdir,$linkname,$pubname,$secure,$lonid);
  629:     if ($name eq 'lonDAV') {
  630:         $lonidsdir=$r->dir_config('lonDAVsessDir');
  631:     } else {
  632:         $lonidsdir=$r->dir_config('lonIDsDir');
  633:         if ($name eq '') {
  634:             $name = 'lonID';
  635:         }
  636:     }
  637:     if ($name eq 'lonID') {
  638:         $secure = 'lonSID';
  639:         $linkname = 'lonLinkID';
  640:         $pubname = 'lonPubID';
  641:         if (exists($cookies{$secure})) {
  642:             $lonid=$cookies{$secure};
  643:         } elsif (exists($cookies{$name})) {
  644:             $lonid=$cookies{$name};
  645:         } elsif ((exists($cookies{$linkname})) && ($ENV{'SERVER_PORT'} != 443)) {
  646:             $lonid=$cookies{$linkname};
  647:         } elsif (exists($cookies{$pubname})) {
  648:             $lonid=$cookies{$pubname};
  649:         }
  650:     } else {
  651:         $lonid=$cookies{$name};
  652:     }
  653:     return undef if (!$lonid);
  654: 
  655:     my $handle=&LONCAPA::clean_handle($lonid->value);
  656:     if (-l "$lonidsdir/$handle.id") {
  657:         my $link = readlink("$lonidsdir/$handle.id");
  658:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
  659:             $handle = $1;
  660:         }
  661:     }
  662:     if (!-e "$lonidsdir/$handle.id") {
  663:         if ((ref($domref)) && ($name eq 'lonID') &&
  664:             ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
  665:             my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
  666:             if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
  667:                 $$domref = $possudom;
  668:             }
  669:         }
  670:         return undef;
  671:     }
  672: 
  673:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  674:     return undef if (!$opened);
  675: 
  676:     flock($idf,LOCK_SH);
  677:     my %disk_env;
  678:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  679: 	    &GDBM_READER(),0640)) {
  680: 	return undef;	
  681:     }
  682: 
  683:     if (!defined($disk_env{'user.name'})
  684: 	|| !defined($disk_env{'user.domain'})) {
  685:         untie(%disk_env);
  686: 	return undef;
  687:     }
  688: 
  689:     if (ref($userhashref) eq 'HASH') {
  690:         $userhashref->{'name'} = $disk_env{'user.name'};
  691:         $userhashref->{'domain'} = $disk_env{'user.domain'};
  692:     }
  693:     untie(%disk_env);
  694: 
  695:     return $handle;
  696: }
  697: 
  698: sub timed_flock {
  699:     my ($file,$lock_type) = @_;
  700:     my $failed=0;
  701:     eval {
  702: 	local $SIG{__DIE__}='DEFAULT';
  703: 	local $SIG{ALRM}=sub {
  704: 	    $failed=1;
  705: 	    die("failed lock");
  706: 	};
  707: 	alarm(13);
  708: 	flock($file,$lock_type);
  709: 	alarm(0);
  710:     };
  711:     if ($failed) {
  712: 	return undef;
  713:     } else {
  714: 	return 1;
  715:     }
  716: }
  717: 
  718: sub get_sessionfile_vars {
  719:     my ($handle,$lonidsdir,$storearr) = @_;
  720:     my %returnhash;
  721:     unless (ref($storearr) eq 'ARRAY') {
  722:         return %returnhash;
  723:     }
  724:     if (-l "$lonidsdir/$handle.id") {
  725:         my $link = readlink("$lonidsdir/$handle.id");
  726:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
  727:             $handle = $1;
  728:         }
  729:     }
  730:     if ((-e "$lonidsdir/$handle.id") &&
  731:         ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
  732:         my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
  733:         if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
  734:             if (open(my $idf,'+<',"$lonidsdir/$handle.id")) {
  735:                 flock($idf,LOCK_SH);
  736:                 if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  737:                         &GDBM_READER(),0640)) {
  738:                     foreach my $item (@{$storearr}) {
  739:                         $returnhash{$item} = $disk_env{$item};
  740:                     }
  741:                     untie(%disk_env);
  742:                 }
  743:             }
  744:         }
  745:     }
  746:     return %returnhash;
  747: }
  748: 
  749: # ---------------------------------------------------------- Append Environment
  750: 
  751: sub appenv {
  752:     my ($newenv,$roles) = @_;
  753:     if (ref($newenv) eq 'HASH') {
  754:         foreach my $key (keys(%{$newenv})) {
  755:             my $refused = 0;
  756: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
  757:                 $refused = 1;
  758:                 if (ref($roles) eq 'ARRAY') {
  759:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
  760:                     if (grep(/^\Q$role\E$/,@{$roles})) {
  761:                         $refused = 0;
  762:                     }
  763:                 }
  764:             }
  765:             if ($refused) {
  766:                 &logthis("<font color=\"blue\">WARNING: ".
  767:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
  768:                          .'</font>');
  769: 	        delete($newenv->{$key});
  770:             } else {
  771:                 $env{$key}=$newenv->{$key};
  772:             }
  773:         }
  774:         my $lonids = $perlvar{'lonIDsDir'};
  775:         if ($env{'user.environment'} =~ m{^\Q$lonids/\E$match_username\_\d+\_$match_domain\_[\w\-.]+\.id$}) {
  776:             my $opened = open(my $env_file,'+<',$env{'user.environment'});
  777:             if ($opened
  778: 	        && &timed_flock($env_file,LOCK_EX)
  779: 	        &&
  780: 	        tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  781: 	            (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  782: 	        while (my ($key,$value) = each(%{$newenv})) {
  783: 	            $disk_env{$key} = $value;
  784: 	        }
  785: 	        untie(%disk_env);
  786:             }
  787:         }
  788:     }
  789:     return 'ok';
  790: }
  791: # ----------------------------------------------------- Delete from Environment
  792: 
  793: sub delenv {
  794:     my ($delthis,$regexp,$roles) = @_;
  795:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
  796:         my $refused = 1;
  797:         if (ref($roles) eq 'ARRAY') {
  798:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
  799:             if (grep(/^\Q$role\E$/,@{$roles})) {
  800:                 $refused = 0;
  801:             }
  802:         }
  803:         if ($refused) {
  804:             &logthis("<font color=\"blue\">WARNING: ".
  805:                      "Attempt to delete from environment ".$delthis);
  806:             return 'error';
  807:         }
  808:     }
  809:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
  810:     if ($opened
  811: 	&& &timed_flock($env_file,LOCK_EX)
  812: 	&&
  813: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  814: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  815: 	foreach my $key (keys(%disk_env)) {
  816: 	    if ($regexp) {
  817:                 if ($key=~/^$delthis/) {
  818:                     delete($env{$key});
  819:                     delete($disk_env{$key});
  820:                 } 
  821:             } else {
  822:                 if ($key=~/^\Q$delthis\E/) {
  823: 		    delete($env{$key});
  824: 		    delete($disk_env{$key});
  825: 	        }
  826:             }
  827: 	}
  828: 	untie(%disk_env);
  829:     }
  830:     return 'ok';
  831: }
  832: 
  833: sub get_env_multiple {
  834:     my ($name) = @_;
  835:     my @values;
  836:     if (defined($env{$name})) {
  837:         # exists is it an array
  838:         if (ref($env{$name})) {
  839:             @values=@{ $env{$name} };
  840:         } else {
  841:             $values[0]=$env{$name};
  842:         }
  843:     }
  844:     return(@values);
  845: }
  846: 
  847: # ------------------------------------------------------------------- Locking
  848: 
  849: sub set_lock {
  850:     my ($text)=@_;
  851:     $locknum++;
  852:     my $id=$$.'-'.$locknum;
  853:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
  854:              'session.lock.'.$id => $text});
  855:     return $id;
  856: }
  857: 
  858: sub get_locks {
  859:     my $num=0;
  860:     my %texts=();
  861:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  862:        if ($lock=~/\w/) {
  863:           $num++;
  864:           $texts{$lock}=$env{'session.lock.'.$lock};
  865:        }
  866:    }
  867:    return ($num,%texts);
  868: }
  869: 
  870: sub remove_lock {
  871:     my ($id)=@_;
  872:     my $newlocks='';
  873:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  874:        if (($lock=~/\w/) && ($lock ne $id)) {
  875:           $newlocks.=','.$lock;
  876:        }
  877:     }
  878:     &appenv({'session.locks' => $newlocks});
  879:     &delenv('session.lock.'.$id);
  880: }
  881: 
  882: sub remove_all_locks {
  883:     my $activelocks=$env{'session.locks'};
  884:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  885:        if ($lock=~/\w/) {
  886:           &remove_lock($lock);
  887:        }
  888:     }
  889: }
  890: 
  891: 
  892: # ------------------------------------------ Find out current server userload
  893: sub userload {
  894:     my $numusers=0;
  895:     {
  896: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  897: 	my $filename;
  898: 	my $curtime=time;
  899: 	while ($filename=readdir(LONIDS)) {
  900: 	    next if ($filename eq '.' || $filename eq '..');
  901: 	    next if ($filename =~ /publicuser_\d+\.id/);
  902:             next if ($filename =~ /^[a-f0-9]+_linked\.id$/);
  903: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  904: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  905: 	}
  906: 	closedir(LONIDS);
  907:     }
  908:     my $userloadpercent=0;
  909:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  910:     if ($maxuserload) {
  911: 	$userloadpercent=100*$numusers/$maxuserload;
  912:     }
  913:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  914:     return $userloadpercent;
  915: }
  916: 
  917: # ------------------------------ Find server with least workload from spare.tab
  918: 
  919: sub spareserver {
  920:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
  921:     my $spare_server;
  922:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  923:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
  924:                                                      :  $userloadpercent;
  925:     my ($uint_dom,$remotesessions);
  926:     if (($udom ne '') && (&domain($udom) ne '')) {
  927:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
  928:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
  929:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
  930:         $remotesessions = $udomdefaults{'remotesessions'};
  931:     }
  932:     my $spareshash = &this_host_spares($udom);
  933:     if (ref($spareshash) eq 'HASH') {
  934:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
  935:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
  936:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
  937:                                              $try_server));
  938: 	        ($spare_server, $lowest_load) =
  939: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
  940:             }
  941:         }
  942: 
  943:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
  944: 
  945:         if (!$found_server) {
  946:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
  947: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
  948:                     next unless (&spare_can_host($udom,$uint_dom,
  949:                                                  $remotesessions,$try_server));
  950: 	            ($spare_server, $lowest_load) =
  951: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
  952:                 }
  953: 	    }
  954:         }
  955:     }
  956: 
  957:     if (!$want_server_name) {
  958:         if (defined($spare_server)) {
  959:             my $hostname = &hostname($spare_server);
  960:             if (defined($hostname)) {
  961:                 my $protocol = 'http';
  962:                 if ($protocol{$spare_server} eq 'https') {
  963:                     $protocol = $protocol{$spare_server};
  964:                 }
  965: 	        $spare_server = $protocol.'://'.$hostname;
  966:             }
  967:         }
  968:     }
  969:     return $spare_server;
  970: }
  971: 
  972: sub compare_server_load {
  973:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
  974: 
  975:     if ($required) {
  976:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
  977:         my $remoterev = &get_server_loncaparev(undef,$try_server);
  978:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
  979:         if (($major eq '' && $minor eq '') ||
  980:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
  981:             return ($spare_server,$lowest_load);
  982:         }
  983:     }
  984: 
  985:     my $loadans     = &reply('load',    $try_server);
  986:     my $userloadans = &reply('userload',$try_server);
  987: 
  988:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
  989: 	return ($spare_server, $lowest_load); #didn't get a number from the server
  990:     }
  991: 
  992:     my $load;
  993:     if ($loadans =~ /\d/) {
  994: 	if ($userloadans =~ /\d/) {
  995: 	    #both are numbers, pick the bigger one
  996: 	    $load = ($loadans > $userloadans) ? $loadans 
  997: 		                              : $userloadans;
  998: 	} else {
  999: 	    $load = $loadans;
 1000: 	}
 1001:     } else {
 1002: 	$load = $userloadans;
 1003:     }
 1004: 
 1005:     if (($load =~ /\d/) && ($load < $lowest_load)) {
 1006: 	$spare_server = $try_server;
 1007: 	$lowest_load  = $load;
 1008:     }
 1009:     return ($spare_server,$lowest_load);
 1010: }
 1011: 
 1012: # --------------------------- ask offload servers if user already has a session
 1013: sub find_existing_session {
 1014:     my ($udom,$uname) = @_;
 1015:     my $spareshash = &this_host_spares($udom);
 1016:     if (ref($spareshash) eq 'HASH') {
 1017:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
 1018:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
 1019:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
 1020:             }
 1021:         }
 1022:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
 1023:             foreach my $try_server (@{ $spareshash->{'default'} }) {
 1024:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
 1025:             }
 1026:         }
 1027:     }
 1028:     return;
 1029: }
 1030: 
 1031: # check if user's browser sent load balancer cookie and server still has session
 1032: # and is not overloaded.
 1033: sub check_for_balancer_cookie {
 1034:     my ($r,$update_mtime) = @_;
 1035:     my ($otherserver,$cookie);
 1036:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
 1037:     if (exists($cookies{'balanceID'})) {
 1038:         my $balid = $cookies{'balanceID'};
 1039:         $cookie=&LONCAPA::clean_handle($balid->value);
 1040:         my $balancedir=$r->dir_config('lonBalanceDir');
 1041:         if ((-d $balancedir) && (-e "$balancedir/$cookie.id")) {
 1042:             if ($cookie =~ /^($match_domain)_($match_username)_[a-f0-9]+$/) {
 1043:                 my ($possudom,$possuname) = ($1,$2);
 1044:                 my $has_session = 0;
 1045:                 if ((&domain($possudom) ne '') &&
 1046:                     (&homeserver($possuname,$possudom) ne 'no_host')) {
 1047:                     my $try_server;
 1048:                     my $opened = open(my $idf,'+<',"$balancedir/$cookie.id");
 1049:                     if ($opened) {
 1050:                         flock($idf,LOCK_SH);
 1051:                         while (my $line = <$idf>) {
 1052:                             chomp($line);
 1053:                             if (&hostname($line) ne '') {
 1054:                                 $try_server = $line;
 1055:                                 last;
 1056:                             }
 1057:                         }
 1058:                         close($idf);
 1059:                         if (($try_server) &&
 1060:                             (&has_user_session($try_server,$possudom,$possuname))) {
 1061:                             my $lowest_load = 30000;
 1062:                             ($otherserver,$lowest_load) =
 1063:                                 &compare_server_load($try_server,undef,$lowest_load);
 1064:                             if ($otherserver ne '' && $lowest_load < 100) {
 1065:                                 $has_session = 1;
 1066:                             } else {
 1067:                                 undef($otherserver);
 1068:                             }
 1069:                         }
 1070:                     }
 1071:                 }
 1072:                 if ($has_session) {
 1073:                     if ($update_mtime) {
 1074:                         my $atime = my $mtime = time;
 1075:                         utime($atime,$mtime,"$balancedir/$cookie.id");
 1076:                     }
 1077:                 } else {
 1078:                     unlink("$balancedir/$cookie.id");
 1079:                 }
 1080:             }
 1081:         }
 1082:     }
 1083:     return ($otherserver,$cookie);
 1084: }
 1085: 
 1086: sub updatebalcookie {
 1087:     my ($cookie,$balancer,$lastentry)=@_;
 1088:     if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
 1089:         my ($udom,$uname) = ($1,$2);
 1090:         my $uprimary_id = &domain($udom,'primary');
 1091:         my $uintdom = &internet_dom($uprimary_id);
 1092:         my $intdom = &internet_dom($balancer);
 1093:         my $serverhomedom = &host_domain($balancer);
 1094:         if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1095:             return &reply('updatebalcookie:'.&escape($cookie).':'.&escape($lastentry),$balancer);
 1096:         }
 1097:     }
 1098:     return;
 1099: }
 1100: 
 1101: sub delbalcookie {
 1102:     my ($cookie,$balancer) =@_;
 1103:     if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
 1104:         my ($udom,$uname) = ($1,$2);
 1105:         my $uprimary_id = &domain($udom,'primary');
 1106:         my $uintdom = &internet_dom($uprimary_id);
 1107:         my $intdom = &internet_dom($balancer);
 1108:         my $serverhomedom = &host_domain($balancer);
 1109:         if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1110:             return &reply('delbalcookie:'.&escape($cookie),$balancer);
 1111:         }
 1112:     }
 1113: }
 1114: 
 1115: # -------------------------------- ask if server already has a session for user
 1116: sub has_user_session {
 1117:     my ($lonid,$udom,$uname) = @_;
 1118:     my $result = &reply(join(':','userhassession',
 1119: 			     map {&escape($_)} ($udom,$uname)),$lonid);
 1120:     return 1 if ($result eq 'ok');
 1121: 
 1122:     return 0;
 1123: }
 1124: 
 1125: # --------- determine least loaded server in a user's domain which allows login
 1126: 
 1127: sub choose_server {
 1128:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
 1129:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
 1130:     my %servers = &get_servers($udom);
 1131:     my $lowest_load = 30000;
 1132:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
 1133:     if ($skiploadbal) {
 1134:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
 1135:         unless (defined($cached)) {
 1136:             my $cachetime = 60*60*24;
 1137:             my %domconfig =
 1138:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
 1139:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1140:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
 1141:                                            $cachetime);
 1142:             }
 1143:         }
 1144:     }
 1145:     foreach my $lonhost (keys(%servers)) {
 1146:         my $loginvia;
 1147:         if ($skiploadbal) {
 1148:             if (ref($balancers) eq 'HASH') {
 1149:                 next if (exists($balancers->{$lonhost}));
 1150:             }
 1151:         }
 1152:         if ($checkloginvia) {
 1153:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
 1154:             if ($loginvia) {
 1155:                 my ($server,$path) = split(/:/,$loginvia);
 1156:                 ($login_host, $lowest_load) =
 1157:                     &compare_server_load($server, $login_host, $lowest_load, $required);
 1158:                 if ($login_host eq $server) {
 1159:                     $portal_path = $path;
 1160:                     $isredirect = 1;
 1161:                 }
 1162:             } else {
 1163:                 ($login_host, $lowest_load) =
 1164:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
 1165:                 if ($login_host eq $lonhost) {
 1166:                     $portal_path = '';
 1167:                     $isredirect = ''; 
 1168:                 }
 1169:             }
 1170:         } else {
 1171:             ($login_host, $lowest_load) =
 1172:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
 1173:         }
 1174:     }
 1175:     if ($login_host ne '') {
 1176:         $hostname = &hostname($login_host);
 1177:     }
 1178:     return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
 1179: }
 1180: 
 1181: sub get_course_sessions {
 1182:     my ($cnum,$cdom,$lastactivity) = @_;
 1183:     my %servers = &internet_dom_servers($cdom);
 1184:     my %returnhash;
 1185:     foreach my $server (sort(keys(%servers))) {
 1186:         my $rep = &reply("coursesessions:$cdom:$cnum:$lastactivity",$server);
 1187:         my @pairs=split(/\&/,$rep);
 1188:         unless (($rep eq 'unknown_cmd') || ($rep =~ /^error/)) {
 1189:             foreach my $item (@pairs) {
 1190:                 my ($key,$value)=split(/=/,$item,2);
 1191:                 $key = &unescape($key);
 1192:                 next if ($key =~ /^error: 2 /);
 1193:                 if (exists($returnhash{$key})) {
 1194:                     next if ($value < $returnhash{$key});
 1195:                 }
 1196:                 $returnhash{$key}=$value;
 1197:             }
 1198:         }
 1199:     }
 1200:     return %returnhash;
 1201: }
 1202: 
 1203: # --------------------------------------------- Try to change a user's password
 1204: 
 1205: sub changepass {
 1206:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
 1207:     $currentpass = &escape($currentpass);
 1208:     $newpass     = &escape($newpass);
 1209:     my $lonhost = $perlvar{'lonHostID'};
 1210:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
 1211: 		       $server);
 1212:     if (! $answer) {
 1213: 	&logthis("No reply on password change request to $server ".
 1214: 		 "by $uname in domain $udom.");
 1215:     } elsif ($answer =~ "^ok") {
 1216:         &logthis("$uname in $udom successfully changed their password ".
 1217: 		 "on $server.");
 1218:     } elsif ($answer =~ "^pwchange_failure") {
 1219: 	&logthis("$uname in $udom was unable to change their password ".
 1220: 		 "on $server.  The action was blocked by either lcpasswd ".
 1221: 		 "or pwchange");
 1222:     } elsif ($answer =~ "^non_authorized") {
 1223:         &logthis("$uname in $udom did not get their password correct when ".
 1224: 		 "attempting to change it on $server.");
 1225:     } elsif ($answer =~ "^auth_mode_error") {
 1226:         &logthis("$uname in $udom attempted to change their password despite ".
 1227: 		 "not being locally or internally authenticated on $server.");
 1228:     } elsif ($answer =~ "^unknown_user") {
 1229:         &logthis("$uname in $udom attempted to change their password ".
 1230: 		 "on $server but were unable to because $server is not ".
 1231: 		 "their home server.");
 1232:     } elsif ($answer =~ "^refused") {
 1233: 	&logthis("$server refused to change $uname in $udom password because ".
 1234: 		 "it was sent an unencrypted request to change the password.");
 1235:     } elsif ($answer =~ "invalid_client") {
 1236:         &logthis("$server refused to change $uname in $udom password because ".
 1237:                  "it was a reset by e-mail originating from an invalid server.");
 1238:     } elsif ($answer =~ "^prioruse") {
 1239:        &logthis("$server refused to change $uname in $udom password because ".
 1240:                 "the password had been used before");
 1241:     }
 1242:     return $answer;
 1243: }
 1244: 
 1245: # ----------------------- Try to determine user's current authentication scheme
 1246: 
 1247: sub queryauthenticate {
 1248:     my ($uname,$udom)=@_;
 1249:     my $uhome=&homeserver($uname,$udom);
 1250:     if (!$uhome) {
 1251: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
 1252: 	return 'no_host';
 1253:     }
 1254:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
 1255:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
 1256: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1257:     }
 1258:     return $answer;
 1259: }
 1260: 
 1261: # --------- Try to authenticate user from domain's lib servers (first this one)
 1262: 
 1263: sub authenticate {
 1264:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
 1265:     $upass=&escape($upass);
 1266:     $uname= &LONCAPA::clean_username($uname);
 1267:     my $uhome=&homeserver($uname,$udom,1);
 1268:     my $newhome;
 1269:     if ((!$uhome) || ($uhome eq 'no_host')) {
 1270: # Maybe the machine was offline and only re-appeared again recently?
 1271:         &reconlonc();
 1272: # One more
 1273: 	$uhome=&homeserver($uname,$udom,1);
 1274:         if (($uhome eq 'no_host') && $checkdefauth) {
 1275:             if (defined(&domain($udom,'primary'))) {
 1276:                 $newhome=&domain($udom,'primary');
 1277:             }
 1278:             if ($newhome ne '') {
 1279:                 $uhome = $newhome;
 1280:             }
 1281:         }
 1282: 	if ((!$uhome) || ($uhome eq 'no_host')) {
 1283: 	    &logthis("User $uname at $udom is unknown in authenticate");
 1284: 	    return 'no_host';
 1285:         }
 1286:     }
 1287:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
 1288:     if ($answer eq 'authorized') {
 1289:         if ($newhome) {
 1290:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
 1291:             return 'no_account_on_host'; 
 1292:         } else {
 1293:             &logthis("User $uname at $udom authorized by $uhome");
 1294:             return $uhome;
 1295:         }
 1296:     }
 1297:     if ($answer eq 'non_authorized') {
 1298: 	&logthis("User $uname at $udom rejected by $uhome");
 1299: 	return 'no_host'; 
 1300:     }
 1301:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1302:     return 'no_host';
 1303: }
 1304: 
 1305: sub can_host_session {
 1306:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
 1307:     my $canhost = 1;
 1308:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
 1309:     if (ref($remotesessions) eq 'HASH') {
 1310:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
 1311:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
 1312:                 $canhost = 0;
 1313:             } else {
 1314:                 $canhost = 1;
 1315:             }
 1316:         }
 1317:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
 1318:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
 1319:                 $canhost = 1;
 1320:             } else {
 1321:                 $canhost = 0;
 1322:             }
 1323:         }
 1324:         if ($canhost) {
 1325:             if ($remotesessions->{'version'} ne '') {
 1326:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
 1327:                 if ($reqmajor ne '' && $reqminor ne '') {
 1328:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
 1329:                         my $major = $1;
 1330:                         my $minor = $2;
 1331:                         if (($major < $reqmajor ) ||
 1332:                             (($major == $reqmajor) && ($minor < $reqminor))) {
 1333:                             $canhost = 0;
 1334:                         }
 1335:                     } else {
 1336:                         $canhost = 0;
 1337:                     }
 1338:                 }
 1339:             }
 1340:         }
 1341:     }
 1342:     if ($canhost) {
 1343:         if (ref($hostedsessions) eq 'HASH') {
 1344:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1345:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
 1346:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
 1347:                 if (($uint_dom ne '') && 
 1348:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
 1349:                     $canhost = 0;
 1350:                 } else {
 1351:                     $canhost = 1;
 1352:                 }
 1353:             }
 1354:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
 1355:                 if (($uint_dom ne '') && 
 1356:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
 1357:                     $canhost = 1;
 1358:                 } else {
 1359:                     $canhost = 0;
 1360:                 }
 1361:             }
 1362:         }
 1363:     }
 1364:     return $canhost;
 1365: }
 1366: 
 1367: sub spare_can_host {
 1368:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
 1369:     my $canhost=1;
 1370:     my $try_server_hostname = &hostname($try_server);
 1371:     my $serverhomeID = &get_server_homeID($try_server_hostname);
 1372:     my $serverhomedom = &host_domain($serverhomeID);
 1373:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
 1374:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
 1375:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
 1376:             $canhost = 0;
 1377:         }
 1378:     }
 1379:     if ($canhost) {
 1380:         if (ref($defdomdefaults{'offloadoth'}) eq 'HASH') {
 1381:             if ($defdomdefaults{'offloadoth'}{$try_server}) {
 1382:                 unless (&shared_institution($udom,$try_server)) {
 1383:                     $canhost = 0;
 1384:                 }
 1385:             }
 1386:         }
 1387:     }
 1388:     if (($canhost) && ($uint_dom)) {
 1389:         my @intdoms;
 1390:         my $internet_names = &get_internet_names($try_server);
 1391:         if (ref($internet_names) eq 'ARRAY') {
 1392:             @intdoms = @{$internet_names};
 1393:         }
 1394:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
 1395:             my $remoterev = &get_server_loncaparev(undef,$try_server);
 1396:             $canhost = &can_host_session($udom,$try_server,$remoterev,
 1397:                                          $remotesessions,
 1398:                                          $defdomdefaults{'hostedsessions'});
 1399:         }
 1400:     }
 1401:     return $canhost;
 1402: }
 1403: 
 1404: sub this_host_spares {
 1405:     my ($dom) = @_;
 1406:     my ($dom_in_use,$lonhost_in_use,$result);
 1407:     my @hosts = &current_machine_ids();
 1408:     foreach my $lonhost (@hosts) {
 1409:         if (&host_domain($lonhost) eq $dom) {
 1410:             $dom_in_use = $dom;
 1411:             $lonhost_in_use = $lonhost;
 1412:             last;
 1413:         }
 1414:     }
 1415:     if ($dom_in_use ne '') {
 1416:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1417:     }
 1418:     if (ref($result) ne 'HASH') {
 1419:         $lonhost_in_use = $perlvar{'lonHostID'};
 1420:         $dom_in_use = &host_domain($lonhost_in_use);
 1421:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1422:         if (ref($result) ne 'HASH') {
 1423:             $result = \%spareid;
 1424:         }
 1425:     }
 1426:     return $result;
 1427: }
 1428: 
 1429: sub spares_for_offload  {
 1430:     my ($dom_in_use,$lonhost_in_use) = @_;
 1431:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
 1432:     if (defined($cached)) {
 1433:         return $result;
 1434:     } else {
 1435:         my $cachetime = 60*60*24;
 1436:         my %domconfig =
 1437:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
 1438:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
 1439:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
 1440:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
 1441:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
 1442:                 }
 1443:             }
 1444:         }
 1445:     }
 1446:     return;
 1447: }
 1448: 
 1449: sub get_lonbalancer_config {
 1450:     my ($servers) = @_;
 1451:     my ($currbalancer,$currtargets);
 1452:     if (ref($servers) eq 'HASH') {
 1453:         foreach my $server (keys(%{$servers})) {
 1454:             my %what = (
 1455:                          spareid => 1,
 1456:                          perlvar => 1,
 1457:                        );
 1458:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
 1459:             if ($result eq 'ok') {
 1460:                 if (ref($returnhash) eq 'HASH') {
 1461:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
 1462:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
 1463:                             $currbalancer = $server;
 1464:                             $currtargets = {};
 1465:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
 1466:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
 1467:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
 1468:                                 }
 1469:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
 1470:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
 1471:                                 }
 1472:                             }
 1473:                             last;
 1474:                         }
 1475:                     }
 1476:                 }
 1477:             }
 1478:         }
 1479:     }
 1480:     return ($currbalancer,$currtargets);
 1481: }
 1482: 
 1483: sub check_loadbalancing {
 1484:     my ($uname,$udom,$caller) = @_;
 1485:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
 1486:         $rule_in_effect,$offloadto,$otherserver,$setcookie);
 1487:     my $lonhost = $perlvar{'lonHostID'};
 1488:     my @hosts = &current_machine_ids();
 1489:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1490:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
 1491:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
 1492:     my $serverhomedom = &host_domain($lonhost);
 1493:     my $domneedscache; 
 1494:     my $cachetime = 60*60*24;
 1495: 
 1496:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1497:         $dom_in_use = $udom;
 1498:         $homeintdom = 1;
 1499:     } else {
 1500:         $dom_in_use = $serverhomedom;
 1501:     }
 1502:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
 1503:     unless (defined($cached)) {
 1504:         my %domconfig =
 1505:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
 1506:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1507:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1508:         } else {
 1509:             $domneedscache = $dom_in_use;
 1510:         }
 1511:     }
 1512:     if (ref($result) eq 'HASH') {
 1513:         ($is_balancer,$currtargets,$currrules,$setcookie) =
 1514:             &check_balancer_result($result,@hosts);
 1515:         if ($is_balancer) {
 1516:             if (ref($currrules) eq 'HASH') {
 1517:                 if ($homeintdom) {
 1518:                     if ($uname ne '') {
 1519:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
 1520:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
 1521:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
 1522:                                 $rule_in_effect = $currrules->{'_LC_author'};
 1523:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
 1524:                                 $rule_in_effect = $currrules->{'_LC_adv'}
 1525:                             }
 1526:                         }
 1527:                         if ($rule_in_effect eq '') {
 1528:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
 1529:                             if ($userenv{'inststatus'} ne '') {
 1530:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
 1531:                                 my ($othertitle,$usertypes,$types) =
 1532:                                     &Apache::loncommon::sorted_inst_types($udom);
 1533:                                 if (ref($types) eq 'ARRAY') {
 1534:                                     foreach my $type (@{$types}) {
 1535:                                         if (grep(/^\Q$type\E$/,@statuses)) {
 1536:                                             if (exists($currrules->{$type})) {
 1537:                                                 $rule_in_effect = $currrules->{$type};
 1538:                                             }
 1539:                                         }
 1540:                                     }
 1541:                                 }
 1542:                             } else {
 1543:                                 if (exists($currrules->{'default'})) {
 1544:                                     $rule_in_effect = $currrules->{'default'};
 1545:                                 }
 1546:                             }
 1547:                         }
 1548:                     } else {
 1549:                         if (exists($currrules->{'default'})) {
 1550:                             $rule_in_effect = $currrules->{'default'};
 1551:                         }
 1552:                     }
 1553:                 } else {
 1554:                     if ($currrules->{'_LC_external'} ne '') {
 1555:                         $rule_in_effect = $currrules->{'_LC_external'};
 1556:                     }
 1557:                 }
 1558:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1559:                                                        $uname,$udom);
 1560:             }
 1561:         }
 1562:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
 1563:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
 1564:         unless (defined($cached)) {
 1565:             my %domconfig =
 1566:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
 1567:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1568:                 $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
 1569:             } else {
 1570:                 $domneedscache = $serverhomedom;
 1571:             }
 1572:         }
 1573:         if (ref($result) eq 'HASH') {
 1574:             ($is_balancer,$currtargets,$currrules,$setcookie) =
 1575:                 &check_balancer_result($result,@hosts);
 1576:             if ($is_balancer) {
 1577:                 if (ref($currrules) eq 'HASH') {
 1578:                     if ($currrules->{'_LC_internetdom'} ne '') {
 1579:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
 1580:                     }
 1581:                 }
 1582:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1583:                                                        $uname,$udom);
 1584:             }
 1585:         } else {
 1586:             if ($perlvar{'lonBalancer'} eq 'yes') {
 1587:                 $is_balancer = 1;
 1588:                 $offloadto = &this_host_spares($dom_in_use);
 1589:             }
 1590:             unless (defined($cached)) {
 1591:                 $domneedscache = $serverhomedom;
 1592:             }
 1593:         }
 1594:     } else {
 1595:         if ($perlvar{'lonBalancer'} eq 'yes') {
 1596:             $is_balancer = 1;
 1597:             $offloadto = &this_host_spares($dom_in_use);
 1598:         }
 1599:         unless (defined($cached)) {
 1600:             $domneedscache = $serverhomedom;
 1601:         }
 1602:     }
 1603:     if ($domneedscache) {
 1604:         &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
 1605:     }
 1606:     if (($is_balancer) && ($caller ne 'switchserver')) {
 1607:         my $lowest_load = 30000;
 1608:         if (ref($offloadto) eq 'HASH') {
 1609:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
 1610:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
 1611:                     ($otherserver,$lowest_load) =
 1612:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1613:                 }
 1614:             }
 1615:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
 1616: 
 1617:             if (!$found_server) {
 1618:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
 1619:                     foreach my $try_server (@{$offloadto->{'default'}}) {
 1620:                         ($otherserver,$lowest_load) =
 1621:                             &compare_server_load($try_server,$otherserver,$lowest_load);
 1622:                     }
 1623:                 }
 1624:             }
 1625:         } elsif (ref($offloadto) eq 'ARRAY') {
 1626:             if (@{$offloadto} == 1) {
 1627:                 $otherserver = $offloadto->[0];
 1628:             } elsif (@{$offloadto} > 1) {
 1629:                 foreach my $try_server (@{$offloadto}) {
 1630:                     ($otherserver,$lowest_load) =
 1631:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1632:                 }
 1633:             }
 1634:         }
 1635:         unless ($caller eq 'login') {
 1636:             if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
 1637:                 $is_balancer = 0;
 1638:                 if ($uname ne '' && $udom ne '') {
 1639:                     if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
 1640:                         &appenv({'user.loadbalexempt'     => $lonhost,
 1641:                                  'user.loadbalcheck.time' => time});
 1642:                     }
 1643:                 }
 1644:             }
 1645:         }
 1646:     }
 1647:     if (($is_balancer) && (!$homeintdom)) {
 1648:         undef($setcookie);
 1649:     }
 1650:     return ($is_balancer,$otherserver,$setcookie);
 1651: }
 1652: 
 1653: sub check_balancer_result {
 1654:     my ($result,@hosts) = @_;
 1655:     my ($is_balancer,$currtargets,$currrules,$setcookie);
 1656:     if (ref($result) eq 'HASH') {
 1657:         if ($result->{'lonhost'} ne '') {
 1658:             my $currbalancer = $result->{'lonhost'};
 1659:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
 1660:                 $is_balancer = 1;
 1661:                 $currtargets = $result->{'targets'};
 1662:                 $currrules = $result->{'rules'};
 1663:             }
 1664:         } else {
 1665:             foreach my $key (keys(%{$result})) {
 1666:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
 1667:                     (ref($result->{$key}) eq 'HASH')) {
 1668:                     $is_balancer = 1;
 1669:                     $currrules = $result->{$key}{'rules'};
 1670:                     $currtargets = $result->{$key}{'targets'};
 1671:                     $setcookie = $result->{$key}{'cookie'};
 1672:                     last;
 1673:                 }
 1674:             }
 1675:         }
 1676:     }
 1677:     return ($is_balancer,$currtargets,$currrules,$setcookie);
 1678: }
 1679: 
 1680: sub get_loadbalancer_targets {
 1681:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
 1682:     my $offloadto;
 1683:     if ($rule_in_effect eq 'none') {
 1684:         return [$perlvar{'lonHostID'}];
 1685:     } elsif ($rule_in_effect eq '') {
 1686:         $offloadto = $currtargets;
 1687:     } else {
 1688:         if ($rule_in_effect eq 'homeserver') {
 1689:             my $homeserver = &homeserver($uname,$udom);
 1690:             if ($homeserver ne 'no_host') {
 1691:                 $offloadto = [$homeserver];
 1692:             }
 1693:         } elsif ($rule_in_effect eq 'externalbalancer') {
 1694:             my %domconfig =
 1695:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
 1696:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1697:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
 1698:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
 1699:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
 1700:                     }
 1701:                 }
 1702:             } else {
 1703:                 my %servers = &internet_dom_servers($udom);
 1704:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
 1705:                 if (&hostname($remotebalancer) ne '') {
 1706:                     $offloadto = [$remotebalancer];
 1707:                 }
 1708:             }
 1709:         } elsif (&hostname($rule_in_effect) ne '') {
 1710:             $offloadto = [$rule_in_effect];
 1711:         }
 1712:     }
 1713:     return $offloadto;
 1714: }
 1715: 
 1716: sub internet_dom_servers {
 1717:     my ($dom) = @_;
 1718:     my (%uniqservers,%servers);
 1719:     my $primaryserver = &hostname(&domain($dom,'primary'));
 1720:     my @machinedoms = &machine_domains($primaryserver);
 1721:     foreach my $mdom (@machinedoms) {
 1722:         my %currservers = %servers;
 1723:         my %server = &get_servers($mdom);
 1724:         %servers = (%currservers,%server);
 1725:     }
 1726:     my %by_hostname;
 1727:     foreach my $id (keys(%servers)) {
 1728:         push(@{$by_hostname{$servers{$id}}},$id);
 1729:     }
 1730:     foreach my $hostname (sort(keys(%by_hostname))) {
 1731:         if (@{$by_hostname{$hostname}} > 1) {
 1732:             my $match = 0;
 1733:             foreach my $id (@{$by_hostname{$hostname}}) {
 1734:                 if (&host_domain($id) eq $dom) {
 1735:                     $uniqservers{$id} = $hostname;
 1736:                     $match = 1;
 1737:                 }
 1738:             }
 1739:             unless ($match) {
 1740:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1741:             }
 1742:         } else {
 1743:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1744:         }
 1745:     }
 1746:     return %uniqservers;
 1747: }
 1748: 
 1749: # ---------------------- Find the homebase for a user from domain's lib servers
 1750: 
 1751: my %homecache;
 1752: sub homeserver {
 1753:     my ($uname,$udom,$ignoreBadCache)=@_;
 1754:     my $index="$uname:$udom";
 1755: 
 1756:     if (exists($homecache{$index})) { return $homecache{$index}; }
 1757: 
 1758:     my %servers = &get_servers($udom,'library');
 1759:     foreach my $tryserver (keys(%servers)) {
 1760:         next if ($ignoreBadCache ne 'true' && 
 1761: 		 exists($badServerCache{$tryserver}));
 1762: 
 1763: 	my $answer=reply("home:$udom:$uname",$tryserver);
 1764: 	if ($answer eq 'found') {
 1765: 	    delete($badServerCache{$tryserver}); 
 1766: 	    return $homecache{$index}=$tryserver;
 1767: 	} elsif ($answer eq 'no_host') {
 1768: 	    $badServerCache{$tryserver}=1;
 1769: 	}
 1770:     }    
 1771:     return 'no_host';
 1772: }
 1773: 
 1774: # ------------------------------------- Find the usernames behind a list of IDs
 1775: 
 1776: sub idget {
 1777:     my ($udom,@ids)=@_;
 1778:     my %returnhash=();
 1779:     
 1780:     my %servers = &get_servers($udom,'library');
 1781:     foreach my $tryserver (keys(%servers)) {
 1782: 	my $idlist=join('&', map { &escape($_); } @ids);
 1783: 	$idlist=~tr/A-Z/a-z/; 
 1784: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
 1785: 	my @answer=();
 1786: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
 1787: 	    @answer=split(/\&/,$reply);
 1788: 	}                    ;
 1789: 	my $i;
 1790: 	for ($i=0;$i<=$#ids;$i++) {
 1791: 	    if ($answer[$i]) {
 1792: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
 1793: 	    } 
 1794: 	}
 1795:     } 
 1796:     return %returnhash;
 1797: }
 1798: 
 1799: # ------------------------------------- Find the IDs behind a list of usernames
 1800: 
 1801: sub idrget {
 1802:     my ($udom,@unames)=@_;
 1803:     my %returnhash=();
 1804:     foreach my $uname (@unames) {
 1805:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
 1806:     }
 1807:     return %returnhash;
 1808: }
 1809: 
 1810: # ------------------------------- Store away a list of names and associated IDs
 1811: 
 1812: sub idput {
 1813:     my ($udom,%ids)=@_;
 1814:     my %servers=();
 1815:     foreach my $uname (keys(%ids)) {
 1816: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
 1817:         my $uhom=&homeserver($uname,$udom);
 1818:         if ($uhom ne 'no_host') {
 1819:             my $id=&escape($ids{$uname});
 1820:             $id=~tr/A-Z/a-z/;
 1821:             my $esc_unam=&escape($uname);
 1822: 	    if ($servers{$uhom}) {
 1823: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
 1824:             } else {
 1825:                 $servers{$uhom}=$id.'='.$esc_unam;
 1826:             }
 1827:         }
 1828:     }
 1829:     foreach my $server (keys(%servers)) {
 1830:         &critical('idput:'.$udom.':'.$servers{$server},$server);
 1831:     }
 1832: }
 1833: 
 1834: # ---------------------------------------- Delete unwanted IDs from ids.db file
 1835: 
 1836: sub iddel {
 1837:     my ($udom,$idshashref,$uhome)=@_;
 1838:     my %result=();
 1839:     unless (ref($idshashref) eq 'HASH') {
 1840:         return %result;
 1841:     }
 1842:     my %servers=();
 1843:     while (my ($id,$uname) = each(%{$idshashref})) {
 1844:         my $uhom;
 1845:         if ($uhome) {
 1846:             $uhom = $uhome;
 1847:         } else {
 1848:             $uhom=&homeserver($uname,$udom);
 1849:         }
 1850:         if ($uhom ne 'no_host') {
 1851:             if ($servers{$uhom}) {
 1852:                 $servers{$uhom}.='&'.&escape($id);
 1853:             } else {
 1854:                 $servers{$uhom}=&escape($id);
 1855:             }
 1856:         }
 1857:     }
 1858:     foreach my $server (keys(%servers)) {
 1859:         $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
 1860:     }
 1861:     return %result;
 1862: }
 1863: 
 1864: # ------------------------------dump from db file owned by domainconfig user
 1865: sub dump_dom {
 1866:     my ($namespace, $udom, $regexp) = @_;
 1867: 
 1868:     $udom ||= $env{'user.domain'};
 1869: 
 1870:     return () unless $udom;
 1871: 
 1872:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
 1873: }
 1874: 
 1875: # ------------------------------------------ get items from domain db files   
 1876: 
 1877: sub get_dom {
 1878:     my ($namespace,$storearr,$udom,$uhome)=@_;
 1879:     return if ($udom eq 'public');
 1880:     my $items='';
 1881:     foreach my $item (@$storearr) {
 1882:         $items.=&escape($item).'&';
 1883:     }
 1884:     $items=~s/\&$//;
 1885:     if (!$udom) {
 1886:         $udom=$env{'user.domain'};
 1887:         return if ($udom eq 'public');
 1888:         if (defined(&domain($udom,'primary'))) {
 1889:             $uhome=&domain($udom,'primary');
 1890:         } else {
 1891:             undef($uhome);
 1892:         }
 1893:     } else {
 1894:         if (!$uhome) {
 1895:             if (defined(&domain($udom,'primary'))) {
 1896:                 $uhome=&domain($udom,'primary');
 1897:             }
 1898:         }
 1899:     }
 1900:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1901:         my $rep;
 1902:         if (grep { $_ eq $uhome } &current_machine_ids()) {
 1903:             # domain information is hosted on this machine
 1904:             $rep = &LONCAPA::Lond::get_dom("getdom:$udom:$namespace:$items");
 1905:         } else {        
 1906:             $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
 1907:         }
 1908:         my %returnhash;
 1909:         if ($rep eq '' || $rep =~ /^error: 2 /) {
 1910:             return %returnhash;
 1911:         }
 1912:         my @pairs=split(/\&/,$rep);
 1913:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 1914:             return @pairs;
 1915:         }
 1916:         my $i=0;
 1917:         foreach my $item (@$storearr) {
 1918:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
 1919:             $i++;
 1920:         }
 1921:         return %returnhash;
 1922:     } else {
 1923:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
 1924:     }
 1925: }
 1926: 
 1927: # -------------------------------------------- put items in domain db files 
 1928: 
 1929: sub put_dom {
 1930:     my ($namespace,$storehash,$udom,$uhome)=@_;
 1931:     if (!$udom) {
 1932:         $udom=$env{'user.domain'};
 1933:         if (defined(&domain($udom,'primary'))) {
 1934:             $uhome=&domain($udom,'primary');
 1935:         } else {
 1936:             undef($uhome);
 1937:         }
 1938:     } else {
 1939:         if (!$uhome) {
 1940:             if (defined(&domain($udom,'primary'))) {
 1941:                 $uhome=&domain($udom,'primary');
 1942:             }
 1943:         }
 1944:     } 
 1945:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1946:         my $items='';
 1947:         foreach my $item (keys(%$storehash)) {
 1948:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 1949:         }
 1950:         $items=~s/\&$//;
 1951:         return &reply("putdom:$udom:$namespace:$items",$uhome);
 1952:     } else {
 1953:         &logthis("put_dom failed - no homeserver and/or domain");
 1954:     }
 1955: }
 1956: 
 1957: # --------------------- newput for items in db file owned by domainconfig user
 1958: sub newput_dom {
 1959:     my ($namespace,$storehash,$udom) = @_;
 1960:     my $result;
 1961:     if (!$udom) {
 1962:         $udom=$env{'user.domain'};
 1963:     }
 1964:     if ($udom) {
 1965:         my $uname = &get_domainconfiguser($udom);
 1966:         $result = &newput($namespace,$storehash,$udom,$uname);
 1967:     }
 1968:     return $result;
 1969: }
 1970: 
 1971: # --------------------- delete for items in db file owned by domainconfig user
 1972: sub del_dom {
 1973:     my ($namespace,$storearr,$udom)=@_;
 1974:     if (ref($storearr) eq 'ARRAY') {
 1975:         if (!$udom) {
 1976:             $udom=$env{'user.domain'};
 1977:         }
 1978:         if ($udom) {
 1979:             my $uname = &get_domainconfiguser($udom); 
 1980:             return &del($namespace,$storearr,$udom,$uname);
 1981:         }
 1982:     }
 1983: }
 1984: 
 1985: # ----------------------------------construct domainconfig user for a domain 
 1986: sub get_domainconfiguser {
 1987:     my ($udom) = @_;
 1988:     return $udom.'-domainconfig';
 1989: }
 1990: 
 1991: sub retrieve_inst_usertypes {
 1992:     my ($udom) = @_;
 1993:     my (%returnhash,@order);
 1994:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 1995:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
 1996:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
 1997:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
 1998:     } else {
 1999:         if (defined(&domain($udom,'primary'))) {
 2000:             my $uhome=&domain($udom,'primary');
 2001:             my $rep=&reply("inst_usertypes:$udom",$uhome);
 2002:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
 2003:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
 2004:                 return (\%returnhash,\@order);
 2005:             }
 2006:             my ($hashitems,$orderitems) = split(/:/,$rep); 
 2007:             my @pairs=split(/\&/,$hashitems);
 2008:             foreach my $item (@pairs) {
 2009:                 my ($key,$value)=split(/=/,$item,2);
 2010:                 $key = &unescape($key);
 2011:                 next if ($key =~ /^error: 2 /);
 2012:                 $returnhash{$key}=&thaw_unescape($value);
 2013:             }
 2014:             my @esc_order = split(/\&/,$orderitems);
 2015:             foreach my $item (@esc_order) {
 2016:                 push(@order,&unescape($item));
 2017:             }
 2018:         } else {
 2019:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
 2020:         }
 2021:         return (\%returnhash,\@order);
 2022:     }
 2023: }
 2024: 
 2025: sub is_domainimage {
 2026:     my ($url) = @_;
 2027:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
 2028:         if (&domain($1) ne '') {
 2029:             return '1';
 2030:         }
 2031:     }
 2032:     return;
 2033: }
 2034: 
 2035: sub inst_directory_query {
 2036:     my ($srch) = @_;
 2037:     my $udom = $srch->{'srchdomain'};
 2038:     my %results;
 2039:     my $homeserver = &domain($udom,'primary');
 2040:     my $outcome;
 2041:     if ($homeserver ne '') {
 2042:         unless ($homeserver eq $perlvar{'lonHostID'}) {
 2043:             if ($srch->{'srchby'} eq 'email') {
 2044:                 my $lcrev = &get_server_loncaparev($udom,$homeserver);
 2045:                 my ($major,$minor,$subver) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.(\d+)[\w.\-]+\'?$/);
 2046:                 if (($major eq '' && $minor eq '') || ($major < 2) ||
 2047:                     (($major == 2) && ($minor < 11)) ||
 2048:                     (($major == 2) && ($minor == 11) && ($subver < 3))) {
 2049:                     return;
 2050:                 }
 2051:             }
 2052:         }
 2053: 	my $queryid=&reply("querysend:instdirsearch:".
 2054: 			   &escape($srch->{'srchby'}).':'.
 2055: 			   &escape($srch->{'srchterm'}).':'.
 2056: 			   &escape($srch->{'srchtype'}),$homeserver);
 2057: 	my $host=&hostname($homeserver);
 2058: 	if ($queryid !~/^\Q$host\E\_/) {
 2059: 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
 2060: 	    return;
 2061: 	}
 2062: 	my $response = &get_query_reply($queryid);
 2063: 	my $maxtries = 5;
 2064: 	my $tries = 1;
 2065: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 2066: 	    $response = &get_query_reply($queryid);
 2067: 	    $tries ++;
 2068: 	}
 2069: 
 2070:         if (!&error($response) && $response ne 'refused') {
 2071:             if ($response eq 'unavailable') {
 2072:                 $outcome = $response;
 2073:             } else {
 2074:                 $outcome = 'ok';
 2075:                 my @matches = split(/\n/,$response);
 2076:                 foreach my $match (@matches) {
 2077:                     my ($key,$value) = split(/=/,$match);
 2078:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 2079:                 }
 2080:             }
 2081:         }
 2082:     }
 2083:     return ($outcome,%results);
 2084: }
 2085: 
 2086: sub usersearch {
 2087:     my ($srch) = @_;
 2088:     my $dom = $srch->{'srchdomain'};
 2089:     my %results;
 2090:     my %libserv = &all_library();
 2091:     my $query = 'usersearch';
 2092:     foreach my $tryserver (keys(%libserv)) {
 2093:         if (&host_domain($tryserver) eq $dom) {
 2094:             unless ($tryserver eq $perlvar{'lonHostID'}) {
 2095:                 if ($srch->{'srchby'} eq 'email') {
 2096:                     my $lcrev = &get_server_loncaparev($dom,$tryserver);
 2097:                     my ($major,$minor,$subver) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.(\d+)[\w.\-]+\'?$/);
 2098:                     next if (($major eq '' && $minor eq '') || ($major < 2) ||
 2099:                              (($major == 2) && ($minor < 11)) ||
 2100:                              (($major == 2) && ($minor == 11) && ($subver < 3)));
 2101:                 }
 2102:             }
 2103:             my $host=&hostname($tryserver);
 2104:             my $queryid=
 2105:                 &reply("querysend:".&escape($query).':'.
 2106:                        &escape($srch->{'srchby'}).':'.
 2107:                        &escape($srch->{'srchtype'}).':'.
 2108:                        &escape($srch->{'srchterm'}),$tryserver);
 2109:             if ($queryid !~/^\Q$host\E\_/) {
 2110:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 2111:                 next;
 2112:             }
 2113:             my $reply = &get_query_reply($queryid);
 2114:             my $maxtries = 1;
 2115:             my $tries = 1;
 2116:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 2117:                 $reply = &get_query_reply($queryid);
 2118:                 $tries ++;
 2119:             }
 2120:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 2121:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 2122:             } else {
 2123:                 my @matches;
 2124:                 if ($reply =~ /\n/) {
 2125:                     @matches = split(/\n/,$reply);
 2126:                 } else {
 2127:                     @matches = split(/\&/,$reply);
 2128:                 }
 2129:                 foreach my $match (@matches) {
 2130:                     my ($uname,$udom,%userhash);
 2131:                     foreach my $entry (split(/:/,$match)) {
 2132:                         my ($key,$value) =
 2133:                             map {&unescape($_);} split(/=/,$entry);
 2134:                         $userhash{$key} = $value;
 2135:                         if ($key eq 'username') {
 2136:                             $uname = $value;
 2137:                         } elsif ($key eq 'domain') {
 2138:                             $udom = $value;
 2139:                         }
 2140:                     }
 2141:                     $results{$uname.':'.$udom} = \%userhash;
 2142:                 }
 2143:             }
 2144:         }
 2145:     }
 2146:     return %results;
 2147: }
 2148: 
 2149: sub get_instuser {
 2150:     my ($udom,$uname,$id) = @_;
 2151:     my $homeserver = &domain($udom,'primary');
 2152:     my ($outcome,%results);
 2153:     if ($homeserver ne '') {
 2154:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 2155:                            &escape($id).':'.&escape($udom),$homeserver);
 2156:         my $host=&hostname($homeserver);
 2157:         if ($queryid !~/^\Q$host\E\_/) {
 2158:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 2159:             return;
 2160:         }
 2161:         my $response = &get_query_reply($queryid);
 2162:         my $maxtries = 5;
 2163:         my $tries = 1;
 2164:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 2165:             $response = &get_query_reply($queryid);
 2166:             $tries ++;
 2167:         }
 2168:         if (!&error($response) && $response ne 'refused') {
 2169:             if ($response eq 'unavailable') {
 2170:                 $outcome = $response;
 2171:             } else {
 2172:                 $outcome = 'ok';
 2173:                 my @matches = split(/\n/,$response);
 2174:                 foreach my $match (@matches) {
 2175:                     my ($key,$value) = split(/=/,$match);
 2176:                     $results{&unescape($key)} = &thaw_unescape($value);
 2177:                 }
 2178:             }
 2179:         }
 2180:     }
 2181:     my %userinfo;
 2182:     if (ref($results{$uname}) eq 'HASH') {
 2183:         %userinfo = %{$results{$uname}};
 2184:     } 
 2185:     return ($outcome,%userinfo);
 2186: }
 2187: 
 2188: sub get_multiple_instusers {
 2189:     my ($udom,$users,$caller) = @_;
 2190:     my ($outcome,$results);
 2191:     if (ref($users) eq 'HASH') {
 2192:         my $count = keys(%{$users});
 2193:         my $requested = &freeze_escape($users);
 2194:         my $homeserver = &domain($udom,'primary');
 2195:         if ($homeserver ne '') {
 2196:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
 2197:             my $host=&hostname($homeserver);
 2198:             if ($queryid !~/^\Q$host\E\_/) {
 2199:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
 2200:                          ' for host: '.$homeserver.'in domain '.$udom);
 2201:                 return ($outcome,$results);
 2202:             }
 2203:             my $response = &get_query_reply($queryid);
 2204:             my $maxtries = 5;
 2205:             if ($count > 100) {
 2206:                 $maxtries = 1+int($count/20);
 2207:             }
 2208:             my $tries = 1;
 2209:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
 2210:                 $response = &get_query_reply($queryid);
 2211:                 $tries ++;
 2212:             }
 2213:             if ($response eq '') {
 2214:                 $results = {};
 2215:                 foreach my $key (keys(%{$users})) {
 2216:                     my ($uname,$id);
 2217:                     if ($caller eq 'id') {
 2218:                         $id = $key;
 2219:                     } else {
 2220:                         $uname = $key;
 2221:                     }
 2222:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
 2223:                     $outcome = $resp;
 2224:                     if ($resp eq 'ok') {
 2225:                         %{$results} = (%{$results}, %info);
 2226:                     } else {
 2227:                         last;
 2228:                     }
 2229:                 }
 2230:             } elsif(!&error($response) && ($response ne 'refused')) {
 2231:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
 2232:                     $outcome = $response;
 2233:                 } else {
 2234:                     ($outcome,my $userdata) = split(/=/,$response,2);
 2235:                     if ($outcome eq 'ok') {
 2236:                         $results = &thaw_unescape($userdata);
 2237:                     }
 2238:                 }
 2239:             }
 2240:         }
 2241:     }
 2242:     return ($outcome,$results);
 2243: }
 2244: 
 2245: sub inst_rulecheck {
 2246:     my ($udom,$uname,$id,$item,$rules) = @_;
 2247:     my %returnhash;
 2248:     if ($udom ne '') {
 2249:         if (ref($rules) eq 'ARRAY') {
 2250:             @{$rules} = map {&escape($_);} (@{$rules});
 2251:             my $rulestr = join(':',@{$rules});
 2252:             my $homeserver=&domain($udom,'primary');
 2253:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 2254:                 my $response;
 2255:                 if ($item eq 'username') {                
 2256:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 2257:                                               ':'.&escape($uname).':'.$rulestr,
 2258:                                               $homeserver));
 2259:                 } elsif ($item eq 'id') {
 2260:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 2261:                                               ':'.&escape($id).':'.$rulestr,
 2262:                                               $homeserver));
 2263:                 } elsif ($item eq 'selfcreate') {
 2264:                     $response=&unescape(&reply('instselfcreatecheck:'.
 2265:                                                &escape($udom).':'.&escape($uname).
 2266:                                               ':'.$rulestr,$homeserver));
 2267:                 }
 2268:                 if ($response ne 'refused') {
 2269:                     my @pairs=split(/\&/,$response);
 2270:                     foreach my $item (@pairs) {
 2271:                         my ($key,$value)=split(/=/,$item,2);
 2272:                         $key = &unescape($key);
 2273:                         next if ($key =~ /^error: 2 /);
 2274:                         $returnhash{$key}=&thaw_unescape($value);
 2275:                     }
 2276:                 }
 2277:             }
 2278:         }
 2279:     }
 2280:     return %returnhash;
 2281: }
 2282: 
 2283: sub inst_userrules {
 2284:     my ($udom,$check) = @_;
 2285:     my (%ruleshash,@ruleorder);
 2286:     if ($udom ne '') {
 2287:         my $homeserver=&domain($udom,'primary');
 2288:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 2289:             my $response;
 2290:             if ($check eq 'id') {
 2291:                 $response=&reply('instidrules:'.&escape($udom),
 2292:                                  $homeserver);
 2293:             } elsif ($check eq 'email') {
 2294:                 $response=&reply('instemailrules:'.&escape($udom),
 2295:                                  $homeserver);
 2296:             } else {
 2297:                 $response=&reply('instuserrules:'.&escape($udom),
 2298:                                  $homeserver);
 2299:             }
 2300:             if (($response ne 'refused') && ($response ne 'error') && 
 2301:                 ($response ne 'unknown_cmd') && 
 2302:                 ($response ne 'no_such_host')) {
 2303:                 my ($hashitems,$orderitems) = split(/:/,$response);
 2304:                 my @pairs=split(/\&/,$hashitems);
 2305:                 foreach my $item (@pairs) {
 2306:                     my ($key,$value)=split(/=/,$item,2);
 2307:                     $key = &unescape($key);
 2308:                     next if ($key =~ /^error: 2 /);
 2309:                     $ruleshash{$key}=&thaw_unescape($value);
 2310:                 }
 2311:                 my @esc_order = split(/\&/,$orderitems);
 2312:                 foreach my $item (@esc_order) {
 2313:                     push(@ruleorder,&unescape($item));
 2314:                 }
 2315:             }
 2316:         }
 2317:     }
 2318:     return (\%ruleshash,\@ruleorder);
 2319: }
 2320: 
 2321: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 2322: 
 2323: sub get_domain_defaults {
 2324:     my ($domain,$ignore_cache) = @_;
 2325:     return if (($domain eq '') || ($domain eq 'public'));
 2326:     my $cachetime = 60*60*24;
 2327:     unless ($ignore_cache) {
 2328:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 2329:         if (defined($cached)) {
 2330:             if (ref($result) eq 'HASH') {
 2331:                 return %{$result};
 2332:             }
 2333:         }
 2334:     }
 2335:     my %domdefaults;
 2336:     my %domconfig =
 2337:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
 2338:                                   'requestcourses','inststatus',
 2339:                                   'coursedefaults','usersessions',
 2340:                                   'requestauthor','selfenrollment',
 2341:                                   'coursecategories','autoenroll',
 2342:                                   'helpsettings'],$domain);
 2343:     my @coursetypes = ('official','unofficial','community','textbook');
 2344:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 2345:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 2346:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 2347:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 2348:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 2349:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
 2350:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
 2351:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
 2352:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
 2353:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
 2354:     } else {
 2355:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 2356:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 2357:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 2358:     }
 2359:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 2360:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 2361:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 2362:         } else {
 2363:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 2364:         }
 2365:         my @usertools = ('aboutme','blog','webdav','portfolio');
 2366:         foreach my $item (@usertools) {
 2367:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 2368:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 2369:             }
 2370:         }
 2371:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
 2372:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
 2373:         }
 2374:     }
 2375:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 2376:         foreach my $item ('official','unofficial','community','textbook') {
 2377:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
 2378:         }
 2379:     }
 2380:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
 2381:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
 2382:     }
 2383:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
 2384:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
 2385:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
 2386:         }
 2387:     }
 2388:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
 2389:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
 2390:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
 2391:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
 2392:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
 2393:         }
 2394:         foreach my $type (@coursetypes) {
 2395:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
 2396:                 unless ($type eq 'community') {
 2397:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
 2398:                 }
 2399:             }
 2400:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
 2401:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
 2402:             }
 2403:             if ($domdefaults{'postsubmit'} eq 'on') {
 2404:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
 2405:                     $domdefaults{$type.'postsubtimeout'} =
 2406:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
 2407:                 }
 2408:             }
 2409:         }
 2410:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
 2411:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
 2412:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
 2413:                 if (@clonecodes) {
 2414:                     $domdefaults{'canclone'} = join('+',@clonecodes);
 2415:                 }
 2416:             }
 2417:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
 2418:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
 2419:         }
 2420:         if ($domconfig{'coursedefaults'}{'texengine'}) {
 2421:             $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
 2422:         }
 2423:     }
 2424:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
 2425:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
 2426:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
 2427:         }
 2428:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
 2429:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
 2430:         }
 2431:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
 2432:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
 2433:         }
 2434:         if (ref($domconfig{'usersessions'}{'offloadoth'}) eq 'HASH') {
 2435:             $domdefaults{'offloadoth'} = $domconfig{'usersessions'}{'offloadoth'};
 2436:         }
 2437:     }
 2438:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
 2439:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
 2440:             my @settings = ('types','registered','enroll_dates','access_dates','section',
 2441:                             'approval','limit');
 2442:             foreach my $type (@coursetypes) {
 2443:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
 2444:                     my @mgrdc = ();
 2445:                     foreach my $item (@settings) {
 2446:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
 2447:                             push(@mgrdc,$item);
 2448:                         }
 2449:                     }
 2450:                     if (@mgrdc) {
 2451:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
 2452:                     }
 2453:                 }
 2454:             }
 2455:         }
 2456:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
 2457:             foreach my $type (@coursetypes) {
 2458:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
 2459:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
 2460:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
 2461:                     }
 2462:                 }
 2463:             }
 2464:         }
 2465:     }
 2466:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 2467:         $domdefaults{'catauth'} = 'std';
 2468:         $domdefaults{'catunauth'} = 'std';
 2469:         if ($domconfig{'coursecategories'}{'auth'}) {
 2470:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
 2471:         }
 2472:         if ($domconfig{'coursecategories'}{'unauth'}) {
 2473:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
 2474:         }
 2475:     }
 2476:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 2477:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
 2478:     }
 2479:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
 2480:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
 2481:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
 2482:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
 2483:         }
 2484:     }
 2485:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
 2486:     return %domdefaults;
 2487: }
 2488: 
 2489: sub get_dom_cats {
 2490:     my ($dom) = @_;
 2491:     return unless (&domain($dom));
 2492:     my ($cats,$cached)=&is_cached_new('cats',$dom);
 2493:     unless (defined($cached)) {
 2494:         my %domconfig = &get_dom('configuration',['coursecategories'],$dom);
 2495:         if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 2496:             if (ref($domconfig{'coursecategories'}{'cats'}) eq 'HASH') {
 2497:                 %{$cats} = %{$domconfig{'coursecategories'}{'cats'}};
 2498:             } else {
 2499:                 $cats = {};
 2500:             }
 2501:         } else {
 2502:             $cats = {};
 2503:         }
 2504:         &Apache::lonnet::do_cache_new('cats',$dom,$cats,3600);
 2505:     }
 2506:     return $cats;
 2507: }
 2508: 
 2509: sub get_dom_instcats {
 2510:     my ($dom) = @_;
 2511:     return unless (&domain($dom));
 2512:     my ($instcats,$cached)=&is_cached_new('instcats',$dom);
 2513:     unless (defined($cached)) {
 2514:         my (%coursecodes,%codes,@codetitles,%cat_titles,%cat_order);
 2515:         my $totcodes = &retrieve_instcodes(\%coursecodes,$dom);
 2516:         if ($totcodes > 0) {
 2517:             my $caller = 'global';
 2518:             if (&auto_instcode_format($caller,$dom,\%coursecodes,\%codes,
 2519:                                       \@codetitles,\%cat_titles,\%cat_order) eq 'ok') {
 2520:                 $instcats = {
 2521:                                 codes => \%codes,
 2522:                                 codetitles => \@codetitles,
 2523:                                 cat_titles => \%cat_titles,
 2524:                                 cat_order => \%cat_order,
 2525:                             };
 2526:                 &do_cache_new('instcats',$dom,$instcats,3600);
 2527:             }
 2528:         }
 2529:     }
 2530:     return $instcats;
 2531: }
 2532: 
 2533: sub retrieve_instcodes {
 2534:     my ($coursecodes,$dom) = @_;
 2535:     my $totcodes;
 2536:     my %courses = &courseiddump($dom,'.',1,'.','.','.',undef,undef,'Course');
 2537:     foreach my $course (keys(%courses)) {
 2538:         if (ref($courses{$course}) eq 'HASH') {
 2539:             if ($courses{$course}{'inst_code'} ne '') {
 2540:                 $$coursecodes{$course} = $courses{$course}{'inst_code'};
 2541:                 $totcodes ++;
 2542:             }
 2543:         }
 2544:     }
 2545:     return $totcodes;
 2546: }
 2547: 
 2548: # --------------------------------------------- Get domain config for passwords
 2549: 
 2550: sub get_passwdconf {
 2551:     my ($dom) = @_;
 2552:     my (%passwdconf,$gotconf,$lookup);
 2553:     my ($result,$cached)=&is_cached_new('passwdconf',$dom);
 2554:     if (defined($cached)) {
 2555:         if (ref($result) eq 'HASH') {
 2556:             %passwdconf = %{$result};
 2557:             $gotconf = 1;
 2558:         }
 2559:     }
 2560:     unless ($gotconf) {
 2561:         my %domconfig = &get_dom('configuration',['passwords'],$dom);
 2562:         if (ref($domconfig{'passwords'}) eq 'HASH') {
 2563:             %passwdconf = %{$domconfig{'passwords'}};
 2564:         }
 2565:         my $cachetime = 24*60*60;
 2566:         &do_cache_new('passwdconf',$dom,\%passwdconf,$cachetime);
 2567:     }
 2568:     return %passwdconf;
 2569: }
 2570: 
 2571: # --------------------------------------------------- Assign a key to a student
 2572: 
 2573: sub assign_access_key {
 2574: #
 2575: # a valid key looks like uname:udom#comments
 2576: # comments are being appended
 2577: #
 2578:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 2579:     $kdom=
 2580:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 2581:     $knum=
 2582:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 2583:     $cdom=
 2584:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2585:     $cnum=
 2586:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2587:     $udom=$env{'user.name'} unless (defined($udom));
 2588:     $uname=$env{'user.domain'} unless (defined($uname));
 2589:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 2590:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 2591:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 2592:                                                   # assigned to this person
 2593:                                                   # - this should not happen,
 2594:                                                   # unless something went wrong
 2595:                                                   # the first time around
 2596: # ready to assign
 2597:         $logentry=$1.'; '.$logentry;
 2598:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 2599:                                                  $kdom,$knum) eq 'ok') {
 2600: # key now belongs to user
 2601: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 2602:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 2603:                 &appenv({'environment.'.$envkey => $ckey});
 2604:                 return 'ok';
 2605:             } else {
 2606:                 return 
 2607:   'error: Count not permanently assign key, will need to be re-entered later.';
 2608: 	    }
 2609:         } else {
 2610:             return 'error: Could not assign key, try again later.';
 2611:         }
 2612:     } elsif (!$existing{$ckey}) {
 2613: # the key does not exist
 2614: 	return 'error: The key does not exist';
 2615:     } else {
 2616: # the key is somebody else's
 2617: 	return 'error: The key is already in use';
 2618:     }
 2619: }
 2620: 
 2621: # ------------------------------------------ put an additional comment on a key
 2622: 
 2623: sub comment_access_key {
 2624: #
 2625: # a valid key looks like uname:udom#comments
 2626: # comments are being appended
 2627: #
 2628:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 2629:     $cdom=
 2630:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2631:     $cnum=
 2632:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2633:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2634:     if ($existing{$ckey}) {
 2635:         $existing{$ckey}.='; '.$logentry;
 2636: # ready to assign
 2637:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 2638:                                                  $cdom,$cnum) eq 'ok') {
 2639: 	    return 'ok';
 2640:         } else {
 2641: 	    return 'error: Count not store comment.';
 2642:         }
 2643:     } else {
 2644: # the key does not exist
 2645: 	return 'error: The key does not exist';
 2646:     }
 2647: }
 2648: 
 2649: # ------------------------------------------------------ Generate a set of keys
 2650: 
 2651: sub generate_access_keys {
 2652:     my ($number,$cdom,$cnum,$logentry)=@_;
 2653:     $cdom=
 2654:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2655:     $cnum=
 2656:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2657:     unless (&allowed('mky',$cdom)) { return 0; }
 2658:     unless (($cdom) && ($cnum)) { return 0; }
 2659:     if ($number>10000) { return 0; }
 2660:     sleep(2); # make sure don't get same seed twice
 2661:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 2662:     my $total=0;
 2663:     for (my $i=1;$i<=$number;$i++) {
 2664:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 2665:                   sprintf("%lx",int(100000*rand)).'-'.
 2666:                   sprintf("%lx",int(100000*rand));
 2667:        $newkey=~s/1/g/g; # folks mix up 1 and l
 2668:        $newkey=~s/0/h/g; # and also 0 and O
 2669:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 2670:        if ($existing{$newkey}) {
 2671:            $i--;
 2672:        } else {
 2673: 	  if (&put('accesskeys',
 2674:               { $newkey => '# generated '.localtime().
 2675:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 2676:                            '; '.$logentry },
 2677: 		   $cdom,$cnum) eq 'ok') {
 2678:               $total++;
 2679: 	  }
 2680:        }
 2681:     }
 2682:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 2683:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 2684:     return $total;
 2685: }
 2686: 
 2687: # ------------------------------------------------------- Validate an accesskey
 2688: 
 2689: sub validate_access_key {
 2690:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 2691:     $cdom=
 2692:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2693:     $cnum=
 2694:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2695:     $udom=$env{'user.domain'} unless (defined($udom));
 2696:     $uname=$env{'user.name'} unless (defined($uname));
 2697:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2698:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 2699: }
 2700: 
 2701: # ------------------------------------- Find the section of student in a course
 2702: sub devalidate_getsection_cache {
 2703:     my ($udom,$unam,$courseid)=@_;
 2704:     my $hashid="$udom:$unam:$courseid";
 2705:     &devalidate_cache_new('getsection',$hashid);
 2706: }
 2707: 
 2708: sub courseid_to_courseurl {
 2709:     my ($courseid) = @_;
 2710:     #already url style courseid
 2711:     return $courseid if ($courseid =~ m{^/});
 2712: 
 2713:     if (exists($env{'course.'.$courseid.'.num'})) {
 2714: 	my $cnum = $env{'course.'.$courseid.'.num'};
 2715: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 2716: 	return "/$cdom/$cnum";
 2717:     }
 2718: 
 2719:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 2720:     if (exists($courseinfo{'num'})) {
 2721: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 2722:     }
 2723: 
 2724:     return undef;
 2725: }
 2726: 
 2727: sub getsection {
 2728:     my ($udom,$unam,$courseid)=@_;
 2729:     my $cachetime=1800;
 2730: 
 2731:     my $hashid="$udom:$unam:$courseid";
 2732:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 2733:     if (defined($cached)) { return $result; }
 2734: 
 2735:     my %Pending; 
 2736:     my %Expired;
 2737:     #
 2738:     # Each role can either have not started yet (pending), be active, 
 2739:     #    or have expired.
 2740:     #
 2741:     # If there is an active role, we are done.
 2742:     #
 2743:     # If there is more than one role which has not started yet, 
 2744:     #     choose the one which will start sooner
 2745:     # If there is one role which has not started yet, return it.
 2746:     #
 2747:     # If there is more than one expired role, choose the one which ended last.
 2748:     # If there is a role which has expired, return it.
 2749:     #
 2750:     $courseid = &courseid_to_courseurl($courseid);
 2751:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 2752:     foreach my $key (keys(%roleshash)) {
 2753:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 2754:         my $section=$1;
 2755:         if ($key eq $courseid.'_st') { $section=''; }
 2756:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 2757:         my $now=time;
 2758:         if (defined($end) && $end && ($now > $end)) {
 2759:             $Expired{$end}=$section;
 2760:             next;
 2761:         }
 2762:         if (defined($start) && $start && ($now < $start)) {
 2763:             $Pending{$start}=$section;
 2764:             next;
 2765:         }
 2766:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 2767:     }
 2768:     #
 2769:     # Presumedly there will be few matching roles from the above
 2770:     # loop and the sorting time will be negligible.
 2771:     if (scalar(keys(%Pending))) {
 2772:         my ($time) = sort {$a <=> $b} keys(%Pending);
 2773:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 2774:     } 
 2775:     if (scalar(keys(%Expired))) {
 2776:         my @sorted = sort {$a <=> $b} keys(%Expired);
 2777:         my $time = pop(@sorted);
 2778:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 2779:     }
 2780:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 2781: }
 2782: 
 2783: sub save_cache {
 2784:     &purge_remembered();
 2785:     #&Apache::loncommon::validate_page();
 2786:     undef(%env);
 2787:     undef($env_loaded);
 2788: }
 2789: 
 2790: my $to_remember=-1;
 2791: my %remembered;
 2792: my %accessed;
 2793: my $kicks=0;
 2794: my $hits=0;
 2795: sub make_key {
 2796:     my ($name,$id) = @_;
 2797:     if (length($id) > 65 
 2798: 	&& length(&escape($id)) > 200) {
 2799: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 2800:     }
 2801:     return &escape($name.':'.$id);
 2802: }
 2803: 
 2804: sub devalidate_cache_new {
 2805:     my ($name,$id,$debug) = @_;
 2806:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 2807:     my $remembered_id=$name.':'.$id;
 2808:     $id=&make_key($name,$id);
 2809:     $memcache->delete($id);
 2810:     delete($remembered{$remembered_id});
 2811:     delete($accessed{$remembered_id});
 2812: }
 2813: 
 2814: sub is_cached_new {
 2815:     my ($name,$id,$debug) = @_;
 2816:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) for 
 2817:                                      # keys in %remembered hash, which persists for
 2818:                                      # duration of request (no restriction on key length).
 2819:     if (exists($remembered{$remembered_id})) {
 2820: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
 2821: 	$accessed{$remembered_id}=[&gettimeofday()];
 2822: 	$hits++;
 2823: 	return ($remembered{$remembered_id},1);
 2824:     }
 2825:     $id=&make_key($name,$id);
 2826:     my $value = $memcache->get($id);
 2827:     if (!(defined($value))) {
 2828: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 2829: 	return (undef,undef);
 2830:     }
 2831:     if ($value eq '__undef__') {
 2832: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 2833: 	$value=undef;
 2834:     }
 2835:     &make_room($remembered_id,$value,$debug);
 2836:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 2837:     return ($value,1);
 2838: }
 2839: 
 2840: sub do_cache_new {
 2841:     my ($name,$id,$value,$time,$debug) = @_;
 2842:     my $remembered_id=$name.':'.$id;
 2843:     $id=&make_key($name,$id);
 2844:     my $setvalue=$value;
 2845:     if (!defined($setvalue)) {
 2846: 	$setvalue='__undef__';
 2847:     }
 2848:     if (!defined($time) ) {
 2849: 	$time=600;
 2850:     }
 2851:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 2852:     my $result = $memcache->set($id,$setvalue,$time);
 2853:     if (! $result) {
 2854: 	&logthis("caching of id -> $id  failed");
 2855: 	$memcache->disconnect_all();
 2856:     }
 2857:     # need to make a copy of $value
 2858:     &make_room($remembered_id,$value,$debug);
 2859:     return $value;
 2860: }
 2861: 
 2862: sub make_room {
 2863:     my ($remembered_id,$value,$debug)=@_;
 2864: 
 2865:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
 2866:                                     : $value;
 2867:     if ($to_remember<0) { return; }
 2868:     $accessed{$remembered_id}=[&gettimeofday()];
 2869:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 2870:     my $to_kick;
 2871:     my $max_time=0;
 2872:     foreach my $other (keys(%accessed)) {
 2873: 	if (&tv_interval($accessed{$other}) > $max_time) {
 2874: 	    $to_kick=$other;
 2875: 	    $max_time=&tv_interval($accessed{$other});
 2876: 	}
 2877:     }
 2878:     delete($remembered{$to_kick});
 2879:     delete($accessed{$to_kick});
 2880:     $kicks++;
 2881:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 2882:     return;
 2883: }
 2884: 
 2885: sub purge_remembered {
 2886:     #&logthis("Tossing ".scalar(keys(%remembered)));
 2887:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 2888:     undef(%remembered);
 2889:     undef(%accessed);
 2890: }
 2891: # ------------------------------------- Read an entry from a user's environment
 2892: 
 2893: sub userenvironment {
 2894:     my ($udom,$unam,@what)=@_;
 2895:     my $items;
 2896:     foreach my $item (@what) {
 2897:         $items.=&escape($item).'&';
 2898:     }
 2899:     $items=~s/\&$//;
 2900:     my %returnhash=();
 2901:     my $uhome = &homeserver($unam,$udom);
 2902:     unless ($uhome eq 'no_host') {
 2903:         my @answer=split(/\&/, 
 2904:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
 2905:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
 2906:             return %returnhash;
 2907:         }
 2908:         my $i;
 2909:         for ($i=0;$i<=$#what;$i++) {
 2910: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
 2911:         }
 2912:     }
 2913:     return %returnhash;
 2914: }
 2915: 
 2916: # ---------------------------------------------------------- Get a studentphoto
 2917: sub studentphoto {
 2918:     my ($udom,$unam,$ext) = @_;
 2919:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 2920:     if (defined($env{'request.course.id'})) {
 2921:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 2922:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 2923:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 2924:             } else {
 2925:                 my ($result,$perm_reqd)=
 2926: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 2927:                 if ($result eq 'ok') {
 2928:                     if (!($perm_reqd eq 'yes')) {
 2929:                         return(&retrievestudentphoto($udom,$unam,$ext));
 2930:                     }
 2931:                 }
 2932:             }
 2933:         }
 2934:     } else {
 2935:         my ($result,$perm_reqd) = 
 2936: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 2937:         if ($result eq 'ok') {
 2938:             if (!($perm_reqd eq 'yes')) {
 2939:                 return(&retrievestudentphoto($udom,$unam,$ext));
 2940:             }
 2941:         }
 2942:     }
 2943:     return '/adm/lonKaputt/lonlogo_broken.gif';
 2944: }
 2945: 
 2946: sub retrievestudentphoto {
 2947:     my ($udom,$unam,$ext,$type) = @_;
 2948:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 2949:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 2950:     if ($ret eq 'ok') {
 2951:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 2952:         if ($type eq 'thumbnail') {
 2953:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 2954:         }
 2955:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 2956:         return $tokenurl;
 2957:     } else {
 2958:         if ($type eq 'thumbnail') {
 2959:             return '/adm/lonKaputt/genericstudent_tn.gif';
 2960:         } else { 
 2961:             return '/adm/lonKaputt/lonlogo_broken.gif';
 2962:         }
 2963:     }
 2964: }
 2965: 
 2966: # -------------------------------------------------------------------- New chat
 2967: 
 2968: sub chatsend {
 2969:     my ($newentry,$anon,$group)=@_;
 2970:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 2971:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2972:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 2973:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 2974: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 2975: 		   &escape($newentry)).':'.$group,$chome);
 2976: }
 2977: 
 2978: # ------------------------------------------ Find current version of a resource
 2979: 
 2980: sub getversion {
 2981:     my $fname=&clutter(shift);
 2982:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
 2983:     return &currentversion(&filelocation('',$fname));
 2984: }
 2985: 
 2986: sub currentversion {
 2987:     my $fname=shift;
 2988:     my $author=$fname;
 2989:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2990:     my ($udom,$uname)=split(/\//,$author);
 2991:     my $home=&homeserver($uname,$udom);
 2992:     if ($home eq 'no_host') { 
 2993:         return -1; 
 2994:     }
 2995:     my $answer=&reply("currentversion:$fname",$home);
 2996:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 2997: 	return -1;
 2998:     }
 2999:     return $answer;
 3000: }
 3001: 
 3002: #
 3003: # Return special version number of resource if set by override, empty otherwise
 3004: #
 3005: sub usedversion {
 3006:     my $fname=shift;
 3007:     unless ($fname) { $fname=$env{'request.uri'}; }
 3008:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
 3009:     if ($urlversion) { return $urlversion; }
 3010:     return '';
 3011: }
 3012: 
 3013: # ----------------------------- Subscribe to a resource, return URL if possible
 3014: 
 3015: sub subscribe {
 3016:     my $fname=shift;
 3017:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 3018:     $fname=~s/[\n\r]//g;
 3019:     my $author=$fname;
 3020:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3021:     my ($udom,$uname)=split(/\//,$author);
 3022:     my $home=homeserver($uname,$udom);
 3023:     if ($home eq 'no_host') {
 3024:         return 'not_found';
 3025:     }
 3026:     my $answer=reply("sub:$fname",$home);
 3027:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 3028: 	$answer.=' by '.$home;
 3029:     }
 3030:     return $answer;
 3031: }
 3032:     
 3033: # -------------------------------------------------------------- Replicate file
 3034: 
 3035: sub repcopy {
 3036:     my $filename=shift;
 3037:     $filename=~s/\/+/\//g;
 3038:     my $londocroot = $perlvar{'lonDocRoot'};
 3039:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
 3040:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
 3041:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
 3042: 	$filename=~m{^/*(uploaded|editupload)/}) {
 3043: 	return &repcopy_userfile($filename);
 3044:     }
 3045:     $filename=~s/[\n\r]//g;
 3046:     my $transname="$filename.in.transfer";
 3047: # FIXME: this should flock
 3048:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 3049:     my $remoteurl=subscribe($filename);
 3050:     if ($remoteurl =~ /^con_lost by/) {
 3051: 	   &logthis("Subscribe returned $remoteurl: $filename");
 3052:            return 'unavailable';
 3053:     } elsif ($remoteurl eq 'not_found') {
 3054: 	   #&logthis("Subscribe returned not_found: $filename");
 3055: 	   return 'not_found';
 3056:     } elsif ($remoteurl =~ /^rejected by/) {
 3057: 	   &logthis("Subscribe returned $remoteurl: $filename");
 3058:            return 'forbidden';
 3059:     } elsif ($remoteurl eq 'directory') {
 3060:            return 'ok';
 3061:     } else {
 3062:         my $author=$filename;
 3063:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3064:         my ($udom,$uname)=split(/\//,$author);
 3065:         my $home=homeserver($uname,$udom);
 3066:         unless ($home eq $perlvar{'lonHostID'}) {
 3067:            my @parts=split(/\//,$filename);
 3068:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 3069:            if ($path ne "$londocroot/res") {
 3070:                &logthis("Malconfiguration for replication: $filename");
 3071: 	       return 'bad_request';
 3072:            }
 3073:            my $count;
 3074:            for ($count=5;$count<$#parts;$count++) {
 3075:                $path.="/$parts[$count]";
 3076:                if ((-e $path)!=1) {
 3077: 		   mkdir($path,0777);
 3078:                }
 3079:            }
 3080:            my $ua=new LWP::UserAgent;
 3081:            my $request=new HTTP::Request('GET',"$remoteurl");
 3082:            my $response=$ua->request($request,$transname);
 3083:            if ($response->is_error()) {
 3084: 	       unlink($transname);
 3085:                my $message=$response->status_line;
 3086:                &logthis("<font color=\"blue\">WARNING:"
 3087:                        ." LWP get: $message: $filename</font>");
 3088:                return 'unavailable';
 3089:            } else {
 3090: 	       if ($remoteurl!~/\.meta$/) {
 3091:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 3092:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
 3093:                   if ($mresponse->is_error()) {
 3094: 		      unlink($filename.'.meta');
 3095:                       &logthis(
 3096:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 3097:                   }
 3098: 	       }
 3099:                rename($transname,$filename);
 3100:                return 'ok';
 3101:            }
 3102:        }
 3103:     }
 3104: }
 3105: 
 3106: # ------------------------------------------------- Unsubscribe from a resource
 3107: 
 3108: sub unsubscribe {
 3109:     my ($fname) = @_;
 3110:     my $answer;
 3111:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return $answer; }
 3112:     $fname=~s/[\n\r]//g;
 3113:     my $author=$fname;
 3114:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3115:     my ($udom,$uname)=split(/\//,$author);
 3116:     my $home=homeserver($uname,$udom);
 3117:     if ($home eq 'no_host') {
 3118:         $answer = 'no_host';
 3119:     } elsif (grep { $_ eq $home } &current_machine_ids()) {
 3120:         $answer = 'home';
 3121:     } else {
 3122:         $answer = reply("unsub:$fname",$home);
 3123:     }
 3124:     return $answer;
 3125: }
 3126: 
 3127: # ------------------------------------------------ Get server side include body
 3128: sub ssi_body {
 3129:     my ($filelink,%form)=@_;
 3130:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 3131:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 3132:     }
 3133:     my $output='';
 3134:     my $response;
 3135:     if ($filelink=~/^https?\:/) {
 3136:        ($output,$response)=&externalssi($filelink);
 3137:     } else {
 3138:        $filelink .= $filelink=~/\?/ ? '&' : '?';
 3139:        $filelink .= 'inhibitmenu=yes';
 3140:        ($output,$response)=&ssi($filelink,%form);
 3141:     }
 3142:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 3143:     $output=~s/^.*?\<body[^\>]*\>//si;
 3144:     $output=~s/\<\/body\s*\>.*?$//si;
 3145:     if (wantarray) {
 3146:         return ($output, $response);
 3147:     } else {
 3148:         return $output;
 3149:     }
 3150: }
 3151: 
 3152: # --------------------------------------------------------- Server Side Include
 3153: 
 3154: sub absolute_url {
 3155:     my ($host_name) = @_;
 3156:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 3157:     if ($host_name eq '') {
 3158: 	$host_name = $ENV{'SERVER_NAME'};
 3159:     }
 3160:     return $protocol.$host_name;
 3161: }
 3162: 
 3163: #
 3164: #   Server side include.
 3165: # Parameters:
 3166: #  fn     Possibly encrypted resource name/id.
 3167: #  form   Hash that describes how the rendering should be done
 3168: #         and other things.
 3169: # Returns:
 3170: #   Scalar context: The content of the response.
 3171: #   Array context:  2 element list of the content and the full response object.
 3172: #     
 3173: sub ssi {
 3174: 
 3175:     my ($fn,%form)=@_;
 3176:     my ($request,$response);
 3177: 
 3178:     $form{'no_update_last_known'}=1;
 3179:     &Apache::lonenc::check_encrypt(\$fn);
 3180:     if (%form) {
 3181:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 3182:       $request->content(join('&',map {
 3183:             my $name = escape($_);
 3184:             "$name=" . ( ref($form{$_}) eq 'ARRAY'
 3185:             ? join("&$name=", map {escape($_) } @{$form{$_}})
 3186:             : &escape($form{$_}) );
 3187:         } keys(%form)));
 3188:     } else {
 3189:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 3190:     }
 3191: 
 3192:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 3193: 
 3194:     if (($env{'request.course.id'}) &&
 3195:         ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
 3196:         ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
 3197:         ($form{'grade_symb'} ne '') &&
 3198:         (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
 3199:                                  ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
 3200:         if (LWP::UserAgent->VERSION >= 5.834) {
 3201:             my $ua=new LWP::UserAgent;
 3202:             $ua->local_address('127.0.0.1');
 3203:             $response = $ua->request($request);
 3204:         } else {
 3205:             {
 3206:                 require LWP::Protocol::http;
 3207:                 local @LWP::Protocol::http::EXTRA_SOCK_OPTS = (LocalAddr => '127.0.0.1');
 3208:                 my $ua=new LWP::UserAgent;
 3209:                 $response = $ua->request($request);
 3210:                 @LWP::Protocol::http::EXTRA_SOCK_OPTS = ();
 3211:             }
 3212:         }
 3213:     } else {
 3214:         my $ua=new LWP::UserAgent;
 3215:         $response = $ua->request($request);
 3216:     }
 3217:     if (wantarray) {
 3218: 	return ($response->content, $response);
 3219:     } else {
 3220: 	return $response->content;
 3221:     }
 3222: }
 3223: 
 3224: sub externalssi {
 3225:     my ($url)=@_;
 3226:     my $ua=new LWP::UserAgent;
 3227:     my $request=new HTTP::Request('GET',$url);
 3228:     my $response=$ua->request($request);
 3229:     if (wantarray) {
 3230:         return ($response->content, $response);
 3231:     } else {
 3232:         return $response->content;
 3233:     }
 3234: }
 3235: 
 3236: # If the local copy of a replicated resource is outdated, trigger a
 3237: # connection from the homeserver to flush the delayed queue. If no update
 3238: # happens, remove local copies of outdated resource (and corresponding
 3239: # metadata file).
 3240: 
 3241: sub remove_stale_resfile {
 3242:     my ($url) = @_;
 3243:     my $removed;
 3244:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
 3245:         my $audom = $1;
 3246:         my $auname = $2;
 3247:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
 3248:             my $homeserver = &homeserver($auname,$audom);
 3249:             unless (($homeserver eq 'no_host') ||
 3250:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
 3251:                 my $fname = &filelocation('',$url);
 3252:                 if (-e $fname) {
 3253:                     my $hostname = &hostname($homeserver);
 3254:                     if ($hostname) {
 3255:                         my $protocol = $protocol{$homeserver};
 3256:                         $protocol = 'http' if ($protocol ne 'https');
 3257:                         my $uri = $protocol.'://'.$hostname.'/raw/'.&declutter($url);
 3258:                         my $ua=new LWP::UserAgent;
 3259:                         $ua->timeout(5);
 3260:                         my $request=new HTTP::Request('HEAD',$uri);
 3261:                         my $response=$ua->request($request);
 3262:                         if ($response->is_success()) {
 3263:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
 3264:                             my $locmodtime = (stat($fname))[9];
 3265:                             if ($locmodtime < $remmodtime) {
 3266:                                 my $stale;
 3267:                                 my $answer = &reply('pong',$homeserver);
 3268:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
 3269:                                     sleep(0.2);
 3270:                                     $locmodtime = (stat($fname))[9];
 3271:                                     if ($locmodtime < $remmodtime) {
 3272:                                         my $posstransfer = $fname.'.in.transfer';
 3273:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
 3274:                                             $removed = 1;
 3275:                                         } else {
 3276:                                             $stale = 1;
 3277:                                         }
 3278:                                     } else {
 3279:                                         $removed = 1;
 3280:                                     }
 3281:                                 } else {
 3282:                                     $stale = 1;
 3283:                                 }
 3284:                                 if ($stale) {
 3285:                                     if (unlink($fname)) {
 3286:                                         if ($uri!~/\.meta$/) {
 3287:                                             if (-e $fname.'.meta') {
 3288:                                                 unlink($fname.'.meta');
 3289:                                             }
 3290:                                         }
 3291:                                         my $unsubresult = &unsubscribe($fname);
 3292:                                         unless ($unsubresult eq 'ok') {
 3293:                                             &logthis("no unsub of $fname from $homeserver, reason: $unsubresult");
 3294:                                         }
 3295:                                         $removed = 1;
 3296:                                     }
 3297:                                 }
 3298:                             }
 3299:                         }
 3300:                     }
 3301:                 }
 3302:             }
 3303:         }
 3304:     }
 3305:     return $removed;
 3306: }
 3307: 
 3308: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 3309: 
 3310: sub allowuploaded {
 3311:     my ($srcurl,$url)=@_;
 3312:     $url=&clutter(&declutter($url));
 3313:     my $dir=$url;
 3314:     $dir=~s/\/[^\/]+$//;
 3315:     my %httpref=();
 3316:     my $httpurl=&hreflocation('',$url);
 3317:     $httpref{'httpref.'.$httpurl}=$srcurl;
 3318:     &Apache::lonnet::appenv(\%httpref);
 3319: }
 3320: 
 3321: #
 3322: # Determine if the current user should be able to edit a particular resource,
 3323: # when viewing in course context.
 3324: # (a) When viewing resource used to determine if "Edit" item is included in
 3325: #     Functions.
 3326: # (b) When displaying folder contents in course editor, used to determine if
 3327: #     "Edit" link will be displayed alongside resource.
 3328: #
 3329: #  input: six args -- filename (decluttered), course number, course domain,
 3330: #                   url, symb (if registered) and group (if this is a group
 3331: #                   item -- e.g., bulletin board, group page etc.).
 3332: #  output: array of five scalars --
 3333: #          $cfile -- url for file editing if editable on current server
 3334: #          $home -- homeserver of resource (i.e., for author if published,
 3335: #                                           or course if uploaded.).
 3336: #          $switchserver --  1 if server switch will be needed.
 3337: #          $forceedit -- 1 if icon/link should be to go to edit mode
 3338: #          $forceview -- 1 if icon/link should be to go to view mode
 3339: #
 3340: 
 3341: sub can_edit_resource {
 3342:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
 3343:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
 3344: #
 3345: # For aboutme pages user can only edit his/her own.
 3346: #
 3347:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
 3348:         my ($sdom,$sname) = ($1,$2);
 3349:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
 3350:             $home = $env{'user.home'};
 3351:             $cfile = $resurl;
 3352:             if ($env{'form.forceedit'}) {
 3353:                 $forceview = 1;
 3354:             } else {
 3355:                 $forceedit = 1;
 3356:             }
 3357:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
 3358:         } else {
 3359:             return;
 3360:         }
 3361:     }
 3362: 
 3363:     if ($env{'request.course.id'}) {
 3364:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
 3365:         if ($group ne '') {
 3366: # if this is a group homepage or group bulletin board, check group privs
 3367:             my $allowed = 0;
 3368:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
 3369:                 if ((&allowed('mdg',$env{'request.course.id'}.
 3370:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 3371:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 3372:                     $allowed = 1;
 3373:                 }
 3374:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
 3375:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 3376:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 3377:                     $allowed = 1;
 3378:                 }
 3379:             }
 3380:             if ($allowed) {
 3381:                 $home=&homeserver($cnum,$cdom);
 3382:                 if ($env{'form.forceedit'}) {
 3383:                     $forceview = 1;
 3384:                 } else {
 3385:                     $forceedit = 1;
 3386:                 }
 3387:                 $cfile = $resurl;
 3388:             } else {
 3389:                 return;
 3390:             }
 3391:         } else {
 3392:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
 3393:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
 3394:                     return;
 3395:                 }
 3396:             } elsif (!$crsedit) {
 3397: #
 3398: # No edit allowed where CC has switched to student role.
 3399: #
 3400:                 return;
 3401:             }
 3402:         }
 3403:     }
 3404: 
 3405:     if ($file ne '') {
 3406:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
 3407:             if (&is_course_upload($file,$cnum,$cdom)) {
 3408:                 $uploaded = 1;
 3409:                 $incourse = 1;
 3410:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
 3411:                     $cfile = &hreflocation('',$file);
 3412:                     if ($env{'form.forceedit'}) {
 3413:                         $forceview = 1;
 3414:                     } else {
 3415:                         $forceedit = 1;
 3416:                     }
 3417:                 }
 3418:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
 3419:                 $incourse = 1;
 3420:                 if ($env{'form.forceedit'}) {
 3421:                     $forceview = 1;
 3422:                 } else {
 3423:                     $forceedit = 1;
 3424:                 }
 3425:                 $cfile = $resurl;
 3426:             } elsif (($resurl ne '') && (&is_on_map($resurl))) {
 3427:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
 3428:                     $incourse = 1;
 3429:                     if ($env{'form.forceedit'}) {
 3430:                         $forceview = 1;
 3431:                     } else {
 3432:                         $forceedit = 1;
 3433:                     }
 3434:                     $cfile = $resurl;
 3435:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
 3436:                     $incourse = 1;
 3437:                     $cfile = $resurl.'/smpedit';
 3438:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
 3439:                     $incourse = 1;
 3440:                     if ($env{'form.forceedit'}) {
 3441:                         $forceview = 1;
 3442:                     } else {
 3443:                         $forceedit = 1;
 3444:                     }
 3445:                     $cfile = $resurl;
 3446:                 } elsif (($resurl =~ m{^/ext/}) && ($symb ne '')) {
 3447:                     my ($map,$id,$res) = &decode_symb($symb);
 3448:                     if ($map =~ /\.page$/) {
 3449:                         $incourse = 1;
 3450:                         if ($env{'form.forceedit'}) {
 3451:                             $forceview = 1;
 3452:                             $cfile = $map;
 3453:                         } else {
 3454:                             $forceedit = 1;
 3455:                             $cfile =  '/adm/wrapper'.$resurl;
 3456:                         }
 3457:                     }
 3458:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 3459:                     $incourse = 1;
 3460:                     if ($env{'form.forceedit'}) {
 3461:                         $forceview = 1;
 3462:                     } else {
 3463:                         $forceedit = 1;
 3464:                     }
 3465:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 3466:                 }
 3467:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
 3468:                 my $template = '/res/lib/templates/simpleproblem.problem';
 3469:                 if (&is_on_map($template)) {
 3470:                     $incourse = 1;
 3471:                     $forceview = 1;
 3472:                     $cfile = $template;
 3473:                 }
 3474:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 3475:                 $incourse = 1;
 3476:                 if ($env{'form.forceedit'}) {
 3477:                     $forceview = 1;
 3478:                 } else {
 3479:                     $forceedit = 1;
 3480:                 }
 3481:                 $cfile = $resurl;
 3482:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
 3483:                 $incourse = 1;
 3484:                 $forceview = 1;
 3485:                 if ($symb) {
 3486:                     my ($map,$id,$res)=&decode_symb($symb);
 3487:                     $env{'request.symb'} = $symb;
 3488:                     $cfile = &clutter($res);
 3489:                 } else {
 3490:                     $cfile = $env{'form.suppurl'};
 3491:                     $cfile =~ s{^http://}{};
 3492:                     $cfile = '/adm/wrapper/ext/'.$cfile;
 3493:                 }
 3494:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 3495:                 if ($env{'form.forceedit'}) {
 3496:                     $forceview = 1;
 3497:                 } else {
 3498:                     $forceedit = 1;
 3499:                 }
 3500:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 3501:             }
 3502:         }
 3503:         if ($uploaded || $incourse) {
 3504:             $home=&homeserver($cnum,$cdom);
 3505:         } elsif ($file !~ m{/$}) {
 3506:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
 3507:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
 3508:             # Check that the user has permission to edit this resource
 3509:             my $setpriv = 1;
 3510:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
 3511:             if (defined($cfudom)) {
 3512:                 $home=&homeserver($cfuname,$cfudom);
 3513:                 $cfile=$file;
 3514:             }
 3515:         }
 3516:         if (($cfile ne '') && (!$incourse || $uploaded) &&
 3517:             (($home ne '') && ($home ne 'no_host'))) {
 3518:             my @ids=&current_machine_ids();
 3519:             unless (grep(/^\Q$home\E$/,@ids)) {
 3520:                 $switchserver=1;
 3521:             }
 3522:         }
 3523:     }
 3524:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
 3525: }
 3526: 
 3527: sub is_course_upload {
 3528:     my ($file,$cnum,$cdom) = @_;
 3529:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
 3530:     $uploadpath =~ s{^\/}{};
 3531:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
 3532:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
 3533:         return 1;
 3534:     }
 3535:     return;
 3536: }
 3537: 
 3538: sub in_course {
 3539:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
 3540:     if ($hideprivileged) {
 3541:         my $skipuser;
 3542:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
 3543:         my @possdoms = ($cdom);
 3544:         if ($coursehash{'checkforpriv'}) {
 3545:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
 3546:         }
 3547:         if (&privileged($uname,$udom,\@possdoms)) {
 3548:             $skipuser = 1;
 3549:             if ($coursehash{'nothideprivileged'}) {
 3550:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3551:                     my $user;
 3552:                     if ($item =~ /:/) {
 3553:                         $user = $item;
 3554:                     } else {
 3555:                         $user = join(':',split(/[\@]/,$item));
 3556:                     }
 3557:                     if ($user eq $uname.':'.$udom) {
 3558:                         undef($skipuser);
 3559:                         last;
 3560:                     }
 3561:                 }
 3562:             }
 3563:             if ($skipuser) {
 3564:                 return 0;
 3565:             }
 3566:         }
 3567:     }
 3568:     $type ||= 'any';
 3569:     if (!defined($cdom) || !defined($cnum)) {
 3570:         my $cid  = $env{'request.course.id'};
 3571:         $cdom = $env{'course.'.$cid.'.domain'};
 3572:         $cnum = $env{'course.'.$cid.'.num'};
 3573:     }
 3574:     my $typesref;
 3575:     if (($type eq 'any') || ($type eq 'all')) {
 3576:         $typesref = ['active','previous','future'];
 3577:     } elsif ($type eq 'previous' || $type eq 'future') {
 3578:         $typesref = [$type];
 3579:     }
 3580:     my %roles = &get_my_roles($uname,$udom,'userroles',
 3581:                               $typesref,undef,[$cdom]);
 3582:     my ($tmp) = keys(%roles);
 3583:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
 3584:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
 3585:     if (@course_roles > 0) {
 3586:         return 1;
 3587:     }
 3588:     return 0;
 3589: }
 3590: 
 3591: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 3592: # input: action, courseID, current domain, intended
 3593: #        path to file, source of file, instruction to parse file for objects,
 3594: #        ref to hash for embedded objects,
 3595: #        ref to hash for codebase of java objects.
 3596: #        reference to scalar to accommodate mime type determined
 3597: #          from File::MMagic if $parser = parse.
 3598: #
 3599: # output: url to file (if action was uploaddoc), 
 3600: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 3601: #
 3602: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 3603: # course.
 3604: #
 3605: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3606: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 3607: #          course's home server.
 3608: #
 3609: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 3610: #          be copied from $source (current location) to 
 3611: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3612: #         and will then be copied to
 3613: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 3614: #         course's home server.
 3615: #
 3616: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3617: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 3618: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3619: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 3620: #         in course's home server.
 3621: #
 3622: 
 3623: sub process_coursefile {
 3624:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
 3625:         $mimetype)=@_;
 3626:     my $fetchresult;
 3627:     my $home=&homeserver($docuname,$docudom);
 3628:     if ($action eq 'propagate') {
 3629:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3630: 			     $home);
 3631:     } else {
 3632:         my $fpath = '';
 3633:         my $fname = $file;
 3634:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3635:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3636:         my $filepath = &build_filepath($fpath);
 3637:         if ($action eq 'copy') {
 3638:             if ($source eq '') {
 3639:                 $fetchresult = 'no source file';
 3640:                 return $fetchresult;
 3641:             } else {
 3642:                 my $destination = $filepath.'/'.$fname;
 3643:                 rename($source,$destination);
 3644:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3645:                                  $home);
 3646:             }
 3647:         } elsif ($action eq 'uploaddoc') {
 3648:             open(my $fh,'>',$filepath.'/'.$fname);
 3649:             print $fh $env{'form.'.$source};
 3650:             close($fh);
 3651:             if ($parser eq 'parse') {
 3652:                 my $mm = new File::MMagic;
 3653:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
 3654:                 if ($type eq 'text/html') {
 3655:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 3656:                     unless ($parse_result eq 'ok') {
 3657:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 3658:                     }
 3659:                 }
 3660:                 if (ref($mimetype)) {
 3661:                     $$mimetype = $type;
 3662:                 } 
 3663:             }
 3664:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3665:                                  $home);
 3666:             if ($fetchresult eq 'ok') {
 3667:                 return '/uploaded/'.$fpath.'/'.$fname;
 3668:             } else {
 3669:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3670:                         ' to host '.$home.': '.$fetchresult);
 3671:                 return '/adm/notfound.html';
 3672:             }
 3673:         }
 3674:     }
 3675:     unless ( $fetchresult eq 'ok') {
 3676:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3677:              ' to host '.$home.': '.$fetchresult);
 3678:     }
 3679:     return $fetchresult;
 3680: }
 3681: 
 3682: sub build_filepath {
 3683:     my ($fpath) = @_;
 3684:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 3685:     unless ($fpath eq '') {
 3686:         my @parts=split('/',$fpath);
 3687:         foreach my $part (@parts) {
 3688:             $filepath.= '/'.$part;
 3689:             if ((-e $filepath)!=1) {
 3690:                 mkdir($filepath,0777);
 3691:             }
 3692:         }
 3693:     }
 3694:     return $filepath;
 3695: }
 3696: 
 3697: sub store_edited_file {
 3698:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 3699:     my $file = $primary_url;
 3700:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 3701:     my $fpath = '';
 3702:     my $fname = $file;
 3703:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3704:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3705:     my $filepath = &build_filepath($fpath);
 3706:     open(my $fh,'>',$filepath.'/'.$fname);
 3707:     print $fh $content;
 3708:     close($fh);
 3709:     my $home=&homeserver($docuname,$docudom);
 3710:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3711: 			  $home);
 3712:     if ($$fetchresult eq 'ok') {
 3713:         return '/uploaded/'.$fpath.'/'.$fname;
 3714:     } else {
 3715:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3716: 		 ' to host '.$home.': '.$$fetchresult);
 3717:         return '/adm/notfound.html';
 3718:     }
 3719: }
 3720: 
 3721: sub clean_filename {
 3722:     my ($fname,$args)=@_;
 3723: # Replace Windows backslashes by forward slashes
 3724:     $fname=~s/\\/\//g;
 3725:     if (!$args->{'keep_path'}) {
 3726:         # Get rid of everything but the actual filename
 3727: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 3728:     }
 3729: # Replace spaces by underscores
 3730:     $fname=~s/\s+/\_/g;
 3731: # Transliterate non-ascii text to ascii
 3732:     my $lang = &Apache::lonlocal::current_language();
 3733:     $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
 3734: # Replace all other weird characters by nothing
 3735:     $fname=~s{[^/\w\.\-]}{}g;
 3736: # Replace all .\d. sequences with _\d. so they no longer look like version
 3737: # numbers
 3738:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 3739: # Replace three or more adjacent underscores with one for consistency
 3740: # with loncfile::filename_check() so complete url can be extracted by
 3741: # lonnet::decode_symb()
 3742:     $fname=~s/_{3,}/_/g;
 3743:     return $fname;
 3744: }
 3745: 
 3746: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
 3747: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
 3748: # image with the same aspect ratio as the original, but with dimensions which do 
 3749: # not exceed $resizewidth and $resizeheight.
 3750:  
 3751: sub resizeImage {
 3752:     my ($img_path,$resizewidth,$resizeheight) = @_;
 3753:     my $ima = Image::Magick->new;
 3754:     my $resized;
 3755:     if (-e $img_path) {
 3756:         $ima->Read($img_path);
 3757:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
 3758:             my $width = $ima->Get('width');
 3759:             my $height = $ima->Get('height');
 3760:             if ($width > $resizewidth) {
 3761: 	        my $factor = $width/$resizewidth;
 3762:                 my $newheight = $height/$factor;
 3763:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
 3764:                 $resized = 1;
 3765:             }
 3766:         }
 3767:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
 3768:             my $width = $ima->Get('width');
 3769:             my $height = $ima->Get('height');
 3770:             if ($height > $resizeheight) {
 3771:                 my $factor = $height/$resizeheight;
 3772:                 my $newwidth = $width/$factor;
 3773:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
 3774:                 $resized = 1;
 3775:             }
 3776:         }
 3777:         if ($resized) {
 3778:             $ima->Write($img_path);
 3779:         }
 3780:     }
 3781:     return;
 3782: }
 3783: 
 3784: # --------------- Take an uploaded file and put it into the userfiles directory
 3785: # input: $formname - the contents of the file are in $env{"form.$formname"}
 3786: #                    the desired filename is in $env{"form.$formname.filename"}
 3787: #        $context - possible values: coursedoc, existingfile, overwrite, 
 3788: #                                    canceloverwrite, scantron or ''. 
 3789: #                   if 'coursedoc': upload to the current course
 3790: #                   if 'existingfile': write file to tmp/overwrites directory 
 3791: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
 3792: #                   $context is passed as argument to &finishuserfileupload
 3793: #        $subdir - directory in userfile to store the file into
 3794: #        $parser - instruction to parse file for objects ($parser = parse) or
 3795: #                  if context is 'scantron', $parser is hashref of csv column mapping
 3796: #                  (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3,
 3797: #                          Section => 4, CODE => 5, FirstQuestion => 9 }).
 3798: #        $allfiles - reference to hash for embedded objects
 3799: #        $codebase - reference to hash for codebase of java objects
 3800: #        $desuname - username for permanent storage of uploaded file
 3801: #        $dsetudom - domain for permanaent storage of uploaded file
 3802: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 3803: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 3804: #        $resizewidth - width (pixels) to which to resize uploaded image
 3805: #        $resizeheight - height (pixels) to which to resize uploaded image
 3806: #        $mimetype - reference to scalar to accommodate mime type determined
 3807: #                    from File::MMagic.
 3808: # 
 3809: # output: url of file in userspace, or error: <message> 
 3810: #             or /adm/notfound.html if failure to upload occurse
 3811: 
 3812: sub userfileupload {
 3813:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
 3814:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
 3815:     if (!defined($subdir)) { $subdir='unknown'; }
 3816:     my $fname=$env{'form.'.$formname.'.filename'};
 3817:     $fname=&clean_filename($fname);
 3818:     # See if there is anything left
 3819:     unless ($fname) { return 'error: no uploaded file'; }
 3820:     # If filename now begins with a . prepend unix timestamp _ milliseconds
 3821:     if ($fname =~ /^\./) {
 3822:         my ($s,$usec) = &gettimeofday();
 3823:         while (length($usec) < 6) {
 3824:             $usec = '0'.$usec;
 3825:         }
 3826:         $fname = $s.'_'.substr($usec,0,3).$fname;
 3827:     }
 3828:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
 3829:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
 3830:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
 3831:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3832:         my $now = time;
 3833:         my $filepath;
 3834:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
 3835:              $filepath = 'tmp/helprequests/'.$now;
 3836:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
 3837:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 3838:                          '_'.$env{'user.domain'}.'/pending';
 3839:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3840:             my ($docuname,$docudom);
 3841:             if ($destudom =~ /^$match_domain$/) {
 3842:                 $docudom = $destudom;
 3843:             } else {
 3844:                 $docudom = $env{'user.domain'};
 3845:             }
 3846:             if ($destuname =~ /^$match_username$/) { 
 3847:                 $docuname = $destuname;
 3848:             } else {
 3849:                 $docuname = $env{'user.name'};
 3850:             }
 3851:             if (exists($env{'form.group'})) {
 3852:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3853:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3854:             }
 3855:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
 3856:             if ($context eq 'canceloverwrite') {
 3857:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
 3858:                 if (-e  $tempfile) {
 3859:                     my @info = stat($tempfile);
 3860:                     if ($info[9] eq $env{'form.timestamp'}) {
 3861:                         unlink($tempfile);
 3862:                     }
 3863:                 }
 3864:                 return;
 3865:             }
 3866:         }
 3867:         # Create the directory if not present
 3868:         my @parts=split(/\//,$filepath);
 3869:         my $fullpath = $perlvar{'lonDaemons'};
 3870:         for (my $i=0;$i<@parts;$i++) {
 3871:             $fullpath .= '/'.$parts[$i];
 3872:             if ((-e $fullpath)!=1) {
 3873:                 mkdir($fullpath,0777);
 3874:             }
 3875:         }
 3876:         open(my $fh,'>',$fullpath.'/'.$fname);
 3877:         print $fh $env{'form.'.$formname};
 3878:         close($fh);
 3879:         if ($context eq 'existingfile') {
 3880:             my @info = stat($fullpath.'/'.$fname);
 3881:             return ($fullpath.'/'.$fname,$info[9]);
 3882:         } else {
 3883:             return $fullpath.'/'.$fname;
 3884:         }
 3885:     }
 3886:     if ($subdir eq 'scantron') {
 3887:         $fname = 'scantron_orig_'.$fname;
 3888:     } else {
 3889:         $fname="$subdir/$fname";
 3890:     }
 3891:     if ($context eq 'coursedoc') {
 3892: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3893: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3894:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 3895:             return &finishuserfileupload($docuname,$docudom,
 3896: 					 $formname,$fname,$parser,$allfiles,
 3897: 					 $codebase,$thumbwidth,$thumbheight,
 3898:                                          $resizewidth,$resizeheight,$context,$mimetype);
 3899:         } else {
 3900:             if ($env{'form.folder'}) {
 3901:                 $fname=$env{'form.folder'}.'/'.$fname;
 3902:             }
 3903:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 3904: 				       $fname,$formname,$parser,
 3905: 				       $allfiles,$codebase,$mimetype);
 3906:         }
 3907:     } elsif (defined($destuname)) {
 3908:         my $docuname=$destuname;
 3909:         my $docudom=$destudom;
 3910: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 3911: 				     $parser,$allfiles,$codebase,
 3912:                                      $thumbwidth,$thumbheight,
 3913:                                      $resizewidth,$resizeheight,$context,$mimetype);
 3914:     } else {
 3915:         my $docuname=$env{'user.name'};
 3916:         my $docudom=$env{'user.domain'};
 3917:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
 3918:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3919:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3920:         }
 3921: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 3922: 				     $parser,$allfiles,$codebase,
 3923:                                      $thumbwidth,$thumbheight,
 3924:                                      $resizewidth,$resizeheight,$context,$mimetype);
 3925:     }
 3926: }
 3927: 
 3928: sub finishuserfileupload {
 3929:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 3930:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
 3931:     my $path=$docudom.'/'.$docuname.'/';
 3932:     my $filepath=$perlvar{'lonDocRoot'};
 3933:   
 3934:     my ($fnamepath,$file,$fetchthumb);
 3935:     $file=$fname;
 3936:     if ($fname=~m|/|) {
 3937:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 3938: 	$path.=$fnamepath.'/';
 3939:     }
 3940:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 3941:     my $count;
 3942:     for ($count=4;$count<=$#parts;$count++) {
 3943:         $filepath.="/$parts[$count]";
 3944:         if ((-e $filepath)!=1) {
 3945: 	    mkdir($filepath,0777);
 3946:         }
 3947:     }
 3948: 
 3949: # Save the file
 3950:     {
 3951: 	if (!open(FH,'>',$filepath.'/'.$file)) {
 3952: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 3953: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 3954: 	    return '/adm/notfound.html';
 3955: 	}
 3956:         if ($context eq 'overwrite') {
 3957:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
 3958:             my $target = $filepath.'/'.$file;
 3959:             if (-e $source) {
 3960:                 my @info = stat($source);
 3961:                 if ($info[9] eq $env{'form.timestamp'}) {   
 3962:                     unless (&File::Copy::move($source,$target)) {
 3963:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
 3964:                         return "Moving from $source failed";
 3965:                     }
 3966:                 } else {
 3967:                     return "Temporary file: $source had unexpected date/time for last modification";
 3968:                 }
 3969:             } else {
 3970:                 return "Temporary file: $source missing";
 3971:             }
 3972:         } elsif (!print FH ($env{'form.'.$formname})) {
 3973: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 3974: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 3975: 	    return '/adm/notfound.html';
 3976: 	}
 3977: 	close(FH);
 3978:         if ($resizewidth && $resizeheight) {
 3979:             my $mm = new File::MMagic;
 3980:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
 3981:             if ($mime_type =~ m{^image/}) {
 3982: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
 3983:             }  
 3984: 	}
 3985:     }
 3986:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
 3987:         if (ref($mimetype)) {
 3988:             if ($$mimetype eq '') {
 3989:                 my $mm = new File::MMagic;
 3990:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
 3991:                 $$mimetype = $type;
 3992:             }
 3993:         }
 3994:     }
 3995:     if (($context ne 'scantron') && ($parser eq 'parse')) {
 3996:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
 3997:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
 3998:                                                        $allfiles,$codebase);
 3999:             unless ($parse_result eq 'ok') {
 4000:                 &logthis('Failed to parse '.$filepath.$file.
 4001: 	   	         ' for embedded media: '.$parse_result); 
 4002:             }
 4003:         }
 4004:     } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
 4005:         my $format = $env{'form.scantron_format'};
 4006:         &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
 4007:     }
 4008:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 4009:         my $input = $filepath.'/'.$file;
 4010:         my $output = $filepath.'/'.'tn-'.$file;
 4011:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 4012:         my @args = ('convert','-sample',$thumbsize,$input,$output);
 4013:         system({$args[0]} @args);
 4014:         if (-e $filepath.'/'.'tn-'.$file) {
 4015:             $fetchthumb  = 1; 
 4016:         }
 4017:     }
 4018:  
 4019: # Notify homeserver to grep it
 4020: #
 4021:     my $docuhome=&homeserver($docuname,$docudom);	
 4022:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 4023:     if ($fetchresult eq 'ok') {
 4024:         if ($fetchthumb) {
 4025:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 4026:             if ($thumbresult ne 'ok') {
 4027:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 4028:                          $docuhome.': '.$thumbresult);
 4029:             }
 4030:         }
 4031: #
 4032: # Return the URL to it
 4033:         return '/uploaded/'.$path.$file;
 4034:     } else {
 4035:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 4036: 		 ': '.$fetchresult);
 4037:         return '/adm/notfound.html';
 4038:     }
 4039: }
 4040: 
 4041: sub extract_embedded_items {
 4042:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 4043:     my @state = ();
 4044:     my (%lastids,%related,%shockwave,%flashvars);
 4045:     my %javafiles = (
 4046:                       codebase => '',
 4047:                       code => '',
 4048:                       archive => ''
 4049:                     );
 4050:     my %mediafiles = (
 4051:                       src => '',
 4052:                       movie => '',
 4053:                      );
 4054:     my $p;
 4055:     if ($content) {
 4056:         $p = HTML::LCParser->new($content);
 4057:     } else {
 4058:         $p = HTML::LCParser->new($fullpath);
 4059:     }
 4060:     while (my $t=$p->get_token()) {
 4061: 	if ($t->[0] eq 'S') {
 4062: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 4063: 	    push(@state, $tagname);
 4064:             if (lc($tagname) eq 'allow') {
 4065:                 &add_filetype($allfiles,$attr->{'src'},'src');
 4066:             }
 4067: 	    if (lc($tagname) eq 'img') {
 4068: 		&add_filetype($allfiles,$attr->{'src'},'src');
 4069: 	    }
 4070: 	    if (lc($tagname) eq 'a') {
 4071:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
 4072: 		    &add_filetype($allfiles,$attr->{'href'},'href');
 4073:                 }
 4074: 	    }
 4075:             if (lc($tagname) eq 'script') {
 4076:                 my $src;
 4077:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 4078:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 4079:                 } else {
 4080:                     if ($attr->{'src'} ne '') {
 4081:                         $src = $attr->{'src'};
 4082:                         &add_filetype($allfiles,$src,'src');
 4083:                     }
 4084:                 }
 4085:                 my $text = $p->get_trimmed_text();
 4086:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
 4087:                     my @swfargs = split(/,/,$1);
 4088:                     foreach my $item (@swfargs) {
 4089:                         $item =~ s/["']//g;
 4090:                         $item =~ s/^\s+//;
 4091:                         $item =~ s/\s+$//;
 4092:                     }
 4093:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
 4094:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
 4095:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
 4096:                         } else {
 4097:                             $related{$swfargs[0]} = [$swfargs[2]];
 4098:                         }
 4099:                     }
 4100:                 }
 4101:             }
 4102:             if (lc($tagname) eq 'link') {
 4103:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 4104:                     &add_filetype($allfiles,$attr->{'href'},'href');
 4105:                 }
 4106:             }
 4107: 	    if (lc($tagname) eq 'object' ||
 4108: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 4109: 		foreach my $item (keys(%javafiles)) {
 4110: 		    $javafiles{$item} = '';
 4111: 		}
 4112:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
 4113:                     $lastids{lc($tagname)} = $attr->{'id'};
 4114:                 }
 4115: 	    }
 4116: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 4117: 		my $name = lc($attr->{'name'});
 4118: 		foreach my $item (keys(%javafiles)) {
 4119: 		    if ($name eq $item) {
 4120: 			$javafiles{$item} = $attr->{'value'};
 4121: 			last;
 4122: 		    }
 4123: 		}
 4124:                 my $pathfrom;
 4125: 		foreach my $item (keys(%mediafiles)) {
 4126: 		    if ($name eq $item) {
 4127:                         $pathfrom = $attr->{'value'};
 4128:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
 4129: 			&add_filetype($allfiles,$pathfrom,$name);
 4130: 			last;
 4131: 		    }
 4132: 		}
 4133:                 if ($name eq 'flashvars') {
 4134:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
 4135:                 }
 4136:                 if ($pathfrom ne '') {
 4137:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
 4138:                                          $pathfrom);
 4139:                 }
 4140: 	    }
 4141: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 4142: 		foreach my $item (keys(%javafiles)) {
 4143: 		    if ($attr->{$item}) {
 4144: 			$javafiles{$item} = $attr->{$item};
 4145: 			last;
 4146: 		    }
 4147: 		}
 4148: 		foreach my $item (keys(%mediafiles)) {
 4149: 		    if ($attr->{$item}) {
 4150: 			&add_filetype($allfiles,$attr->{$item},$item);
 4151: 			last;
 4152: 		    }
 4153: 		}
 4154:                 if (lc($tagname) eq 'embed') {
 4155:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
 4156:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
 4157:                                              $attr->{'src'});
 4158:                     }
 4159:                 }
 4160: 	    }
 4161:             if (lc($tagname) eq 'iframe') {
 4162:                 my $src = $attr->{'src'} ;
 4163:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
 4164:                     &add_filetype($allfiles,$src,'src');
 4165:                 } elsif ($src =~ m{^/}) {
 4166:                     if ($env{'request.course.id'}) {
 4167:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4168:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4169:                         my $url = &hreflocation('',$fullpath);
 4170:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
 4171:                             my $relpath = $1;
 4172:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
 4173:                                 &add_filetype($allfiles,$1,'src');
 4174:                             }
 4175:                         }
 4176:                     }
 4177:                 }
 4178:             }
 4179:             if ($t->[4] =~ m{/>$}) {
 4180:                 pop(@state);
 4181:             }
 4182: 	} elsif ($t->[0] eq 'E') {
 4183: 	    my ($tagname) = ($t->[1]);
 4184: 	    if ($javafiles{'codebase'} ne '') {
 4185: 		$javafiles{'codebase'} .= '/';
 4186: 	    }  
 4187: 	    if (lc($tagname) eq 'applet' ||
 4188: 		lc($tagname) eq 'object' ||
 4189: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 4190: 		) {
 4191: 		foreach my $item (keys(%javafiles)) {
 4192: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 4193: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 4194: 			&add_filetype($allfiles,$file,$item);
 4195: 		    }
 4196: 		}
 4197: 	    } 
 4198: 	    pop @state;
 4199: 	}
 4200:     }
 4201:     foreach my $id (sort(keys(%flashvars))) {
 4202:         if ($shockwave{$id} ne '') {
 4203:             my @pairs = split(/\&/,$flashvars{$id});
 4204:             foreach my $pair (@pairs) {
 4205:                 my ($key,$value) = split(/\=/,$pair);
 4206:                 if ($key eq 'thumb') {
 4207:                     &add_filetype($allfiles,$value,$key);
 4208:                 } elsif ($key eq 'content') {
 4209:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
 4210:                     my ($ext) = ($value =~ /\.([^.]+)$/);
 4211:                     if ($ext ne '') {
 4212:                         &add_filetype($allfiles,$path.$value,$ext);
 4213:                     }
 4214:                 }
 4215:             }
 4216:         }
 4217:     }
 4218:     return 'ok';
 4219: }
 4220: 
 4221: sub add_filetype {
 4222:     my ($allfiles,$file,$type)=@_;
 4223:     if (exists($allfiles->{$file})) {
 4224: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 4225: 	    push(@{$allfiles->{$file}}, &escape($type));
 4226: 	}
 4227:     } else {
 4228: 	@{$allfiles->{$file}} = (&escape($type));
 4229:     }
 4230: }
 4231: 
 4232: sub embedded_dependency {
 4233:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
 4234:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
 4235:         if (($identifier ne '') &&
 4236:             (ref($related->{$identifier}) eq 'ARRAY') &&
 4237:             ($pathfrom ne '')) {
 4238:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
 4239:             foreach my $dep (@{$related->{$identifier}}) {
 4240:                 &add_filetype($allfiles,$path.$dep,'object');
 4241:             }
 4242:         }
 4243:     }
 4244:     return;
 4245: }
 4246: 
 4247: sub bubblesheet_converter {
 4248:     my ($cdom,$fullpath,$config,$format) = @_;
 4249:     if ((&domain($cdom) ne '') &&
 4250:         ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
 4251:         (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
 4252:         my (%csvcols,%csvoptions);
 4253:         if (ref($config->{'fields'}) eq 'HASH') {
 4254:             %csvcols = %{$config->{'fields'}};
 4255:         }
 4256:         if (ref($config->{'options'}) eq 'HASH') {
 4257:             %csvoptions = %{$config->{'options'}};
 4258:         }
 4259:         my %csvbynum = reverse(%csvcols);
 4260:         my %scantronconf = &get_scantron_config($format,$cdom);
 4261:         if (keys(%scantronconf)) {
 4262:             my %bynum = (
 4263:                           $scantronconf{CODEstart} => 'CODEstart',
 4264:                           $scantronconf{IDstart}   => 'IDstart',
 4265:                           $scantronconf{PaperID}   => 'PaperID',
 4266:                           $scantronconf{FirstName} => 'FirstName',
 4267:                           $scantronconf{LastName}  => 'LastName',
 4268:                           $scantronconf{Qstart}    => 'Qstart',
 4269:                         );
 4270:             my @ordered;
 4271:             foreach my $item (sort { $a <=> $b } keys(%bynum)) {
 4272:                 push(@ordered,$bynum{$item});
 4273:             }
 4274:             my %mapstart = (
 4275:                               CODEstart => 'CODE',
 4276:                               IDstart   => 'ID',
 4277:                               PaperID   => 'PaperID',
 4278:                               FirstName => 'FirstName',
 4279:                               LastName  => 'LastName',
 4280:                               Qstart    => 'FirstQuestion',
 4281:                            );
 4282:             my %maplength = (
 4283:                               CODEstart => 'CODElength',
 4284:                               IDstart   => 'IDlength',
 4285:                               PaperID   => 'PaperIDlength',
 4286:                               FirstName => 'FirstNamelength',
 4287:                               LastName  => 'LastNamelength',
 4288:             );
 4289:             if (open(my $fh,'<',$fullpath)) {
 4290:                 my $output;
 4291:                 my %lettdig = &letter_to_digits();
 4292:                 my %diglett = reverse(%lettdig);
 4293:                 my $numletts = scalar(keys(%lettdig));
 4294:                 my $num = 0;
 4295:                 while (my $line=<$fh>) {
 4296:                     $num ++;
 4297:                     next if (($num == 1) && ($csvoptions{'hdr'} == 1));
 4298:                     $line =~ s{[\r\n]+$}{};
 4299:                     my %found;
 4300:                     my @values = split(/,/,$line);
 4301:                     my ($qstart,$record);
 4302:                     for (my $i=0; $i<@values; $i++) {
 4303:                         if ((($qstart ne '') && ($i > $qstart)) ||
 4304:                             ($csvbynum{$i} eq 'FirstQuestion')) {
 4305:                             if ($values[$i] eq '') {
 4306:                                 $values[$i] = $scantronconf{'Qoff'};
 4307:                             } elsif ($scantronconf{'Qon'} eq 'number') {
 4308:                                 if ($values[$i] =~ /^[A-Ja-j]$/) {
 4309:                                     $values[$i] = $lettdig{uc($values[$i])};
 4310:                                 }
 4311:                             } elsif ($scantronconf{'Qon'} eq 'letter') {
 4312:                                 if ($values[$i] =~ /^[0-9]$/) {
 4313:                                     $values[$i] = $diglett{$values[$i]};
 4314:                                 }
 4315:                             } else {
 4316:                                 if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
 4317:                                     my $digit;
 4318:                                     if ($values[$i] =~ /^[A-Ja-j]$/) {
 4319:                                         $digit = $lettdig{uc($values[$i])}-1;
 4320:                                         if ($values[$i] eq 'J') {
 4321:                                             $digit += $numletts;
 4322:                                         }
 4323:                                     } elsif ($values[$i] =~ /^[0-9]$/) {
 4324:                                         $digit = $values[$i]-1;
 4325:                                         if ($values[$i] eq '0') {
 4326:                                             $digit += $numletts;
 4327:                                         }
 4328:                                     }
 4329:                                     my $qval='';
 4330:                                     for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
 4331:                                         if ($j == $digit) {
 4332:                                             $qval .= $scantronconf{'Qon'};
 4333:                                         } else {
 4334:                                             $qval .= $scantronconf{'Qoff'};
 4335:                                         }
 4336:                                     }
 4337:                                     $values[$i] = $qval;
 4338:                                 }
 4339:                             }
 4340:                             if (length($values[$i]) > $scantronconf{'Qlength'}) {
 4341:                                 $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
 4342:                             }
 4343:                             my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
 4344:                             if ($numblank > 0) {
 4345:                                  $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
 4346:                             }
 4347:                             if ($csvbynum{$i} eq 'FirstQuestion') {
 4348:                                 $qstart = $i;
 4349:                                 $found{$csvbynum{$i}} = $values[$i];
 4350:                             } else {
 4351:                                 $found{'FirstQuestion'} .= $values[$i];
 4352:                             }
 4353:                         } elsif (exists($csvbynum{$i})) {
 4354:                             if ($csvoptions{'rem'}) {
 4355:                                 $values[$i] =~ s/^\s+//;
 4356:                             }
 4357:                             if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
 4358:                                 while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
 4359:                                     $values[$i] = '0'.$values[$i];
 4360:                                 }
 4361:                             }
 4362:                             $found{$csvbynum{$i}} = $values[$i];
 4363:                         }
 4364:                     }
 4365:                     foreach my $item (@ordered) {
 4366:                         my $currlength = 1+length($record);
 4367:                         my $numspaces = $scantronconf{$item} - $currlength;
 4368:                         if ($numspaces > 0) {
 4369:                             $record .= (' ' x $numspaces);
 4370:                         }
 4371:                         if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
 4372:                             unless ($item eq 'Qstart') {
 4373:                                 if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
 4374:                                     $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
 4375:                                 }
 4376:                             }
 4377:                             $record .= $found{$mapstart{$item}};
 4378:                         }
 4379:                     }
 4380:                     $output .= "$record\n";
 4381:                 }
 4382:                 close($fh);
 4383:                 if ($output) {
 4384:                     if (open(my $fh,'>',$fullpath)) {
 4385:                         print $fh $output;
 4386:                         close($fh);
 4387:                     }
 4388:                 }
 4389:             }
 4390:         }
 4391:         return;
 4392:     }
 4393: }
 4394: 
 4395: sub letter_to_digits {
 4396:     my %lettdig = (
 4397:                     A => 1,
 4398:                     B => 2,
 4399:                     C => 3,
 4400:                     D => 4,
 4401:                     E => 5,
 4402:                     F => 6,
 4403:                     G => 7,
 4404:                     H => 8,
 4405:                     I => 9,
 4406:                     J => 0,
 4407:                   );
 4408:     return %lettdig;
 4409: }
 4410: 
 4411: sub get_scantron_config {
 4412:     my ($which,$cdom) = @_;
 4413:     my @lines = &get_scantronformat_file($cdom);
 4414:     my %config;
 4415:     #FIXME probably should move to XML it has already gotten a bit much now
 4416:     foreach my $line (@lines) {
 4417:         my ($name,$descrip)=split(/:/,$line);
 4418:         if ($name ne $which ) { next; }
 4419:         chomp($line);
 4420:         my @config=split(/:/,$line);
 4421:         $config{'name'}=$config[0];
 4422:         $config{'description'}=$config[1];
 4423:         $config{'CODElocation'}=$config[2];
 4424:         $config{'CODEstart'}=$config[3];
 4425:         $config{'CODElength'}=$config[4];
 4426:         $config{'IDstart'}=$config[5];
 4427:         $config{'IDlength'}=$config[6];
 4428:         $config{'Qstart'}=$config[7];
 4429:         $config{'Qlength'}=$config[8];
 4430:         $config{'Qoff'}=$config[9];
 4431:         $config{'Qon'}=$config[10];
 4432:         $config{'PaperID'}=$config[11];
 4433:         $config{'PaperIDlength'}=$config[12];
 4434:         $config{'FirstName'}=$config[13];
 4435:         $config{'FirstNamelength'}=$config[14];
 4436:         $config{'LastName'}=$config[15];
 4437:         $config{'LastNamelength'}=$config[16];
 4438:         $config{'BubblesPerRow'}=$config[17];
 4439:         last;
 4440:     }
 4441:     return %config;
 4442: }
 4443: 
 4444: sub get_scantronformat_file {
 4445:     my ($cdom) = @_;
 4446:     if ($cdom eq '') {
 4447:         $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 4448:     }
 4449:     my %domconfig = &get_dom('configuration',['scantron'],$cdom);
 4450:     my $gottab = 0;
 4451:     my @lines;
 4452:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 4453:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
 4454:             my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
 4455:             if ($formatfile ne '-1') {
 4456:                 @lines = split("\n",$formatfile,-1);
 4457:                 $gottab = 1;
 4458:             }
 4459:         }
 4460:     }
 4461:     if (!$gottab) {
 4462:         my $confname = $cdom.'-domainconfig';
 4463:         my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
 4464:         my $formatfile = &getfile($default);
 4465:         if ($formatfile ne '-1') {
 4466:             @lines = split("\n",$formatfile,-1);
 4467:             $gottab = 1;
 4468:         }
 4469:     }
 4470:     if (!$gottab) {
 4471:         my @domains = &current_machine_domains();
 4472:         if (grep(/^\Q$cdom\E$/,@domains)) {
 4473:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
 4474:                 @lines = <$fh>;
 4475:                 close($fh);
 4476:             }
 4477:         } else {
 4478:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
 4479:                 @lines = <$fh>;
 4480:                 close($fh);
 4481:             }
 4482:         }
 4483:     }
 4484:     return @lines;
 4485: }
 4486: 
 4487: sub removeuploadedurl {
 4488:     my ($url)=@_;	
 4489:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 4490:     return &removeuserfile($uname,$udom,$fname);
 4491: }
 4492: 
 4493: sub removeuserfile {
 4494:     my ($docuname,$docudom,$fname)=@_;
 4495:     my $home=&homeserver($docuname,$docudom);    
 4496:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 4497:     if ($result eq 'ok') {	
 4498:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 4499:             my $metafile = $fname.'.meta';
 4500:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 4501: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 4502:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 4503:             my $sqlresult = 
 4504:                 &update_portfolio_table($docuname,$docudom,$file,
 4505:                                         'portfolio_metadata',$group,
 4506:                                         'delete');
 4507:         }
 4508:     }
 4509:     return $result;
 4510: }
 4511: 
 4512: sub mkdiruserfile {
 4513:     my ($docuname,$docudom,$dir)=@_;
 4514:     my $home=&homeserver($docuname,$docudom);
 4515:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 4516: }
 4517: 
 4518: sub renameuserfile {
 4519:     my ($docuname,$docudom,$old,$new)=@_;
 4520:     my $home=&homeserver($docuname,$docudom);
 4521:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 4522:                         &escape("$old").':'.&escape("$new"),$home);
 4523:     if ($result eq 'ok') {
 4524:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 4525:             my $oldmeta = $old.'.meta';
 4526:             my $newmeta = $new.'.meta';
 4527:             my $metaresult = 
 4528:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 4529: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 4530:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 4531:             my $sqlresult = 
 4532:                 &update_portfolio_table($docuname,$docudom,$file,
 4533:                                         'portfolio_metadata',$group,
 4534:                                         'delete');
 4535:         }
 4536:     }
 4537:     return $result;
 4538: }
 4539: 
 4540: # ------------------------------------------------------------------------- Log
 4541: 
 4542: sub log {
 4543:     my ($dom,$nam,$hom,$what)=@_;
 4544:     return critical("log:$dom:$nam:$what",$hom);
 4545: }
 4546: 
 4547: # ------------------------------------------------------------------ Course Log
 4548: #
 4549: # This routine flushes several buffers of non-mission-critical nature
 4550: #
 4551: 
 4552: sub flushcourselogs {
 4553:     &logthis('Flushing log buffers');
 4554: #
 4555: # course logs
 4556: # This is a log of all transactions in a course, which can be used
 4557: # for data mining purposes
 4558: #
 4559: # It also collects the courseid database, which lists last transaction
 4560: # times and course titles for all courseids
 4561: #
 4562:     my %courseidbuffer=();
 4563:     foreach my $crsid (keys(%courselogs)) {
 4564:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 4565: 		          &escape($courselogs{$crsid}),
 4566: 		          $coursehombuf{$crsid}) eq 'ok') {
 4567: 	    delete $courselogs{$crsid};
 4568:         } else {
 4569:             &logthis('Failed to flush log buffer for '.$crsid);
 4570:             if (length($courselogs{$crsid})>40000) {
 4571:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 4572:                         " exceeded maximum size, deleting.</font>");
 4573:                delete $courselogs{$crsid};
 4574:             }
 4575:         }
 4576:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 4577:             'description' => $coursedescrbuf{$crsid},
 4578:             'inst_code'    => $courseinstcodebuf{$crsid},
 4579:             'type'        => $coursetypebuf{$crsid},
 4580:             'owner'       => $courseownerbuf{$crsid},
 4581:         };
 4582:     }
 4583: #
 4584: # Write course id database (reverse lookup) to homeserver of courses 
 4585: # Is used in pickcourse
 4586: #
 4587:     foreach my $crs_home (keys(%courseidbuffer)) {
 4588:         my $response = &courseidput(&host_domain($crs_home),
 4589:                                     $courseidbuffer{$crs_home},
 4590:                                     $crs_home,'timeonly');
 4591:     }
 4592: #
 4593: # File accesses
 4594: # Writes to the dynamic metadata of resources to get hit counts, etc.
 4595: #
 4596:     foreach my $entry (keys(%accesshash)) {
 4597:         if ($entry =~ /___count$/) {
 4598:             my ($dom,$name);
 4599:             ($dom,$name,undef)=
 4600: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 4601:             if (! defined($dom) || $dom eq '' || 
 4602:                 ! defined($name) || $name eq '') {
 4603:                 my $cid = $env{'request.course.id'};
 4604:                 $dom  = $env{'request.'.$cid.'.domain'};
 4605:                 $name = $env{'request.'.$cid.'.num'};
 4606:             }
 4607:             my $value = $accesshash{$entry};
 4608:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 4609:             my %temphash=($url => $value);
 4610:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 4611:             if ($result eq 'ok') {
 4612:                 delete $accesshash{$entry};
 4613:             }
 4614:         } else {
 4615:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 4616:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
 4617:             my %temphash=($entry => $accesshash{$entry});
 4618:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 4619:                 delete $accesshash{$entry};
 4620:             }
 4621:         }
 4622:     }
 4623: #
 4624: # Roles
 4625: # Reverse lookup of user roles for course faculty/staff and co-authorship
 4626: #
 4627:     foreach my $entry (keys(%userrolehash)) {
 4628:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 4629: 	    split(/\:/,$entry);
 4630:         if (&Apache::lonnet::put('nohist_userroles',
 4631:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 4632:                 $rudom,$runame) eq 'ok') {
 4633: 	    delete $userrolehash{$entry};
 4634:         }
 4635:     }
 4636: #
 4637: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
 4638: #
 4639:     my %domrolebuffer = ();
 4640:     foreach my $entry (keys(%domainrolehash)) {
 4641:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 4642:         if ($domrolebuffer{$rudom}) {
 4643:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 4644:                       '='.&escape($domainrolehash{$entry});
 4645:         } else {
 4646:             $domrolebuffer{$rudom}.=&escape($entry).
 4647:                       '='.&escape($domainrolehash{$entry});
 4648:         }
 4649:         delete $domainrolehash{$entry};
 4650:     }
 4651:     foreach my $dom (keys(%domrolebuffer)) {
 4652:         my %servers;
 4653:         if (defined(&domain($dom,'primary'))) {
 4654:             my $primary=&domain($dom,'primary');
 4655:             my $hostname=&hostname($primary);
 4656:             $servers{$primary} = $hostname;
 4657:         } else {
 4658:             %servers = &get_servers($dom,'library');
 4659:         }
 4660: 	foreach my $tryserver (keys(%servers)) {
 4661: 	    if (&reply('domroleput:'.$dom.':'.
 4662: 	               $domrolebuffer{$dom},$tryserver) eq 'ok') {
 4663: 	        last;
 4664: 	    } else {
 4665: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 4666: 	    }
 4667:         }
 4668:     }
 4669:     $dumpcount++;
 4670: }
 4671: 
 4672: sub courselog {
 4673:     my $what=shift;
 4674:     $what=time.':'.$what;
 4675:     unless ($env{'request.course.id'}) { return ''; }
 4676:     $coursedombuf{$env{'request.course.id'}}=
 4677:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 4678:     $coursenumbuf{$env{'request.course.id'}}=
 4679:        $env{'course.'.$env{'request.course.id'}.'.num'};
 4680:     $coursehombuf{$env{'request.course.id'}}=
 4681:        $env{'course.'.$env{'request.course.id'}.'.home'};
 4682:     $coursedescrbuf{$env{'request.course.id'}}=
 4683:        $env{'course.'.$env{'request.course.id'}.'.description'};
 4684:     $courseinstcodebuf{$env{'request.course.id'}}=
 4685:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 4686:     $courseownerbuf{$env{'request.course.id'}}=
 4687:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 4688:     $coursetypebuf{$env{'request.course.id'}}=
 4689:        $env{'course.'.$env{'request.course.id'}.'.type'};
 4690:     if (defined $courselogs{$env{'request.course.id'}}) {
 4691: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 4692:     } else {
 4693: 	$courselogs{$env{'request.course.id'}}.=$what;
 4694:     }
 4695:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 4696: 	&flushcourselogs();
 4697:     }
 4698: }
 4699: 
 4700: sub courseacclog {
 4701:     my $fnsymb=shift;
 4702:     unless ($env{'request.course.id'}) { return ''; }
 4703:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 4704:     if ($fnsymb=~/$LONCAPA::assess_re/) {
 4705:         $what.=':POST';
 4706:         # FIXME: Probably ought to escape things....
 4707: 	foreach my $key (keys(%env)) {
 4708:             if ($key=~/^form\.(.*)/) {
 4709:                 my $formitem = $1;
 4710:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 4711:                     $what.=':'.$formitem.'='.$env{$key};
 4712:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 4713:                     if ($formitem eq 'proctorpassword') {
 4714:                         $what.=':'.$formitem.'=' . '*' x length($env{$key});
 4715:                     } else {
 4716:                         $what.=':'.$formitem.'='.$env{$key};
 4717:                     }
 4718:                 }
 4719:             }
 4720:         }
 4721:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 4722:         # FIXME: We should not be depending on a form parameter that someone
 4723:         # editing lonsearchcat.pm might change in the future.
 4724:         if ($env{'form.phase'} eq 'course_search') {
 4725:             $what.= ':POST';
 4726:             # FIXME: Probably ought to escape things....
 4727:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 4728:                                  'crsdiscuss') {
 4729:                 $what.=':'.$element.'='.$env{'form.'.$element};
 4730:             }
 4731:         }
 4732:     }
 4733:     &courselog($what);
 4734: }
 4735: 
 4736: sub countacc {
 4737:     my $url=&declutter(shift);
 4738:     return if (! defined($url) || $url eq '');
 4739:     unless ($env{'request.course.id'}) { return ''; }
 4740: #
 4741: # Mark that this url was used in this course
 4742: #
 4743:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 4744: #
 4745: # Increase the access count for this resource in this child process
 4746: #
 4747:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 4748:     $accesshash{$key}++;
 4749: }
 4750: 
 4751: sub linklog {
 4752:     my ($from,$to)=@_;
 4753:     $from=&declutter($from);
 4754:     $to=&declutter($to);
 4755:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 4756:     $accesshash{$to.'___'.$from.'___goto'}=1;
 4757: }
 4758: 
 4759: sub statslog {
 4760:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
 4761:     if ($users<2) { return; }
 4762:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
 4763:             'course'       => $env{'request.course.id'},
 4764:             'sections'     => '"all"',
 4765:             'num_students' => $users,
 4766:             'part'         => $part,
 4767:             'symb'         => $symb,
 4768:             'mean_tries'   => $av_attempts,
 4769:             'deg_of_diff'  => $degdiff});
 4770:     foreach my $key (keys(%dynstore)) {
 4771:         $accesshash{$key}=$dynstore{$key};
 4772:     }
 4773: }
 4774:   
 4775: sub userrolelog {
 4776:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 4777:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
 4778:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 4779:        $userrolehash
 4780:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 4781:                     =$tend.':'.$tstart;
 4782:     }
 4783:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
 4784:        $userrolehash
 4785:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 4786:                     =$tend.':'.$tstart;
 4787:     }
 4788:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
 4789:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 4790:        $domainrolehash
 4791:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 4792:                     = $tend.':'.$tstart;
 4793:     }
 4794: }
 4795: 
 4796: sub courserolelog {
 4797:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 4798:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 4799:         my $cdom = $1;
 4800:         my $cnum = $2;
 4801:         my $sec = $3;
 4802:         my $namespace = 'rolelog';
 4803:         my %storehash = (
 4804:                            role    => $trole,
 4805:                            start   => $tstart,
 4806:                            end     => $tend,
 4807:                            selfenroll => $selfenroll,
 4808:                            context    => $context,
 4809:                         );
 4810:         if ($trole eq 'gr') {
 4811:             $namespace = 'groupslog';
 4812:             $storehash{'group'} = $sec;
 4813:         } else {
 4814:             $storehash{'section'} = $sec;
 4815:         }
 4816:         &write_log('course',$namespace,\%storehash,$delflag,$username,
 4817:                    $domain,$cnum,$cdom);
 4818:         if (($trole ne 'st') || ($sec ne '')) {
 4819:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 4820:         }
 4821:     }
 4822:     return;
 4823: }
 4824: 
 4825: sub domainrolelog {
 4826:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 4827:     if ($area =~ m{^/($match_domain)/$}) {
 4828:         my $cdom = $1;
 4829:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
 4830:         my $namespace = 'rolelog';
 4831:         my %storehash = (
 4832:                            role    => $trole,
 4833:                            start   => $tstart,
 4834:                            end     => $tend,
 4835:                            context => $context,
 4836:                         );
 4837:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
 4838:                    $domain,$domconfiguser,$cdom);
 4839:     }
 4840:     return;
 4841: 
 4842: }
 4843: 
 4844: sub coauthorrolelog {
 4845:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 4846:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
 4847:         my $audom = $1;
 4848:         my $auname = $2;
 4849:         my $namespace = 'rolelog';
 4850:         my %storehash = (
 4851:                            role    => $trole,
 4852:                            start   => $tstart,
 4853:                            end     => $tend,
 4854:                            context => $context,
 4855:                         );
 4856:         &write_log('author',$namespace,\%storehash,$delflag,$username,
 4857:                    $domain,$auname,$audom);
 4858:     }
 4859:     return;
 4860: }
 4861: 
 4862: sub get_course_adv_roles {
 4863:     my ($cid,$codes) = @_;
 4864:     $cid=$env{'request.course.id'} unless (defined($cid));
 4865:     my %coursehash=&coursedescription($cid);
 4866:     my $crstype = &Apache::loncommon::course_type($cid);
 4867:     my %nothide=();
 4868:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 4869:         if ($user !~ /:/) {
 4870: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 4871:         } else {
 4872:             $nothide{$user}=1;
 4873:         }
 4874:     }
 4875:     my @possdoms = ($coursehash{'domain'});
 4876:     if ($coursehash{'checkforpriv'}) {
 4877:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
 4878:     }
 4879:     my %returnhash=();
 4880:     my %dumphash=
 4881:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 4882:     my $now=time;
 4883:     my %privileged;
 4884:     foreach my $entry (keys(%dumphash)) {
 4885: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 4886:         if (($tstart) && ($tstart<0)) { next; }
 4887:         if (($tend) && ($tend<$now)) { next; }
 4888:         if (($tstart) && ($now<$tstart)) { next; }
 4889:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 4890: 	if ($username eq '' || $domain eq '') { next; }
 4891:         if ((&privileged($username,$domain,\@possdoms)) &&
 4892:             (!$nothide{$username.':'.$domain})) { next; }
 4893: 	if ($role eq 'cr') { next; }
 4894:         if ($codes) {
 4895:             if ($section) { $role .= ':'.$section; }
 4896:             if ($returnhash{$role}) {
 4897:                 $returnhash{$role}.=','.$username.':'.$domain;
 4898:             } else {
 4899:                 $returnhash{$role}=$username.':'.$domain;
 4900:             }
 4901:         } else {
 4902:             my $key=&plaintext($role,$crstype);
 4903:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 4904:             if ($returnhash{$key}) {
 4905: 	        $returnhash{$key}.=','.$username.':'.$domain;
 4906:             } else {
 4907:                 $returnhash{$key}=$username.':'.$domain;
 4908:             }
 4909:         }
 4910:     }
 4911:     return %returnhash;
 4912: }
 4913: 
 4914: sub get_my_roles {
 4915:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 4916:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 4917:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 4918:     my (%dumphash,%nothide);
 4919:     if ($context eq 'userroles') {
 4920:         %dumphash = &dump('roles',$udom,$uname);
 4921:     } else {
 4922:         %dumphash = &dump('nohist_userroles',$udom,$uname);
 4923:         if ($hidepriv) {
 4924:             my %coursehash=&coursedescription($udom.'_'.$uname);
 4925:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 4926:                 if ($user !~ /:/) {
 4927:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 4928:                 } else {
 4929:                     $nothide{$user} = 1;
 4930:                 }
 4931:             }
 4932:         }
 4933:     }
 4934:     my %returnhash=();
 4935:     my $now=time;
 4936:     my %privileged;
 4937:     foreach my $entry (keys(%dumphash)) {
 4938:         my ($role,$tend,$tstart);
 4939:         if ($context eq 'userroles') {
 4940:             next if ($entry =~ /^rolesdef/);
 4941: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 4942:         } else {
 4943:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 4944:         }
 4945:         if (($tstart) && ($tstart<0)) { next; }
 4946:         my $status = 'active';
 4947:         if (($tend) && ($tend<=$now)) {
 4948:             $status = 'previous';
 4949:         } 
 4950:         if (($tstart) && ($now<$tstart)) {
 4951:             $status = 'future';
 4952:         }
 4953:         if (ref($types) eq 'ARRAY') {
 4954:             if (!grep(/^\Q$status\E$/,@{$types})) {
 4955:                 next;
 4956:             } 
 4957:         } else {
 4958:             if ($status ne 'active') {
 4959:                 next;
 4960:             }
 4961:         }
 4962:         my ($rolecode,$username,$domain,$section,$area);
 4963:         if ($context eq 'userroles') {
 4964:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
 4965:             (undef,$domain,$username,$section) = split(/\//,$area);
 4966:         } else {
 4967:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 4968:         }
 4969:         if (ref($roledoms) eq 'ARRAY') {
 4970:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 4971:                 next;
 4972:             }
 4973:         }
 4974:         if (ref($roles) eq 'ARRAY') {
 4975:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 4976:                 if ($role =~ /^cr\//) {
 4977:                     if (!grep(/^cr$/,@{$roles})) {
 4978:                         next;
 4979:                     }
 4980:                 } elsif ($role =~ /^gr\//) {
 4981:                     if (!grep(/^gr$/,@{$roles})) {
 4982:                         next;
 4983:                     }
 4984:                 } else {
 4985:                     next;
 4986:                 }
 4987:             }
 4988:         }
 4989:         if ($hidepriv) {
 4990:             my @privroles = ('dc','su');
 4991:             if ($context eq 'userroles') {
 4992:                 next if (grep(/^\Q$role\E$/,@privroles));
 4993:             } else {
 4994:                 my $possdoms = [$domain];
 4995:                 if (ref($roledoms) eq 'ARRAY') {
 4996:                    push(@{$possdoms},@{$roledoms});
 4997:                 }
 4998:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
 4999:                     if (!$nothide{$username.':'.$domain}) {
 5000:                         next;
 5001:                     }
 5002:                 }
 5003:             }
 5004:         }
 5005:         if ($withsec) {
 5006:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 5007:                 $tstart.':'.$tend;
 5008:         } else {
 5009:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 5010:         }
 5011:     }
 5012:     return %returnhash;
 5013: }
 5014: 
 5015: sub get_all_adhocroles {
 5016:     my ($dom) = @_;
 5017:     my @roles_by_num = ();
 5018:     my %domdefaults = &get_domain_defaults($dom);
 5019:     my (%description,%access_in_dom,%access_info);
 5020:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
 5021:         my $count = 0;
 5022:         my %domcurrent = %{$domdefaults{'adhocroles'}};
 5023:         my %ordered;
 5024:         foreach my $role (sort(keys(%domcurrent))) {
 5025:             my ($order,$desc,$access_in_dom);
 5026:             if (ref($domcurrent{$role}) eq 'HASH') {
 5027:                 $order = $domcurrent{$role}{'order'};
 5028:                 $desc = $domcurrent{$role}{'desc'};
 5029:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
 5030:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
 5031:             }
 5032:             if ($order eq '') {
 5033:                 $order = $count;
 5034:             }
 5035:             $ordered{$order} = $role;
 5036:             if ($desc ne '') {
 5037:                 $description{$role} = $desc;
 5038:             } else {
 5039:                 $description{$role}= $role;
 5040:             }
 5041:             $count++;
 5042:         }
 5043:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 5044:             push(@roles_by_num,$ordered{$item});
 5045:         }
 5046:     }
 5047:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
 5048: }
 5049: 
 5050: sub get_my_adhocroles {
 5051:     my ($cid,$checkreg) = @_;
 5052:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
 5053:     if ($env{'request.course.id'} eq $cid) {
 5054:         $cdom = $env{'course.'.$cid.'.domain'};
 5055:         $cnum = $env{'course.'.$cid.'.num'};
 5056:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
 5057:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
 5058:         $cdom = $1;
 5059:         $cnum = $2;
 5060:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
 5061:                                      $cdom,$cnum);
 5062:     }
 5063:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
 5064:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
 5065:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
 5066:         if ($rosterhash{$user} ne '') {
 5067:             my $type = (split(/:/,$rosterhash{$user}))[5];
 5068:             return ([],{}) if ($type eq 'auto');
 5069:         }
 5070:     }
 5071:     if (($cdom ne '') && ($cnum ne ''))  {
 5072:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
 5073:             my $then=$env{'user.login.time'};
 5074:             my $update=$env{'user.update.time'};
 5075:             if (!$update) {
 5076:                 $update = $then;
 5077:             }
 5078:             my @liveroles;
 5079:             foreach my $role ('dh','da') {
 5080:                 if ($env{"user.role.$role./$cdom/"}) {
 5081:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
 5082:                     my $limit = $update;
 5083:                     if ($env{'request.role'} eq "$role./$cdom/") {
 5084:                         $limit = $then;
 5085:                     }
 5086:                     my $activerole = 1;
 5087:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
 5088:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
 5089:                     if ($activerole) {
 5090:                         push(@liveroles,$role);
 5091:                     }
 5092:                 }
 5093:             }
 5094:             if (@liveroles) {
 5095:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
 5096:                     my ($accessref,$accessinfo,%access_in_dom);
 5097:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
 5098:                     if (ref($roles_by_num) eq 'ARRAY') {
 5099:                         if (@{$roles_by_num}) {
 5100:                             my %settings;
 5101:                             if ($env{'request.course.id'} eq $cid) {
 5102:                                 foreach my $envkey (keys(%env)) {
 5103:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
 5104:                                         $settings{$1} = $env{$envkey};
 5105:                                     }
 5106:                                 }
 5107:                             } else {
 5108:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
 5109:                             }
 5110:                             my %setincrs;
 5111:                             if ($settings{'internal.adhocaccess'}) {
 5112:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
 5113:                             }
 5114:                             my @statuses;
 5115:                             if ($env{'environment.inststatus'}) {
 5116:                                 @statuses = split(/,/,$env{'environment.inststatus'});
 5117:                             }
 5118:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
 5119:                             if (ref($accessref) eq 'HASH') {
 5120:                                 %access_in_dom = %{$accessref};
 5121:                             }
 5122:                             foreach my $role (@{$roles_by_num}) {
 5123:                                 my ($curraccess,@okstatus,@personnel);
 5124:                                 if ($setincrs{$role}) {
 5125:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
 5126:                                     if ($curraccess eq 'status') {
 5127:                                         @okstatus = split(/\&/,$rest);
 5128:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5129:                                         @personnel = split(/\&/,$rest);
 5130:                                     }
 5131:                                 } else {
 5132:                                     $curraccess = $access_in_dom{$role};
 5133:                                     if (ref($accessinfo) eq 'HASH') {
 5134:                                         if ($curraccess eq 'status') {
 5135:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
 5136:                                                 @okstatus = @{$accessinfo->{$role}};
 5137:                                             }
 5138:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5139:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
 5140:                                                 @personnel = @{$accessinfo->{$role}};
 5141:                                             }
 5142:                                         }
 5143:                                     }
 5144:                                 }
 5145:                                 if ($curraccess eq 'none') {
 5146:                                     next;
 5147:                                 } elsif ($curraccess eq 'all') {
 5148:                                     push(@possroles,$role);
 5149:                                 } elsif ($curraccess eq 'dh') {
 5150:                                     if (grep(/^dh$/,@liveroles)) {
 5151:                                         push(@possroles,$role);
 5152:                                     } else {
 5153:                                         next;
 5154:                                     }
 5155:                                 } elsif ($curraccess eq 'da') {
 5156:                                     if (grep(/^da$/,@liveroles)) {
 5157:                                         push(@possroles,$role);
 5158:                                     } else {
 5159:                                         next;
 5160:                                     }
 5161:                                 } elsif ($curraccess eq 'status') {
 5162:                                     if (@okstatus) {
 5163:                                         if (!@statuses) {
 5164:                                             if (grep(/^default$/,@okstatus)) {
 5165:                                                 push(@possroles,$role);
 5166:                                             }
 5167:                                         } else {
 5168:                                             foreach my $status (@okstatus) {
 5169:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
 5170:                                                     push(@possroles,$role);
 5171:                                                     last;
 5172:                                                 }
 5173:                                             }
 5174:                                         }
 5175:                                     }
 5176:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5177:                                     if (grep(/^\Q$user\E$/,@personnel)) {
 5178:                                         if ($curraccess eq 'exc') {
 5179:                                             push(@possroles,$role);
 5180:                                         }
 5181:                                     } elsif ($curraccess eq 'inc') {
 5182:                                         push(@possroles,$role);
 5183:                                     }
 5184:                                 }
 5185:                             }
 5186:                         }
 5187:                     }
 5188:                 }
 5189:             }
 5190:         }
 5191:     }
 5192:     unless (ref($description) eq 'HASH') {
 5193:         if (ref($roles_by_num) eq 'ARRAY') {
 5194:             my %desc;
 5195:             map { $desc{$_} = $_; } (@{$roles_by_num});
 5196:             $description = \%desc;
 5197:         } else {
 5198:             $description = {};
 5199:         }
 5200:     }
 5201:     return (\@possroles,$description);
 5202: }
 5203: 
 5204: # ----------------------------------------------------- Frontpage Announcements
 5205: #
 5206: #
 5207: 
 5208: sub postannounce {
 5209:     my ($server,$text)=@_;
 5210:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 5211:     unless ($text=~/\w/) { $text=''; }
 5212:     return &reply('setannounce:'.&escape($text),$server);
 5213: }
 5214: 
 5215: sub getannounce {
 5216: 
 5217:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 5218: 	my $announcement='';
 5219: 	while (my $line = <$fh>) { $announcement .= $line; }
 5220: 	close($fh);
 5221: 	if ($announcement=~/\w/) { 
 5222: 	    return 
 5223:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 5224:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 5225: 	} else {
 5226: 	    return '';
 5227: 	}
 5228:     } else {
 5229: 	return '';
 5230:     }
 5231: }
 5232: 
 5233: # ---------------------------------------------------------- Course ID routines
 5234: # Deal with domain's nohist_courseid.db files
 5235: #
 5236: 
 5237: sub courseidput {
 5238:     my ($domain,$storehash,$coursehome,$caller) = @_;
 5239:     return unless (ref($storehash) eq 'HASH');
 5240:     my $outcome;
 5241:     if ($caller eq 'timeonly') {
 5242:         my $cids = '';
 5243:         foreach my $item (keys(%$storehash)) {
 5244:             $cids.=&escape($item).'&';
 5245:         }
 5246:         $cids=~s/\&$//;
 5247:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 5248:                           $coursehome);       
 5249:     } else {
 5250:         my $items = '';
 5251:         foreach my $item (keys(%$storehash)) {
 5252:             $items.= &escape($item).'='.
 5253:                      &freeze_escape($$storehash{$item}).'&';
 5254:         }
 5255:         $items=~s/\&$//;
 5256:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 5257:                           $coursehome);
 5258:     }
 5259:     if ($outcome eq 'unknown_cmd') {
 5260:         my $what;
 5261:         foreach my $cid (keys(%$storehash)) {
 5262:             $what .= &escape($cid).'=';
 5263:             foreach my $item ('description','inst_code','owner','type') {
 5264:                 $what .= &escape($storehash->{$cid}{$item}).':';
 5265:             }
 5266:             $what =~ s/\:$/&/;
 5267:         }
 5268:         $what =~ s/\&$//;  
 5269:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 5270:     } else {
 5271:         return $outcome;
 5272:     }
 5273: }
 5274: 
 5275: sub courseiddump {
 5276:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 5277:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 5278:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
 5279:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
 5280:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
 5281:     my $as_hash = 1;
 5282:     my %returnhash;
 5283:     if (!$domfilter) { $domfilter=''; }
 5284:     my %libserv = &all_library();
 5285:     foreach my $tryserver (keys(%libserv)) {
 5286:         if ( (  $hostidflag == 1 
 5287: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 5288: 	     || (!defined($hostidflag)) ) {
 5289: 
 5290: 	    if (($domfilter eq '') ||
 5291: 		(&host_domain($tryserver) eq $domfilter)) {
 5292:                 my $rep;
 5293:                 if (grep { $_ eq $tryserver } &current_machine_ids()) {
 5294:                     $rep = &LONCAPA::Lond::dump_course_id_handler(
 5295:                         join(":", (&host_domain($tryserver), $sincefilter,
 5296:                                 &escape($descfilter), &escape($instcodefilter),
 5297:                                 &escape($ownerfilter), &escape($coursefilter),
 5298:                                 &escape($typefilter), &escape($regexp_ok),
 5299:                                 $as_hash, &escape($selfenrollonly),
 5300:                                 &escape($catfilter), $showhidden, $caller,
 5301:                                 &escape($cloner), &escape($cc_clone), $cloneonly,
 5302:                                 &escape($createdbefore), &escape($createdafter),
 5303:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
 5304:                                 $reqcrsdom,&escape($reqinstcode))));
 5305:                 } else {
 5306:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
 5307:                              $sincefilter.':'.&escape($descfilter).':'.
 5308:                              &escape($instcodefilter).':'.&escape($ownerfilter).
 5309:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
 5310:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
 5311:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
 5312:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
 5313:                              &escape($cc_clone).':'.$cloneonly.':'.
 5314:                              &escape($createdbefore).':'.&escape($createdafter).':'.
 5315:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
 5316:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
 5317:                 }
 5318: 
 5319:                 my @pairs=split(/\&/,$rep);
 5320:                 foreach my $item (@pairs) {
 5321:                     my ($key,$value)=split(/\=/,$item,2);
 5322:                     $key = &unescape($key);
 5323:                     next if ($key =~ /^error: 2 /);
 5324:                     my $result = &thaw_unescape($value);
 5325:                     if (ref($result) eq 'HASH') {
 5326:                         $returnhash{$key}=$result;
 5327:                     } else {
 5328:                         my @responses = split(/:/,$value);
 5329:                         my @items = ('description','inst_code','owner','type');
 5330:                         for (my $i=0; $i<@responses; $i++) {
 5331:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 5332:                         }
 5333:                     }
 5334:                 }
 5335:             }
 5336:         }
 5337:     }
 5338:     return %returnhash;
 5339: }
 5340: 
 5341: sub courselastaccess {
 5342:     my ($cdom,$cnum,$hostidref) = @_;
 5343:     my %returnhash;
 5344:     if ($cdom && $cnum) {
 5345:         my $chome = &homeserver($cnum,$cdom);
 5346:         if ($chome ne 'no_host') {
 5347:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
 5348:             &extract_lastaccess(\%returnhash,$rep);
 5349:         }
 5350:     } else {
 5351:         if (!$cdom) { $cdom=''; }
 5352:         my %libserv = &all_library();
 5353:         foreach my $tryserver (keys(%libserv)) {
 5354:             if (ref($hostidref) eq 'ARRAY') {
 5355:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
 5356:             } 
 5357:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
 5358:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
 5359:                 &extract_lastaccess(\%returnhash,$rep);
 5360:             }
 5361:         }
 5362:     }
 5363:     return %returnhash;
 5364: }
 5365: 
 5366: sub extract_lastaccess {
 5367:     my ($returnhash,$rep) = @_;
 5368:     if (ref($returnhash) eq 'HASH') {
 5369:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
 5370:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
 5371:                  $rep eq '') {
 5372:             my @pairs=split(/\&/,$rep);
 5373:             foreach my $item (@pairs) {
 5374:                 my ($key,$value)=split(/\=/,$item,2);
 5375:                 $key = &unescape($key);
 5376:                 next if ($key =~ /^error: 2 /);
 5377:                 $returnhash->{$key} = &thaw_unescape($value);
 5378:             }
 5379:         }
 5380:     }
 5381:     return;
 5382: }
 5383: 
 5384: # ---------------------------------------------------------- DC e-mail
 5385: 
 5386: sub dcmailput {
 5387:     my ($domain,$msgid,$message,$server)=@_;
 5388:     my $status = &Apache::lonnet::critical(
 5389:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 5390:        &escape($message),$server);
 5391:     return $status;
 5392: }
 5393: 
 5394: sub dcmaildump {
 5395:     my ($dom,$startdate,$enddate,$senders) = @_;
 5396:     my %returnhash=();
 5397: 
 5398:     if (defined(&domain($dom,'primary'))) {
 5399:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 5400:                                                          &escape($enddate).':';
 5401: 	my @esc_senders=map { &escape($_)} @$senders;
 5402: 	$cmd.=&escape(join('&',@esc_senders));
 5403: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 5404:             my ($key,$value) = split(/\=/,$line,2);
 5405:             if (($key) && ($value)) {
 5406:                 $returnhash{&unescape($key)} = &unescape($value);
 5407:             }
 5408:         }
 5409:     }
 5410:     return %returnhash;
 5411: }
 5412: # ---------------------------------------------------------- Domain roles
 5413: 
 5414: sub get_domain_roles {
 5415:     my ($dom,$roles,$startdate,$enddate)=@_;
 5416:     if ((!defined($startdate)) || ($startdate eq '')) {
 5417:         $startdate = '.';
 5418:     }
 5419:     if ((!defined($enddate)) || ($enddate eq '')) {
 5420:         $enddate = '.';
 5421:     }
 5422:     my $rolelist;
 5423:     if (ref($roles) eq 'ARRAY') {
 5424:         $rolelist = join('&',@{$roles});
 5425:     }
 5426:     my %personnel = ();
 5427: 
 5428:     my %servers = &get_servers($dom,'library');
 5429:     foreach my $tryserver (keys(%servers)) {
 5430: 	%{$personnel{$tryserver}}=();
 5431: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 5432: 					    &escape($startdate).':'.
 5433: 					    &escape($enddate).':'.
 5434: 					    &escape($rolelist), $tryserver))) {
 5435: 	    my ($key,$value) = split(/\=/,$line,2);
 5436: 	    if (($key) && ($value)) {
 5437: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 5438: 	    }
 5439: 	}
 5440:     }
 5441:     return %personnel;
 5442: }
 5443: 
 5444: sub get_active_domroles {
 5445:     my ($dom,$roles) = @_;
 5446:     return () unless (ref($roles) eq 'ARRAY');
 5447:     my $now = time;
 5448:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
 5449:     my %domroles;
 5450:     foreach my $server (keys(%dompersonnel)) {
 5451:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
 5452:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
 5453:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
 5454:         }
 5455:     }
 5456:     return %domroles;
 5457: }
 5458: 
 5459: # ----------------------------------------------------------- Interval timing 
 5460: 
 5461: {
 5462: # Caches needed for speedup of navmaps
 5463: # We don't want to cache this for very long at all (5 seconds at most)
 5464: # 
 5465: # The user for whom we cache
 5466: my $cachedkey='';
 5467: # The cached times for this user
 5468: my %cachedtimes=();
 5469: # When this was last done
 5470: my $cachedtime='';
 5471: 
 5472: sub load_all_first_access {
 5473:     my ($uname,$udom,$ignorecache)=@_;
 5474:     if (($cachedkey eq $uname.':'.$udom) &&
 5475:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
 5476:         (!$ignorecache)) {
 5477:         return;
 5478:     }
 5479:     $cachedtime=time;
 5480:     $cachedkey=$uname.':'.$udom;
 5481:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
 5482: }
 5483: 
 5484: sub get_first_access {
 5485:     my ($type,$argsymb,$argmap,$ignorecache)=@_;
 5486:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 5487:     if ($argsymb) { $symb=$argsymb; }
 5488:     my ($map,$id,$res)=&decode_symb($symb);
 5489:     if ($argmap) { $map = $argmap; }
 5490:     if ($type eq 'course') {
 5491: 	$res='course';
 5492:     } elsif ($type eq 'map') {
 5493: 	$res=&symbread($map);
 5494:     } else {
 5495: 	$res=$symb;
 5496:     }
 5497:     &load_all_first_access($uname,$udom,$ignorecache);
 5498:     return $cachedtimes{"$courseid\0$res"};
 5499: }
 5500: 
 5501: sub set_first_access {
 5502:     my ($type,$interval)=@_;
 5503:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 5504:     my ($map,$id,$res)=&decode_symb($symb);
 5505:     if ($type eq 'course') {
 5506: 	$res='course';
 5507:     } elsif ($type eq 'map') {
 5508: 	$res=&symbread($map);
 5509:     } else {
 5510: 	$res=$symb;
 5511:     }
 5512:     $cachedkey='';
 5513:     my $firstaccess=&get_first_access($type,$symb,$map);
 5514:     if ($firstaccess) {
 5515:         &logthis("First access time already set ($firstaccess) when attempting ".
 5516:                  "to set new value (type: $type, extent: $res) for $uname:$udom ".
 5517:                  "in $courseid");
 5518:         return 'already_set';
 5519:     } else {
 5520:         my $start = time;
 5521: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
 5522:                           $udom,$uname);
 5523:         if ($putres eq 'ok') {
 5524:             &put('timerinterval',{"$courseid\0$res"=>$interval},
 5525:                  $udom,$uname); 
 5526:             &appenv(
 5527:                      {
 5528:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
 5529:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
 5530:                      }
 5531:                   );
 5532:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
 5533:                 $cachedtimes{"$courseid\0$res"} = $start;
 5534:             }
 5535:         } elsif ($putres ne 'refused') {
 5536:             &logthis("Result: $putres when attempting to set first access time ".
 5537:                      "(type: $type, extent: $res) for $uname:$udom in $courseid");
 5538:         }
 5539:         return $putres;
 5540:     }
 5541:     return 'already_set';
 5542: }
 5543: }
 5544: 
 5545: sub checkout {
 5546:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
 5547:     my $now=time;
 5548:     my $lonhost=$perlvar{'lonHostID'};
 5549:     my $ip = &get_requestor_ip();
 5550:     my $infostr=&escape(
 5551:                  'CHECKOUTTOKEN&'.
 5552:                  $tuname.'&'.
 5553:                  $tudom.'&'.
 5554:                  $tcrsid.'&'.
 5555:                  $symb.'&'.
 5556:                  $now.'&'.$ip);
 5557:     my $token=&reply('tmpput:'.$infostr,$lonhost);
 5558:     if ($token=~/^error\:/) {
 5559:         &logthis("<font color=\"blue\">WARNING: ".
 5560:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
 5561:                  "</font>");
 5562:         return '';
 5563:     }
 5564: 
 5565:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
 5566:     $token=~tr/a-z/A-Z/;
 5567: 
 5568:     my %infohash=('resource.0.outtoken' => $token,
 5569:                   'resource.0.checkouttime' => $now,
 5570:                   'resource.0.outremote' => $ip);
 5571: 
 5572:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 5573:        return '';
 5574:     } else {
 5575:         &logthis("<font color=\"blue\">WARNING: ".
 5576:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
 5577:                  "</font>");
 5578:     }
 5579: 
 5580:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 5581:                          &escape('Checkout '.$infostr.' - '.
 5582:                                                  $token)) ne 'ok') {
 5583:         return '';
 5584:     } else {
 5585:         &logthis("<font color=\"blue\">WARNING: ".
 5586:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
 5587:                  "</font>");
 5588:     }
 5589:     return $token;
 5590: }
 5591: 
 5592: # ------------------------------------------------------------ Check in an item
 5593: 
 5594: sub checkin {
 5595:     my $token=shift;
 5596:     my $now=time;
 5597:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
 5598:     $lonhost=~tr/A-Z/a-z/;
 5599:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
 5600:     $dtoken=~s/\W/\_/g;
 5601:     my $ip = &get_requestor_ip();
 5602:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
 5603:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
 5604: 
 5605:     unless (($tuname) && ($tudom)) {
 5606:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
 5607:         return '';
 5608:     }
 5609: 
 5610:     unless (&allowed('mgr',$tcrsid)) {
 5611:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
 5612:                  $env{'user.name'}.' - '.$env{'user.domain'});
 5613:         return '';
 5614:     }
 5615: 
 5616:     my %infohash=('resource.0.intoken' => $token,
 5617:                   'resource.0.checkintime' => $now,
 5618:                   'resource.0.inremote' => $ip);
 5619: 
 5620:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 5621:        return '';
 5622:     }
 5623: 
 5624:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 5625:                          &escape('Checkin - '.$token)) ne 'ok') {
 5626:         return '';
 5627:     }
 5628: 
 5629:     return ($symb,$tuname,$tudom,$tcrsid);
 5630: }
 5631: 
 5632: # --------------------------------------------- Set Expire Date for Spreadsheet
 5633: 
 5634: sub expirespread {
 5635:     my ($uname,$udom,$stype,$usymb)=@_;
 5636:     my $cid=$env{'request.course.id'}; 
 5637:     if ($cid) {
 5638:        my $now=time;
 5639:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 5640:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 5641:                             $env{'course.'.$cid.'.num'}.
 5642: 	        	    ':nohist_expirationdates:'.
 5643:                             &escape($key).'='.$now,
 5644:                             $env{'course.'.$cid.'.home'})
 5645:     }
 5646:     return 'ok';
 5647: }
 5648: 
 5649: # ----------------------------------------------------- Devalidate Spreadsheets
 5650: 
 5651: sub devalidate {
 5652:     my ($symb,$uname,$udom)=@_;
 5653:     my $cid=$env{'request.course.id'}; 
 5654:     if ($cid) {
 5655:         # delete the stored spreadsheets for
 5656:         # - the student level sheet of this user in course's homespace
 5657:         # - the assessment level sheet for this resource 
 5658:         #   for this user in user's homespace
 5659: 	# - current conditional state info
 5660: 	my $key=$uname.':'.$udom.':';
 5661:         my $status=
 5662: 	    &del('nohist_calculatedsheets',
 5663: 		 [$key.'studentcalc:'],
 5664: 		 $env{'course.'.$cid.'.domain'},
 5665: 		 $env{'course.'.$cid.'.num'})
 5666: 		.' '.
 5667: 	    &del('nohist_calculatedsheets_'.$cid,
 5668: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 5669:         unless ($status eq 'ok ok') {
 5670:            &logthis('Could not devalidate spreadsheet '.
 5671:                     $uname.' at '.$udom.' for '.
 5672: 		    $symb.': '.$status);
 5673:         }
 5674: 	&delenv('user.state.'.$cid);
 5675:     }
 5676: }
 5677: 
 5678: sub get_scalar {
 5679:     my ($string,$end) = @_;
 5680:     my $value;
 5681:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 5682: 	$value = $1;
 5683:     } elsif ($$string =~ s/^([^&]*?)&//) {
 5684: 	$value = $1;
 5685:     }
 5686:     return &unescape($value);
 5687: }
 5688: 
 5689: sub array2str {
 5690:   my (@array) = @_;
 5691:   my $result=&arrayref2str(\@array);
 5692:   $result=~s/^__ARRAY_REF__//;
 5693:   $result=~s/__END_ARRAY_REF__$//;
 5694:   return $result;
 5695: }
 5696: 
 5697: sub arrayref2str {
 5698:   my ($arrayref) = @_;
 5699:   my $result='__ARRAY_REF__';
 5700:   foreach my $elem (@$arrayref) {
 5701:     if(ref($elem) eq 'ARRAY') {
 5702:       $result.=&arrayref2str($elem).'&';
 5703:     } elsif(ref($elem) eq 'HASH') {
 5704:       $result.=&hashref2str($elem).'&';
 5705:     } elsif(ref($elem)) {
 5706:       #print("Got a ref of ".(ref($elem))." skipping.");
 5707:     } else {
 5708:       $result.=&escape($elem).'&';
 5709:     }
 5710:   }
 5711:   $result=~s/\&$//;
 5712:   $result .= '__END_ARRAY_REF__';
 5713:   return $result;
 5714: }
 5715: 
 5716: sub hash2str {
 5717:   my (%hash) = @_;
 5718:   my $result=&hashref2str(\%hash);
 5719:   $result=~s/^__HASH_REF__//;
 5720:   $result=~s/__END_HASH_REF__$//;
 5721:   return $result;
 5722: }
 5723: 
 5724: sub hashref2str {
 5725:   my ($hashref)=@_;
 5726:   my $result='__HASH_REF__';
 5727:   foreach my $key (sort(keys(%$hashref))) {
 5728:     if (ref($key) eq 'ARRAY') {
 5729:       $result.=&arrayref2str($key).'=';
 5730:     } elsif (ref($key) eq 'HASH') {
 5731:       $result.=&hashref2str($key).'=';
 5732:     } elsif (ref($key)) {
 5733:       $result.='=';
 5734:       #print("Got a ref of ".(ref($key))." skipping.");
 5735:     } else {
 5736: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
 5737:     }
 5738: 
 5739:     if(ref($hashref->{$key}) eq 'ARRAY') {
 5740:       $result.=&arrayref2str($hashref->{$key}).'&';
 5741:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 5742:       $result.=&hashref2str($hashref->{$key}).'&';
 5743:     } elsif(ref($hashref->{$key})) {
 5744:        $result.='&';
 5745:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 5746:     } else {
 5747:       $result.=&escape($hashref->{$key}).'&';
 5748:     }
 5749:   }
 5750:   $result=~s/\&$//;
 5751:   $result .= '__END_HASH_REF__';
 5752:   return $result;
 5753: }
 5754: 
 5755: sub str2hash {
 5756:     my ($string)=@_;
 5757:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 5758:     return %$hash;
 5759: }
 5760: 
 5761: sub str2hashref {
 5762:   my ($string) = @_;
 5763: 
 5764:   my %hash;
 5765: 
 5766:   if($string !~ /^__HASH_REF__/) {
 5767:       if (! ($string eq '' || !defined($string))) {
 5768: 	  $hash{'error'}='Not hash reference';
 5769:       }
 5770:       return (\%hash, $string);
 5771:   }
 5772: 
 5773:   $string =~ s/^__HASH_REF__//;
 5774: 
 5775:   while($string !~ /^__END_HASH_REF__/) {
 5776:       #key
 5777:       my $key='';
 5778:       if($string =~ /^__HASH_REF__/) {
 5779:           ($key, $string)=&str2hashref($string);
 5780:           if(defined($key->{'error'})) {
 5781:               $hash{'error'}='Bad data';
 5782:               return (\%hash, $string);
 5783:           }
 5784:       } elsif($string =~ /^__ARRAY_REF__/) {
 5785:           ($key, $string)=&str2arrayref($string);
 5786:           if($key->[0] eq 'Array reference error') {
 5787:               $hash{'error'}='Bad data';
 5788:               return (\%hash, $string);
 5789:           }
 5790:       } else {
 5791:           $string =~ s/^(.*?)=//;
 5792: 	  $key=&unescape($1);
 5793:       }
 5794:       $string =~ s/^=//;
 5795: 
 5796:       #value
 5797:       my $value='';
 5798:       if($string =~ /^__HASH_REF__/) {
 5799:           ($value, $string)=&str2hashref($string);
 5800:           if(defined($value->{'error'})) {
 5801:               $hash{'error'}='Bad data';
 5802:               return (\%hash, $string);
 5803:           }
 5804:       } elsif($string =~ /^__ARRAY_REF__/) {
 5805:           ($value, $string)=&str2arrayref($string);
 5806:           if($value->[0] eq 'Array reference error') {
 5807:               $hash{'error'}='Bad data';
 5808:               return (\%hash, $string);
 5809:           }
 5810:       } else {
 5811: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 5812:       }
 5813:       $string =~ s/^&//;
 5814: 
 5815:       $hash{$key}=$value;
 5816:   }
 5817: 
 5818:   $string =~ s/^__END_HASH_REF__//;
 5819: 
 5820:   return (\%hash, $string);
 5821: }
 5822: 
 5823: sub str2array {
 5824:     my ($string)=@_;
 5825:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 5826:     return @$array;
 5827: }
 5828: 
 5829: sub str2arrayref {
 5830:   my ($string) = @_;
 5831:   my @array;
 5832: 
 5833:   if($string !~ /^__ARRAY_REF__/) {
 5834:       if (! ($string eq '' || !defined($string))) {
 5835: 	  $array[0]='Array reference error';
 5836:       }
 5837:       return (\@array, $string);
 5838:   }
 5839: 
 5840:   $string =~ s/^__ARRAY_REF__//;
 5841: 
 5842:   while($string !~ /^__END_ARRAY_REF__/) {
 5843:       my $value='';
 5844:       if($string =~ /^__HASH_REF__/) {
 5845:           ($value, $string)=&str2hashref($string);
 5846:           if(defined($value->{'error'})) {
 5847:               $array[0] ='Array reference error';
 5848:               return (\@array, $string);
 5849:           }
 5850:       } elsif($string =~ /^__ARRAY_REF__/) {
 5851:           ($value, $string)=&str2arrayref($string);
 5852:           if($value->[0] eq 'Array reference error') {
 5853:               $array[0] ='Array reference error';
 5854:               return (\@array, $string);
 5855:           }
 5856:       } else {
 5857: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 5858:       }
 5859:       $string =~ s/^&//;
 5860: 
 5861:       push(@array, $value);
 5862:   }
 5863: 
 5864:   $string =~ s/^__END_ARRAY_REF__//;
 5865: 
 5866:   return (\@array, $string);
 5867: }
 5868: 
 5869: # -------------------------------------------------------------------Temp Store
 5870: 
 5871: sub tmpreset {
 5872:   my ($symb,$namespace,$domain,$stuname) = @_;
 5873:   if (!$symb) {
 5874:     $symb=&symbread();
 5875:     if (!$symb) { $symb= $env{'request.url'}; }
 5876:   }
 5877:   $symb=escape($symb);
 5878: 
 5879:   if (!$namespace) { $namespace=$env{'request.state'}; }
 5880:   $namespace=~s/\//\_/g;
 5881:   $namespace=~s/\W//g;
 5882: 
 5883:   if (!$domain) { $domain=$env{'user.domain'}; }
 5884:   if (!$stuname) { $stuname=$env{'user.name'}; }
 5885:   if ($domain eq 'public' && $stuname eq 'public') {
 5886:       $stuname=&get_requestor_ip();
 5887:   }
 5888:   my $path=LONCAPA::tempdir();
 5889:   my %hash;
 5890:   if (tie(%hash,'GDBM_File',
 5891: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 5892: 	  &GDBM_WRCREAT(),0640)) {
 5893:     foreach my $key (keys(%hash)) {
 5894:       if ($key=~ /:$symb/) {
 5895: 	delete($hash{$key});
 5896:       }
 5897:     }
 5898:   }
 5899: }
 5900: 
 5901: sub tmpstore {
 5902:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 5903: 
 5904:   if (!$symb) {
 5905:     $symb=&symbread();
 5906:     if (!$symb) { $symb= $env{'request.url'}; }
 5907:   }
 5908:   $symb=escape($symb);
 5909: 
 5910:   if (!$namespace) {
 5911:     # I don't think we would ever want to store this for a course.
 5912:     # it seems this will only be used if we don't have a course.
 5913:     #$namespace=$env{'request.course.id'};
 5914:     #if (!$namespace) {
 5915:       $namespace=$env{'request.state'};
 5916:     #}
 5917:   }
 5918:   $namespace=~s/\//\_/g;
 5919:   $namespace=~s/\W//g;
 5920:   if (!$domain) { $domain=$env{'user.domain'}; }
 5921:   if (!$stuname) { $stuname=$env{'user.name'}; }
 5922:   if ($domain eq 'public' && $stuname eq 'public') {
 5923:       $stuname=&get_requestor_ip();
 5924:   }
 5925:   my $now=time;
 5926:   my %hash;
 5927:   my $path=LONCAPA::tempdir();
 5928:   if (tie(%hash,'GDBM_File',
 5929: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 5930: 	  &GDBM_WRCREAT(),0640)) {
 5931:     $hash{"version:$symb"}++;
 5932:     my $version=$hash{"version:$symb"};
 5933:     my $allkeys=''; 
 5934:     foreach my $key (keys(%$storehash)) {
 5935:       $allkeys.=$key.':';
 5936:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 5937:     }
 5938:     $hash{"$version:$symb:timestamp"}=$now;
 5939:     $allkeys.='timestamp';
 5940:     $hash{"$version:keys:$symb"}=$allkeys;
 5941:     if (untie(%hash)) {
 5942:       return 'ok';
 5943:     } else {
 5944:       return "error:$!";
 5945:     }
 5946:   } else {
 5947:     return "error:$!";
 5948:   }
 5949: }
 5950: 
 5951: # -----------------------------------------------------------------Temp Restore
 5952: 
 5953: sub tmprestore {
 5954:   my ($symb,$namespace,$domain,$stuname) = @_;
 5955: 
 5956:   if (!$symb) {
 5957:     $symb=&symbread();
 5958:     if (!$symb) { $symb= $env{'request.url'}; }
 5959:   }
 5960:   $symb=escape($symb);
 5961: 
 5962:   if (!$namespace) { $namespace=$env{'request.state'}; }
 5963: 
 5964:   if (!$domain) { $domain=$env{'user.domain'}; }
 5965:   if (!$stuname) { $stuname=$env{'user.name'}; }
 5966:   if ($domain eq 'public' && $stuname eq 'public') {
 5967:       $stuname=&get_requestor_ip();
 5968:   }
 5969:   my %returnhash;
 5970:   $namespace=~s/\//\_/g;
 5971:   $namespace=~s/\W//g;
 5972:   my %hash;
 5973:   my $path=LONCAPA::tempdir();
 5974:   if (tie(%hash,'GDBM_File',
 5975: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 5976: 	  &GDBM_READER(),0640)) {
 5977:     my $version=$hash{"version:$symb"};
 5978:     $returnhash{'version'}=$version;
 5979:     my $scope;
 5980:     for ($scope=1;$scope<=$version;$scope++) {
 5981:       my $vkeys=$hash{"$scope:keys:$symb"};
 5982:       my @keys=split(/:/,$vkeys);
 5983:       my $key;
 5984:       $returnhash{"$scope:keys"}=$vkeys;
 5985:       foreach $key (@keys) {
 5986: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 5987: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 5988:       }
 5989:     }
 5990:     if (!(untie(%hash))) {
 5991:       return "error:$!";
 5992:     }
 5993:   } else {
 5994:     return "error:$!";
 5995:   }
 5996:   return %returnhash;
 5997: }
 5998: 
 5999: # ----------------------------------------------------------------------- Store
 6000: 
 6001: sub store {
 6002:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 6003:     my $home='';
 6004: 
 6005:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 6006: 
 6007:     $symb=&symbclean($symb);
 6008:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 6009: 
 6010:     if (!$domain) { $domain=$env{'user.domain'}; }
 6011:     if (!$stuname) { $stuname=$env{'user.name'}; }
 6012: 
 6013:     &devalidate($symb,$stuname,$domain);
 6014: 
 6015:     $symb=escape($symb);
 6016:     if (!$namespace) { 
 6017:        unless ($namespace=$env{'request.course.id'}) { 
 6018:           return ''; 
 6019:        } 
 6020:     }
 6021:     if (!$home) { $home=$env{'user.home'}; }
 6022: 
 6023:     $$storehash{'ip'}=&get_requestor_ip();
 6024:     $$storehash{'host'}=$perlvar{'lonHostID'};
 6025: 
 6026:     my $namevalue='';
 6027:     foreach my $key (keys(%$storehash)) {
 6028:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 6029:     }
 6030:     $namevalue=~s/\&$//;
 6031:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 6032:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 6033: }
 6034: 
 6035: # -------------------------------------------------------------- Critical Store
 6036: 
 6037: sub cstore {
 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'}=&get_requestor_ip();
 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.':CSTORE:'.$namevalue);
 6068:     return critical
 6069:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 6070: }
 6071: 
 6072: # --------------------------------------------------------------------- Restore
 6073: 
 6074: sub restore {
 6075:     my ($symb,$namespace,$domain,$stuname) = @_;
 6076:     my $home='';
 6077: 
 6078:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 6079: 
 6080:     if (!$symb) {
 6081:         return if ($namespace eq 'courserequests');
 6082:         unless ($symb=escape(&symbread())) { return ''; }
 6083:     } else {
 6084:         unless ($namespace eq 'courserequests') {
 6085:             $symb=&escape(&symbclean($symb));
 6086:         }
 6087:     }
 6088:     if (!$namespace) { 
 6089:        unless ($namespace=$env{'request.course.id'}) { 
 6090:           return ''; 
 6091:        } 
 6092:     }
 6093:     if (!$domain) { $domain=$env{'user.domain'}; }
 6094:     if (!$stuname) { $stuname=$env{'user.name'}; }
 6095:     if (!$home) { $home=$env{'user.home'}; }
 6096:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 6097: 
 6098:     my %returnhash=();
 6099:     foreach my $line (split(/\&/,$answer)) {
 6100: 	my ($name,$value)=split(/\=/,$line);
 6101:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 6102:     }
 6103:     my $version;
 6104:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 6105:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 6106:           $returnhash{$item}=$returnhash{$version.':'.$item};
 6107:        }
 6108:     }
 6109:     return %returnhash;
 6110: }
 6111: 
 6112: # ---------------------------------------------------------- Course Description
 6113: #
 6114: #  
 6115: 
 6116: sub coursedescription {
 6117:     my ($courseid,$args)=@_;
 6118:     $courseid=~s/^\///;
 6119:     $courseid=~s/\_/\//g;
 6120:     my ($cdomain,$cnum)=split(/\//,$courseid);
 6121:     my $chome=&homeserver($cnum,$cdomain);
 6122:     my $normalid=$cdomain.'_'.$cnum;
 6123:     # need to always cache even if we get errors otherwise we keep 
 6124:     # trying and trying and trying to get the course description.
 6125:     my %envhash=();
 6126:     my %returnhash=();
 6127:     
 6128:     my $expiretime=600;
 6129:     if ($env{'request.course.id'} eq $normalid) {
 6130: 	$expiretime=120;
 6131:     }
 6132: 
 6133:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 6134:     if (!$args->{'freshen_cache'}
 6135: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 6136: 	foreach my $key (keys(%env)) {
 6137: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 6138: 	    my ($setting) = $1;
 6139: 	    $returnhash{$setting} = $env{$key};
 6140: 	}
 6141: 	return %returnhash;
 6142:     }
 6143: 
 6144:     # get the data again
 6145: 
 6146:     if (!$args->{'one_time'}) {
 6147: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 6148:     }
 6149: 
 6150:     if ($chome ne 'no_host') {
 6151:        %returnhash=&dump('environment',$cdomain,$cnum);
 6152:        if (!exists($returnhash{'con_lost'})) {
 6153: 	   my $username = $env{'user.name'}; # Defult username
 6154: 	   if(defined $args->{'user'}) {
 6155: 	       $username = $args->{'user'};
 6156: 	   }
 6157:            $returnhash{'home'}= $chome;
 6158: 	   $returnhash{'domain'} = $cdomain;
 6159: 	   $returnhash{'num'} = $cnum;
 6160:            if (!defined($returnhash{'type'})) {
 6161:                $returnhash{'type'} = 'Course';
 6162:            }
 6163:            while (my ($name,$value) = each %returnhash) {
 6164:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 6165:            }
 6166:            $returnhash{'url'}=&clutter($returnhash{'url'});
 6167:            $returnhash{'fn'}=LONCAPA::tempdir() .
 6168: 	       $username.'_'.$cdomain.'_'.$cnum;
 6169:            $envhash{'course.'.$normalid.'.home'}=$chome;
 6170:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 6171:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 6172:        }
 6173:     }
 6174:     if (!$args->{'one_time'}) {
 6175: 	&appenv(\%envhash);
 6176:     }
 6177:     return %returnhash;
 6178: }
 6179: 
 6180: sub update_released_required {
 6181:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
 6182:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
 6183:         $cid = $env{'request.course.id'};
 6184:         $cdom = $env{'course.'.$cid.'.domain'};
 6185:         $cnum = $env{'course.'.$cid.'.num'};
 6186:         $chome = $env{'course.'.$cid.'.home'};
 6187:     }
 6188:     if ($needsrelease) {
 6189:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
 6190:         my $needsupdate;
 6191:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
 6192:             $needsupdate = 1;
 6193:         } else {
 6194:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
 6195:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
 6196:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
 6197:                 $needsupdate = 1;
 6198:             }
 6199:         }
 6200:         if ($needsupdate) {
 6201:             my %needshash = (
 6202:                              'internal.releaserequired' => $needsrelease,
 6203:                             );
 6204:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
 6205:             if ($putresult eq 'ok') {
 6206:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
 6207:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 6208:                 if (ref($crsinfo{$cid}) eq 'HASH') {
 6209:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
 6210:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
 6211:                 }
 6212:             }
 6213:         }
 6214:     }
 6215:     return;
 6216: }
 6217: 
 6218: # -------------------------------------------------See if a user is privileged
 6219: 
 6220: sub privileged {
 6221:     my ($username,$domain,$possdomains,$possroles)=@_;
 6222:     my $now = time;
 6223:     my $roles;
 6224:     if (ref($possroles) eq 'ARRAY') {
 6225:         $roles = $possroles;
 6226:     } else {
 6227:         $roles = ['dc','su'];
 6228:     }
 6229:     if (ref($possdomains) eq 'ARRAY') {
 6230:         my %privileged = &privileged_by_domain($possdomains,$roles);
 6231:         foreach my $dom (@{$possdomains}) {
 6232:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
 6233:                 (ref($privileged{$dom}) eq 'HASH')) {
 6234:                 foreach my $role (@{$roles}) {
 6235:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 6236:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
 6237:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
 6238:                             return 1 unless (($end && $end < $now) ||
 6239:                                              ($start && $start > $now));
 6240:                         }
 6241:                     }
 6242:                 }
 6243:             }
 6244:         }
 6245:     } else {
 6246:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
 6247:         my $now = time;
 6248: 
 6249:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
 6250:             my ($trole, $tend, $tstart) = split(/_/, $role);
 6251:             if (grep(/^\Q$trole\E$/,@{$roles})) {
 6252:                 return 1 unless ($tend && $tend < $now)
 6253:                         or ($tstart && $tstart > $now);
 6254:             }
 6255:         }
 6256:     }
 6257:     return 0;
 6258: }
 6259: 
 6260: sub privileged_by_domain {
 6261:     my ($domains,$roles) = @_;
 6262:     my %privileged = ();
 6263:     my $cachetime = 60*60*24;
 6264:     my $now = time;
 6265:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
 6266:         return %privileged;
 6267:     }
 6268:     foreach my $dom (@{$domains}) {
 6269:         next if (ref($privileged{$dom}) eq 'HASH');
 6270:         my $needroles;
 6271:         foreach my $role (@{$roles}) {
 6272:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
 6273:             if (defined($cached)) {
 6274:                 if (ref($result) eq 'HASH') {
 6275:                     $privileged{$dom}{$role} = $result;
 6276:                 }
 6277:             } else {
 6278:                 $needroles = 1;
 6279:             }
 6280:         }
 6281:         if ($needroles) {
 6282:             my %dompersonnel = &get_domain_roles($dom,$roles);
 6283:             $privileged{$dom} = {};
 6284:             foreach my $server (keys(%dompersonnel)) {
 6285:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 6286:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
 6287:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
 6288:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
 6289:                         next if ($end && $end < $now);
 6290:                         $privileged{$dom}{$trole}{$uname.':'.$udom} =
 6291:                             $dompersonnel{$server}{$item};
 6292:                     }
 6293:                 }
 6294:             }
 6295:             if (ref($privileged{$dom}) eq 'HASH') {
 6296:                 foreach my $role (@{$roles}) {
 6297:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 6298:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
 6299:                     } else {
 6300:                         my %hash = ();
 6301:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
 6302:                     }
 6303:                 }
 6304:             }
 6305:         }
 6306:     }
 6307:     return %privileged;
 6308: }
 6309: 
 6310: # -------------------------------------------------------- Get user privileges
 6311: 
 6312: sub rolesinit {
 6313:     my ($domain, $username) = @_;
 6314:     my %userroles = ('user.login.time' => time);
 6315:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
 6316: 
 6317:     # firstaccess and timerinterval are related to timed maps/resources. 
 6318:     # also, blocking can be triggered by an activating timer
 6319:     # it's saved in the user's %env.
 6320:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
 6321:     my %timerinterval = &dump('timerinterval', $domain, $username);
 6322:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
 6323:         %timerintchk, %timerintenv);
 6324: 
 6325:     foreach my $key (keys(%firstaccess)) {
 6326:         my ($cid, $rest) = split(/\0/, $key);
 6327:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
 6328:     }
 6329: 
 6330:     foreach my $key (keys(%timerinterval)) {
 6331:         my ($cid,$rest) = split(/\0/,$key);
 6332:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
 6333:     }
 6334: 
 6335:     my %allroles=();
 6336:     my %allgroups=();
 6337: 
 6338:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
 6339:         my $role = $rolesdump{$area};
 6340:         $area =~ s/\_\w\w$//;
 6341: 
 6342:         my ($trole, $tend, $tstart, $group_privs);
 6343: 
 6344:         if ($role =~ /^cr/) {
 6345:         # Custom role, defined by a user 
 6346:         # e.g., user.role.cr/msu/smith/mynewrole
 6347:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 6348:                 $trole = $1;
 6349:                 ($tend, $tstart) = split('_', $2);
 6350:             } else {
 6351:                 $trole = $role;
 6352:             }
 6353:         } elsif ($role =~ m|^gr/|) {
 6354:         # Role of member in a group, defined within a course/community
 6355:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
 6356:             ($trole, $tend, $tstart) = split(/_/, $role);
 6357:             next if $tstart eq '-1';
 6358:             ($trole, $group_privs) = split(/\//, $trole);
 6359:             $group_privs = &unescape($group_privs);
 6360:         } else {
 6361:         # Just a normal role, defined in roles.tab
 6362:             ($trole, $tend, $tstart) = split(/_/,$role);
 6363:         }
 6364: 
 6365:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 6366:                  $username);
 6367:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 6368: 
 6369:         # role expired or not available yet?
 6370:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
 6371:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
 6372: 
 6373:         next if $area eq '' or $trole eq '';
 6374: 
 6375:         my $spec = "$trole.$area";
 6376:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
 6377: 
 6378:         if ($trole =~ /^cr\//) {
 6379:         # Custom role, defined by a user
 6380:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 6381:         } elsif ($trole eq 'gr') {
 6382:         # Role of a member in a group, defined within a course/community
 6383:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 6384:             next;
 6385:         } else {
 6386:         # Normal role, defined in roles.tab
 6387:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 6388:         }
 6389: 
 6390:         my $cid = $tdomain.'_'.$trest;
 6391:         unless ($firstaccchk{$cid}) {
 6392:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
 6393:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
 6394:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
 6395:                         $coursetimerstarts{$cid}{$item}; 
 6396:                 }
 6397:             }
 6398:             $firstaccchk{$cid} = 1;
 6399:         }
 6400:         unless ($timerintchk{$cid}) {
 6401:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
 6402:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
 6403:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
 6404:                        $coursetimerintervals{$cid}{$item};
 6405:                 }
 6406:             }
 6407:             $timerintchk{$cid} = 1;
 6408:         }
 6409:     }
 6410: 
 6411:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
 6412:                                                           \%allroles, \%allgroups);
 6413:     $env{'user.adv'} = $userroles{'user.adv'};
 6414:     $env{'user.rar'} = $userroles{'user.rar'};
 6415: 
 6416:     return (\%userroles,\%firstaccenv,\%timerintenv);
 6417: }
 6418: 
 6419: sub set_arearole {
 6420:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
 6421:     unless ($nolog) {
 6422: # log the associated role with the area
 6423:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 6424:     }
 6425:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 6426: }
 6427: 
 6428: sub custom_roleprivs {
 6429:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 6430:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 6431:     my $homsvr = &homeserver($rauthor,$rdomain);
 6432:     if (&hostname($homsvr) ne '') {
 6433:         my ($rdummy,$roledef)=
 6434:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 6435:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 6436:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 6437:             if (defined($syspriv)) {
 6438:                 if ($trest =~ /^$match_community$/) {
 6439:                     $syspriv =~ s/bre\&S//; 
 6440:                 }
 6441:                 $$allroles{'cm./'}.=':'.$syspriv;
 6442:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 6443:             }
 6444:             if ($tdomain ne '') {
 6445:                 if (defined($dompriv)) {
 6446:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 6447:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 6448:                 }
 6449:                 if (($trest ne '') && (defined($coursepriv))) {
 6450:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
 6451:                         my $rolename = $1;
 6452:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
 6453:                     }
 6454:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 6455:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 6456:                 }
 6457:             }
 6458:         }
 6459:     }
 6460: }
 6461: 
 6462: sub course_adhocrole_privs {
 6463:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
 6464:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
 6465:     if ($overrides{"internal.adhocpriv.$rolename"}) {
 6466:         my (%currprivs,%storeprivs);
 6467:         foreach my $item (split(/:/,$coursepriv)) {
 6468:             my ($priv,$restrict) = split(/\&/,$item);
 6469:             $currprivs{$priv} = $restrict;
 6470:         }
 6471:         my (%possadd,%possremove,%full);
 6472:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
 6473:             my ($priv,$restrict)=split(/\&/,$item);
 6474:             $full{$priv} = $restrict;
 6475:         }
 6476:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
 6477:              next if ($item eq '');
 6478:              my ($rule,$rest) = split(/=/,$item);
 6479:              next unless (($rule eq 'off') || ($rule eq 'on'));
 6480:              foreach my $priv (split(/:/,$rest)) {
 6481:                  if ($priv ne '') {
 6482:                      if ($rule eq 'off') {
 6483:                          $possremove{$priv} = 1;
 6484:                      } else {
 6485:                          $possadd{$priv} = 1;
 6486:                      }
 6487:                  }
 6488:              }
 6489:          }
 6490:          foreach my $priv (sort(keys(%full))) {
 6491:              if (exists($currprivs{$priv})) {
 6492:                  unless (exists($possremove{$priv})) {
 6493:                      $storeprivs{$priv} = $currprivs{$priv};
 6494:                  }
 6495:              } elsif (exists($possadd{$priv})) {
 6496:                  $storeprivs{$priv} = $full{$priv};
 6497:              }
 6498:          }
 6499:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
 6500:      }
 6501:      return $coursepriv;
 6502: }
 6503: 
 6504: sub group_roleprivs {
 6505:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 6506:     my $access = 1;
 6507:     my $now = time;
 6508:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 6509:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 6510:     if ($access) {
 6511:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 6512:         $$allgroups{$course}{$group} .=':'.$group_privs;
 6513:     }
 6514: }
 6515: 
 6516: sub standard_roleprivs {
 6517:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 6518:     if (defined($pr{$trole.':s'})) {
 6519:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 6520:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 6521:     }
 6522:     if ($tdomain ne '') {
 6523:         if (defined($pr{$trole.':d'})) {
 6524:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 6525:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 6526:         }
 6527:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 6528:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 6529:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 6530:         }
 6531:     }
 6532: }
 6533: 
 6534: sub set_userprivs {
 6535:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
 6536:     my $author=0;
 6537:     my $adv=0;
 6538:     my $rar=0;
 6539:     my %grouproles = ();
 6540:     if (keys(%{$allgroups}) > 0) {
 6541:         my @groupkeys; 
 6542:         foreach my $role (keys(%{$allroles})) {
 6543:             push(@groupkeys,$role);
 6544:         }
 6545:         if (ref($groups_roles) eq 'HASH') {
 6546:             foreach my $key (keys(%{$groups_roles})) {
 6547:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
 6548:                     push(@groupkeys,$key);
 6549:                 }
 6550:             }
 6551:         }
 6552:         if (@groupkeys > 0) {
 6553:             foreach my $role (@groupkeys) {
 6554:                 my ($trole,$area,$sec,$extendedarea);
 6555:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 6556:                     $trole = $1;
 6557:                     $area = $2;
 6558:                     $sec = $3;
 6559:                     $extendedarea = $area.$sec;
 6560:                     if (exists($$allgroups{$area})) {
 6561:                         foreach my $group (keys(%{$$allgroups{$area}})) {
 6562:                             my $spec = $trole.'.'.$extendedarea;
 6563:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
 6564:                                                 $$allgroups{$area}{$group};
 6565:                         }
 6566:                     }
 6567:                 }
 6568:             }
 6569:         }
 6570:     }
 6571:     foreach my $group (keys(%grouproles)) {
 6572:         $$allroles{$group} = $grouproles{$group};
 6573:     }
 6574:     foreach my $role (keys(%{$allroles})) {
 6575:         my %thesepriv;
 6576:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 6577:         foreach my $item (split(/:/,$$allroles{$role})) {
 6578:             if ($item ne '') {
 6579:                 my ($privilege,$restrictions)=split(/&/,$item);
 6580:                 if ($restrictions eq '') {
 6581:                     $thesepriv{$privilege}='F';
 6582:                 } elsif ($thesepriv{$privilege} ne 'F') {
 6583:                     $thesepriv{$privilege}.=$restrictions;
 6584:                 }
 6585:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 6586:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
 6587:             }
 6588:         }
 6589:         my $thesestr='';
 6590:         foreach my $priv (sort(keys(%thesepriv))) {
 6591: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 6592: 	}
 6593:         $userroles->{'user.priv.'.$role} = $thesestr;
 6594:     }
 6595:     return ($author,$adv,$rar);
 6596: }
 6597: 
 6598: sub role_status {
 6599:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 6600:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 6601:         my ($one,$two) = split(m{\./},$rolekey,2);
 6602:         (undef,undef,$$role) = split(/\./,$one,3);
 6603:         unless (!defined($$role) || $$role eq '') {
 6604:             $$where = '/'.$two;
 6605:             $$trolecode=$$role.'.'.$$where;
 6606:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 6607:             $$tstatus='is';
 6608:             if ($$tstart && $$tstart>$update) {
 6609:                 $$tstatus='future';
 6610:                 if ($$tstart<$now) {
 6611:                     if ($$tstart && $$tstart>$refresh) {
 6612:                         if (($$where ne '') && ($$role ne '')) {
 6613:                             my (%allroles,%allgroups,$group_privs,
 6614:                                 %groups_roles,@rolecodes);
 6615:                             my %userroles = (
 6616:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 6617:                             );
 6618:                             @rolecodes = ('cm'); 
 6619:                             my $spec=$$role.'.'.$$where;
 6620:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 6621:                             if ($$role =~ /^cr\//) {
 6622:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 6623:                                 push(@rolecodes,'cr');
 6624:                             } elsif ($$role eq 'gr') {
 6625:                                 push(@rolecodes,$$role);
 6626:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 6627:                                                     $env{'user.name'});
 6628:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
 6629:                                 (undef,my $group_privs) = split(/\//,$trole);
 6630:                                 $group_privs = &unescape($group_privs);
 6631:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 6632:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
 6633:                                 &get_groups_roles($tdomain,$trest,
 6634:                                                   \%course_roles,\@rolecodes,
 6635:                                                   \%groups_roles);
 6636:                             } else {
 6637:                                 push(@rolecodes,$$role);
 6638:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 6639:                             }
 6640:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
 6641:                                                                    \%groups_roles);
 6642:                             &appenv(\%userroles,\@rolecodes);
 6643:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
 6644:                         }
 6645:                     }
 6646:                     $$tstatus = 'is';
 6647:                 }
 6648:             }
 6649:             if ($$tend) {
 6650:                 if ($$tend<$update) {
 6651:                     $$tstatus='expired';
 6652:                 } elsif ($$tend<$now) {
 6653:                     $$tstatus='will_not';
 6654:                 }
 6655:             }
 6656:         }
 6657:     }
 6658: }
 6659: 
 6660: sub get_groups_roles {
 6661:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
 6662:     return unless((ref($cdom_courseroles) eq 'HASH') && 
 6663:                   (ref($rolecodes) eq 'ARRAY') && 
 6664:                   (ref($groups_roles) eq 'HASH')); 
 6665:     if (keys(%{$cdom_courseroles}) > 0) {
 6666:         my ($cnum) = ($rest =~ /^($match_courseid)/);
 6667:         if ($cdom ne '' && $cnum ne '') {
 6668:             foreach my $key (keys(%{$cdom_courseroles})) {
 6669:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
 6670:                     my $crsrole = $1;
 6671:                     my $crssec = $2;
 6672:                     if ($crsrole =~ /^cr/) {
 6673:                         unless (grep(/^cr$/,@{$rolecodes})) {
 6674:                             push(@{$rolecodes},'cr');
 6675:                         }
 6676:                     } else {
 6677:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
 6678:                             push(@{$rolecodes},$crsrole);
 6679:                         }
 6680:                     }
 6681:                     my $rolekey = "$crsrole./$cdom/$cnum";
 6682:                     if ($crssec ne '') {
 6683:                         $rolekey .= "/$crssec";
 6684:                     }
 6685:                     $rolekey .= './';
 6686:                     $groups_roles->{$rolekey} = $rolecodes;
 6687:                 }
 6688:             }
 6689:         }
 6690:     }
 6691:     return;
 6692: }
 6693: 
 6694: sub delete_env_groupprivs {
 6695:     my ($where,$courseroles,$possroles) = @_;
 6696:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
 6697:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
 6698:     unless (ref($courseroles->{$udom}) eq 'HASH') {
 6699:         %{$courseroles->{$udom}} =
 6700:             &get_my_roles('','','userroles',['active'],
 6701:                           $possroles,[$udom],1);
 6702:     }
 6703:     if (ref($courseroles->{$udom}) eq 'HASH') {
 6704:         foreach my $item (keys(%{$courseroles->{$udom}})) {
 6705:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
 6706:             my $area = '/'.$cdom.'/'.$cnum;
 6707:             my $privkey = "user.priv.$crsrole.$area";
 6708:             if ($crssec ne '') {
 6709:                 $privkey .= '/'.$crssec;
 6710:             }
 6711:             $privkey .= ".$area/$group";
 6712:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
 6713:         }
 6714:     }
 6715:     return;
 6716: }
 6717: 
 6718: sub check_adhoc_privs {
 6719:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
 6720:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 6721:     if ($sec) {
 6722:         $cckey .= '/'.$sec;
 6723:     }
 6724:     my $setprivs;
 6725:     if ($env{$cckey}) {
 6726:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 6727:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 6728:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 6729:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
 6730:             $setprivs = 1;
 6731:         }
 6732:     } else {
 6733:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
 6734:         $setprivs = 1;
 6735:     }
 6736:     return $setprivs;
 6737: }
 6738: 
 6739: sub set_adhoc_privileges {
 6740: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
 6741:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
 6742:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 6743:     if ($sec ne '') {
 6744:         $area .= '/'.$sec;
 6745:     }
 6746:     my $spec = $role.'.'.$area;
 6747:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 6748:                                   $env{'user.name'},1);
 6749:     my %rolehash = ();
 6750:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
 6751:         my $rolename = $1;
 6752:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
 6753:         my %domdef = &get_domain_defaults($dcdom);
 6754:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
 6755:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
 6756:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
 6757:             }
 6758:         }
 6759:     } else {
 6760:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
 6761:     }
 6762:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
 6763:     &appenv(\%userroles,[$role,'cm']);
 6764:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
 6765:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
 6766:         &appenv( {'request.role'        => $spec,
 6767:                   'request.role.domain' => $dcdom,
 6768:                   'request.course.sec'  => $sec, 
 6769:                  }
 6770:                );
 6771:         my $tadv=0;
 6772:         if (&allowed('adv') eq 'F') { $tadv=1; }
 6773:         &appenv({'request.role.adv'    => $tadv});
 6774:     }
 6775: }
 6776: 
 6777: # --------------------------------------------------------------- get interface
 6778: 
 6779: sub get {
 6780:    my ($namespace,$storearr,$udomain,$uname)=@_;
 6781:    my $items='';
 6782:    foreach my $item (@$storearr) {
 6783:        $items.=&escape($item).'&';
 6784:    }
 6785:    $items=~s/\&$//;
 6786:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6787:    if (!$uname) { $uname=$env{'user.name'}; }
 6788:    my $uhome=&homeserver($uname,$udomain);
 6789: 
 6790:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 6791:    my @pairs=split(/\&/,$rep);
 6792:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 6793:      return @pairs;
 6794:    }
 6795:    my %returnhash=();
 6796:    my $i=0;
 6797:    foreach my $item (@$storearr) {
 6798:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 6799:       $i++;
 6800:    }
 6801:    return %returnhash;
 6802: }
 6803: 
 6804: # --------------------------------------------------------------- del interface
 6805: 
 6806: sub del {
 6807:    my ($namespace,$storearr,$udomain,$uname)=@_;
 6808:    my $items='';
 6809:    foreach my $item (@$storearr) {
 6810:        $items.=&escape($item).'&';
 6811:    }
 6812: 
 6813:    $items=~s/\&$//;
 6814:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6815:    if (!$uname) { $uname=$env{'user.name'}; }
 6816:    my $uhome=&homeserver($uname,$udomain);
 6817:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 6818: }
 6819: 
 6820: # -------------------------------------------------------------- dump interface
 6821: 
 6822: sub unserialize {
 6823:     my ($rep, $escapedkeys) = @_;
 6824: 
 6825:     return {} if $rep =~ /^error/;
 6826: 
 6827:     my %returnhash=();
 6828:     foreach my $item (split(/\&/,$rep)) {
 6829:         my ($key, $value) = split(/=/, $item, 2);
 6830:         $key = unescape($key) unless $escapedkeys;
 6831:         next if $key =~ /^error: 2 /;
 6832:         $returnhash{$key} = &thaw_unescape($value);
 6833:     }
 6834:     return \%returnhash;
 6835: }
 6836: 
 6837: # see Lond::dump_with_regexp
 6838: # if $escapedkeys hash keys won't get unescaped.
 6839: sub dump {
 6840:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
 6841:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 6842:     if (!$uname) { $uname=$env{'user.name'}; }
 6843:     my $uhome=&homeserver($uname,$udomain);
 6844: 
 6845:     if ($regexp) {
 6846:         $regexp=&escape($regexp);
 6847:     } else {
 6848:         $regexp='.';
 6849:     }
 6850:     if (grep { $_ eq $uhome } &current_machine_ids()) {
 6851:         # user is hosted on this machine
 6852:         my $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
 6853:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
 6854:         return %{&unserialize($reply, $escapedkeys)};
 6855:     }
 6856:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 6857:     my @pairs=split(/\&/,$rep);
 6858:     my %returnhash=();
 6859:     if (!($rep =~ /^error/ )) {
 6860: 	foreach my $item (@pairs) {
 6861: 	    my ($key,$value)=split(/=/,$item,2);
 6862:             $key = &unescape($key) unless ($escapedkeys);
 6863: 	    next if ($key =~ /^error: 2 /);
 6864: 	    $returnhash{$key}=&thaw_unescape($value);
 6865: 	}
 6866:     }
 6867:     return %returnhash;
 6868: }
 6869: 
 6870: 
 6871: # --------------------------------------------------------- dumpstore interface
 6872: 
 6873: sub dumpstore {
 6874:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 6875:    # same as dump but keys must be escaped. They may contain colon separated
 6876:    # lists of values that may themself contain colons (e.g. symbs).
 6877:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
 6878: }
 6879: 
 6880: # -------------------------------------------------------------- keys interface
 6881: 
 6882: sub getkeys {
 6883:    my ($namespace,$udomain,$uname)=@_;
 6884:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6885:    if (!$uname) { $uname=$env{'user.name'}; }
 6886:    my $uhome=&homeserver($uname,$udomain);
 6887:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 6888:    my @keyarray=();
 6889:    foreach my $key (split(/\&/,$rep)) {
 6890:       next if ($key =~ /^error: 2 /);
 6891:       push(@keyarray,&unescape($key));
 6892:    }
 6893:    return @keyarray;
 6894: }
 6895: 
 6896: # --------------------------------------------------------------- currentdump
 6897: sub currentdump {
 6898:    my ($courseid,$sdom,$sname)=@_;
 6899:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 6900:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 6901:    $sname    = $env{'user.name'}         if (! defined($sname));
 6902:    my $uhome = &homeserver($sname,$sdom);
 6903:    my $rep;
 6904: 
 6905:    if (grep { $_ eq $uhome } current_machine_ids()) {
 6906:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
 6907:                    $courseid)));
 6908:    } else {
 6909:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 6910:    }
 6911: 
 6912:    return if ($rep =~ /^(error:|no_such_host)/);
 6913:    #
 6914:    my %returnhash=();
 6915:    #
 6916:    if ($rep eq "unknown_cmd") { 
 6917:        # an old lond will not know currentdump
 6918:        # Do a dump and make it look like a currentdump
 6919:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 6920:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 6921:        my %hash = @tmp;
 6922:        @tmp=();
 6923:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 6924:    } else {
 6925:        my @pairs=split(/\&/,$rep);
 6926:        foreach my $pair (@pairs) {
 6927:            my ($key,$value)=split(/=/,$pair,2);
 6928:            my ($symb,$param) = split(/:/,$key);
 6929:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 6930:                                                         &thaw_unescape($value);
 6931:        }
 6932:    }
 6933:    return %returnhash;
 6934: }
 6935: 
 6936: sub convert_dump_to_currentdump{
 6937:     my %hash = %{shift()};
 6938:     my %returnhash;
 6939:     # Code ripped from lond, essentially.  The only difference
 6940:     # here is the unescaping done by lonnet::dump().  Conceivably
 6941:     # we might run in to problems with parameter names =~ /^v\./
 6942:     while (my ($key,$value) = each(%hash)) {
 6943:         my ($v,$symb,$param) = split(/:/,$key);
 6944: 	$symb  = &unescape($symb);
 6945: 	$param = &unescape($param);
 6946:         next if ($v eq 'version' || $symb eq 'keys');
 6947:         next if (exists($returnhash{$symb}) &&
 6948:                  exists($returnhash{$symb}->{$param}) &&
 6949:                  $returnhash{$symb}->{'v.'.$param} > $v);
 6950:         $returnhash{$symb}->{$param}=$value;
 6951:         $returnhash{$symb}->{'v.'.$param}=$v;
 6952:     }
 6953:     #
 6954:     # Remove all of the keys in the hashes which keep track of
 6955:     # the version of the parameter.
 6956:     while (my ($symb,$param_hash) = each(%returnhash)) {
 6957:         # use a foreach because we are going to delete from the hash.
 6958:         foreach my $key (keys(%$param_hash)) {
 6959:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 6960:         }
 6961:     }
 6962:     return \%returnhash;
 6963: }
 6964: 
 6965: # ------------------------------------------------------ critical inc interface
 6966: 
 6967: sub cinc {
 6968:     return &inc(@_,'critical');
 6969: }
 6970: 
 6971: # --------------------------------------------------------------- inc interface
 6972: 
 6973: sub inc {
 6974:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 6975:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 6976:     if (!$uname) { $uname=$env{'user.name'}; }
 6977:     my $uhome=&homeserver($uname,$udomain);
 6978:     my $items='';
 6979:     if (! ref($store)) {
 6980:         # got a single value, so use that instead
 6981:         $items = &escape($store).'=&';
 6982:     } elsif (ref($store) eq 'SCALAR') {
 6983:         $items = &escape($$store).'=&';        
 6984:     } elsif (ref($store) eq 'ARRAY') {
 6985:         $items = join('=&',map {&escape($_);} @{$store});
 6986:     } elsif (ref($store) eq 'HASH') {
 6987:         while (my($key,$value) = each(%{$store})) {
 6988:             $items.= &escape($key).'='.&escape($value).'&';
 6989:         }
 6990:     }
 6991:     $items=~s/\&$//;
 6992:     if ($critical) {
 6993: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 6994:     } else {
 6995: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 6996:     }
 6997: }
 6998: 
 6999: # --------------------------------------------------------------- put interface
 7000: 
 7001: sub put {
 7002:    my ($namespace,$storehash,$udomain,$uname)=@_;
 7003:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7004:    if (!$uname) { $uname=$env{'user.name'}; }
 7005:    my $uhome=&homeserver($uname,$udomain);
 7006:    my $items='';
 7007:    foreach my $item (keys(%$storehash)) {
 7008:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 7009:    }
 7010:    $items=~s/\&$//;
 7011:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 7012: }
 7013: 
 7014: # ------------------------------------------------------------ newput interface
 7015: 
 7016: sub newput {
 7017:    my ($namespace,$storehash,$udomain,$uname)=@_;
 7018:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7019:    if (!$uname) { $uname=$env{'user.name'}; }
 7020:    my $uhome=&homeserver($uname,$udomain);
 7021:    my $items='';
 7022:    foreach my $key (keys(%$storehash)) {
 7023:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 7024:    }
 7025:    $items=~s/\&$//;
 7026:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 7027: }
 7028: 
 7029: # ---------------------------------------------------------  putstore interface
 7030: 
 7031: sub putstore {
 7032:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
 7033:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7034:    if (!$uname) { $uname=$env{'user.name'}; }
 7035:    my $uhome=&homeserver($uname,$udomain);
 7036:    my $items='';
 7037:    foreach my $key (keys(%$storehash)) {
 7038:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 7039:    }
 7040:    $items=~s/\&$//;
 7041:    my $esc_symb=&escape($symb);
 7042:    my $esc_v=&escape($version);
 7043:    my $reply =
 7044:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 7045: 	      $uhome);
 7046:    if (($tolog) && ($reply eq 'ok')) {
 7047:        my $namevalue='';
 7048:        foreach my $key (keys(%{$storehash})) {
 7049:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 7050:        }
 7051:        my $ip = &get_requestor_ip();
 7052:        $namevalue .= 'ip='.&escape($ip).
 7053:                      '&host='.&escape($perlvar{'lonHostID'}).
 7054:                      '&version='.$esc_v.
 7055:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
 7056:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
 7057:    }
 7058:    if ($reply eq 'unknown_cmd') {
 7059:        # gfall back to way things use to be done
 7060:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 7061: 			    $uname);
 7062:    }
 7063:    return $reply;
 7064: }
 7065: 
 7066: sub old_putstore {
 7067:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 7068:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 7069:     if (!$uname) { $uname=$env{'user.name'}; }
 7070:     my $uhome=&homeserver($uname,$udomain);
 7071:     my %newstorehash;
 7072:     foreach my $item (keys(%$storehash)) {
 7073: 	my $key = $version.':'.&escape($symb).':'.$item;
 7074: 	$newstorehash{$key} = $storehash->{$item};
 7075:     }
 7076:     my $items='';
 7077:     my %allitems = ();
 7078:     foreach my $item (keys(%newstorehash)) {
 7079: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 7080: 	    my $key = $1.':keys:'.$2;
 7081: 	    $allitems{$key} .= $3.':';
 7082: 	}
 7083: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 7084:     }
 7085:     foreach my $item (keys(%allitems)) {
 7086: 	$allitems{$item} =~ s/\:$//;
 7087: 	$items.= $item.'='.$allitems{$item}.'&';
 7088:     }
 7089:     $items=~s/\&$//;
 7090:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 7091: }
 7092: 
 7093: # ------------------------------------------------------ critical put interface
 7094: 
 7095: sub cput {
 7096:    my ($namespace,$storehash,$udomain,$uname)=@_;
 7097:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7098:    if (!$uname) { $uname=$env{'user.name'}; }
 7099:    my $uhome=&homeserver($uname,$udomain);
 7100:    my $items='';
 7101:    foreach my $item (keys(%$storehash)) {
 7102:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 7103:    }
 7104:    $items=~s/\&$//;
 7105:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 7106: }
 7107: 
 7108: # -------------------------------------------------------------- eget interface
 7109: 
 7110: sub eget {
 7111:    my ($namespace,$storearr,$udomain,$uname)=@_;
 7112:    my $items='';
 7113:    foreach my $item (@$storearr) {
 7114:        $items.=&escape($item).'&';
 7115:    }
 7116:    $items=~s/\&$//;
 7117:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7118:    if (!$uname) { $uname=$env{'user.name'}; }
 7119:    my $uhome=&homeserver($uname,$udomain);
 7120:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 7121:    my @pairs=split(/\&/,$rep);
 7122:    my %returnhash=();
 7123:    my $i=0;
 7124:    foreach my $item (@$storearr) {
 7125:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 7126:       $i++;
 7127:    }
 7128:    return %returnhash;
 7129: }
 7130: 
 7131: # ------------------------------------------------------------ tmpput interface
 7132: sub tmpput {
 7133:     my ($storehash,$server,$context)=@_;
 7134:     my $items='';
 7135:     foreach my $item (keys(%$storehash)) {
 7136: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 7137:     }
 7138:     $items=~s/\&$//;
 7139:     if (defined($context)) {
 7140:         $items .= ':'.&escape($context);
 7141:     }
 7142:     return &reply("tmpput:$items",$server);
 7143: }
 7144: 
 7145: # ------------------------------------------------------------ tmpget interface
 7146: sub tmpget {
 7147:     my ($token,$server)=@_;
 7148:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 7149:     my $rep=&reply("tmpget:$token",$server);
 7150:     my %returnhash;
 7151:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
 7152:         return %returnhash;
 7153:     }
 7154:     foreach my $item (split(/\&/,$rep)) {
 7155: 	my ($key,$value)=split(/=/,$item);
 7156: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 7157:     }
 7158:     return %returnhash;
 7159: }
 7160: 
 7161: # ------------------------------------------------------------ tmpdel interface
 7162: sub tmpdel {
 7163:     my ($token,$server)=@_;
 7164:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 7165:     return &reply("tmpdel:$token",$server);
 7166: }
 7167: 
 7168: # ------------------------------------------------------------ get_timebased_id
 7169: 
 7170: sub get_timebased_id {
 7171:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
 7172:         $maxtries) = @_;
 7173:     my ($newid,$error,$dellock);
 7174:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
 7175:         return ('','ok','invalid call to get suffix');
 7176:     }
 7177: 
 7178: # set defaults for any optional args for which values were not supplied
 7179:     if ($who eq '') {
 7180:         $who = $env{'user.name'}.':'.$env{'user.domain'};
 7181:     }
 7182:     if (!$locktries) {
 7183:         $locktries = 3;
 7184:     }
 7185:     if (!$maxtries) {
 7186:         $maxtries = 10;
 7187:     }
 7188: 
 7189:     if (($cdom eq '') || ($cnum eq '')) {
 7190:         if ($env{'request.course.id'}) {
 7191:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7192:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7193:         }
 7194:         if (($cdom eq '') || ($cnum eq '')) {
 7195:             return ('','ok','call to get suffix not in course context');
 7196:         }
 7197:     }
 7198: 
 7199: # construct locking item
 7200:     my $lockhash = {
 7201:                       $prefix."\0".'locked_'.$keyid => $who,
 7202:                    };
 7203:     my $tries = 0;
 7204: 
 7205: # attempt to get lock on nohist_$namespace file
 7206:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 7207:     while (($gotlock ne 'ok') && $tries <$locktries) {
 7208:         $tries ++;
 7209:         sleep 1;
 7210:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 7211:     }
 7212: 
 7213: # attempt to get unique identifier, based on current timestamp
 7214:     if ($gotlock eq 'ok') {
 7215:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
 7216:         my $id = time;
 7217:         $newid = $id;
 7218:         if ($idtype eq 'addcode') {
 7219:             $newid .= &sixnum_code();
 7220:         }
 7221:         my $idtries = 0;
 7222:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
 7223:             if ($idtype eq 'concat') {
 7224:                 $newid = $id.$idtries;
 7225:             } elsif ($idtype eq 'addcode') {
 7226:                 $newid = $newid.&sixnum_code();
 7227:             } else {
 7228:                 $newid ++;
 7229:             }
 7230:             $idtries ++;
 7231:         }
 7232:         if (!exists($inuse{$prefix."\0".$newid})) {
 7233:             my %new_item =  (
 7234:                               $prefix."\0".$newid => $who,
 7235:                             );
 7236:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
 7237:                                                  $cdom,$cnum);
 7238:             if ($putresult ne 'ok') {
 7239:                 undef($newid);
 7240:                 $error = 'error saving new item: '.$putresult;
 7241:             }
 7242:         } else {
 7243:              undef($newid);
 7244:              $error = ('error: no unique suffix available for the new item ');
 7245:         }
 7246: #  remove lock
 7247:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
 7248:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
 7249:     } else {
 7250:         $error = "error: could not obtain lockfile\n";
 7251:         $dellock = 'ok';
 7252:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
 7253:             $dellock = 'nolock';
 7254:         }
 7255:     }
 7256:     return ($newid,$dellock,$error);
 7257: }
 7258: 
 7259: sub sixnum_code {
 7260:     my $code;
 7261:     for (0..6) {
 7262:         $code .= int( rand(9) );
 7263:     }
 7264:     return $code;
 7265: }
 7266: 
 7267: # -------------------------------------------------- portfolio access checking
 7268: 
 7269: sub portfolio_access {
 7270:     my ($requrl,$clientip) = @_;
 7271:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 7272:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
 7273:     if ($result) {
 7274:         my %setters;
 7275:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 7276:             my ($startblock,$endblock) =
 7277:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 7278:             if ($startblock && $endblock) {
 7279:                 return 'B';
 7280:             }
 7281:         } else {
 7282:             my ($startblock,$endblock) =
 7283:                 &Apache::loncommon::blockcheck(\%setters,'port');
 7284:             if ($startblock && $endblock) {
 7285:                 return 'B';
 7286:             }
 7287:         }
 7288:     }
 7289:     if ($result eq 'ok') {
 7290:        return 'F';
 7291:     } elsif ($result =~ /^[^:]+:guest_/) {
 7292:        return 'A';
 7293:     }
 7294:     return '';
 7295: }
 7296: 
 7297: sub get_portfolio_access {
 7298:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
 7299: 
 7300:     if (!ref($access_hash)) {
 7301: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 7302: 	my %access_controls = &get_access_controls($current_perms,$group,
 7303: 						   $file_name);
 7304: 	$access_hash = $access_controls{$file_name};
 7305:     }
 7306: 
 7307:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
 7308:     my $now = time;
 7309:     if (ref($access_hash) eq 'HASH') {
 7310:         foreach my $key (keys(%{$access_hash})) {
 7311:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 7312:             if ($start > $now) {
 7313:                 next;
 7314:             }
 7315:             if ($end && $end<$now) {
 7316:                 next;
 7317:             }
 7318:             if ($scope eq 'public') {
 7319:                 $public = $key;
 7320:                 last;
 7321:             } elsif ($scope eq 'guest') {
 7322:                 $guest = $key;
 7323:             } elsif ($scope eq 'domains') {
 7324:                 push(@domains,$key);
 7325:             } elsif ($scope eq 'users') {
 7326:                 push(@users,$key);
 7327:             } elsif ($scope eq 'course') {
 7328:                 push(@courses,$key);
 7329:             } elsif ($scope eq 'group') {
 7330:                 push(@groups,$key);
 7331:             } elsif ($scope eq 'ip') {
 7332:                 push(@ips,$key);
 7333:             }
 7334:         }
 7335:         if ($public) {
 7336:             return 'ok';
 7337:         } elsif (@ips > 0) {
 7338:             my $allowed;
 7339:             foreach my $ipkey (@ips) {
 7340:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
 7341:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
 7342:                         $allowed = 1;
 7343:                         last;
 7344:                     }
 7345:                 }
 7346:             }
 7347:             if ($allowed) {
 7348:                 return 'ok';
 7349:             }
 7350:         }
 7351:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 7352:             if ($guest) {
 7353:                 return $guest;
 7354:             }
 7355:         } else {
 7356:             if (@domains > 0) {
 7357:                 foreach my $domkey (@domains) {
 7358:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 7359:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 7360:                             return 'ok';
 7361:                         }
 7362:                     }
 7363:                 }
 7364:             }
 7365:             if (@users > 0) {
 7366:                 foreach my $userkey (@users) {
 7367:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 7368:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 7369:                             if (ref($item) eq 'HASH') {
 7370:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 7371:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 7372:                                     return 'ok';
 7373:                                 }
 7374:                             }
 7375:                         }
 7376:                     } 
 7377:                 }
 7378:             }
 7379:             my %roleshash;
 7380:             my @courses_and_groups = @courses;
 7381:             push(@courses_and_groups,@groups); 
 7382:             if (@courses_and_groups > 0) {
 7383:                 my (%allgroups,%allroles); 
 7384:                 my ($start,$end,$role,$sec,$group);
 7385:                 foreach my $envkey (%env) {
 7386:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 7387:                         my $cid = $2.'_'.$3; 
 7388:                         if ($1 eq 'gr') {
 7389:                             $group = $4;
 7390:                             $allgroups{$cid}{$group} = $env{$envkey};
 7391:                         } else {
 7392:                             if ($4 eq '') {
 7393:                                 $sec = 'none';
 7394:                             } else {
 7395:                                 $sec = $4;
 7396:                             }
 7397:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 7398:                         }
 7399:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 7400:                         my $cid = $2.'_'.$3;
 7401:                         if ($4 eq '') {
 7402:                             $sec = 'none';
 7403:                         } else {
 7404:                             $sec = $4;
 7405:                         }
 7406:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 7407:                     }
 7408:                 }
 7409:                 if (keys(%allroles) == 0) {
 7410:                     return;
 7411:                 }
 7412:                 foreach my $key (@courses_and_groups) {
 7413:                     my %content = %{$$access_hash{$key}};
 7414:                     my $cnum = $content{'number'};
 7415:                     my $cdom = $content{'domain'};
 7416:                     my $cid = $cdom.'_'.$cnum;
 7417:                     if (!exists($allroles{$cid})) {
 7418:                         next;
 7419:                     }    
 7420:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 7421:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 7422:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 7423:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 7424:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 7425:                         foreach my $role (keys(%{$allroles{$cid}})) {
 7426:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 7427:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 7428:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 7429:                                         if (grep/^all$/,@sections) {
 7430:                                             return 'ok';
 7431:                                         } else {
 7432:                                             if (grep/^$sec$/,@sections) {
 7433:                                                 return 'ok';
 7434:                                             }
 7435:                                         }
 7436:                                     }
 7437:                                 }
 7438:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 7439:                                     if (grep/^none$/,@groups) {
 7440:                                         return 'ok';
 7441:                                     }
 7442:                                 } else {
 7443:                                     if (grep/^all$/,@groups) {
 7444:                                         return 'ok';
 7445:                                     } 
 7446:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 7447:                                         if (grep/^$group$/,@groups) {
 7448:                                             return 'ok';
 7449:                                         }
 7450:                                     }
 7451:                                 } 
 7452:                             }
 7453:                         }
 7454:                     }
 7455:                 }
 7456:             }
 7457:             if ($guest) {
 7458:                 return $guest;
 7459:             }
 7460:         }
 7461:     }
 7462:     return;
 7463: }
 7464: 
 7465: sub course_group_datechecker {
 7466:     my ($dates,$now,$status) = @_;
 7467:     my ($start,$end) = split(/\./,$dates);
 7468:     if (!$start && !$end) {
 7469:         return 'ok';
 7470:     }
 7471:     if (grep/^active$/,@{$status}) {
 7472:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 7473:             return 'ok';
 7474:         }
 7475:     }
 7476:     if (grep/^previous$/,@{$status}) {
 7477:         if ($end > $now ) {
 7478:             return 'ok';
 7479:         }
 7480:     }
 7481:     if (grep/^future$/,@{$status}) {
 7482:         if ($start > $now) {
 7483:             return 'ok';
 7484:         }
 7485:     }
 7486:     return; 
 7487: }
 7488: 
 7489: sub parse_portfolio_url {
 7490:     my ($url) = @_;
 7491: 
 7492:     my ($type,$udom,$unum,$group,$file_name);
 7493:     
 7494:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 7495: 	$type = 1;
 7496:         $udom = $1;
 7497:         $unum = $2;
 7498:         $file_name = $3;
 7499:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 7500: 	$type = 2;
 7501:         $udom = $1;
 7502:         $unum = $2;
 7503:         $group = $3;
 7504:         $file_name = $3.'/'.$4;
 7505:     }
 7506:     if (wantarray) {
 7507: 	return ($type,$udom,$unum,$file_name,$group);
 7508:     }
 7509:     return $type;
 7510: }
 7511: 
 7512: sub is_portfolio_url {
 7513:     my ($url) = @_;
 7514:     return scalar(&parse_portfolio_url($url));
 7515: }
 7516: 
 7517: sub is_portfolio_file {
 7518:     my ($file) = @_;
 7519:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 7520:         return 1;
 7521:     }
 7522:     return;
 7523: }
 7524: 
 7525: sub usertools_access {
 7526:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
 7527:     my ($access,%tools);
 7528:     if ($context eq '') {
 7529:         $context = 'tools';
 7530:     }
 7531:     if ($context eq 'requestcourses') {
 7532:         %tools = (
 7533:                       official   => 1,
 7534:                       unofficial => 1,
 7535:                       community  => 1,
 7536:                       textbook   => 1,
 7537:                  );
 7538:     } elsif ($context eq 'requestauthor') {
 7539:         %tools = (
 7540:                       requestauthor => 1,
 7541:                  );
 7542:     } else {
 7543:         %tools = (
 7544:                       aboutme   => 1,
 7545:                       blog      => 1,
 7546:                       webdav    => 1,
 7547:                       portfolio => 1,
 7548:                  );
 7549:     }
 7550:     return if (!defined($tools{$tool}));
 7551: 
 7552:     if (($udom eq '') || ($uname eq '')) {
 7553:         $udom = $env{'user.domain'};
 7554:         $uname = $env{'user.name'};
 7555:     }
 7556: 
 7557:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 7558:         if ($action ne 'reload') {
 7559:             if ($context eq 'requestcourses') {
 7560:                 return $env{'environment.canrequest.'.$tool};
 7561:             } elsif ($context eq 'requestauthor') {
 7562:                 return $env{'environment.canrequest.author'};
 7563:             } else {
 7564:                 return $env{'environment.availabletools.'.$tool};
 7565:             }
 7566:         }
 7567:     }
 7568: 
 7569:     my ($toolstatus,$inststatus,$envkey);
 7570:     if ($context eq 'requestauthor') {
 7571:         $envkey = $context;
 7572:     } else {
 7573:         $envkey = $context.'.'.$tool;
 7574:     }
 7575: 
 7576:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 7577:          ($action ne 'reload')) {
 7578:         $toolstatus = $env{'environment.'.$envkey};
 7579:         $inststatus = $env{'environment.inststatus'};
 7580:     } else {
 7581:         if (ref($userenvref) eq 'HASH') {
 7582:             $toolstatus = $userenvref->{$envkey};
 7583:             $inststatus = $userenvref->{'inststatus'};
 7584:         } else {
 7585:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
 7586:             $toolstatus = $userenv{$envkey};
 7587:             $inststatus = $userenv{'inststatus'};
 7588:         }
 7589:     }
 7590: 
 7591:     if ($toolstatus ne '') {
 7592:         if ($toolstatus) {
 7593:             $access = 1;
 7594:         } else {
 7595:             $access = 0;
 7596:         }
 7597:         return $access;
 7598:     }
 7599: 
 7600:     my ($is_adv,%domdef);
 7601:     if (ref($is_advref) eq 'HASH') {
 7602:         $is_adv = $is_advref->{'is_adv'};
 7603:     } else {
 7604:         $is_adv = &is_advanced_user($udom,$uname);
 7605:     }
 7606:     if (ref($domdefref) eq 'HASH') {
 7607:         %domdef = %{$domdefref};
 7608:     } else {
 7609:         %domdef = &get_domain_defaults($udom);
 7610:     }
 7611:     if (ref($domdef{$tool}) eq 'HASH') {
 7612:         if ($is_adv) {
 7613:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 7614:                 if ($domdef{$tool}{'_LC_adv'}) { 
 7615:                     $access = 1;
 7616:                 } else {
 7617:                     $access = 0;
 7618:                 }
 7619:                 return $access;
 7620:             }
 7621:         }
 7622:         if ($inststatus ne '') {
 7623:             my ($hasaccess,$hasnoaccess);
 7624:             foreach my $affiliation (split(/:/,$inststatus)) {
 7625:                 if ($domdef{$tool}{$affiliation} ne '') { 
 7626:                     if ($domdef{$tool}{$affiliation}) {
 7627:                         $hasaccess = 1;
 7628:                     } else {
 7629:                         $hasnoaccess = 1;
 7630:                     }
 7631:                 }
 7632:             }
 7633:             if ($hasaccess || $hasnoaccess) {
 7634:                 if ($hasaccess) {
 7635:                     $access = 1;
 7636:                 } elsif ($hasnoaccess) {
 7637:                     $access = 0; 
 7638:                 }
 7639:                 return $access;
 7640:             }
 7641:         } else {
 7642:             if ($domdef{$tool}{'default'} ne '') {
 7643:                 if ($domdef{$tool}{'default'}) {
 7644:                     $access = 1;
 7645:                 } elsif ($domdef{$tool}{'default'} == 0) {
 7646:                     $access = 0;
 7647:                 }
 7648:                 return $access;
 7649:             }
 7650:         }
 7651:     } else {
 7652:         if (($context eq 'tools') && ($tool ne 'webdav')) {
 7653:             $access = 1;
 7654:         } else {
 7655:             $access = 0;
 7656:         }
 7657:         return $access;
 7658:     }
 7659: }
 7660: 
 7661: sub is_course_owner {
 7662:     my ($cdom,$cnum,$udom,$uname) = @_;
 7663:     if (($udom eq '') || ($uname eq '')) {
 7664:         $udom = $env{'user.domain'};
 7665:         $uname = $env{'user.name'};
 7666:     }
 7667:     unless (($udom eq '') || ($uname eq '')) {
 7668:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
 7669:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
 7670:                 return 1;
 7671:             } else {
 7672:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
 7673:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
 7674:                     return 1;
 7675:                 }
 7676:             }
 7677:         }
 7678:     }
 7679:     return;
 7680: }
 7681: 
 7682: sub is_advanced_user {
 7683:     my ($udom,$uname) = @_;
 7684:     if ($udom ne '' && $uname ne '') {
 7685:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 7686:             if (wantarray) {
 7687:                 return ($env{'user.adv'},$env{'user.author'});
 7688:             } else {
 7689:                 return $env{'user.adv'};
 7690:             }
 7691:         }
 7692:     }
 7693:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 7694:     my %allroles;
 7695:     my ($is_adv,$is_author);
 7696:     foreach my $role (keys(%roleshash)) {
 7697:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 7698:         my $area = '/'.$tdomain.'/'.$trest;
 7699:         if ($sec ne '') {
 7700:             $area .= '/'.$sec;
 7701:         }
 7702:         if (($area ne '') && ($trole ne '')) {
 7703:             my $spec=$trole.'.'.$area;
 7704:             if ($trole =~ /^cr\//) {
 7705:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 7706:             } elsif ($trole ne 'gr') {
 7707:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 7708:             }
 7709:             if ($trole eq 'au') {
 7710:                 $is_author = 1;
 7711:             }
 7712:         }
 7713:     }
 7714:     foreach my $role (keys(%allroles)) {
 7715:         last if ($is_adv);
 7716:         foreach my $item (split(/:/,$allroles{$role})) {
 7717:             if ($item ne '') {
 7718:                 my ($privilege,$restrictions)=split(/&/,$item);
 7719:                 if ($privilege eq 'adv') {
 7720:                     $is_adv = 1;
 7721:                     last;
 7722:                 }
 7723:             }
 7724:         }
 7725:     }
 7726:     if (wantarray) {
 7727:         return ($is_adv,$is_author);
 7728:     }
 7729:     return $is_adv;
 7730: }
 7731: 
 7732: sub check_can_request {
 7733:     my ($dom,$can_request,$request_domains) = @_;
 7734:     my $canreq = 0;
 7735:     my ($types,$typename) = &Apache::loncommon::course_types();
 7736:     my @options = ('approval','validate','autolimit');
 7737:     my $optregex = join('|',@options);
 7738:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
 7739:         foreach my $type (@{$types}) {
 7740:             if (&usertools_access($env{'user.name'},
 7741:                                   $env{'user.domain'},
 7742:                                   $type,undef,'requestcourses')) {
 7743:                 $canreq ++;
 7744:                 if (ref($request_domains) eq 'HASH') {
 7745:                     push(@{$request_domains->{$type}},$env{'user.domain'});
 7746:                 }
 7747:                 if ($dom eq $env{'user.domain'}) {
 7748:                     $can_request->{$type} = 1;
 7749:                 }
 7750:             }
 7751:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
 7752:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
 7753:                 if (@curr > 0) {
 7754:                     foreach my $item (@curr) {
 7755:                         if (ref($request_domains) eq 'HASH') {
 7756:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
 7757:                             if ($otherdom ne '') {
 7758:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
 7759:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
 7760:                                         push(@{$request_domains->{$type}},$otherdom);
 7761:                                     }
 7762:                                 } else {
 7763:                                     push(@{$request_domains->{$type}},$otherdom);
 7764:                                 }
 7765:                             }
 7766:                         }
 7767:                     }
 7768:                     unless($dom eq $env{'user.domain'}) {
 7769:                         $canreq ++;
 7770:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
 7771:                             $can_request->{$type} = 1;
 7772:                         }
 7773:                     }
 7774:                 }
 7775:             }
 7776:         }
 7777:     }
 7778:     return $canreq;
 7779: }
 7780: 
 7781: # ---------------------------------------------- Custom access rule evaluation
 7782: 
 7783: sub customaccess {
 7784:     my ($priv,$uri)=@_;
 7785:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 7786:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 7787:     $udom = &LONCAPA::clean_domain($udom);
 7788:     $ucrs = &LONCAPA::clean_username($ucrs);
 7789:     my $access=0;
 7790:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 7791: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 7792: 	if ($type eq 'user') {
 7793: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 7794: 		my ($tdom,$tuname)=split(m{/},$scope);
 7795: 		if ($tdom) {
 7796: 		    if ($tdom ne $env{'user.domain'}) { next; }
 7797: 		}
 7798: 		if ($tuname) {
 7799: 		    if ($tuname ne $env{'user.name'}) { next; }
 7800: 		}
 7801: 		$access=($effect eq 'allow');
 7802: 		last;
 7803: 	    }
 7804: 	} else {
 7805: 	    if ($role) {
 7806: 		if ($role ne $urole) { next; }
 7807: 	    }
 7808: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 7809: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 7810: 		if ($tdom) {
 7811: 		    if ($tdom ne $udom) { next; }
 7812: 		}
 7813: 		if ($tcrs) {
 7814: 		    if ($tcrs ne $ucrs) { next; }
 7815: 		}
 7816: 		if ($tsec) {
 7817: 		    if ($tsec ne $usec) { next; }
 7818: 		}
 7819: 		$access=($effect eq 'allow');
 7820: 		last;
 7821: 	    }
 7822: 	    if ($realm eq '' && $role eq '') {
 7823: 		$access=($effect eq 'allow');
 7824: 	    }
 7825: 	}
 7826:     }
 7827:     return $access;
 7828: }
 7829: 
 7830: # ------------------------------------------------- Check for a user privilege
 7831: 
 7832: sub allowed {
 7833:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck,$ignorecache)=@_;
 7834:     my $ver_orguri=$uri;
 7835:     $uri=&deversion($uri);
 7836:     my $orguri=$uri;
 7837:     $uri=&declutter($uri);
 7838: 
 7839:     if ($priv eq 'evb') {
 7840: # Evade communication block restrictions for specified role in a course
 7841:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 7842:             return $1;
 7843:         } else {
 7844:             return;
 7845:         }
 7846:     }
 7847: 
 7848:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 7849: # Free bre access to adm and meta resources
 7850:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|viewclasslist|aboutme)$})) 
 7851: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 7852: 	&& ($priv eq 'bre')) {
 7853: 	return 'F';
 7854:     }
 7855: 
 7856: # Free bre access to user's own portfolio contents
 7857:     my ($space,$domain,$name,@dir)=split('/',$uri);
 7858:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 7859: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 7860:         my %setters;
 7861:         my ($startblock,$endblock) = 
 7862:             &Apache::loncommon::blockcheck(\%setters,'port');
 7863:         if ($startblock && $endblock) {
 7864:             return 'B';
 7865:         } else {
 7866:             return 'F';
 7867:         }
 7868:     }
 7869: 
 7870: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 7871:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 7872:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 7873:         if (exists($env{'request.course.id'})) {
 7874:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7875:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7876:             if (($domain eq $cdom) && ($name eq $cnum)) {
 7877:                 my $courseprivid=$env{'request.course.id'};
 7878:                 $courseprivid=~s/\_/\//;
 7879:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 7880:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 7881:                     return $1; 
 7882:                 } else {
 7883:                     if ($env{'request.course.sec'}) {
 7884:                         $courseprivid.='/'.$env{'request.course.sec'};
 7885:                     }
 7886:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 7887:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 7888:                         return $2;
 7889:                     }
 7890:                 }
 7891:             }
 7892:         }
 7893:     }
 7894: 
 7895: # Free bre to public access
 7896: 
 7897:     if ($priv eq 'bre') {
 7898:         my $copyright=&metadata($uri,'copyright');
 7899: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 7900:            return 'F'; 
 7901:         }
 7902:         if ($copyright eq 'priv') {
 7903:             $uri=~/([^\/]+)\/([^\/]+)\//;
 7904: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 7905: 		return '';
 7906:             }
 7907:         }
 7908:         if ($copyright eq 'domain') {
 7909:             $uri=~/([^\/]+)\/([^\/]+)\//;
 7910: 	    unless (($env{'user.domain'} eq $1) ||
 7911:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 7912: 		return '';
 7913:             }
 7914:         }
 7915:         if ($env{'request.role'}=~ /li\.\//) {
 7916:             # Library role, so allow browsing of resources in this domain.
 7917:             return 'F';
 7918:         }
 7919:         if ($copyright eq 'custom') {
 7920: 	    unless (&customaccess($priv,$uri)) { return ''; }
 7921:         }
 7922:     }
 7923:     # Domain coordinator is trying to create a course
 7924:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 7925:         # uri is the requested domain in this case.
 7926:         # comparison to 'request.role.domain' shows if the user has selected
 7927:         # a role of dc for the domain in question.
 7928:         return 'F' if ($uri eq $env{'request.role.domain'});
 7929:     }
 7930: 
 7931:     my $thisallowed='';
 7932:     my $statecond=0;
 7933:     my $courseprivid='';
 7934: 
 7935:     my $ownaccess;
 7936:     # Community Coordinator or Assistant Co-author browsing resource space.
 7937:     if (($priv eq 'bro') && ($env{'user.author'})) {
 7938:         if ($uri eq '') {
 7939:             $ownaccess = 1;
 7940:         } else {
 7941:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
 7942:                 my $udom = $env{'user.domain'};
 7943:                 my $uname = $env{'user.name'};
 7944:                 if ($uri =~ m{^\Q$udom\E/?$}) {
 7945:                     $ownaccess = 1;
 7946:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
 7947:                     unless ($uri =~ m{\.\./}) {
 7948:                         $ownaccess = 1;
 7949:                     }
 7950:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
 7951:                     my $now = time;
 7952:                     if ($uri =~ m{^([^/]+)/?$}) {
 7953:                         my $adom = $1;
 7954:                         foreach my $key (keys(%env)) {
 7955:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
 7956:                                 my ($start,$end) = split('.',$env{$key});
 7957:                                 if (($now >= $start) && (!$end || $end < $now)) {
 7958:                                     $ownaccess = 1;
 7959:                                     last;
 7960:                                 }
 7961:                             }
 7962:                         }
 7963:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
 7964:                         my $adom = $1;
 7965:                         my $aname = $2;
 7966:                         foreach my $role ('ca','aa') { 
 7967:                             if ($env{"user.role.$role./$adom/$aname"}) {
 7968:                                 my ($start,$end) =
 7969:                                     split('.',$env{"user.role.$role./$adom/$aname"});
 7970:                                 if (($now >= $start) && (!$end || $end < $now)) {
 7971:                                     $ownaccess = 1;
 7972:                                     last;
 7973:                                 }
 7974:                             }
 7975:                         }
 7976:                     }
 7977:                 }
 7978:             }
 7979:         }
 7980:     }
 7981: 
 7982: # Course
 7983: 
 7984:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 7985:         unless (($priv eq 'bro') && (!$ownaccess)) {
 7986:             $thisallowed.=$1;
 7987:         }
 7988:     }
 7989: 
 7990: # Domain
 7991: 
 7992:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 7993:        =~/\Q$priv\E\&([^\:]*)/) {
 7994:         unless (($priv eq 'bro') && (!$ownaccess)) {
 7995:             $thisallowed.=$1;
 7996:         }
 7997:     }
 7998: 
 7999: # User who is not author or co-author might still be able to edit
 8000: # resource of an author in the domain (e.g., if Domain Coordinator).
 8001:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
 8002:         (&allowed('mdc',$env{'request.course.id'}))) {
 8003:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
 8004:             $thisallowed.=$1;
 8005:         }
 8006:     }
 8007: 
 8008: # Course: uri itself is a course
 8009:     my $courseuri=$uri;
 8010:     $courseuri=~s/\_(\d)/\/$1/;
 8011:     $courseuri=~s/^([^\/])/\/$1/;
 8012: 
 8013:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 8014:        =~/\Q$priv\E\&([^\:]*)/) {
 8015:         if ($priv eq 'mip') {
 8016:             my $rem = $1;
 8017:             if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
 8018:                 ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
 8019:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8020:                 if ($cdom ne '') {
 8021:                     my %passwdconf = &get_passwdconf($cdom);
 8022:                     if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
 8023:                         if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
 8024:                             if (@{$passwdconf{'crsownerchg'}{'by'}}) {
 8025:                                 my @inststatuses = split(':',$env{'environment.inststatus'});
 8026:                                 unless (@inststatuses) {
 8027:                                     @inststatuses = ('default');
 8028:                                 }
 8029:                                 foreach my $status (@inststatuses) {
 8030:                                     if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
 8031:                                         $thisallowed.=$rem;
 8032:                                     }
 8033:                                 }
 8034:                             }
 8035:                         }
 8036:                     }
 8037:                 }
 8038:             }
 8039:         } else {
 8040:             unless (($priv eq 'bro') && (!$ownaccess)) {
 8041:                 $thisallowed.=$1;
 8042:             }
 8043:         }
 8044:     }
 8045: 
 8046: # URI is an uploaded document for this course, default permissions don't matter
 8047: # not allowing 'edit' access (editupload) to uploaded course docs
 8048:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 8049: 	$thisallowed='';
 8050:         my ($match)=&is_on_map($uri);
 8051:         if ($match) {
 8052:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 8053:                   =~/\Q$priv\E\&([^\:]*)/) {
 8054:                 my $value = $1;
 8055:                 if ($noblockcheck) {
 8056:                     $thisallowed.=$value;
 8057:                 } else {
 8058:                     my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
 8059:                     if (@blockers > 0) {
 8060:                         $thisallowed = 'B';
 8061:                     } else {
 8062:                         $thisallowed.=$value;
 8063:                     }
 8064:                 }
 8065:             }
 8066:         } else {
 8067:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 8068:             if ($refuri) {
 8069:                 if ($refuri =~ m|^/adm/|) {
 8070:                     $thisallowed='F';
 8071:                 } else {
 8072:                     $refuri=&declutter($refuri);
 8073:                     my ($match) = &is_on_map($refuri);
 8074:                     if ($match) {
 8075:                         if ($noblockcheck) {
 8076:                             $thisallowed='F';
 8077:                         } else {
 8078:                             my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
 8079:                             if (@blockers > 0) {
 8080:                                 $thisallowed = 'B';
 8081:                             } else {
 8082:                                 $thisallowed='F';
 8083:                             }
 8084:                         }
 8085:                     }
 8086:                 }
 8087:             }
 8088:         }
 8089:     }
 8090: 
 8091:     if ($priv eq 'bre'
 8092: 	&& $thisallowed ne 'F' 
 8093: 	&& $thisallowed ne '2'
 8094: 	&& &is_portfolio_url($uri)) {
 8095: 	$thisallowed = &portfolio_access($uri,$clientip);
 8096:     }
 8097:     
 8098: # Full access at system, domain or course-wide level? Exit.
 8099:     if ($thisallowed=~/F/) {
 8100: 	return 'F';
 8101:     }
 8102: 
 8103: # If this is generating or modifying users, exit with special codes
 8104: 
 8105:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 8106: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 8107: 	    my ($audom,$auname)=split('/',$uri);
 8108: # no author name given, so this just checks on the general right to make a co-author in this domain
 8109: 	    unless ($auname) { return $thisallowed; }
 8110: # an author name is given, so we are about to actually make a co-author for a certain account
 8111: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 8112: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 8113: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 8114: 	}
 8115: 	return $thisallowed;
 8116:     }
 8117: #
 8118: # Gathered so far: system, domain and course wide privileges
 8119: #
 8120: # Course: See if uri or referer is an individual resource that is part of 
 8121: # the course
 8122: 
 8123:     if ($env{'request.course.id'}) {
 8124: 
 8125: # If this is modifying password (internal auth) domains must match for user and user's role.
 8126: 
 8127:         if ($priv eq 'mip') {
 8128:             if ($env{'user.domain'} eq $env{'request.role.domain'}) {
 8129:                 return $thisallowed;
 8130:             } else {
 8131:                 return '';
 8132:             }
 8133:         }
 8134: 
 8135:        $courseprivid=$env{'request.course.id'};
 8136:        if ($env{'request.course.sec'}) {
 8137:           $courseprivid.='/'.$env{'request.course.sec'};
 8138:        }
 8139:        $courseprivid=~s/\_/\//;
 8140:        my $checkreferer=1;
 8141:        my ($match,$cond)=&is_on_map($uri);
 8142:        if ($match) {
 8143:            $statecond=$cond;
 8144:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 8145:                =~/\Q$priv\E\&([^\:]*)/) {
 8146:                my $value = $1;
 8147:                if ($priv eq 'bre') {
 8148:                    if ($noblockcheck) {
 8149:                        $thisallowed.=$value;
 8150:                    } else {
 8151:                        my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
 8152:                        if (@blockers > 0) {
 8153:                            $thisallowed = 'B';
 8154:                        } else {
 8155:                            $thisallowed.=$value;
 8156:                        }
 8157:                    }
 8158:                } else {
 8159:                    $thisallowed.=$value;
 8160:                }
 8161:                $checkreferer=0;
 8162:            }
 8163:        }
 8164: 
 8165:        if ($checkreferer) {
 8166: 	  my $refuri=$env{'httpref.'.$orguri};
 8167:             unless ($refuri) {
 8168:                 foreach my $key (keys(%env)) {
 8169: 		    if ($key=~/^httpref\..*\*/) {
 8170: 			my $pattern=$key;
 8171:                         $pattern=~s/^httpref\.\/res\///;
 8172:                         $pattern=~s/\*/\[\^\/\]\+/g;
 8173:                         $pattern=~s/\//\\\//g;
 8174:                         if ($orguri=~/$pattern/) {
 8175: 			    $refuri=$env{$key};
 8176:                         }
 8177:                     }
 8178:                 }
 8179:             }
 8180: 
 8181:          if ($refuri) { 
 8182: 	  $refuri=&declutter($refuri);
 8183:           my ($match,$cond)=&is_on_map($refuri);
 8184:             if ($match) {
 8185:               my $refstatecond=$cond;
 8186:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 8187:                   =~/\Q$priv\E\&([^\:]*)/) {
 8188:                   my $value = $1;
 8189:                   if ($priv eq 'bre') {
 8190:                       if ($noblockcheck) {
 8191:                           $thisallowed.=$value;
 8192:                       } else {
 8193:                           my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
 8194:                           if (@blockers > 0) {
 8195:                               $thisallowed = 'B';
 8196:                           } else {
 8197:                               $thisallowed.=$value;
 8198:                           }
 8199:                       }
 8200:                   } else {
 8201:                       $thisallowed.=$value;
 8202:                   }
 8203:                   $uri=$refuri;
 8204:                   $statecond=$refstatecond;
 8205:               }
 8206:           }
 8207:         }
 8208:        }
 8209:    }
 8210: 
 8211: #
 8212: # Gathered now: all privileges that could apply, and condition number
 8213: # 
 8214: #
 8215: # Full or no access?
 8216: #
 8217: 
 8218:     if ($thisallowed=~/F/) {
 8219: 	return 'F';
 8220:     }
 8221: 
 8222:     unless ($thisallowed) {
 8223:         return '';
 8224:     }
 8225: 
 8226: # Restrictions exist, deal with them
 8227: #
 8228: #   C:according to course preferences
 8229: #   R:according to resource settings
 8230: #   L:unless locked
 8231: #   X:according to user session state
 8232: #
 8233: 
 8234: # Possibly locked functionality, check all courses
 8235: # Locks might take effect only after 10 minutes cache expiration for other
 8236: # courses, and 2 minutes for current course
 8237: 
 8238:     my $envkey;
 8239:     if ($thisallowed=~/L/) {
 8240:         foreach $envkey (keys(%env)) {
 8241:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 8242:                my $courseid=$2;
 8243:                my $roleid=$1.'.'.$2;
 8244:                $courseid=~s/^\///;
 8245:                my $expiretime=600;
 8246:                if ($env{'request.role'} eq $roleid) {
 8247: 		  $expiretime=120;
 8248:                }
 8249: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 8250:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 8251:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 8252: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 8253:                }
 8254:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 8255:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 8256: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 8257:                        &log($env{'user.domain'},$env{'user.name'},
 8258:                             $env{'user.home'},
 8259:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 8260:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 8261:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 8262: 		       return '';
 8263:                    }
 8264:                }
 8265:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 8266:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 8267: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 8268:                        &log($env{'user.domain'},$env{'user.name'},
 8269:                             $env{'user.home'},
 8270:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 8271:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 8272:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 8273: 		       return '';
 8274:                    }
 8275:                }
 8276: 	   }
 8277:        }
 8278:     }
 8279: 
 8280: #
 8281: # Rest of the restrictions depend on selected course
 8282: #
 8283: 
 8284:     unless ($env{'request.course.id'}) {
 8285: 	if ($thisallowed eq 'A') {
 8286: 	    return 'A';
 8287:         } elsif ($thisallowed eq 'B') {
 8288:             return 'B';
 8289: 	} else {
 8290: 	    return '1';
 8291: 	}
 8292:     }
 8293: 
 8294: #
 8295: # Now user is definitely in a course
 8296: #
 8297: 
 8298: 
 8299: # Course preferences
 8300: 
 8301:    if ($thisallowed=~/C/) {
 8302:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 8303:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 8304:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 8305: 	   =~/\Q$rolecode\E/) {
 8306: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 8307: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 8308: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 8309: 			$env{'request.course.id'});
 8310: 	   }
 8311:            return '';
 8312:        }
 8313: 
 8314:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 8315: 	   =~/\Q$unamedom\E/) {
 8316: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 8317: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 8318: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 8319: 			$env{'request.course.id'});
 8320: 	   }
 8321:            return '';
 8322:        }
 8323:    }
 8324: 
 8325: # Resource preferences
 8326: 
 8327:    if ($thisallowed=~/R/) {
 8328:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 8329:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 8330: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 8331: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 8332: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 8333: 	   }
 8334: 	   return '';
 8335:        }
 8336:    }
 8337: 
 8338: # Restricted by state or randomout?
 8339: 
 8340:    if ($thisallowed=~/X/) {
 8341:       if ($env{'acc.randomout'}) {
 8342: 	 if (!$symb) { $symb=&symbread($uri,1); }
 8343:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 8344:             return ''; 
 8345:          }
 8346:       }
 8347:       if (&condval($statecond)) {
 8348: 	 return '2';
 8349:       } else {
 8350:          return '';
 8351:       }
 8352:    }
 8353: 
 8354:     if ($thisallowed eq 'A') {
 8355: 	return 'A';
 8356:     } elsif ($thisallowed eq 'B') {
 8357:         return 'B';
 8358:     }
 8359:    return 'F';
 8360: }
 8361: 
 8362: # ------------------------------------------- Check construction space access
 8363: 
 8364: sub constructaccess {
 8365:     my ($url,$setpriv)=@_;
 8366: 
 8367: # We do not allow editing of previous versions of files
 8368:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
 8369: 
 8370: # Get username and domain from URL
 8371:     my ($ownername,$ownerdomain,$ownerhome);
 8372: 
 8373:     ($ownerdomain,$ownername) =
 8374:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)(?:/|$)});
 8375: 
 8376: # The URL does not really point to any authorspace, forget it
 8377:     unless (($ownername) && ($ownerdomain)) { return ''; }
 8378: 
 8379: # Now we need to see if the user has access to the authorspace of
 8380: # $ownername at $ownerdomain
 8381: 
 8382:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
 8383: # Real author for this?
 8384:        $ownerhome = $env{'user.home'};
 8385:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
 8386:           return ($ownername,$ownerdomain,$ownerhome);
 8387:        }
 8388:     } else {
 8389: # Co-author for this?
 8390:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
 8391:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
 8392:             $ownerhome = &homeserver($ownername,$ownerdomain);
 8393:             return ($ownername,$ownerdomain,$ownerhome);
 8394:         }
 8395:     }
 8396: 
 8397: # We don't have any access right now. If we are not possibly going to do anything about this,
 8398: # we might as well leave
 8399:    unless ($setpriv) { return ''; }
 8400: 
 8401: # Backdoor access?
 8402:     my $allowed=&allowed('eco',$ownerdomain);
 8403: # Nope
 8404:     unless ($allowed) { return ''; }
 8405: # Looks like we may have access, but could be locked by the owner of the construction space
 8406:     if ($allowed eq 'U') {
 8407:         my %blocked=&get('environment',['domcoord.author'],
 8408:                          $ownerdomain,$ownername);
 8409: # Is blocked by owner
 8410:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
 8411:     }
 8412:     if (($allowed eq 'F') || ($allowed eq 'U')) {
 8413: # Grant temporary access
 8414:         my $then=$env{'user.login.time'};
 8415:         my $update=$env{'user.update.time'};
 8416:         if (!$update) { $update = $then; }
 8417:         my $refresh=$env{'user.refresh.time'};
 8418:         if (!$refresh) { $refresh = $update; }
 8419:         my $now = time;
 8420:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
 8421:                            $now,'ca','constructaccess');
 8422:         $ownerhome = &homeserver($ownername,$ownerdomain);
 8423:         return($ownername,$ownerdomain,$ownerhome);
 8424:     }
 8425: # No business here
 8426:     return '';
 8427: }
 8428: 
 8429: # ----------------------------------------------------------- Content Blocking
 8430: 
 8431: {
 8432: # Caches for faster Course Contents display where content blocking
 8433: # is in operation (i.e., interval param set) for timed quiz.
 8434: #
 8435: # User for whom data are being temporarily cached.
 8436: my $cacheduser='';
 8437: # Course for which data are being temporarily cached.
 8438: my $cachedcid='';
 8439: # Cached blockers for this user (a hash of blocking items).
 8440: my %cachedblockers=();
 8441: # When the data were last cached.
 8442: my $cachedlast='';
 8443: 
 8444: sub load_all_blockers {
 8445:     my ($uname,$udom)=@_;
 8446:     if (($uname ne '') && ($udom ne '')) {
 8447:         if (($cacheduser eq $uname.':'.$udom) &&
 8448:             ($cachedcid eq $env{'request.course.id'}) &&
 8449:             (abs($cachedlast-time)<5)) {
 8450:             return;
 8451:         }
 8452:     }
 8453:     $cachedlast=time;
 8454:     $cacheduser=$uname.':'.$udom;
 8455:     $cachedcid=$env{'request.course.id'};
 8456:     %cachedblockers = &get_commblock_resources();
 8457:     return;
 8458: }
 8459: 
 8460: sub get_comm_blocks {
 8461:     my ($cdom,$cnum) = @_;
 8462:     if ($cdom eq '' || $cnum eq '') {
 8463:         return unless ($env{'request.course.id'});
 8464:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8465:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8466:     }
 8467:     my %commblocks;
 8468:     my $hashid=$cdom.'_'.$cnum;
 8469:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
 8470:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
 8471:         %commblocks = %{$blocksref};
 8472:     } else {
 8473:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
 8474:         my $cachetime = 600;
 8475:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
 8476:     }
 8477:     return %commblocks;
 8478: }
 8479: 
 8480: sub get_commblock_resources {
 8481:     my ($blocks) = @_;
 8482:     my %blockers = ();
 8483:     return %blockers unless ($env{'request.course.id'});
 8484:     my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
 8485:     if ($env{'request.course.sec'}) {
 8486:         $courseurl .= '/'.$env{'request.course.sec'};
 8487:     }
 8488:     return %blockers if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
 8489:     my %commblocks;
 8490:     if (ref($blocks) eq 'HASH') {
 8491:         %commblocks = %{$blocks};
 8492:     } else {
 8493:         %commblocks = &get_comm_blocks();
 8494:     }
 8495:     return %blockers unless (keys(%commblocks) > 0);
 8496:     my $navmap = Apache::lonnavmaps::navmap->new();
 8497:     return %blockers unless (ref($navmap));
 8498:     my $now = time;
 8499:     foreach my $block (keys(%commblocks)) {
 8500:         if ($block =~ /^(\d+)____(\d+)$/) {
 8501:             my ($start,$end) = ($1,$2);
 8502:             if ($start <= $now && $end >= $now) {
 8503:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 8504:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 8505:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 8506:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 8507:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
 8508:                             }
 8509:                         }
 8510:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 8511:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 8512:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 8513:                             }
 8514:                         }
 8515:                     }
 8516:                 }
 8517:             }
 8518:         } elsif ($block =~ /^firstaccess____(.+)$/) {
 8519:             my $item = $1;
 8520:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 8521:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 8522:                     my (@interval,$mapname);
 8523:                     my $type = 'map';
 8524:                     if ($item eq 'course') {
 8525:                         $type = 'course';
 8526:                         @interval=&EXT("resource.0.interval");
 8527:                     } else {
 8528:                         if ($item =~ /___\d+___/) {
 8529:                             $type = 'resource';
 8530:                             @interval=&EXT("resource.0.interval",$item);
 8531:                         } else {
 8532:                             $mapname = &deversion($item);
 8533:                             if (ref($navmap)) {
 8534:                                 my $timelimit = $navmap->get_mapparam(undef,$mapname,'0.interval');
 8535:                                 @interval = ($timelimit,'map');
 8536:                             }
 8537:                         }
 8538:                     }
 8539:                     if ($interval[0] =~ /^(\d+)/) {
 8540:                         my $timelimit = $1;
 8541:                         my $first_access;
 8542:                         if ($type eq 'resource') {
 8543:                             $first_access=&get_first_access($interval[1],$item);
 8544:                         } elsif ($type eq 'map') {
 8545:                             $first_access=&get_first_access($interval[1],undef,$item);
 8546:                         } else {
 8547:                             $first_access=&get_first_access($interval[1]);
 8548:                         }
 8549:                         if ($first_access) {
 8550:                             my $timesup = $first_access+$timelimit;
 8551:                             if ($timesup > $now) {
 8552:                                 my $activeblock;
 8553:                                 if ($type eq 'resource') {
 8554:                                     if (ref($navmap)) {
 8555:                                         my $res = $navmap->getBySymb($item);
 8556:                                         if ($res->answerable()) {
 8557:                                             $activeblock = 1;
 8558:                                         }
 8559:                                     }
 8560:                                 } elsif ($type eq 'map') {
 8561:                                     my $mapsymb = &symbread($mapname,1);
 8562:                                     if (($mapsymb) && (ref($navmap))) {
 8563:                                         my $mapres = $navmap->getBySymb($mapsymb);
 8564:                                         if (ref($mapres)) {
 8565:                                             my $first = $mapres->map_start();
 8566:                                             my $finish = $mapres->map_finish();
 8567:                                             my $it = $navmap->getIterator($first,$finish,undef,0,0);
 8568:                                             if (ref($it)) {
 8569:                                                 my $res;
 8570:                                                 while ($res = $it->next(undef,1)) {
 8571:                                                     next unless (ref($res));
 8572:                                                     my $symb = $res->symb();
 8573:                                                     next if (($symb eq $mapsymb) || ($symb eq ''));
 8574:                                                     @interval=&EXT("resource.0.interval",$symb);
 8575:                                                     if ($interval[1] eq 'map') {
 8576:                                                         if ($res->answerable()) {
 8577:                                                             $activeblock = 1;
 8578:                                                             last;
 8579:                                                         }
 8580:                                                     }
 8581:                                                 }
 8582:                                             }
 8583:                                         }
 8584:                                     }
 8585:                                 }
 8586:                                 if ($activeblock) {
 8587:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 8588:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 8589:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
 8590:                                          }
 8591:                                     }
 8592:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 8593:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 8594:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 8595:                                         }
 8596:                                     }
 8597:                                 }
 8598:                             }
 8599:                         }
 8600:                     }
 8601:                 }
 8602:             }
 8603:         }
 8604:     }
 8605:     return %blockers;
 8606: }
 8607: 
 8608: sub has_comm_blocking {
 8609:     my ($priv,$symb,$uri,$ignoresymbdb,$noenccheck,$blocked,$blocks) = @_;
 8610:     my @blockers;
 8611:     return unless ($env{'request.course.id'});
 8612:     return unless ($priv eq 'bre');
 8613:     return if ($env{'request.state'} eq 'construct');
 8614:     my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
 8615:     if ($env{'request.course.sec'}) {
 8616:         $courseurl .= '/'.$env{'request.course.sec'};
 8617:     }
 8618:     return if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
 8619:     my %blockinfo;
 8620:     if (ref($blocks) eq 'HASH') {
 8621:         %blockinfo = &get_commblock_resources($blocks);
 8622:     } else {
 8623:         &load_all_blockers($env{'user.name'},$env{'user.domain'});
 8624:         %blockinfo = %cachedblockers;
 8625:     }
 8626:     return unless (keys(%blockinfo) > 0);
 8627:     my (%possibles,@symbs);
 8628:     if (!$symb) {
 8629:         $symb = &symbread($uri,1,1,1,\%possibles,$ignoresymbdb,$noenccheck);
 8630:     }
 8631:     if ($symb) {
 8632:         @symbs = ($symb);
 8633:     } elsif (keys(%possibles)) {
 8634:         @symbs = keys(%possibles);
 8635:     }
 8636:     my $noblock;
 8637:     foreach my $symb (@symbs) {
 8638:         last if ($noblock);
 8639:         my ($map,$resid,$resurl)=&decode_symb($symb);
 8640:         foreach my $block (keys(%blockinfo)) {
 8641:             if ($block =~ /^firstaccess____(.+)$/) {
 8642:                 my $item = $1;
 8643:                 unless ($blocked) {
 8644:                     if (($item eq $map) || ($item eq $symb)) {
 8645:                         $noblock = 1;
 8646:                         last;
 8647:                     }
 8648:                 }
 8649:             }
 8650:             if (ref($blockinfo{$block}) eq 'HASH') {
 8651:                 if (ref($blockinfo{$block}{'resources'}) eq 'HASH') {
 8652:                     if ($blockinfo{$block}{'resources'}{$symb}) {
 8653:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 8654:                             push(@blockers,$block);
 8655:                         }
 8656:                     }
 8657:                 }
 8658:                 if (ref($blockinfo{$block}{'maps'}) eq 'HASH') {
 8659:                     if ($blockinfo{$block}{'maps'}{$map}) {
 8660:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 8661:                             push(@blockers,$block);
 8662:                         }
 8663:                     }
 8664:                 }
 8665:             }
 8666:         }
 8667:     }
 8668:     unless ($noblock) {
 8669:         return @blockers;
 8670:     }
 8671:     return;
 8672: }
 8673: }
 8674: 
 8675: # -------------------------------- Deversion and split uri into path an filename
 8676: 
 8677: #
 8678: #   Removes the version from a URI and
 8679: #   splits it in to its filename and path to the filename.
 8680: #   Seems like File::Basename could have done this more clearly.
 8681: #   Parameters:
 8682: #      $uri   - input URI
 8683: #   Returns:
 8684: #     Two element list consisting of 
 8685: #     $pathname  - the URI up to and excluding the trailing /
 8686: #     $filename  - The part of the URI following the last /
 8687: #  NOTE:
 8688: #    Another realization of this is simply:
 8689: #    use File::Basename;
 8690: #    ...
 8691: #    $uri = shift;
 8692: #    $filename = basename($uri);
 8693: #    $path     = dirname($uri);
 8694: #    return ($filename, $path);
 8695: #
 8696: #     The implementation below is probably faster however.
 8697: #
 8698: sub split_uri_for_cond {
 8699:     my $uri=&deversion(&declutter(shift));
 8700:     my @uriparts=split(/\//,$uri);
 8701:     my $filename=pop(@uriparts);
 8702:     my $pathname=join('/',@uriparts);
 8703:     return ($pathname,$filename);
 8704: }
 8705: # --------------------------------------------------- Is a resource on the map?
 8706: 
 8707: sub is_on_map {
 8708:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 8709:     #Trying to find the conditional for the file
 8710:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 8711: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 8712:     if ($match) {
 8713: 	return (1,$1);
 8714:     } else {
 8715: 	return (0,0);
 8716:     }
 8717: }
 8718: 
 8719: # --------------------------------------------------------- Get symb from alias
 8720: 
 8721: sub get_symb_from_alias {
 8722:     my $symb=shift;
 8723:     my ($map,$resid,$url)=&decode_symb($symb);
 8724: # Already is a symb
 8725:     if ($url) { return $symb; }
 8726: # Must be an alias
 8727:     my $aliassymb='';
 8728:     my %bighash;
 8729:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 8730:                             &GDBM_READER(),0640)) {
 8731:         my $rid=$bighash{'mapalias_'.$symb};
 8732: 	if ($rid) {
 8733: 	    my ($mapid,$resid)=split(/\./,$rid);
 8734: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 8735: 				    $resid,$bighash{'src_'.$rid});
 8736: 	}
 8737:         untie %bighash;
 8738:     }
 8739:     return $aliassymb;
 8740: }
 8741: 
 8742: # ----------------------------------------------------------------- Define Role
 8743: 
 8744: sub definerole {
 8745:   if (allowed('mcr','/')) {
 8746:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
 8747:     foreach my $role (split(':',$sysrole)) {
 8748: 	my ($crole,$cqual)=split(/\&/,$role);
 8749:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 8750:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 8751: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 8752:                return "refused:s:$crole&$cqual"; 
 8753:             }
 8754:         }
 8755:     }
 8756:     foreach my $role (split(':',$domrole)) {
 8757: 	my ($crole,$cqual)=split(/\&/,$role);
 8758:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 8759:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 8760: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 8761:                return "refused:d:$crole&$cqual"; 
 8762:             }
 8763:         }
 8764:     }
 8765:     foreach my $role (split(':',$courole)) {
 8766: 	my ($crole,$cqual)=split(/\&/,$role);
 8767:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 8768:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 8769: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 8770:                return "refused:c:$crole&$cqual"; 
 8771:             }
 8772:         }
 8773:     }
 8774:     my $uhome;
 8775:     if (($uname ne '') && ($udom ne '')) {
 8776:         $uhome = &homeserver($uname,$udom);
 8777:         return $uhome if ($uhome eq 'no_host');
 8778:     } else {
 8779:         $uname = $env{'user.name'};
 8780:         $udom = $env{'user.domain'};
 8781:         $uhome = $env{'user.home'};
 8782:     }
 8783:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 8784:                 "$udom:$uname:rolesdef_$rolename=".
 8785:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 8786:     return reply($command,$uhome);
 8787:   } else {
 8788:     return 'refused';
 8789:   }
 8790: }
 8791: 
 8792: # ---------------- Make a metadata query against the network of library servers
 8793: 
 8794: sub metadata_query {
 8795:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
 8796:     my %rhash;
 8797:     my %libserv = &all_library();
 8798:     my @server_list = (defined($server_array) ? @$server_array
 8799:                                               : keys(%libserv) );
 8800:     for my $server (@server_list) {
 8801:         my $domains = '';
 8802:         if (ref($domains_hash) eq 'HASH') {
 8803:             $domains = $domains_hash->{$server};    
 8804:         }
 8805: 	unless ($custom or $customshow) {
 8806: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
 8807: 	    $rhash{$server}=$reply;
 8808: 	}
 8809: 	else {
 8810: 	    my $reply=&reply("querysend:".&escape($query).':'.
 8811: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
 8812: 			     $server);
 8813: 	    $rhash{$server}=$reply;
 8814: 	}
 8815:     }
 8816:     return \%rhash;
 8817: }
 8818: 
 8819: # ----------------------------------------- Send log queries and wait for reply
 8820: 
 8821: sub log_query {
 8822:     my ($uname,$udom,$query,%filters)=@_;
 8823:     my $uhome=&homeserver($uname,$udom);
 8824:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 8825:     my $uhost=&hostname($uhome);
 8826:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 8827:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 8828:                        $uhome);
 8829:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 8830:     return get_query_reply($queryid);
 8831: }
 8832: 
 8833: # -------------------------- Update MySQL table for portfolio file
 8834: 
 8835: sub update_portfolio_table {
 8836:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 8837:     if ($group ne '') {
 8838:         $file_name =~s /^\Q$group\E//;
 8839:     }
 8840:     my $homeserver = &homeserver($uname,$udom);
 8841:     my $queryid=
 8842:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 8843:                ':'.&escape($file_name).':'.$action,$homeserver);
 8844:     my $reply = &get_query_reply($queryid);
 8845:     return $reply;
 8846: }
 8847: 
 8848: # -------------------------- Update MySQL allusers table
 8849: 
 8850: sub update_allusers_table {
 8851:     my ($uname,$udom,$names) = @_;
 8852:     my $homeserver = &homeserver($uname,$udom);
 8853:     my $queryid=
 8854:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 8855:                'lastname='.&escape($names->{'lastname'}).'%%'.
 8856:                'firstname='.&escape($names->{'firstname'}).'%%'.
 8857:                'middlename='.&escape($names->{'middlename'}).'%%'.
 8858:                'generation='.&escape($names->{'generation'}).'%%'.
 8859:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 8860:                'id='.&escape($names->{'id'}),$homeserver);
 8861:     return;
 8862: }
 8863: 
 8864: # ------- Request retrieval of institutional classlists for course(s)
 8865: 
 8866: sub fetch_enrollment_query {
 8867:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 8868:     my ($homeserver,$sleep,$loopmax);
 8869:     my $maxtries = 1;
 8870:     if ($context eq 'automated') {
 8871:         $homeserver = $perlvar{'lonHostID'};
 8872:         $sleep = 2;
 8873:         $loopmax = 100;
 8874:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 8875:     } else {
 8876:         $homeserver = &homeserver($cnum,$dom);
 8877:     }
 8878:     my $host=&hostname($homeserver);
 8879:     my $cmd = '';
 8880:     foreach my $affiliate (keys(%{$affiliatesref})) {
 8881:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 8882:     }
 8883:     $cmd =~ s/%%$//;
 8884:     $cmd = &escape($cmd);
 8885:     my $query = 'fetchenrollment';
 8886:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 8887:     unless ($queryid=~/^\Q$host\E\_/) { 
 8888:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 8889:         return 'error: '.$queryid;
 8890:     }
 8891:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
 8892:     my $tries = 1;
 8893:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 8894:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
 8895:         $tries ++;
 8896:     }
 8897:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 8898:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 8899:     } else {
 8900:         my @responses = split(/:/,$reply);
 8901:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
 8902:             foreach my $line (@responses) {
 8903:                 my ($key,$value) = split(/=/,$line,2);
 8904:                 $$replyref{$key} = $value;
 8905:             }
 8906:         } else {
 8907:             my $pathname = LONCAPA::tempdir();
 8908:             foreach my $line (@responses) {
 8909:                 my ($key,$value) = split(/=/,$line);
 8910:                 $$replyref{$key} = $value;
 8911:                 if ($value > 0) {
 8912:                     foreach my $item (@{$$affiliatesref{$key}}) {
 8913:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 8914:                         my $destname = $pathname.'/'.$filename;
 8915:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 8916:                         if ($xml_classlist =~ /^error/) {
 8917:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 8918:                         } else {
 8919:                             if ( open(FILE,">",$destname) ) {
 8920:                                 print FILE &unescape($xml_classlist);
 8921:                                 close(FILE);
 8922:                             } else {
 8923:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 8924:                             }
 8925:                         }
 8926:                     }
 8927:                 }
 8928:             }
 8929:         }
 8930:         return 'ok';
 8931:     }
 8932:     return 'error';
 8933: }
 8934: 
 8935: sub get_query_reply {
 8936:     my ($queryid,$sleep,$loopmax) = @_;
 8937:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
 8938:         $sleep = 0.2;
 8939:     }
 8940:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
 8941:         $loopmax = 100;
 8942:     }
 8943:     my $replyfile=LONCAPA::tempdir().$queryid;
 8944:     my $reply='';
 8945:     for (1..$loopmax) {
 8946: 	sleep($sleep);
 8947:         if (-e $replyfile.'.end') {
 8948: 	    if (open(my $fh,"<",$replyfile)) {
 8949: 		$reply = join('',<$fh>);
 8950: 		close($fh);
 8951: 	   } else { return 'error: reply_file_error'; }
 8952:            return &unescape($reply);
 8953: 	}
 8954:     }
 8955:     return 'timeout:'.$queryid;
 8956: }
 8957: 
 8958: sub courselog_query {
 8959: #
 8960: # possible filters:
 8961: # url: url or symb
 8962: # username
 8963: # domain
 8964: # action: view, submit, grade
 8965: # start: timestamp
 8966: # end: timestamp
 8967: #
 8968:     my (%filters)=@_;
 8969:     unless ($env{'request.course.id'}) { return 'no_course'; }
 8970:     if ($filters{'url'}) {
 8971: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 8972:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 8973:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 8974:     }
 8975:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 8976:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 8977:     return &log_query($cname,$cdom,'courselog',%filters);
 8978: }
 8979: 
 8980: sub userlog_query {
 8981: #
 8982: # possible filters:
 8983: # action: log check role
 8984: # start: timestamp
 8985: # end: timestamp
 8986: #
 8987:     my ($uname,$udom,%filters)=@_;
 8988:     return &log_query($uname,$udom,'userlog',%filters);
 8989: }
 8990: 
 8991: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 8992: 
 8993: sub auto_run {
 8994:     my ($cnum,$cdom) = @_;
 8995:     my $response = 0;
 8996:     my $settings;
 8997:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 8998:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 8999:         $settings = $domconfig{'autoenroll'};
 9000:         if ($settings->{'run'} eq '1') {
 9001:             $response = 1;
 9002:         }
 9003:     } else {
 9004:         my $homeserver;
 9005:         if (&is_course($cdom,$cnum)) {
 9006:             $homeserver = &homeserver($cnum,$cdom);
 9007:         } else {
 9008:             $homeserver = &domain($cdom,'primary');
 9009:         }
 9010:         if ($homeserver ne 'no_host') {
 9011:             $response = &reply('autorun:'.$cdom,$homeserver);
 9012:         }
 9013:     }
 9014:     return $response;
 9015: }
 9016: 
 9017: sub auto_get_sections {
 9018:     my ($cnum,$cdom,$inst_coursecode) = @_;
 9019:     my $homeserver;
 9020:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
 9021:         $homeserver = &homeserver($cnum,$cdom);
 9022:     }
 9023:     if (!defined($homeserver)) { 
 9024:         if ($cdom =~ /^$match_domain$/) {
 9025:             $homeserver = &domain($cdom,'primary');
 9026:         }
 9027:     }
 9028:     my @secs;
 9029:     if (defined($homeserver)) {
 9030:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 9031:         unless ($response eq 'refused') {
 9032:             @secs = split(/:/,$response);
 9033:         }
 9034:     }
 9035:     return @secs;
 9036: }
 9037: 
 9038: sub auto_new_course {
 9039:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
 9040:     my $homeserver = &homeserver($cnum,$cdom);
 9041:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
 9042:     return $response;
 9043: }
 9044: 
 9045: sub auto_validate_courseID {
 9046:     my ($cnum,$cdom,$inst_course_id) = @_;
 9047:     my $homeserver = &homeserver($cnum,$cdom);
 9048:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 9049:     return $response;
 9050: }
 9051: 
 9052: sub auto_validate_instcode {
 9053:     my ($cnum,$cdom,$instcode,$owner) = @_;
 9054:     my ($homeserver,$response);
 9055:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 9056:         $homeserver = &homeserver($cnum,$cdom);
 9057:     }
 9058:     if (!defined($homeserver)) {
 9059:         if ($cdom =~ /^$match_domain$/) {
 9060:             $homeserver = &domain($cdom,'primary');
 9061:         }
 9062:     }
 9063:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
 9064:                         &escape($instcode).':'.&escape($owner),$homeserver));
 9065:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
 9066:     return ($outcome,$description,$defaultcredits);
 9067: }
 9068: 
 9069: sub auto_create_password {
 9070:     my ($cnum,$cdom,$authparam,$udom) = @_;
 9071:     my ($homeserver,$response);
 9072:     my $create_passwd = 0;
 9073:     my $authchk = '';
 9074:     if ($udom =~ /^$match_domain$/) {
 9075:         $homeserver = &domain($udom,'primary');
 9076:     }
 9077:     if ($homeserver eq '') {
 9078:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 9079:             $homeserver = &homeserver($cnum,$cdom);
 9080:         }
 9081:     }
 9082:     if ($homeserver eq '') {
 9083:         $authchk = 'nodomain';
 9084:     } else {
 9085:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 9086:         if ($response eq 'refused') {
 9087:             $authchk = 'refused';
 9088:         } else {
 9089:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 9090:         }
 9091:     }
 9092:     return ($authparam,$create_passwd,$authchk);
 9093: }
 9094: 
 9095: sub auto_photo_permission {
 9096:     my ($cnum,$cdom,$students) = @_;
 9097:     my $homeserver = &homeserver($cnum,$cdom);
 9098:     my ($outcome,$perm_reqd,$conditions) = 
 9099: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 9100:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 9101: 	return (undef,undef);
 9102:     }
 9103:     return ($outcome,$perm_reqd,$conditions);
 9104: }
 9105: 
 9106: sub auto_checkphotos {
 9107:     my ($uname,$udom,$pid) = @_;
 9108:     my $homeserver = &homeserver($uname,$udom);
 9109:     my ($result,$resulttype);
 9110:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 9111: 				   &escape($uname).':'.&escape($pid),
 9112: 				   $homeserver));
 9113:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 9114: 	return (undef,undef);
 9115:     }
 9116:     if ($outcome) {
 9117:         ($result,$resulttype) = split(/:/,$outcome);
 9118:     } 
 9119:     return ($result,$resulttype);
 9120: }
 9121: 
 9122: sub auto_photochoice {
 9123:     my ($cnum,$cdom) = @_;
 9124:     my $homeserver = &homeserver($cnum,$cdom);
 9125:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 9126: 						       &escape($cdom),
 9127: 						       $homeserver)));
 9128:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 9129: 	return (undef,undef);
 9130:     }
 9131:     return ($update,$comment);
 9132: }
 9133: 
 9134: sub auto_photoupdate {
 9135:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 9136:     my $homeserver = &homeserver($cnum,$dom);
 9137:     my $host=&hostname($homeserver);
 9138:     my $cmd = '';
 9139:     my $maxtries = 1;
 9140:     foreach my $affiliate (keys(%{$affiliatesref})) {
 9141:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 9142:     }
 9143:     $cmd =~ s/%%$//;
 9144:     $cmd = &escape($cmd);
 9145:     my $query = 'institutionalphotos';
 9146:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 9147:     unless ($queryid=~/^\Q$host\E\_/) {
 9148:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 9149:         return 'error: '.$queryid;
 9150:     }
 9151:     my $reply = &get_query_reply($queryid);
 9152:     my $tries = 1;
 9153:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 9154:         $reply = &get_query_reply($queryid);
 9155:         $tries ++;
 9156:     }
 9157:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 9158:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 9159:     } else {
 9160:         my @responses = split(/:/,$reply);
 9161:         my $outcome = shift(@responses); 
 9162:         foreach my $item (@responses) {
 9163:             my ($key,$value) = split(/=/,$item);
 9164:             $$photo{$key} = $value;
 9165:         }
 9166:         return $outcome;
 9167:     }
 9168:     return 'error';
 9169: }
 9170: 
 9171: sub auto_instcode_format {
 9172:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 9173: 	$cat_order) = @_;
 9174:     my $courses = '';
 9175:     my @homeservers;
 9176:     if ($caller eq 'global') {
 9177: 	my %servers = &get_servers($codedom,'library');
 9178: 	foreach my $tryserver (keys(%servers)) {
 9179: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 9180: 		push(@homeservers,$tryserver);
 9181: 	    }
 9182:         }
 9183:     } elsif ($caller eq 'requests') {
 9184:         if ($codedom =~ /^$match_domain$/) {
 9185:             my $chome = &domain($codedom,'primary');
 9186:             unless ($chome eq 'no_host') {
 9187:                 push(@homeservers,$chome);
 9188:             }
 9189:         }
 9190:     } else {
 9191:         push(@homeservers,&homeserver($caller,$codedom));
 9192:     }
 9193:     foreach my $code (keys(%{$instcodes})) {
 9194:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 9195:     }
 9196:     chop($courses);
 9197:     my $ok_response = 0;
 9198:     my $response;
 9199:     while (@homeservers > 0 && $ok_response == 0) {
 9200:         my $server = shift(@homeservers); 
 9201:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 9202:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 9203:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 9204: 		split(/:/,$response);
 9205:             %{$codes} = (%{$codes},&str2hash($codes_str));
 9206:             push(@{$codetitles},&str2array($codetitles_str));
 9207:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 9208:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 9209:             $ok_response = 1;
 9210:         }
 9211:     }
 9212:     if ($ok_response) {
 9213:         return 'ok';
 9214:     } else {
 9215:         return $response;
 9216:     }
 9217: }
 9218: 
 9219: sub auto_instcode_defaults {
 9220:     my ($domain,$returnhash,$code_order) = @_;
 9221:     my @homeservers;
 9222: 
 9223:     my %servers = &get_servers($domain,'library');
 9224:     foreach my $tryserver (keys(%servers)) {
 9225: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 9226: 	    push(@homeservers,$tryserver);
 9227: 	}
 9228:     }
 9229: 
 9230:     my $response;
 9231:     foreach my $server (@homeservers) {
 9232:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 9233:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 9234: 	
 9235: 	foreach my $pair (split(/\&/,$response)) {
 9236: 	    my ($name,$value)=split(/\=/,$pair);
 9237: 	    if ($name eq 'code_order') {
 9238: 		@{$code_order} = split(/\&/,&unescape($value));
 9239: 	    } else {
 9240: 		$returnhash->{&unescape($name)}=&unescape($value);
 9241: 	    }
 9242: 	}
 9243: 	return 'ok';
 9244:     }
 9245: 
 9246:     return $response;
 9247: }
 9248: 
 9249: sub auto_possible_instcodes {
 9250:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
 9251:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
 9252:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 9253:         return;
 9254:     }
 9255:     my (@homeservers,$uhome);
 9256:     if (defined(&domain($domain,'primary'))) {
 9257:         $uhome=&domain($domain,'primary');
 9258:         push(@homeservers,&domain($domain,'primary'));
 9259:     } else {
 9260:         my %servers = &get_servers($domain,'library');
 9261:         foreach my $tryserver (keys(%servers)) {
 9262:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 9263:                 push(@homeservers,$tryserver);
 9264:             }
 9265:         }
 9266:     }
 9267:     my $response;
 9268:     foreach my $server (@homeservers) {
 9269:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
 9270:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 9271:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
 9272:             split(':',$response);
 9273:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
 9274:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
 9275:         foreach my $item (split('&',$cat_title)) {   
 9276:             my ($name,$value)=split('=',$item);
 9277:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
 9278:         }
 9279:         foreach my $item (split('&',$cat_order)) {
 9280:             my ($name,$value)=split('=',$item);
 9281:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
 9282:         }
 9283:         return 'ok';
 9284:     }
 9285:     return $response;
 9286: }
 9287: 
 9288: sub auto_courserequest_checks {
 9289:     my ($dom) = @_;
 9290:     my ($homeserver,%validations);
 9291:     if ($dom =~ /^$match_domain$/) {
 9292:         $homeserver = &domain($dom,'primary');
 9293:     }
 9294:     unless ($homeserver eq 'no_host') {
 9295:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
 9296:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 9297:             my @items = split(/&/,$response);
 9298:             foreach my $item (@items) {
 9299:                 my ($key,$value) = split('=',$item);
 9300:                 $validations{&unescape($key)} = &thaw_unescape($value);
 9301:             }
 9302:         }
 9303:     }
 9304:     return %validations; 
 9305: }
 9306: 
 9307: sub auto_courserequest_validation {
 9308:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
 9309:     my ($homeserver,$response);
 9310:     if ($dom =~ /^$match_domain$/) {
 9311:         $homeserver = &domain($dom,'primary');
 9312:     }
 9313:     unless ($homeserver eq 'no_host') {
 9314:         my $customdata;
 9315:         if (ref($custominfo) eq 'HASH') {
 9316:             $customdata = &freeze_escape($custominfo);
 9317:         }
 9318:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
 9319:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
 9320:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
 9321:                                     $customdata,$homeserver));
 9322:     }
 9323:     return $response;
 9324: }
 9325: 
 9326: sub auto_validate_class_sec {
 9327:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 9328:     my $homeserver = &homeserver($cnum,$cdom);
 9329:     my $ownerlist;
 9330:     if (ref($owners) eq 'ARRAY') {
 9331:         $ownerlist = join(',',@{$owners});
 9332:     } else {
 9333:         $ownerlist = $owners;
 9334:     }
 9335:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 9336:                         &escape($ownerlist).':'.$cdom,$homeserver);
 9337:     return $response;
 9338: }
 9339: 
 9340: sub auto_validate_instclasses {
 9341:     my ($cdom,$cnum,$owners,$classesref) = @_;
 9342:     my ($homeserver,%validations);
 9343:     $homeserver = &homeserver($cnum,$cdom);
 9344:     unless ($homeserver eq 'no_host') {
 9345:         my $ownerlist;
 9346:         if (ref($owners) eq 'ARRAY') {
 9347:             $ownerlist = join(',',@{$owners});
 9348:         } else {
 9349:             $ownerlist = $owners;
 9350:         }
 9351:         if (ref($classesref) eq 'HASH') {
 9352:             my $classes = &freeze_escape($classesref);
 9353:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
 9354:                                 ':'.$cdom.':'.$classes,$homeserver);
 9355:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 9356:                 my @items = split(/&/,$response);
 9357:                 foreach my $item (@items) {
 9358:                     my ($key,$value) = split('=',$item);
 9359:                     $validations{&unescape($key)} = &thaw_unescape($value);
 9360:                 }
 9361:             }
 9362:         }
 9363:     }
 9364:     return %validations;
 9365: }
 9366: 
 9367: sub auto_crsreq_update {
 9368:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
 9369:         $code,$accessstart,$accessend,$inbound) = @_;
 9370:     my ($homeserver,%crsreqresponse);
 9371:     if ($cdom =~ /^$match_domain$/) {
 9372:         $homeserver = &domain($cdom,'primary');
 9373:     }
 9374:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
 9375:         my $info;
 9376:         if (ref($inbound) eq 'HASH') {
 9377:             $info = &freeze_escape($inbound);
 9378:         }
 9379:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
 9380:                             ':'.&escape($action).':'.&escape($ownername).':'.
 9381:                             &escape($ownerdomain).':'.&escape($fullname).':'.
 9382:                             &escape($title).':'.&escape($code).':'.
 9383:                             &escape($accessstart).':'.&escape($accessend).':'.$info,$homeserver);
 9384:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 9385:             my @items = split(/&/,$response);
 9386:             foreach my $item (@items) {
 9387:                 my ($key,$value) = split('=',$item);
 9388:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
 9389:             }
 9390:         }
 9391:     }
 9392:     return \%crsreqresponse;
 9393: }
 9394: 
 9395: sub auto_export_grades {
 9396:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
 9397:     my ($homeserver,%exportresponse);
 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($inforef) eq 'HASH') {
 9404:             $info = &freeze_escape($inforef);
 9405:         }
 9406:         if (ref($gradesref) eq 'HASH') {
 9407:             my $grades = &freeze_escape($gradesref);
 9408:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
 9409:                                 $info.':'.$grades,$homeserver);
 9410:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
 9411:                 my @items = split(/&/,$response);
 9412:                 foreach my $item (@items) {
 9413:                     my ($key,$value) = split('=',$item);
 9414:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
 9415:                 }
 9416:             }
 9417:         }
 9418:     }
 9419:     return \%exportresponse;
 9420: }
 9421: 
 9422: sub check_instcode_cloning {
 9423:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
 9424:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 9425:         return;
 9426:     }
 9427:     my $canclone;
 9428:     if (@{$code_order} > 0) {
 9429:         my $instcoderegexp ='^';
 9430:         my @clonecodes = split(/\&/,$cloner);
 9431:         foreach my $item (@{$code_order}) {
 9432:             if (grep(/^\Q$item\E=/,@clonecodes)) {
 9433:                 foreach my $pair (@clonecodes) {
 9434:                     my ($key,$val) = split(/\=/,$pair,2);
 9435:                     $val = &unescape($val);
 9436:                     if ($key eq $item) {
 9437:                         $instcoderegexp .= '('.$val.')';
 9438:                         last;
 9439:                     }
 9440:                 }
 9441:             } else {
 9442:                 $instcoderegexp .= $codedefaults->{$item};
 9443:             }
 9444:         }
 9445:         $instcoderegexp .= '$';
 9446:         my (@from,@to);
 9447:         eval {
 9448:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
 9449:                (@to) = ($clonetocode =~ /$instcoderegexp/);
 9450:         };
 9451:         if ((@from > 0) && (@to > 0)) {
 9452:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
 9453:             if (!@diffs) {
 9454:                 $canclone = 1;
 9455:             }
 9456:         }
 9457:     }
 9458:     return $canclone;
 9459: }
 9460: 
 9461: sub default_instcode_cloning {
 9462:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
 9463:     my (%codedefaults,@code_order,$canclone);
 9464:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
 9465:         %codedefaults = %{$codedefaultsref};
 9466:         @code_order = @{$codeorderref};
 9467:     } elsif ($clonedom) {
 9468:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
 9469:     }
 9470:     if (($domdefclone) && (@code_order)) {
 9471:         my @clonecodes = split(/\+/,$domdefclone);
 9472:         my $instcoderegexp ='^';
 9473:         foreach my $item (@code_order) {
 9474:             if (grep(/^\Q$item\E$/,@clonecodes)) {
 9475:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
 9476:             } else {
 9477:                 $instcoderegexp .= $codedefaults{$item};
 9478:             }
 9479:         }
 9480:         $instcoderegexp .= '$';
 9481:         my (@from,@to);
 9482:         eval {
 9483:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
 9484:             (@to) = ($clonetocode =~ /$instcoderegexp/);
 9485:         };
 9486:         if ((@from > 0) && (@to > 0)) {
 9487:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
 9488:             if (!@diffs) {
 9489:                 $canclone = 1;
 9490:             }
 9491:         }
 9492:     }
 9493:     return $canclone;
 9494: }
 9495: 
 9496: # ------------------------------------------------------- Course Group routines
 9497: 
 9498: sub get_coursegroups {
 9499:     my ($cdom,$cnum,$group,$namespace) = @_;
 9500:     return(&dump($namespace,$cdom,$cnum,$group));
 9501: }
 9502: 
 9503: sub modify_coursegroup {
 9504:     my ($cdom,$cnum,$groupsettings) = @_;
 9505:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 9506: }
 9507: 
 9508: sub toggle_coursegroup_status {
 9509:     my ($cdom,$cnum,$group,$action) = @_;
 9510:     my ($from_namespace,$to_namespace);
 9511:     if ($action eq 'delete') {
 9512:         $from_namespace = 'coursegroups';
 9513:         $to_namespace = 'deleted_groups';
 9514:     } else {
 9515:         $from_namespace = 'deleted_groups';
 9516:         $to_namespace = 'coursegroups';
 9517:     }
 9518:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 9519:     if (my $tmp = &error(%curr_group)) {
 9520:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 9521:         return ('read error',$tmp);
 9522:     } else {
 9523:         my %savedsettings = %curr_group; 
 9524:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 9525:         my $deloutcome;
 9526:         if ($result eq 'ok') {
 9527:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 9528:         } else {
 9529:             return ('write error',$result);
 9530:         }
 9531:         if ($deloutcome eq 'ok') {
 9532:             return 'ok';
 9533:         } else {
 9534:             return ('delete error',$deloutcome);
 9535:         }
 9536:     }
 9537: }
 9538: 
 9539: sub modify_group_roles {
 9540:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 9541:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 9542:     my $role = 'gr/'.&escape($userprivs);
 9543:     my ($uname,$udom) = split(/:/,$user);
 9544:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 9545:     if ($result eq 'ok') {
 9546:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 9547:     }
 9548:     return $result;
 9549: }
 9550: 
 9551: sub modify_coursegroup_membership {
 9552:     my ($cdom,$cnum,$membership) = @_;
 9553:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 9554:     return $result;
 9555: }
 9556: 
 9557: sub get_active_groups {
 9558:     my ($udom,$uname,$cdom,$cnum) = @_;
 9559:     my $now = time;
 9560:     my %groups = ();
 9561:     foreach my $key (keys(%env)) {
 9562:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 9563:             my ($start,$end) = split(/\./,$env{$key});
 9564:             if (($end!=0) && ($end<$now)) { next; }
 9565:             if (($start!=0) && ($start>$now)) { next; }
 9566:             if ($1 eq $cdom && $2 eq $cnum) {
 9567:                 $groups{$3} = $env{$key} ;
 9568:             }
 9569:         }
 9570:     }
 9571:     return %groups;
 9572: }
 9573: 
 9574: sub get_group_membership {
 9575:     my ($cdom,$cnum,$group) = @_;
 9576:     return(&dump('groupmembership',$cdom,$cnum,$group));
 9577: }
 9578: 
 9579: sub get_users_groups {
 9580:     my ($udom,$uname,$courseid) = @_;
 9581:     my @usersgroups;
 9582:     my $cachetime=1800;
 9583: 
 9584:     my $hashid="$udom:$uname:$courseid";
 9585:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 9586:     if (defined($cached)) {
 9587:         @usersgroups = split(/:/,$grouplist);
 9588:     } else {  
 9589:         $grouplist = '';
 9590:         my $courseurl = &courseid_to_courseurl($courseid);
 9591:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 9592:         my $access_end = $env{'course.'.$courseid.
 9593:                               '.default_enrollment_end_date'};
 9594:         my $now = time;
 9595:         foreach my $key (keys(%roleshash)) {
 9596:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 9597:                 my $group = $1;
 9598:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 9599:                     my $start = $2;
 9600:                     my $end = $1;
 9601:                     if ($start == -1) { next; } # deleted from group
 9602:                     if (($start!=0) && ($start>$now)) { next; }
 9603:                     if (($end!=0) && ($end<$now)) {
 9604:                         if ($access_end && $access_end < $now) {
 9605:                             if ($access_end - $end < 86400) {
 9606:                                 push(@usersgroups,$group);
 9607:                             }
 9608:                         }
 9609:                         next;
 9610:                     }
 9611:                     push(@usersgroups,$group);
 9612:                 }
 9613:             }
 9614:         }
 9615:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 9616:         $grouplist = join(':',@usersgroups);
 9617:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 9618:     }
 9619:     return @usersgroups;
 9620: }
 9621: 
 9622: sub devalidate_getgroups_cache {
 9623:     my ($udom,$uname,$cdom,$cnum)=@_;
 9624:     my $courseid = $cdom.'_'.$cnum;
 9625: 
 9626:     my $hashid="$udom:$uname:$courseid";
 9627:     &devalidate_cache_new('getgroups',$hashid);
 9628: }
 9629: 
 9630: # ------------------------------------------------------------------ Plain Text
 9631: 
 9632: sub plaintext {
 9633:     my ($short,$type,$cid,$forcedefault) = @_;
 9634:     if ($short =~ m{^cr/}) {
 9635: 	return (split('/',$short))[-1];
 9636:     }
 9637:     if (!defined($cid)) {
 9638:         $cid = $env{'request.course.id'};
 9639:     }
 9640:     my %rolenames = (
 9641:                       Course    => 'std',
 9642:                       Community => 'alt1',
 9643:                     );
 9644:     if ($cid ne '') {
 9645:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
 9646:             unless ($forcedefault) {
 9647:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
 9648:                 &Apache::lonlocal::mt_escape(\$roletext);
 9649:                 return &Apache::lonlocal::mt($roletext);
 9650:             }
 9651:         }
 9652:     }
 9653:     if ((defined($type)) && (defined($rolenames{$type})) &&
 9654:         (defined($rolenames{$type})) && 
 9655:         (defined($prp{$short}{$rolenames{$type}}))) {
 9656:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 9657:     } elsif ($cid ne '') {
 9658:         my $crstype = $env{'course.'.$cid.'.type'};
 9659:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
 9660:             (defined($prp{$short}{$rolenames{$crstype}}))) {
 9661:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
 9662:         }
 9663:     }
 9664:     return &Apache::lonlocal::mt($prp{$short}{'std'});
 9665: }
 9666: 
 9667: # ----------------------------------------------------------------- Assign Role
 9668: 
 9669: sub assignrole {
 9670:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
 9671:         $context)=@_;
 9672:     my $mrole;
 9673:     if ($role =~ /^cr\//) {
 9674:         my $cwosec=$url;
 9675:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 9676: 	unless (&allowed('ccr',$cwosec)) {
 9677:            my $refused = 1;
 9678:            if ($context eq 'requestcourses') {
 9679:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 9680:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
 9681:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
 9682:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 9683:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 9684:                            if ($crsenv{'internal.courseowner'} eq
 9685:                                $env{'user.name'}.':'.$env{'user.domain'}) {
 9686:                                $refused = '';
 9687:                            }
 9688:                        }
 9689:                    }
 9690:                }
 9691:            }
 9692:            if ($refused) {
 9693:                &logthis('Refused custom assignrole: '.
 9694:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
 9695:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
 9696:                return 'refused';
 9697:            }
 9698:         }
 9699:         $mrole='cr';
 9700:     } elsif ($role =~ /^gr\//) {
 9701:         my $cwogrp=$url;
 9702:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 9703:         unless (&allowed('mdg',$cwogrp)) {
 9704:             &logthis('Refused group assignrole: '.
 9705:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 9706:                     $env{'user.name'}.' at '.$env{'user.domain'});
 9707:             return 'refused';
 9708:         }
 9709:         $mrole='gr';
 9710:     } else {
 9711:         my $cwosec=$url;
 9712:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 9713:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 9714:             my $refused;
 9715:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 9716:                 if (!(&allowed('c'.$role,$url))) {
 9717:                     $refused = 1;
 9718:                 }
 9719:             } else {
 9720:                 $refused = 1;
 9721:             }
 9722:             if ($refused) {
 9723:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 9724:                 if (!$selfenroll && $context eq 'course') {
 9725:                     my %crsenv;
 9726:                     if ($role eq 'cc' || $role eq 'co') {
 9727:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 9728:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
 9729:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
 9730:                                 if ($crsenv{'internal.courseowner'} eq 
 9731:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 9732:                                     $refused = '';
 9733:                                 }
 9734:                             }
 9735:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
 9736:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
 9737:                                 if ($crsenv{'internal.courseowner'} eq 
 9738:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 9739:                                     $refused = '';
 9740:                                 }
 9741:                             }
 9742:                         }
 9743:                     }
 9744:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 9745:                     $refused = '';
 9746:                 } elsif ($context eq 'requestcourses') {
 9747:                     my @possroles = ('st','ta','ep','in','cc','co');
 9748:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
 9749:                         my $wrongcc;
 9750:                         if ($cnum =~ /^$match_community$/) {
 9751:                             $wrongcc = 1 if ($role eq 'cc');
 9752:                         } else {
 9753:                             $wrongcc = 1 if ($role eq 'co');
 9754:                         }
 9755:                         unless ($wrongcc) {
 9756:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 9757:                             if ($crsenv{'internal.courseowner'} eq 
 9758:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
 9759:                                 $refused = '';
 9760:                             }
 9761:                         }
 9762:                     }
 9763:                 } elsif ($context eq 'requestauthor') {
 9764:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 9765:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
 9766:                         if ($env{'environment.requestauthor'} eq 'automatic') {
 9767:                             $refused = '';
 9768:                         } else {
 9769:                             my %domdefaults = &get_domain_defaults($udom);
 9770:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
 9771:                                 my $checkbystatus;
 9772:                                 if ($env{'user.adv'}) {
 9773:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
 9774:                                     if ($disposition eq 'automatic') {
 9775:                                         $refused = '';
 9776:                                     } elsif ($disposition eq '') {
 9777:                                         $checkbystatus = 1;
 9778:                                     }
 9779:                                 } else {
 9780:                                     $checkbystatus = 1;
 9781:                                 }
 9782:                                 if ($checkbystatus) {
 9783:                                     if ($env{'environment.inststatus'}) {
 9784:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
 9785:                                         foreach my $type (@inststatuses) {
 9786:                                             if (($type ne '') &&
 9787:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
 9788:                                                 $refused = '';
 9789:                                             }
 9790:                                         }
 9791:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
 9792:                                         $refused = '';
 9793:                                     }
 9794:                                 }
 9795:                             }
 9796:                         }
 9797:                     }
 9798:                 }
 9799:                 if ($refused) {
 9800:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 9801:                              ' '.$role.' '.$end.' '.$start.' by '.
 9802: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
 9803:                     return 'refused';
 9804:                 }
 9805:             }
 9806:         } elsif ($role eq 'au') {
 9807:             if ($url ne '/'.$udom.'/') {
 9808:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
 9809:                          ' to assign author role for '.$uname.':'.$udom.
 9810:                          ' in domain: '.$url.' refused (wrong domain).');
 9811:                 return 'refused';
 9812:             }
 9813:         }
 9814:         $mrole=$role;
 9815:     }
 9816:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 9817:                 "$udom:$uname:$url".'_'."$mrole=$role";
 9818:     if ($end) { $command.='_'.$end; }
 9819:     if ($start) {
 9820: 	if ($end) { 
 9821:            $command.='_'.$start; 
 9822:         } else {
 9823:            $command.='_0_'.$start;
 9824:         }
 9825:     }
 9826:     my $origstart = $start;
 9827:     my $origend = $end;
 9828:     my $delflag;
 9829: # actually delete
 9830:     if ($deleteflag) {
 9831: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 9832: # modify command to delete the role
 9833:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 9834:                 "$udom:$uname:$url".'_'."$mrole";
 9835: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 9836: # set start and finish to negative values for userrolelog
 9837:            $start=-1;
 9838:            $end=-1;
 9839:            $delflag = 1;
 9840:         }
 9841:     }
 9842: # send command
 9843:     my $answer=&reply($command,&homeserver($uname,$udom));
 9844: # log new user role if status is ok
 9845:     if ($answer eq 'ok') {
 9846: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 9847:         if (($role eq 'cc') || ($role eq 'in') ||
 9848:             ($role eq 'ep') || ($role eq 'ad') ||
 9849:             ($role eq 'ta') || ($role eq 'st') ||
 9850:             ($role=~/^cr/) || ($role eq 'gr') ||
 9851:             ($role eq 'co')) {
 9852: # for course roles, perform group memberships changes triggered by role change.
 9853:             unless ($role =~ /^gr/) {
 9854:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 9855:                                                  $origstart,$selfenroll,$context);
 9856:             }
 9857:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 9858:                            $selfenroll,$context);
 9859:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
 9860:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
 9861:                  ($role eq 'da')) {
 9862:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 9863:                            $context);
 9864:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
 9865:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 9866:                              $context);
 9867:         }
 9868:         if ($role eq 'cc') {
 9869:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
 9870:         }
 9871:     }
 9872:     return $answer;
 9873: }
 9874: 
 9875: sub autoupdate_coowners {
 9876:     my ($url,$end,$start,$uname,$udom) = @_;
 9877:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
 9878:     if (($cdom ne '') && ($cnum ne '')) {
 9879:         my $now = time;
 9880:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
 9881:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
 9882:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
 9883:             my $instcode = $coursehash{'internal.coursecode'};
 9884:             if ($instcode ne '') {
 9885:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
 9886:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
 9887:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
 9888:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
 9889:                         if ($result eq 'valid') {
 9890:                             if ($coursehash{'internal.co-owners'}) {
 9891:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 9892:                                     push(@newcoowners,$coowner);
 9893:                                 }
 9894:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
 9895:                                     push(@newcoowners,$uname.':'.$udom);
 9896:                                 }
 9897:                                 @newcoowners = sort(@newcoowners);
 9898:                             } else {
 9899:                                 push(@newcoowners,$uname.':'.$udom);
 9900:                             }
 9901:                         } else {
 9902:                             if ($coursehash{'internal.co-owners'}) {
 9903:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 9904:                                     unless ($coowner eq $uname.':'.$udom) {
 9905:                                         push(@newcoowners,$coowner);
 9906:                                     }
 9907:                                 }
 9908:                                 unless (@newcoowners > 0) {
 9909:                                     $delcoowners = 1;
 9910:                                     $coowners = '';
 9911:                                 }
 9912:                             }
 9913:                         }
 9914:                         if (@newcoowners || $delcoowners) {
 9915:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
 9916:                                             $delcoowners,@newcoowners);
 9917:                         }
 9918:                     }
 9919:                 }
 9920:             }
 9921:         }
 9922:     }
 9923: }
 9924: 
 9925: sub store_coowners {
 9926:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
 9927:     my $cid = $cdom.'_'.$cnum;
 9928:     my ($coowners,$delresult,$putresult);
 9929:     if (@newcoowners) {
 9930:         $coowners = join(',',@newcoowners);
 9931:         my %coownershash = (
 9932:                             'internal.co-owners' => $coowners,
 9933:                            );
 9934:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
 9935:         if ($putresult eq 'ok') {
 9936:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
 9937:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
 9938:             }
 9939:         }
 9940:     }
 9941:     if ($delcoowners) {
 9942:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
 9943:         if ($delresult eq 'ok') {
 9944:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
 9945:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
 9946:             }
 9947:         }
 9948:     }
 9949:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
 9950:         my %crsinfo =
 9951:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 9952:         if (ref($crsinfo{$cid}) eq 'HASH') {
 9953:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
 9954:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
 9955:         }
 9956:     }
 9957: }
 9958: 
 9959: # -------------------------------------------------- Modify user authentication
 9960: # Overrides without validation
 9961: 
 9962: sub modifyuserauth {
 9963:     my ($udom,$uname,$umode,$upass)=@_;
 9964:     my $uhome=&homeserver($uname,$udom);
 9965:     my $allowed;
 9966:     if (&allowed('mau',$udom)) {
 9967:         $allowed = 1;
 9968:     } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
 9969:              ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
 9970:              (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
 9971:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 9972:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 9973:         if (($cdom ne '') && ($cnum ne '')) {
 9974:             my $is_owner = &is_course_owner($cdom,$cnum);
 9975:             if ($is_owner) {
 9976:                 $allowed = 1;
 9977:             }
 9978:         }
 9979:     }
 9980:     unless ($allowed) { return 'refused'; }
 9981:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 9982:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 9983:              ' in domain '.$env{'request.role.domain'});  
 9984:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 9985: 		     &escape($upass),$uhome);
 9986:     my $ip = &get_requestor_ip();
 9987:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 9988:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 9989:          '(Remote '.$ip.'): '.$reply);
 9990:     &log($udom,,$uname,$uhome,
 9991:         'Authentication changed by '.$env{'user.domain'}.', '.
 9992:                                      $env{'user.name'}.', '.$umode.
 9993:          '(Remote '.$ip.'): '.$reply);
 9994:     unless ($reply eq 'ok') {
 9995:         &logthis('Authentication mode error: '.$reply);
 9996: 	return 'error: '.$reply;
 9997:     }   
 9998:     return 'ok';
 9999: }
10000: 
10001: # --------------------------------------------------------------- Modify a user
10002: 
10003: sub modifyuser {
10004:     my ($udom,    $uname, $uid,
10005:         $umode,   $upass, $first,
10006:         $middle,  $last,  $gene,
10007:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
10008:     $udom= &LONCAPA::clean_domain($udom);
10009:     $uname=&LONCAPA::clean_username($uname);
10010:     my $showcandelete = 'none';
10011:     if (ref($candelete) eq 'ARRAY') {
10012:         if (@{$candelete} > 0) {
10013:             $showcandelete = join(', ',@{$candelete});
10014:         }
10015:     }
10016:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
10017:              $umode.', '.$first.', '.$middle.', '.
10018: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
10019:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
10020:                                      ' desiredhome not specified'). 
10021:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
10022:              ' in domain '.$env{'request.role.domain'});
10023:     my $uhome=&homeserver($uname,$udom,'true');
10024:     my $newuser;
10025:     if ($uhome eq 'no_host') {
10026:         $newuser = 1;
10027:     }
10028: # ----------------------------------------------------------------- Create User
10029:     if (($uhome eq 'no_host') && 
10030: 	(($umode && $upass) || ($umode eq 'localauth'))) {
10031:         my $unhome='';
10032:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
10033:             $unhome = $desiredhome;
10034: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
10035: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
10036:         } else { # load balancing routine for determining $unhome
10037:             my $loadm=10000000;
10038: 	    my %servers = &get_servers($udom,'library');
10039: 	    foreach my $tryserver (keys(%servers)) {
10040: 		my $answer=reply('load',$tryserver);
10041: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
10042: 		    $loadm=$answer;
10043: 		    $unhome=$tryserver;
10044: 		}
10045: 	    }
10046:         }
10047:         if (($unhome eq '') || ($unhome eq 'no_host')) {
10048: 	    return 'error: unable to find a home server for '.$uname.
10049:                    ' in domain '.$udom;
10050:         }
10051:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
10052:                          &escape($upass),$unhome);
10053: 	unless ($reply eq 'ok') {
10054:             return 'error: '.$reply;
10055:         }   
10056:         $uhome=&homeserver($uname,$udom,'true');
10057:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
10058: 	    return 'error: unable verify users home machine.';
10059:         }
10060:     }   # End of creation of new user
10061: # ---------------------------------------------------------------------- Add ID
10062:     if ($uid) {
10063:        $uid=~tr/A-Z/a-z/;
10064:        my %uidhash=&idrget($udom,$uname);
10065:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
10066:          && (!$forceid)) {
10067: 	  unless ($uid eq $uidhash{$uname}) {
10068: 	      return 'error: user id "'.$uid.'" does not match '.
10069:                   'current user id "'.$uidhash{$uname}.'".';
10070:           }
10071:        } else {
10072: 	  &idput($udom,($uname => $uid));
10073:        }
10074:     }
10075: # -------------------------------------------------------------- Add names, etc
10076:     my @tmp=&get('environment',
10077: 		   ['firstname','middlename','lastname','generation','id',
10078:                     'permanentemail','inststatus'],
10079: 		   $udom,$uname);
10080:     my (%names,%oldnames);
10081:     if ($tmp[0] =~ m/^error:.*/) { 
10082:         %names=(); 
10083:     } else {
10084:         %names = @tmp;
10085:         %oldnames = %names;
10086:     }
10087: #
10088: # If name, email and/or uid are blank (e.g., because an uploaded file
10089: # of users did not contain them), do not overwrite existing values
10090: # unless field is in $candelete array ref.  
10091: #
10092: 
10093:     my @fields = ('firstname','middlename','lastname','generation',
10094:                   'permanentemail','id');
10095:     my %newvalues;
10096:     if (ref($candelete) eq 'ARRAY') {
10097:         foreach my $field (@fields) {
10098:             if (grep(/^\Q$field\E$/,@{$candelete})) {
10099:                 if ($field eq 'firstname') {
10100:                     $names{$field} = $first;
10101:                 } elsif ($field eq 'middlename') {
10102:                     $names{$field} = $middle;
10103:                 } elsif ($field eq 'lastname') {
10104:                     $names{$field} = $last;
10105:                 } elsif ($field eq 'generation') { 
10106:                     $names{$field} = $gene;
10107:                 } elsif ($field eq 'permanentemail') {
10108:                     $names{$field} = $email;
10109:                 } elsif ($field eq 'id') {
10110:                     $names{$field}  = $uid;
10111:                 }
10112:             }
10113:         }
10114:     }
10115:     if ($first)  { $names{'firstname'}  = $first; }
10116:     if (defined($middle)) { $names{'middlename'} = $middle; }
10117:     if ($last)   { $names{'lastname'}   = $last; }
10118:     if (defined($gene))   { $names{'generation'} = $gene; }
10119:     if ($email) {
10120:        $email=~s/[^\w\@\.\-\,]//gs;
10121:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
10122:     }
10123:     if ($uid) { $names{'id'}  = $uid; }
10124:     if (defined($inststatus)) {
10125:         $names{'inststatus'} = '';
10126:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
10127:         if (ref($usertypes) eq 'HASH') {
10128:             my @okstatuses; 
10129:             foreach my $item (split(/:/,$inststatus)) {
10130:                 if (defined($usertypes->{$item})) {
10131:                     push(@okstatuses,$item);  
10132:                 }
10133:             }
10134:             if (@okstatuses) {
10135:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
10136:             }
10137:         }
10138:     }
10139:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
10140:                  $umode.', '.$first.', '.$middle.', '.
10141:                  $last.', '.$gene.', '.$email.', '.$inststatus;
10142:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
10143:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
10144:     } else {
10145:         $logmsg .= ' during self creation';
10146:     }
10147:     my $changed;
10148:     if ($newuser) {
10149:         $changed = 1;
10150:     } else {
10151:         foreach my $field (@fields) {
10152:             if ($names{$field} ne $oldnames{$field}) {
10153:                 $changed = 1;
10154:                 last;
10155:             }
10156:         }
10157:     }
10158:     unless ($changed) {
10159:         $logmsg = 'No changes in user information needed for: '.$logmsg;
10160:         &logthis($logmsg);
10161:         return 'ok';
10162:     }
10163:     my $reply = &put('environment', \%names, $udom,$uname);
10164:     if ($reply ne 'ok') { 
10165:         return 'error: '.$reply;
10166:     }
10167:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
10168:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
10169:     }
10170:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
10171:     &devalidate_cache_new('namescache',$uname.':'.$udom);
10172:     $logmsg = 'Success modifying user '.$logmsg;
10173:     &logthis($logmsg);
10174:     return 'ok';
10175: }
10176: 
10177: # -------------------------------------------------------------- Modify student
10178: 
10179: sub modifystudent {
10180:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
10181:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
10182:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
10183:     if (!$cid) {
10184: 	unless ($cid=$env{'request.course.id'}) {
10185: 	    return 'not_in_class';
10186: 	}
10187:     }
10188: # --------------------------------------------------------------- Make the user
10189:     my $reply=&modifyuser
10190: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
10191:          $desiredhome,$email,$inststatus);
10192:     unless ($reply eq 'ok') { return $reply; }
10193:     # This will cause &modify_student_enrollment to get the uid from the
10194:     # student's environment
10195:     $uid = undef if (!$forceid);
10196:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
10197: 					$gene,$usec,$end,$start,$type,$locktype,
10198:                                         $cid,$selfenroll,$context,$credits,$instsec);
10199:     return $reply;
10200: }
10201: 
10202: sub modify_student_enrollment {
10203:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
10204:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
10205:     my ($cdom,$cnum,$chome);
10206:     if (!$cid) {
10207: 	unless ($cid=$env{'request.course.id'}) {
10208: 	    return 'not_in_class';
10209: 	}
10210: 	$cdom=$env{'course.'.$cid.'.domain'};
10211: 	$cnum=$env{'course.'.$cid.'.num'};
10212:     } else {
10213: 	($cdom,$cnum)=split(/_/,$cid);
10214:     }
10215:     $chome=$env{'course.'.$cid.'.home'};
10216:     if (!$chome) {
10217: 	$chome=&homeserver($cnum,$cdom);
10218:     }
10219:     if (!$chome) { return 'unknown_course'; }
10220:     # Make sure the user exists
10221:     my $uhome=&homeserver($uname,$udom);
10222:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
10223: 	return 'error: no such user';
10224:     }
10225:     # Get student data if we were not given enough information
10226:     if (!defined($first)  || $first  eq '' || 
10227:         !defined($last)   || $last   eq '' || 
10228:         !defined($uid)    || $uid    eq '' || 
10229:         !defined($middle) || $middle eq '' || 
10230:         !defined($gene)   || $gene   eq '') {
10231:         # They did not supply us with enough data to enroll the student, so
10232:         # we need to pick up more information.
10233:         my %tmp = &get('environment',
10234:                        ['firstname','middlename','lastname', 'generation','id']
10235:                        ,$udom,$uname);
10236: 
10237:         #foreach my $key (keys(%tmp)) {
10238:         #    &logthis("key $key = ".$tmp{$key});
10239:         #}
10240:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
10241:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
10242:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
10243:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
10244:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
10245:     }
10246:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
10247:     my $user = "$uname:$udom";
10248:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
10249:     my $reply=cput('classlist',
10250: 		   {$user => 
10251: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
10252: 		   $cdom,$cnum);
10253:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
10254:         &devalidate_getsection_cache($udom,$uname,$cid);
10255:     } else { 
10256: 	return 'error: '.$reply;
10257:     }
10258:     # Add student role to user
10259:     my $uurl='/'.$cid;
10260:     $uurl=~s/\_/\//g;
10261:     if ($usec) {
10262: 	$uurl.='/'.$usec;
10263:     }
10264:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
10265:                              $selfenroll,$context);
10266:     if ($result ne 'ok') {
10267:         if ($old_entry{$user} ne '') {
10268:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
10269:         } else {
10270:             $reply = &del('classlist',[$user],$cdom,$cnum);
10271:         }
10272:     }
10273:     return $result; 
10274: }
10275: 
10276: sub format_name {
10277:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
10278:     my $name;
10279:     if ($first ne 'lastname') {
10280: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
10281:     } else {
10282: 	if ($lastname=~/\S/) {
10283: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
10284: 	    $name=~s/\s+,/,/;
10285: 	} else {
10286: 	    $name.= $firstname.' '.$middlename.' '.$generation;
10287: 	}
10288:     }
10289:     $name=~s/^\s+//;
10290:     $name=~s/\s+$//;
10291:     $name=~s/\s+/ /g;
10292:     return $name;
10293: }
10294: 
10295: # ------------------------------------------------- Write to course preferences
10296: 
10297: sub writecoursepref {
10298:     my ($courseid,%prefs)=@_;
10299:     $courseid=~s/^\///;
10300:     $courseid=~s/\_/\//g;
10301:     my ($cdomain,$cnum)=split(/\//,$courseid);
10302:     my $chome=homeserver($cnum,$cdomain);
10303:     if (($chome eq '') || ($chome eq 'no_host')) { 
10304: 	return 'error: no such course';
10305:     }
10306:     my $cstring='';
10307:     foreach my $pref (keys(%prefs)) {
10308: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
10309:     }
10310:     $cstring=~s/\&$//;
10311:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
10312: }
10313: 
10314: # ---------------------------------------------------------- Make/modify course
10315: 
10316: sub createcourse {
10317:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
10318:         $course_owner,$crstype,$cnum,$context,$category)=@_;
10319:     $url=&declutter($url);
10320:     my $cid='';
10321:     if ($context eq 'requestcourses') {
10322:         my $can_create = 0;
10323:         my ($ownername,$ownerdom) = split(':',$course_owner);
10324:         if ($udom eq $ownerdom) {
10325:             if (&usertools_access($ownername,$ownerdom,$category,undef,
10326:                                   $context)) {
10327:                 $can_create = 1;
10328:             }
10329:         } else {
10330:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
10331:                                            $category);
10332:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
10333:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
10334:                 if (@curr > 0) {
10335:                     my @options = qw(approval validate autolimit);
10336:                     my $optregex = join('|',@options);
10337:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
10338:                         $can_create = 1;
10339:                     }
10340:                 }
10341:             }
10342:         }
10343:         if ($can_create) {
10344:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
10345:                 unless (&allowed('ccc',$udom)) {
10346:                     return 'refused'; 
10347:                 }
10348:             }
10349:         } else {
10350:             return 'refused';
10351:         }
10352:     } elsif (!&allowed('ccc',$udom)) {
10353:         return 'refused';
10354:     }
10355: # --------------------------------------------------------------- Get Unique ID
10356:     my $uname;
10357:     if ($cnum =~ /^$match_courseid$/) {
10358:         my $chome=&homeserver($cnum,$udom,'true');
10359:         if (($chome eq '') || ($chome eq 'no_host')) {
10360:             $uname = $cnum;
10361:         } else {
10362:             $uname = &generate_coursenum($udom,$crstype);
10363:         }
10364:     } else {
10365:         $uname = &generate_coursenum($udom,$crstype);
10366:     }
10367:     return $uname if ($uname =~ /^error/);
10368: # -------------------------------------------------- Check supplied server name
10369:     if (!defined($course_server)) {
10370:         if (defined(&domain($udom,'primary'))) {
10371:             $course_server = &domain($udom,'primary');
10372:         } else {
10373:             $course_server = $env{'user.home'}; 
10374:         }
10375:     }
10376:     my %host_servers =
10377:         &Apache::lonnet::get_servers($udom,'library');
10378:     unless ($host_servers{$course_server}) {
10379:         return 'error: invalid home server for course: '.$course_server;
10380:     }
10381: # ------------------------------------------------------------- Make the course
10382:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
10383:                       $course_server);
10384:     unless ($reply eq 'ok') { return 'error: '.$reply; }
10385:     my $uhome=&homeserver($uname,$udom,'true');
10386:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
10387: 	return 'error: no such course';
10388:     }
10389: # ----------------------------------------------------------------- Course made
10390: # log existence
10391:     my $now = time;
10392:     my $newcourse = {
10393:                     $udom.'_'.$uname => {
10394:                                      description => $description,
10395:                                      inst_code   => $inst_code,
10396:                                      owner       => $course_owner,
10397:                                      type        => $crstype,
10398:                                      creator     => $env{'user.name'}.':'.
10399:                                                     $env{'user.domain'},
10400:                                      created     => $now,
10401:                                      context     => $context,
10402:                                                 },
10403:                     };
10404:     &courseidput($udom,$newcourse,$uhome,'notime');
10405: # set toplevel url
10406:     my $topurl=$url;
10407:     unless ($nonstandard) {
10408: # ------------------------------------------ For standard courses, make top url
10409:         my $mapurl=&clutter($url);
10410:         if ($mapurl eq '/res/') { $mapurl=''; }
10411:         $env{'form.initmap'}=(<<ENDINITMAP);
10412: <map>
10413: <resource id="1" type="start"></resource>
10414: <resource id="2" src="$mapurl"></resource>
10415: <resource id="3" type="finish"></resource>
10416: <link index="1" from="1" to="2"></link>
10417: <link index="2" from="2" to="3"></link>
10418: </map>
10419: ENDINITMAP
10420:         $topurl=&declutter(
10421:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
10422:                           );
10423:     }
10424: # ----------------------------------------------------------- Write preferences
10425:     &writecoursepref($udom.'_'.$uname,
10426:                      ('description'              => $description,
10427:                       'url'                      => $topurl,
10428:                       'internal.creator'         => $env{'user.name'}.':'.
10429:                                                     $env{'user.domain'},
10430:                       'internal.created'         => $now,
10431:                       'internal.creationcontext' => $context)
10432:                     );
10433:     return '/'.$udom.'/'.$uname;
10434: }
10435: 
10436: # ------------------------------------------------------------------- Create ID
10437: sub generate_coursenum {
10438:     my ($udom,$crstype) = @_;
10439:     my $domdesc = &domain($udom);
10440:     return 'error: invalid domain' if ($domdesc eq '');
10441:     my $first;
10442:     if ($crstype eq 'Community') {
10443:         $first = '0';
10444:     } else {
10445:         $first = int(1+rand(9)); 
10446:     } 
10447:     my $uname=$first.
10448:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
10449:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
10450:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
10451: # ----------------------------------------------- Make sure that does not exist
10452:     my $uhome=&homeserver($uname,$udom,'true');
10453:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
10454:         if ($crstype eq 'Community') {
10455:             $first = '0';
10456:         } else {
10457:             $first = int(1+rand(9));
10458:         }
10459:         $uname=$first.
10460:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
10461:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
10462:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
10463:         $uhome=&homeserver($uname,$udom,'true');
10464:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
10465:             return 'error: unable to generate unique course-ID';
10466:         }
10467:     }
10468:     return $uname;
10469: }
10470: 
10471: sub is_course {
10472:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
10473:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
10474:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
10475:     my $uhome=&homeserver($cnum,$cdom);
10476:     my $iscourse;
10477:     if (grep { $_ eq $uhome } current_machine_ids()) {
10478:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
10479:     } else {
10480:         my $hashid = $cdom.':'.$cnum;
10481:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
10482:         unless (defined($cached)) {
10483:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
10484:                                         $cnum,undef,undef,'.');
10485:             $iscourse = 0;
10486:             if (exists($courses{$cdom.'_'.$cnum})) {
10487:                 $iscourse = 1;
10488:             }
10489:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
10490:         }
10491:     }
10492:     return unless($iscourse);
10493:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
10494: }
10495: 
10496: sub store_userdata {
10497:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
10498:     my $result;
10499:     if ($datakey ne '') {
10500:         if (ref($storehash) eq 'HASH') {
10501:             if ($udom eq '' || $uname eq '') {
10502:                 $udom = $env{'user.domain'};
10503:                 $uname = $env{'user.name'};
10504:             }
10505:             my $uhome=&homeserver($uname,$udom);
10506:             if (($uhome eq '') || ($uhome eq 'no_host')) {
10507:                 $result = 'error: no_host';
10508:             } else {
10509:                 $storehash->{'ip'} = &get_requestor_ip();
10510:                 $storehash->{'host'} = $perlvar{'lonHostID'};
10511: 
10512:                 my $namevalue='';
10513:                 foreach my $key (keys(%{$storehash})) {
10514:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
10515:                 }
10516:                 $namevalue=~s/\&$//;
10517:                 unless ($namespace eq 'courserequests') {
10518:                     $datakey = &escape($datakey);
10519:                 }
10520:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
10521:                                   $namevalue,$uhome);
10522:             }
10523:         } else {
10524:             $result = 'error: data to store was not a hash reference'; 
10525:         }
10526:     } else {
10527:         $result= 'error: invalid requestkey'; 
10528:     }
10529:     return $result;
10530: }
10531: 
10532: # ---------------------------------------------------------- Assign Custom Role
10533: 
10534: sub assigncustomrole {
10535:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
10536:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
10537:                        $end,$start,$deleteflag,$selfenroll,$context);
10538: }
10539: 
10540: # ----------------------------------------------------------------- Revoke Role
10541: 
10542: sub revokerole {
10543:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
10544:     my $now=time;
10545:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
10546: }
10547: 
10548: # ---------------------------------------------------------- Revoke Custom Role
10549: 
10550: sub revokecustomrole {
10551:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
10552:     my $now=time;
10553:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
10554:            $deleteflag,$selfenroll,$context);
10555: }
10556: 
10557: # ------------------------------------------------------------ Disk usage
10558: sub diskusage {
10559:     my ($udom,$uname,$directorypath,$getpropath)=@_;
10560:     $directorypath =~ s/\/$//;
10561:     my $listing=&reply('du2:'.&escape($directorypath).':'
10562:                        .&escape($getpropath).':'.&escape($uname).':'
10563:                        .&escape($udom),homeserver($uname,$udom));
10564:     if ($listing eq 'unknown_cmd') {
10565:         if ($getpropath) {
10566:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
10567:         }
10568:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
10569:     }
10570:     return $listing;
10571: }
10572: 
10573: sub is_locked {
10574:     my ($file_name, $domain, $user, $which) = @_;
10575:     my @check;
10576:     my $is_locked;
10577:     push (@check,$file_name);
10578:     my %locked = &get('file_permissions',\@check,
10579: 		      $env{'user.domain'},$env{'user.name'});
10580:     my ($tmp)=keys(%locked);
10581:     if ($tmp=~/^error:/) { undef(%locked); }
10582:     
10583:     if (ref($locked{$file_name}) eq 'ARRAY') {
10584:         $is_locked = 'false';
10585:         foreach my $entry (@{$locked{$file_name}}) {
10586:            if (ref($entry) eq 'ARRAY') {
10587:                $is_locked = 'true';
10588:                if (ref($which) eq 'ARRAY') {
10589:                    push(@{$which},$entry);
10590:                } else {
10591:                    last;
10592:                }
10593:            }
10594:        }
10595:     } else {
10596:         $is_locked = 'false';
10597:     }
10598:     return $is_locked;
10599: }
10600: 
10601: sub declutter_portfile {
10602:     my ($file) = @_;
10603:     $file =~ s{^(/portfolio/|portfolio/)}{/};
10604:     return $file;
10605: }
10606: 
10607: # ------------------------------------------------------------- Mark as Read Only
10608: 
10609: sub mark_as_readonly {
10610:     my ($domain,$user,$files,$what) = @_;
10611:     my %current_permissions = &dump('file_permissions',$domain,$user);
10612:     my ($tmp)=keys(%current_permissions);
10613:     if ($tmp=~/^error:/) { undef(%current_permissions); }
10614:     foreach my $file (@{$files}) {
10615: 	$file = &declutter_portfile($file);
10616:         push(@{$current_permissions{$file}},$what);
10617:     }
10618:     &put('file_permissions',\%current_permissions,$domain,$user);
10619:     return;
10620: }
10621: 
10622: # ------------------------------------------------------------Save Selected Files
10623: 
10624: sub save_selected_files {
10625:     my ($user, $path, @files) = @_;
10626:     my $filename = $user."savedfiles";
10627:     my @other_files = &files_not_in_path($user, $path);
10628:     open (OUT,'>',LONCAPA::tempdir().$filename);
10629:     foreach my $file (@files) {
10630:         print (OUT $env{'form.currentpath'}.$file."\n");
10631:     }
10632:     foreach my $file (@other_files) {
10633:         print (OUT $file."\n");
10634:     }
10635:     close (OUT);
10636:     return 'ok';
10637: }
10638: 
10639: sub clear_selected_files {
10640:     my ($user) = @_;
10641:     my $filename = $user."savedfiles";
10642:     open (OUT,'>',LONCAPA::tempdir().$filename);
10643:     print (OUT undef);
10644:     close (OUT);
10645:     return ("ok");    
10646: }
10647: 
10648: sub files_in_path {
10649:     my ($user, $path) = @_;
10650:     my $filename = $user."savedfiles";
10651:     my %return_files;
10652:     open (IN,'<',LONCAPA::tempdir().$filename);
10653:     while (my $line_in = <IN>) {
10654:         chomp ($line_in);
10655:         my @paths_and_file = split (m!/!, $line_in);
10656:         my $file_part = pop (@paths_and_file);
10657:         my $path_part = join ('/', @paths_and_file);
10658:         $path_part.='/';
10659:         my $path_and_file = $path_part.$file_part;
10660:         if ($path_part eq $path) {
10661:             $return_files{$file_part}= 'selected';
10662:         }
10663:     }
10664:     close (IN);
10665:     return (\%return_files);
10666: }
10667: 
10668: # called in portfolio select mode, to show files selected NOT in current directory
10669: sub files_not_in_path {
10670:     my ($user, $path) = @_;
10671:     my $filename = $user."savedfiles";
10672:     my @return_files;
10673:     my $path_part;
10674:     open(IN, '<',LONCAPA::tempdir().$filename);
10675:     while (my $line = <IN>) {
10676:         #ok, I know it's clunky, but I want it to work
10677:         my @paths_and_file = split(m|/|, $line);
10678:         my $file_part = pop(@paths_and_file);
10679:         chomp($file_part);
10680:         my $path_part = join('/', @paths_and_file);
10681:         $path_part .= '/';
10682:         my $path_and_file = $path_part.$file_part;
10683:         if ($path_part ne $path) {
10684:             push(@return_files, ($path_and_file));
10685:         }
10686:     }
10687:     close(OUT);
10688:     return (@return_files);
10689: }
10690: 
10691: #----------------------------------------------Get portfolio file permissions
10692: 
10693: sub get_portfile_permissions {
10694:     my ($domain,$user) = @_;
10695:     my %current_permissions = &dump('file_permissions',$domain,$user);
10696:     my ($tmp)=keys(%current_permissions);
10697:     if ($tmp=~/^error:/) { undef(%current_permissions); }
10698:     return \%current_permissions;
10699: }
10700: 
10701: #---------------------------------------------Get portfolio file access controls
10702: 
10703: sub get_access_controls {
10704:     my ($current_permissions,$group,$file) = @_;
10705:     my %access;
10706:     my $real_file = $file;
10707:     $file =~ s/\.meta$//;
10708:     if (defined($file)) {
10709:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
10710:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
10711:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
10712:             }
10713:         }
10714:     } else {
10715:         foreach my $key (keys(%{$current_permissions})) {
10716:             if ($key =~ /\0accesscontrol$/) {
10717:                 if (defined($group)) {
10718:                     if ($key !~ m-^\Q$group\E/-) {
10719:                         next;
10720:                     }
10721:                 }
10722:                 my ($fullpath) = split(/\0/,$key);
10723:                 if (ref($$current_permissions{$key}) eq 'HASH') {
10724:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
10725:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
10726:                     }
10727:                 }
10728:             }
10729:         }
10730:     }
10731:     return %access;
10732: }
10733: 
10734: sub modify_access_controls {
10735:     my ($file_name,$changes,$domain,$user)=@_;
10736:     my ($outcome,$deloutcome);
10737:     my %store_permissions;
10738:     my %new_values;
10739:     my %new_control;
10740:     my %translation;
10741:     my @deletions = ();
10742:     my $now = time;
10743:     if (exists($$changes{'activate'})) {
10744:         if (ref($$changes{'activate'}) eq 'HASH') {
10745:             my @newitems = sort(keys(%{$$changes{'activate'}}));
10746:             my $numnew = scalar(@newitems);
10747:             for (my $i=0; $i<$numnew; $i++) {
10748:                 my $newkey = $newitems[$i];
10749:                 my $newid = &Apache::loncommon::get_cgi_id();
10750:                 if ($newkey =~ /^\d+:/) { 
10751:                     $newkey =~ s/^(\d+)/$newid/;
10752:                     $translation{$1} = $newid;
10753:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
10754:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
10755:                     $translation{$1} = $newid;
10756:                 }
10757:                 $new_values{$file_name."\0".$newkey} = 
10758:                                           $$changes{'activate'}{$newitems[$i]};
10759:                 $new_control{$newkey} = $now;
10760:             }
10761:         }
10762:     }
10763:     my %todelete;
10764:     my %changed_items;
10765:     foreach my $action ('delete','update') {
10766:         if (exists($$changes{$action})) {
10767:             if (ref($$changes{$action}) eq 'HASH') {
10768:                 foreach my $key (keys(%{$$changes{$action}})) {
10769:                     my ($itemnum) = ($key =~ /^([^:]+):/);
10770:                     if ($action eq 'delete') { 
10771:                         $todelete{$itemnum} = 1;
10772:                     } else {
10773:                         $changed_items{$itemnum} = $key;
10774:                     }
10775:                 }
10776:             }
10777:         }
10778:     }
10779:     # get lock on access controls for file.
10780:     my $lockhash = {
10781:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
10782:                                                        ':'.$env{'user.domain'},
10783:                    }; 
10784:     my $tries = 0;
10785:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
10786:    
10787:     while (($gotlock ne 'ok') && $tries < 10) {
10788:         $tries ++;
10789:         sleep(0.1);
10790:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
10791:     }
10792:     if ($gotlock eq 'ok') {
10793:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
10794:         my ($tmp)=keys(%curr_permissions);
10795:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
10796:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
10797:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
10798:             if (ref($curr_controls) eq 'HASH') {
10799:                 foreach my $control_item (keys(%{$curr_controls})) {
10800:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
10801:                     if (defined($todelete{$itemnum})) {
10802:                         push(@deletions,$file_name."\0".$control_item);
10803:                     } else {
10804:                         if (defined($changed_items{$itemnum})) {
10805:                             $new_control{$changed_items{$itemnum}} = $now;
10806:                             push(@deletions,$file_name."\0".$control_item);
10807:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
10808:                         } else {
10809:                             $new_control{$control_item} = $$curr_controls{$control_item};
10810:                         }
10811:                     }
10812:                 }
10813:             }
10814:         }
10815:         my ($group);
10816:         if (&is_course($domain,$user)) {
10817:             ($group,my $file) = split(/\//,$file_name,2);
10818:         }
10819:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
10820:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
10821:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
10822:         #  remove lock
10823:         my @del_lock = ($file_name."\0".'locked_access_records');
10824:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
10825:         my $sqlresult =
10826:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
10827:                                     $group);
10828:     } else {
10829:         $outcome = "error: could not obtain lockfile\n";  
10830:     }
10831:     return ($outcome,$deloutcome,\%new_values,\%translation);
10832: }
10833: 
10834: sub make_public_indefinitely {
10835:     my ($requrl) = @_;
10836:     my $now = time;
10837:     my $action = 'activate';
10838:     my $aclnum = 0;
10839:     if (&is_portfolio_url($requrl)) {
10840:         my (undef,$udom,$unum,$file_name,$group) =
10841:             &parse_portfolio_url($requrl);
10842:         my $current_perms = &get_portfile_permissions($udom,$unum);
10843:         my %access_controls = &get_access_controls($current_perms,
10844:                                                    $group,$file_name);
10845:         foreach my $key (keys(%{$access_controls{$file_name}})) {
10846:             my ($num,$scope,$end,$start) = 
10847:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
10848:             if ($scope eq 'public') {
10849:                 if ($start <= $now && $end == 0) {
10850:                     $action = 'none';
10851:                 } else {
10852:                     $action = 'update';
10853:                     $aclnum = $num;
10854:                 }
10855:                 last;
10856:             }
10857:         }
10858:         if ($action eq 'none') {
10859:              return 'ok';
10860:         } else {
10861:             my %changes;
10862:             my $newend = 0;
10863:             my $newstart = $now;
10864:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
10865:             $changes{$action}{$newkey} = {
10866:                 type => 'public',
10867:                 time => {
10868:                     start => $newstart,
10869:                     end   => $newend,
10870:                 },
10871:             };
10872:             my ($outcome,$deloutcome,$new_values,$translation) =
10873:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
10874:             return $outcome;
10875:         }
10876:     } else {
10877:         return 'invalid';
10878:     }
10879: }
10880: 
10881: #------------------------------------------------------Get Marked as Read Only
10882: 
10883: sub get_marked_as_readonly {
10884:     my ($domain,$user,$what,$group) = @_;
10885:     my $current_permissions = &get_portfile_permissions($domain,$user);
10886:     my @readonly_files;
10887:     my $cmp1=$what;
10888:     if (ref($what)) { $cmp1=join('',@{$what}) };
10889:     while (my ($file_name,$value) = each(%{$current_permissions})) {
10890:         if (defined($group)) {
10891:             if ($file_name !~ m-^\Q$group\E/-) {
10892:                 next;
10893:             }
10894:         }
10895:         if (ref($value) eq "ARRAY"){
10896:             foreach my $stored_what (@{$value}) {
10897:                 my $cmp2=$stored_what;
10898:                 if (ref($stored_what) eq 'ARRAY') {
10899:                     $cmp2=join('',@{$stored_what});
10900:                 }
10901:                 if ($cmp1 eq $cmp2) {
10902:                     push(@readonly_files, $file_name);
10903:                     last;
10904:                 } elsif (!defined($what)) {
10905:                     push(@readonly_files, $file_name);
10906:                     last;
10907:                 }
10908:             }
10909:         }
10910:     }
10911:     return @readonly_files;
10912: }
10913: #-----------------------------------------------------------Get Marked as Read Only Hash
10914: 
10915: sub get_marked_as_readonly_hash {
10916:     my ($current_permissions,$group,$what) = @_;
10917:     my %readonly_files;
10918:     while (my ($file_name,$value) = each(%{$current_permissions})) {
10919:         if (defined($group)) {
10920:             if ($file_name !~ m-^\Q$group\E/-) {
10921:                 next;
10922:             }
10923:         }
10924:         if (ref($value) eq "ARRAY"){
10925:             foreach my $stored_what (@{$value}) {
10926:                 if (ref($stored_what) eq 'ARRAY') {
10927:                     foreach my $lock_descriptor(@{$stored_what}) {
10928:                         if ($lock_descriptor eq 'graded') {
10929:                             $readonly_files{$file_name} = 'graded';
10930:                         } elsif ($lock_descriptor eq 'handback') {
10931:                             $readonly_files{$file_name} = 'handback';
10932:                         } else {
10933:                             if (!exists($readonly_files{$file_name})) {
10934:                                 $readonly_files{$file_name} = 'locked';
10935:                             }
10936:                         }
10937:                     }
10938:                 } 
10939:             }
10940:         } 
10941:     }
10942:     return %readonly_files;
10943: }
10944: # ------------------------------------------------------------ Unmark as Read Only
10945: 
10946: sub unmark_as_readonly {
10947:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
10948:     # for portfolio submissions, $what contains [$symb,$crsid] 
10949:     my ($domain,$user,$what,$file_name,$group) = @_;
10950:     $file_name = &declutter_portfile($file_name);
10951:     my $symb_crs = $what;
10952:     if (ref($what)) { $symb_crs=join('',@$what); }
10953:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
10954:     my ($tmp)=keys(%current_permissions);
10955:     if ($tmp=~/^error:/) { undef(%current_permissions); }
10956:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
10957:     foreach my $file (@readonly_files) {
10958: 	my $clean_file = &declutter_portfile($file);
10959: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
10960: 	my $current_locks = $current_permissions{$file};
10961:         my @new_locks;
10962:         my @del_keys;
10963:         if (ref($current_locks) eq "ARRAY"){
10964:             foreach my $locker (@{$current_locks}) {
10965:                 my $compare=$locker;
10966:                 if (ref($locker) eq 'ARRAY') {
10967:                     $compare=join('',@{$locker});
10968:                     if ($compare ne $symb_crs) {
10969:                         push(@new_locks, $locker);
10970:                     }
10971:                 }
10972:             }
10973:             if (scalar(@new_locks) > 0) {
10974:                 $current_permissions{$file} = \@new_locks;
10975:             } else {
10976:                 push(@del_keys, $file);
10977:                 &del('file_permissions',\@del_keys, $domain, $user);
10978:                 delete($current_permissions{$file});
10979:             }
10980:         }
10981:     }
10982:     &put('file_permissions',\%current_permissions,$domain,$user);
10983:     return;
10984: }
10985: 
10986: # ------------------------------------------------------------ Directory lister
10987: 
10988: sub dirlist {
10989:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
10990:     $uri=~s/^\///;
10991:     $uri=~s/\/$//;
10992:     my ($udom, $uname);
10993:     if ($getuserdir) {
10994:         $udom = $userdomain;
10995:         $uname = $username;
10996:     } else {
10997:         (undef,$udom,$uname)=split(/\//,$uri);
10998:         if(defined($userdomain)) {
10999:             $udom = $userdomain;
11000:         }
11001:         if(defined($username)) {
11002:             $uname = $username;
11003:         }
11004:     }
11005:     my ($dirRoot,$listing,@listing_results);
11006: 
11007:     $dirRoot = $perlvar{'lonDocRoot'};
11008:     if (defined($getpropath)) {
11009:         $dirRoot = &propath($udom,$uname);
11010:         $dirRoot =~ s/\/$//;
11011:     } elsif (defined($getuserdir)) {
11012:         my $subdir=$uname.'__';
11013:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
11014:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
11015:                    ."/$udom/$subdir/$uname";
11016:     } elsif (defined($alternateRoot)) {
11017:         $dirRoot = $alternateRoot;
11018:     }
11019: 
11020:     if($udom) {
11021:         if($uname) {
11022:             my $uhome = &homeserver($uname,$udom);
11023:             if ($uhome eq 'no_host') {
11024:                 return ([],'no_host');
11025:             }
11026:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
11027:                               .$getuserdir.':'.&escape($dirRoot)
11028:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
11029:             if ($listing eq 'unknown_cmd') {
11030:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
11031:             } else {
11032:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
11033:             }
11034:             if ($listing eq 'unknown_cmd') {
11035:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
11036:                 @listing_results = split(/:/,$listing);
11037:             } else {
11038:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
11039:             }
11040:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
11041:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
11042:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11043:                 return ([],$listing);
11044:             } else {
11045:                 return (\@listing_results);
11046:             }
11047:         } elsif(!$alternateRoot) {
11048:             my (%allusers,%listerror);
11049: 	    my %servers = &get_servers($udom,'library');
11050:  	    foreach my $tryserver (keys(%servers)) {
11051:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
11052:                                   &escape($udom),$tryserver);
11053:                 if ($listing eq 'unknown_cmd') {
11054: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
11055: 				      $udom, $tryserver);
11056:                 } else {
11057:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
11058:                 }
11059: 		if ($listing eq 'unknown_cmd') {
11060: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
11061: 				      $udom, $tryserver);
11062: 		    @listing_results = split(/:/,$listing);
11063: 		} else {
11064: 		    @listing_results =
11065: 			map { &unescape($_); } split(/:/,$listing);
11066: 		}
11067:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
11068:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
11069:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11070:                     $listerror{$tryserver} = $listing;
11071:                 } else {
11072: 		    foreach my $line (@listing_results) {
11073: 			my ($entry) = split(/&/,$line,2);
11074: 			$allusers{$entry} = 1;
11075: 		    }
11076: 		}
11077:             }
11078:             my @alluserslist=();
11079:             foreach my $user (sort(keys(%allusers))) {
11080:                 push(@alluserslist,$user.'&user');
11081:             }
11082:             if (!%listerror) {
11083:                 # no errors
11084:                 return (\@alluserslist);
11085:             } elsif (scalar(keys(%servers)) == 1) {
11086:                 # one library server, one error
11087:                 my ($key) = keys(%listerror);
11088:                 return (\@alluserslist, $listerror{$key});
11089:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
11090:                 # con_lost indicates that we might miss data from at least one
11091:                 # library server
11092:                 return (\@alluserslist, 'con_lost');
11093:             } else {
11094:                 # multiple library servers and no con_lost -> data should be
11095:                 # complete.
11096:                 return (\@alluserslist);
11097:             }
11098: 
11099:         } else {
11100:             return ([],'missing username');
11101:         }
11102:     } elsif(!defined($getpropath)) {
11103:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
11104:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
11105:         return (\@all_domains);
11106:     } else {
11107:         return ([],'missing domain');
11108:     }
11109: }
11110: 
11111: # --------------------------------------------- GetFileTimestamp
11112: # This function utilizes dirlist and returns the date stamp for
11113: # when it was last modified.  It will also return an error of -1
11114: # if an error occurs
11115: 
11116: sub GetFileTimestamp {
11117:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
11118:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
11119:     $studentName   = &LONCAPA::clean_username($studentName);
11120:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
11121:                                     undef,$getuserdir);
11122:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11123:         return -1;
11124:     }
11125:     if (ref($fileref) eq 'ARRAY') {
11126:         my @stats = split('&',$fileref->[0]);
11127:         # @stats contains first the filename, then the stat output
11128:         return $stats[10]; # so this is 10 instead of 9.
11129:     } else {
11130:         return -1;
11131:     }
11132: }
11133: 
11134: sub stat_file {
11135:     my ($uri) = @_;
11136:     $uri = &clutter_with_no_wrapper($uri);
11137: 
11138:     my ($udom,$uname,$file);
11139:     if ($uri =~ m-^/(uploaded|editupload)/-) {
11140: 	($udom,$uname,$file) =
11141: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
11142: 	$file = 'userfiles/'.$file;
11143:     }
11144:     if ($uri =~ m-^/res/-) {
11145: 	($udom,$uname) = 
11146: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
11147: 	$file = $uri;
11148:     }
11149: 
11150:     if (!$udom || !$uname || !$file) {
11151: 	# unable to handle the uri
11152: 	return ();
11153:     }
11154:     my $getpropath;
11155:     if ($file =~ /^userfiles\//) {
11156:         $getpropath = 1;
11157:     }
11158:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
11159:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11160:         return ();
11161:     } else {
11162:         if (ref($listref) eq 'ARRAY') {
11163:             my @stats = split('&',$listref->[0]);
11164: 	    shift(@stats); #filename is first
11165: 	    return @stats;
11166:         }
11167:     }
11168:     return ();
11169: }
11170: 
11171: # -------------------------------------------------------- Value of a Condition
11172: 
11173: # gets the value of a specific preevaluated condition
11174: #    stored in the string  $env{user.state.<cid>}
11175: # or looks up a condition reference in the bighash and if if hasn't
11176: # already been evaluated recurses into docondval to get the value of
11177: # the condition, then memoizing it to 
11178: #   $env{user.state.<cid>.<condition>}
11179: sub directcondval {
11180:     my $number=shift;
11181:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
11182: 	&Apache::lonuserstate::evalstate();
11183:     }
11184:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
11185: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
11186:     } elsif ($number =~ /^_/) {
11187: 	my $sub_condition;
11188: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
11189: 		&GDBM_READER(),0640)) {
11190: 	    $sub_condition=$bighash{'conditions'.$number};
11191: 	    untie(%bighash);
11192: 	}
11193: 	my $value = &docondval($sub_condition);
11194: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
11195: 	return $value;
11196:     }
11197:     if ($env{'user.state.'.$env{'request.course.id'}}) {
11198:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
11199:     } else {
11200:        return 2;
11201:     }
11202: }
11203: 
11204: # get the collection of conditions for this resource
11205: sub condval {
11206:     my $condidx=shift;
11207:     my $allpathcond='';
11208:     foreach my $cond (split(/\|/,$condidx)) {
11209: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
11210: 	    $allpathcond.=
11211: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
11212: 	}
11213:     }
11214:     $allpathcond=~s/\|$//;
11215:     return &docondval($allpathcond);
11216: }
11217: 
11218: #evaluates an expression of conditions
11219: sub docondval {
11220:     my ($allpathcond) = @_;
11221:     my $result=0;
11222:     if ($env{'request.course.id'}
11223: 	&& defined($allpathcond)) {
11224: 	my $operand='|';
11225: 	my @stack;
11226: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
11227: 	    if ($chunk eq '(') {
11228: 		push @stack,($operand,$result);
11229: 	    } elsif ($chunk eq ')') {
11230: 		my $before=pop @stack;
11231: 		if (pop @stack eq '&') {
11232: 		    $result=$result>$before?$before:$result;
11233: 		} else {
11234: 		    $result=$result>$before?$result:$before;
11235: 		}
11236: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
11237: 		$operand=$chunk;
11238: 	    } else {
11239: 		my $new=directcondval($chunk);
11240: 		if ($operand eq '&') {
11241: 		    $result=$result>$new?$new:$result;
11242: 		} else {
11243: 		    $result=$result>$new?$result:$new;
11244: 		}
11245: 	    }
11246: 	}
11247:     }
11248:     return $result;
11249: }
11250: 
11251: # ---------------------------------------------------- Devalidate courseresdata
11252: 
11253: sub devalidatecourseresdata {
11254:     my ($coursenum,$coursedomain)=@_;
11255:     my $hashid=$coursenum.':'.$coursedomain;
11256:     &devalidate_cache_new('courseres',$hashid);
11257: }
11258: 
11259: 
11260: # --------------------------------------------------- Course Resourcedata Query
11261: #
11262: #  Parameters:
11263: #      $coursenum    - Number of the course.
11264: #      $coursedomain - Domain at which the course was created.
11265: #  Returns:
11266: #     A hash of the course parameters along (I think) with timestamps
11267: #     and version info.
11268: 
11269: sub get_courseresdata {
11270:     my ($coursenum,$coursedomain)=@_;
11271:     my $coursehom=&homeserver($coursenum,$coursedomain);
11272:     my $hashid=$coursenum.':'.$coursedomain;
11273:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
11274:     my %dumpreply;
11275:     unless (defined($cached)) {
11276: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
11277: 	$result=\%dumpreply;
11278: 	my ($tmp) = keys(%dumpreply);
11279: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
11280: 	    &do_cache_new('courseres',$hashid,$result,600);
11281: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
11282: 	    return $tmp;
11283: 	} elsif ($tmp =~ /^(error)/) {
11284: 	    $result=undef;
11285: 	    &do_cache_new('courseres',$hashid,$result,600);
11286: 	}
11287:     }
11288:     return $result;
11289: }
11290: 
11291: sub devalidateuserresdata {
11292:     my ($uname,$udom)=@_;
11293:     my $hashid="$udom:$uname";
11294:     &devalidate_cache_new('userres',$hashid);
11295: }
11296: 
11297: sub get_userresdata {
11298:     my ($uname,$udom)=@_;
11299:     #most student don\'t have any data set, check if there is some data
11300:     if (&EXT_cache_status($udom,$uname)) { return undef; }
11301: 
11302:     my $hashid="$udom:$uname";
11303:     my ($result,$cached)=&is_cached_new('userres',$hashid);
11304:     if (!defined($cached)) {
11305: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
11306: 	$result=\%resourcedata;
11307: 	&do_cache_new('userres',$hashid,$result,600);
11308:     }
11309:     my ($tmp)=keys(%$result);
11310:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
11311: 	return $result;
11312:     }
11313:     #error 2 occurs when the .db doesn't exist
11314:     if ($tmp!~/error: 2 /) {
11315:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
11316: 	    &logthis("<font color=\"blue\">WARNING:".
11317: 		     " Trying to get resource data for ".
11318: 		     $uname." at ".$udom.": ".
11319: 		     $tmp."</font>");
11320:         }
11321:     } elsif ($tmp=~/error: 2 /) {
11322: 	#&EXT_cache_set($udom,$uname);
11323: 	&do_cache_new('userres',$hashid,undef,600);
11324: 	undef($tmp); # not really an error so don't send it back
11325:     }
11326:     return $tmp;
11327: }
11328: #----------------------------------------------- resdata - return resource data
11329: #  Purpose:
11330: #    Return resource data for either users or for a course.
11331: #  Parameters:
11332: #     $name      - Course/user name.
11333: #     $domain    - Name of the domain the user/course is registered on.
11334: #     $type      - Type of thing $name is (must be 'course' or 'user'
11335: #     @which     - Array of names of resources desired.
11336: #  Returns:
11337: #     The value of the first reasource in @which that is found in the
11338: #     resource hash.
11339: #  Exceptional Conditions:
11340: #     If the $type passed in is not valid (not the string 'course' or 
11341: #     'user', an undefined  reference is returned.
11342: #     If none of the resources are found, an undef is returned
11343: sub resdata {
11344:     my ($name,$domain,$type,@which)=@_;
11345:     my $result;
11346:     if ($type eq 'course') {
11347: 	$result=&get_courseresdata($name,$domain);
11348:     } elsif ($type eq 'user') {
11349: 	$result=&get_userresdata($name,$domain);
11350:     }
11351:     if (!ref($result)) { return $result; }    
11352:     foreach my $item (@which) {
11353: 	if (defined($result->{$item->[0]})) {
11354: 	    return [$result->{$item->[0]},$item->[1]];
11355: 	}
11356:     }
11357:     return undef;
11358: }
11359: 
11360: sub get_numsuppfiles {
11361:     my ($cnum,$cdom,$ignorecache)=@_;
11362:     my $hashid=$cnum.':'.$cdom;
11363:     my ($suppcount,$cached);
11364:     unless ($ignorecache) {
11365:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
11366:     }
11367:     unless (defined($cached)) {
11368:         my $chome=&homeserver($cnum,$cdom);
11369:         unless ($chome eq 'no_host') {
11370:             ($suppcount,my $errors) = (0,0);
11371:             my $suppmap = 'supplemental.sequence';
11372:             ($suppcount,$errors) =
11373:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
11374:         }
11375:         &do_cache_new('suppcount',$hashid,$suppcount,600);
11376:     }
11377:     return $suppcount;
11378: }
11379: 
11380: #
11381: # EXT resource caching routines
11382: #
11383: 
11384: sub clear_EXT_cache_status {
11385:     &delenv('cache.EXT.');
11386: }
11387: 
11388: sub EXT_cache_status {
11389:     my ($target_domain,$target_user) = @_;
11390:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
11391:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
11392:         # We know already the user has no data
11393:         return 1;
11394:     } else {
11395:         return 0;
11396:     }
11397: }
11398: 
11399: sub EXT_cache_set {
11400:     my ($target_domain,$target_user) = @_;
11401:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
11402:     #&appenv({$cachename => time});
11403: }
11404: 
11405: # --------------------------------------------------------- Value of a Variable
11406: sub EXT {
11407: 
11408:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
11409:     unless ($varname) { return ''; }
11410:     #get real user name/domain, courseid and symb
11411:     my $courseid;
11412:     my $publicuser;
11413:     if ($symbparm) {
11414: 	$symbparm=&get_symb_from_alias($symbparm);
11415:     }
11416:     if (!($uname && $udom)) {
11417:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
11418:       if (!$symbparm) {	$symbparm=$cursymb; }
11419:     } else {
11420: 	$courseid=$env{'request.course.id'};
11421:     }
11422:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
11423:     my $rest;
11424:     if (defined($therest[0])) {
11425:        $rest=join('.',@therest);
11426:     } else {
11427:        $rest='';
11428:     }
11429: 
11430:     my $qualifierrest=$qualifier;
11431:     if ($rest) { $qualifierrest.='.'.$rest; }
11432:     my $spacequalifierrest=$space;
11433:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
11434:     if ($realm eq 'user') {
11435: # --------------------------------------------------------------- user.resource
11436: 	if ($space eq 'resource') {
11437: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
11438: 		  || defined($Apache::lonhomework::parsing_a_task))
11439: 		 &&
11440: 		 ($symbparm eq &symbread()) ) {	
11441: 		# if we are in the middle of processing the resource the
11442: 		# get the value we are planning on committing
11443:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
11444:                     return $Apache::lonhomework::results{$qualifierrest};
11445:                 } else {
11446:                     return $Apache::lonhomework::history{$qualifierrest};
11447:                 }
11448: 	    } else {
11449: 		my %restored;
11450: 		if ($publicuser || $env{'request.state'} eq 'construct') {
11451: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
11452: 		} else {
11453: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
11454: 		}
11455: 		return $restored{$qualifierrest};
11456: 	    }
11457: # ----------------------------------------------------------------- user.access
11458:         } elsif ($space eq 'access') {
11459: 	    # FIXME - not supporting calls for a specific user
11460:             return &allowed($qualifier,$rest);
11461: # ------------------------------------------ user.preferences, user.environment
11462:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
11463: 	    if (($uname eq $env{'user.name'}) &&
11464: 		($udom eq $env{'user.domain'})) {
11465: 		return $env{join('.',('environment',$qualifierrest))};
11466: 	    } else {
11467: 		my %returnhash;
11468: 		if (!$publicuser) {
11469: 		    %returnhash=&userenvironment($udom,$uname,
11470: 						 $qualifierrest);
11471: 		}
11472: 		return $returnhash{$qualifierrest};
11473: 	    }
11474: # ----------------------------------------------------------------- user.course
11475:         } elsif ($space eq 'course') {
11476: 	    # FIXME - not supporting calls for a specific user
11477:             return $env{join('.',('request.course',$qualifier))};
11478: # ------------------------------------------------------------------- user.role
11479:         } elsif ($space eq 'role') {
11480: 	    # FIXME - not supporting calls for a specific user
11481:             my ($role,$where)=split(/\./,$env{'request.role'});
11482:             if ($qualifier eq 'value') {
11483: 		return $role;
11484:             } elsif ($qualifier eq 'extent') {
11485:                 return $where;
11486:             }
11487: # ----------------------------------------------------------------- user.domain
11488:         } elsif ($space eq 'domain') {
11489:             return $udom;
11490: # ------------------------------------------------------------------- user.name
11491:         } elsif ($space eq 'name') {
11492:             return $uname;
11493: # ---------------------------------------------------- Any other user namespace
11494:         } else {
11495: 	    my %reply;
11496: 	    if (!$publicuser) {
11497: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
11498: 	    }
11499: 	    return $reply{$qualifierrest};
11500:         }
11501:     } elsif ($realm eq 'query') {
11502: # ---------------------------------------------- pull stuff out of query string
11503:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
11504: 						[$spacequalifierrest]);
11505: 	return $env{'form.'.$spacequalifierrest}; 
11506:    } elsif ($realm eq 'request') {
11507: # ------------------------------------------------------------- request.browser
11508:         if ($space eq 'browser') {
11509:             return $env{'browser.'.$qualifier};
11510: # ------------------------------------------------------------ request.filename
11511:         } else {
11512:             return $env{'request.'.$spacequalifierrest};
11513:         }
11514:     } elsif ($realm eq 'course') {
11515: # ---------------------------------------------------------- course.description
11516:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
11517:     } elsif ($realm eq 'resource') {
11518: 
11519: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
11520: 	    if (!$symbparm) { $symbparm=&symbread(); }
11521: 	}
11522: 
11523:         if ($qualifier eq '') {
11524: 	    if ($space eq 'title') {
11525: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
11526: 	        return &gettitle($symbparm);
11527: 	    }
11528: 	
11529: 	    if ($space eq 'map') {
11530: 	        my ($map) = &decode_symb($symbparm);
11531: 	        return &symbread($map);
11532: 	    }
11533:             if ($space eq 'maptitle') {
11534:                 my ($map) = &decode_symb($symbparm);
11535:                 return &gettitle($map);
11536:             }
11537: 	    if ($space eq 'filename') {
11538: 	        if ($symbparm) {
11539: 		    return &clutter((&decode_symb($symbparm))[2]);
11540: 	        }
11541: 	        return &hreflocation('',$env{'request.filename'});
11542: 	    }
11543: 
11544:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
11545:                 if ($space eq 'visibleparts') {
11546:                     my $navmap = Apache::lonnavmaps::navmap->new();
11547:                     my $item;
11548:                     if (ref($navmap)) {
11549:                         my $res = $navmap->getBySymb($symbparm);
11550:                         my $parts = $res->parts();
11551:                         if (ref($parts) eq 'ARRAY') {
11552:                             $item = join(',',@{$parts});
11553:                         }
11554:                         undef($navmap);
11555:                     }
11556:                     return $item;
11557:                 }
11558:             }
11559:         }
11560: 
11561: 	my ($section, $group, @groups);
11562: 	my ($courselevelm,$courselevel);
11563:         if (($courseid eq '') && ($cid)) {
11564:             $courseid = $cid;
11565:         }
11566: 	if (($symbparm && $courseid) && 
11567: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
11568: 
11569: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
11570: 
11571: # ----------------------------------------------------- Cascading lookup scheme
11572: 	    my $symbp=$symbparm;
11573: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
11574: 
11575: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
11576: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
11577: 
11578: 	    if (($env{'user.name'} eq $uname) &&
11579: 		($env{'user.domain'} eq $udom)) {
11580: 		$section=$env{'request.course.sec'};
11581:                 @groups = split(/:/,$env{'request.course.groups'});  
11582:                 @groups=&sort_course_groups($courseid,@groups); 
11583: 	    } else {
11584: 		if (! defined($usection)) {
11585: 		    $section=&getsection($udom,$uname,$courseid);
11586: 		} else {
11587: 		    $section = $usection;
11588: 		}
11589:                 @groups = &get_users_groups($udom,$uname,$courseid);
11590: 	    }
11591: 
11592: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
11593: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
11594: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
11595: 
11596: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
11597: 	    my $courselevelr=$courseid.'.'.$symbparm;
11598: 	    $courselevelm=$courseid.'.'.$mapparm;
11599: 
11600: # ----------------------------------------------------------- first, check user
11601: 
11602: 	    my $userreply=&resdata($uname,$udom,'user',
11603: 				       ([$courselevelr,'resource'],
11604: 					[$courselevelm,'map'     ],
11605: 					[$courselevel, 'course'  ]));
11606: 	    if (defined($userreply)) { return &get_reply($userreply); }
11607: 
11608: # ------------------------------------------------ second, check some of course
11609:             my $coursereply;
11610:             if (@groups > 0) {
11611:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
11612:                                        $mapparm,$spacequalifierrest);
11613:                 if (defined($coursereply)) { return &get_reply($coursereply); }
11614:             }
11615: 
11616: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
11617: 				  $env{'course.'.$courseid.'.domain'},
11618: 				  'course',
11619: 				  ([$seclevelr,   'resource'],
11620: 				   [$seclevelm,   'map'     ],
11621: 				   [$seclevel,    'course'  ],
11622: 				   [$courselevelr,'resource']));
11623: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
11624: 
11625: # ------------------------------------------------------ third, check map parms
11626: 	    my %parmhash=();
11627: 	    my $thisparm='';
11628: 	    if (tie(%parmhash,'GDBM_File',
11629: 		    $env{'request.course.fn'}.'_parms.db',
11630: 		    &GDBM_READER(),0640)) {
11631: 		$thisparm=$parmhash{$symbparm};
11632: 		untie(%parmhash);
11633: 	    }
11634: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
11635: 	}
11636: # ------------------------------------------ fourth, look in resource metadata
11637: 
11638: 	$spacequalifierrest=~s/\./\_/;
11639: 	my $filename;
11640: 	if (!$symbparm) { $symbparm=&symbread(); }
11641: 	if ($symbparm) {
11642: 	    $filename=(&decode_symb($symbparm))[2];
11643: 	} else {
11644: 	    $filename=$env{'request.filename'};
11645: 	}
11646: 	my $metadata=&metadata($filename,$spacequalifierrest);
11647: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
11648: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
11649: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
11650: 
11651: # ---------------------------------------------- fourth, look in rest of course
11652: 	if ($symbparm && defined($courseid) && 
11653: 	    $courseid eq $env{'request.course.id'}) {
11654: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
11655: 				     $env{'course.'.$courseid.'.domain'},
11656: 				     'course',
11657: 				     ([$courselevelm,'map'   ],
11658: 				      [$courselevel, 'course']));
11659: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
11660: 	}
11661: # ------------------------------------------------------------------ Cascade up
11662: 	unless ($space eq '0') {
11663: 	    my @parts=split(/_/,$space);
11664: 	    my $id=pop(@parts);
11665: 	    my $part=join('_',@parts);
11666: 	    if ($part eq '') { $part='0'; }
11667: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
11668: 				 $symbparm,$udom,$uname,$section,1);
11669: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
11670: 	}
11671: 	if ($recurse) { return undef; }
11672: 	my $pack_def=&packages_tab_default($filename,$varname);
11673: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
11674: # ---------------------------------------------------- Any other user namespace
11675:     } elsif ($realm eq 'environment') {
11676: # ----------------------------------------------------------------- environment
11677: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
11678: 	    return $env{'environment.'.$spacequalifierrest};
11679: 	} else {
11680: 	    if ($uname eq 'anonymous' && $udom eq '') {
11681: 		return '';
11682: 	    }
11683: 	    my %returnhash=&userenvironment($udom,$uname,
11684: 					    $spacequalifierrest);
11685: 	    return $returnhash{$spacequalifierrest};
11686: 	}
11687:     } elsif ($realm eq 'system') {
11688: # ----------------------------------------------------------------- system.time
11689: 	if ($space eq 'time') {
11690: 	    return time;
11691:         }
11692:     } elsif ($realm eq 'server') {
11693: # ----------------------------------------------------------------- system.time
11694: 	if ($space eq 'name') {
11695: 	    return $ENV{'SERVER_NAME'};
11696:         }
11697:     }
11698:     return '';
11699: }
11700: 
11701: sub get_reply {
11702:     my ($reply_value) = @_;
11703:     if (ref($reply_value) eq 'ARRAY') {
11704:         if (wantarray) {
11705: 	    return @$reply_value;
11706:         }
11707:         return $reply_value->[0];
11708:     } else {
11709:         return $reply_value;
11710:     }
11711: }
11712: 
11713: sub check_group_parms {
11714:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
11715:     my @groupitems = ();
11716:     my $resultitem;
11717:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
11718:     foreach my $group (@{$groups}) {
11719:         foreach my $level (@levels) {
11720:              my $item = $courseid.'.['.$group.'].'.$level->[0];
11721:              push(@groupitems,[$item,$level->[1]]);
11722:         }
11723:     }
11724:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
11725:                             $env{'course.'.$courseid.'.domain'},
11726:                                      'course',@groupitems);
11727:     return $coursereply;
11728: }
11729: 
11730: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
11731:     my ($courseid,@groups) = @_;
11732:     @groups = sort(@groups);
11733:     return @groups;
11734: }
11735: 
11736: sub packages_tab_default {
11737:     my ($uri,$varname)=@_;
11738:     my (undef,$part,$name)=split(/\./,$varname);
11739: 
11740:     my (@extension,@specifics,$do_default);
11741:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
11742: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
11743: 	if ($pack_type eq 'default') {
11744: 	    $do_default=1;
11745: 	} elsif ($pack_type eq 'extension') {
11746: 	    push(@extension,[$package,$pack_type,$pack_part]);
11747: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
11748: 	    # only look at packages defaults for packages that this id is
11749: 	    push(@specifics,[$package,$pack_type,$pack_part]);
11750: 	}
11751:     }
11752:     # first look for a package that matches the requested part id
11753:     foreach my $package (@specifics) {
11754: 	my (undef,$pack_type,$pack_part)=@{$package};
11755: 	next if ($pack_part ne $part);
11756: 	if (defined($packagetab{"$pack_type&$name&default"})) {
11757: 	    return $packagetab{"$pack_type&$name&default"};
11758: 	}
11759:     }
11760:     # look for any possible matching non extension_ package
11761:     foreach my $package (@specifics) {
11762: 	my (undef,$pack_type,$pack_part)=@{$package};
11763: 	if (defined($packagetab{"$pack_type&$name&default"})) {
11764: 	    return $packagetab{"$pack_type&$name&default"};
11765: 	}
11766: 	if ($pack_type eq 'part') { $pack_part='0'; }
11767: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
11768: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
11769: 	}
11770:     }
11771:     # look for any posible extension_ match
11772:     foreach my $package (@extension) {
11773: 	my ($package,$pack_type)=@{$package};
11774: 	if (defined($packagetab{"$pack_type&$name&default"})) {
11775: 	    return $packagetab{"$pack_type&$name&default"};
11776: 	}
11777: 	if (defined($packagetab{$package."&$name&default"})) {
11778: 	    return $packagetab{$package."&$name&default"};
11779: 	}
11780:     }
11781:     # look for a global default setting
11782:     if ($do_default && defined($packagetab{"default&$name&default"})) {
11783: 	return $packagetab{"default&$name&default"};
11784:     }
11785:     return undef;
11786: }
11787: 
11788: sub add_prefix_and_part {
11789:     my ($prefix,$part)=@_;
11790:     my $keyroot;
11791:     if (defined($prefix) && $prefix !~ /^__/) {
11792: 	# prefix that has a part already
11793: 	$keyroot=$prefix;
11794:     } elsif (defined($prefix)) {
11795: 	# prefix that is missing a part
11796: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
11797:     } else {
11798: 	# no prefix at all
11799: 	if (defined($part)) { $keyroot='_'.$part; }
11800:     }
11801:     return $keyroot;
11802: }
11803: 
11804: # ---------------------------------------------------------------- Get metadata
11805: 
11806: my %metaentry;
11807: my %importedpartids;
11808: my %importedrespids;
11809: sub metadata {
11810:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
11811:     $uri=&declutter($uri);
11812:     # if it is a non metadata possible uri return quickly
11813:     if (($uri eq '') || 
11814: 	(($uri =~ m|^/*adm/|) && 
11815: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
11816:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
11817: 	return undef;
11818:     }
11819:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
11820: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
11821: 	return undef;
11822:     }
11823:     my $filename=$uri;
11824:     $uri=~s/\.meta$//;
11825: #
11826: # Is the metadata already cached?
11827: # Look at timestamp of caching
11828: # Everything is cached by the main uri, libraries are never directly cached
11829: #
11830:     if (!defined($liburi)) {
11831: 	my ($result,$cached)=&is_cached_new('meta',$uri);
11832: 	if (defined($cached)) { return $result->{':'.$what}; }
11833:     }
11834:     {
11835: # Imported parts would go here
11836:         my @origfiletagids=();
11837:         my $importedparts=0;
11838: 
11839: # Imported responseids would go here
11840:         my $importedresponses=0;
11841: #
11842: # Is this a recursive call for a library?
11843: #
11844: #	if (! exists($metacache{$uri})) {
11845: #	    $metacache{$uri}={};
11846: #	}
11847: 	my $cachetime = 60*60;
11848:         if ($liburi) {
11849: 	    $liburi=&declutter($liburi);
11850:             $filename=$liburi;
11851:         } else {
11852: 	    &devalidate_cache_new('meta',$uri);
11853: 	    undef(%metaentry);
11854: 	}
11855:         my %metathesekeys=();
11856:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
11857: 	my $metastring;
11858: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
11859: 	    my $which = &hreflocation('','/'.($liburi || $uri));
11860: 	    $metastring = 
11861: 		&Apache::lonnet::ssi_body($which,
11862: 					  ('grade_target' => 'meta'));
11863: 	    $cachetime = 1; # only want this cached in the child not long term
11864: 	} elsif (($uri !~ m -^(editupload)/-) && 
11865:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
11866: 	    my $file=&filelocation('',&clutter($filename));
11867: 	    #push(@{$metaentry{$uri.'.file'}},$file);
11868: 	    $metastring=&getfile($file);
11869: 	}
11870:         my $parser=HTML::LCParser->new(\$metastring);
11871:         my $token;
11872:         undef %metathesekeys;
11873:         while ($token=$parser->get_token) {
11874: 	    if ($token->[0] eq 'S') {
11875: 		if (defined($token->[2]->{'package'})) {
11876: #
11877: # This is a package - get package info
11878: #
11879: 		    my $package=$token->[2]->{'package'};
11880: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11881: 		    if (defined($token->[2]->{'id'})) { 
11882: 			$keyroot.='_'.$token->[2]->{'id'}; 
11883: 		    }
11884: 		    if ($metaentry{':packages'}) {
11885: 			$metaentry{':packages'}.=','.$package.$keyroot;
11886: 		    } else {
11887: 			$metaentry{':packages'}=$package.$keyroot;
11888: 		    }
11889: 		    foreach my $pack_entry (keys(%packagetab)) {
11890: 			my $part=$keyroot;
11891: 			$part=~s/^\_//;
11892: 			if ($pack_entry=~/^\Q$package\E\&/ || 
11893: 			    $pack_entry=~/^\Q$package\E_0\&/) {
11894: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
11895: 			    # ignore package.tab specified default values
11896:                             # here &package_tab_default() will fetch those
11897: 			    if ($subp eq 'default') { next; }
11898: 			    my $value=$packagetab{$pack_entry};
11899: 			    my $unikey;
11900: 			    if ($pack =~ /_0$/) {
11901: 				$unikey='parameter_0_'.$name;
11902: 				$part=0;
11903: 			    } else {
11904: 				$unikey='parameter'.$keyroot.'_'.$name;
11905: 			    }
11906: 			    if ($subp eq 'display') {
11907: 				$value.=' [Part: '.$part.']';
11908: 			    }
11909: 			    $metaentry{':'.$unikey.'.part'}=$part;
11910: 			    $metathesekeys{$unikey}=1;
11911: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
11912: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
11913: 			    }
11914: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
11915: 				$metaentry{':'.$unikey}=
11916: 				    $metaentry{':'.$unikey.'.default'};
11917: 			    }
11918: 			}
11919: 		    }
11920: 		} else {
11921: #
11922: # This is not a package - some other kind of start tag
11923: #
11924: 		    my $entry=$token->[1];
11925: 		    my $unikey='';
11926: 
11927: 		    if ($entry eq 'import') {
11928: #
11929: # Importing a library here
11930: #
11931:                         my $location=$parser->get_text('/import');
11932:                         my $dir=$filename;
11933:                         $dir=~s|[^/]*$||;
11934:                         $location=&filelocation($dir,$location);
11935: 
11936:                         my $importid=$token->[2]->{'id'};
11937:                         my $importmode=$token->[2]->{'importmode'};
11938: #
11939: # Check metadata for imported file to
11940: # see if it contained response items
11941: #
11942:                         my %currmetaentry = %metaentry;
11943:                         my $libresponseorder = &metadata($location,'responseorder');
11944:                         my $origfile;
11945:                         if ($libresponseorder ne '') {
11946:                             if ($#origfiletagids<0) {
11947:                                 undef(%importedrespids);
11948:                                 undef(%importedpartids);
11949:                             }
11950:                             @{$importedrespids{$importid}} = split(/\s*,\s*/,$libresponseorder);
11951:                             if (@{$importedrespids{$importid}} > 0) {
11952:                                 $importedresponses = 1;
11953: # We need to get the original file and the imported file to get the response order correct
11954: # Load and inspect original file
11955:                                 if ($#origfiletagids<0) {
11956:                                     my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
11957:                                     $origfile=&getfile($origfilelocation);
11958:                                     @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
11959:                                 }
11960:                             }
11961:                         }
11962: # Do not overwrite contents of %metaentry hash for resource itself with 
11963: # hash populated for imported library file
11964:                         %metaentry = %currmetaentry;
11965:                         undef(%currmetaentry);
11966:                         if ($importmode eq 'problem') {
11967: # Import as problem/response
11968:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11969:                         } elsif ($importmode eq 'part') {
11970: # Import as part(s)
11971:                            $importedparts=1;
11972: # We need to get the original file and the imported file to get the part order correct
11973: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
11974: # Load and inspect original file if we didn't do that already
11975:                            if ($#origfiletagids<0) {
11976:                                undef(%importedrespids);
11977:                                undef(%importedpartids);
11978:                                if ($origfile eq '') {
11979:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
11980:                                    $origfile=&getfile($origfilelocation);
11981:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
11982:                                }
11983:                            }
11984: 
11985: # Load and inspect imported file
11986:                            my $impfile=&getfile($location);
11987:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
11988:                            if ($#impfilepartids>=0) {
11989: # This problem had parts
11990:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
11991:                            } else {
11992: # Importing by turning a single problem into a problem part
11993: # It gets the import-tags ID as part-ID
11994:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
11995:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
11996:                            }
11997:                         } else {
11998: # Normal import
11999:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
12000:                            if (defined($token->[2]->{'id'})) {
12001:                               $unikey.='_'.$token->[2]->{'id'};
12002:                            }
12003:                         }
12004: 
12005: 			if ($depthcount<20) {
12006: 			    my $metadata = 
12007: 				&metadata($uri,'keys', $location,$unikey,
12008: 					  $depthcount+1);
12009: 			    foreach my $meta (split(',',$metadata)) {
12010: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
12011: 				$metathesekeys{$meta}=1;
12012: 			    }
12013: 			
12014:                         }
12015: 		    } else {
12016: #
12017: # Not importing, some other kind of non-package, non-library start tag
12018: # 
12019:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
12020:                         if (defined($token->[2]->{'id'})) {
12021:                             $unikey.='_'.$token->[2]->{'id'};
12022:                         }
12023: 			if (defined($token->[2]->{'name'})) { 
12024: 			    $unikey.='_'.$token->[2]->{'name'}; 
12025: 			}
12026: 			$metathesekeys{$unikey}=1;
12027: 			foreach my $param (@{$token->[3]}) {
12028: 			    $metaentry{':'.$unikey.'.'.$param} =
12029: 				$token->[2]->{$param};
12030: 			}
12031: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
12032: 			my $default=$metaentry{':'.$unikey.'.default'};
12033: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
12034: 		 # only ws inside the tag, and not in default, so use default
12035: 		 # as value
12036: 			    $metaentry{':'.$unikey}=$default;
12037: 			} elsif ( $internaltext =~ /\S/ ) {
12038: 		  # something interesting inside the tag
12039: 			    $metaentry{':'.$unikey}=$internaltext;
12040: 			} else {
12041: 		  # no interesting values, don't set a default
12042: 			}
12043: # end of not-a-package not-a-library import
12044: 		    }
12045: # end of not-a-package start tag
12046: 		}
12047: # the next is the end of "start tag"
12048: 	    }
12049: 	}
12050: 	my ($extension) = ($uri =~ /\.(\w+)$/);
12051: 	$extension = lc($extension);
12052: 	if ($extension eq 'htm') { $extension='html'; }
12053: 
12054: 	foreach my $key (keys(%packagetab)) {
12055: 	    #no specific packages #how's our extension
12056: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
12057: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
12058: 					 \%metathesekeys);
12059: 	}
12060: 
12061: 	if (!exists($metaentry{':packages'})
12062: 	    || $packagetab{"import_defaults&extension_$extension"}) {
12063: 	    foreach my $key (keys(%packagetab)) {
12064: 		#no specific packages well let's get default then
12065: 		if ($key!~/^default&/) { next; }
12066: 		&metadata_create_package_def($uri,$key,'default',
12067: 					     \%metathesekeys);
12068: 	    }
12069: 	}
12070: # are there custom rights to evaluate
12071: 	if ($metaentry{':copyright'} eq 'custom') {
12072: 
12073:     #
12074:     # Importing a rights file here
12075:     #
12076: 	    unless ($depthcount) {
12077: 		my $location=$metaentry{':customdistributionfile'};
12078: 		my $dir=$filename;
12079: 		$dir=~s|[^/]*$||;
12080: 		$location=&filelocation($dir,$location);
12081: 		my $rights_metadata =
12082: 		    &metadata($uri,'keys',$location,'_rights',
12083: 			      $depthcount+1);
12084: 		foreach my $rights (split(',',$rights_metadata)) {
12085: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
12086: 		    $metathesekeys{$rights}=1;
12087: 		}
12088: 	    }
12089: 	}
12090: 	# uniqifiy package listing
12091: 	my %seen;
12092: 	my @uniq_packages =
12093: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
12094: 	$metaentry{':packages'} = join(',',@uniq_packages);
12095: 
12096:         if (($importedresponses) || ($importedparts)) {
12097:             if ($importedparts) {
12098: # We had imported parts and need to rebuild partorder
12099:                 $metaentry{':partorder'}='';
12100:                 $metathesekeys{'partorder'}=1;
12101:             }
12102:             if ($importedresponses) {
12103: # We had imported responses and need to rebuild responseorder
12104:                 $metaentry{':responseorder'}='';
12105:                 $metathesekeys{'responseorder'}=1;
12106:             }
12107:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
12108:                 my $origid = $origfiletagids[$index+1];
12109:                 if ($origfiletagids[$index] eq 'part') {
12110: # Original part, part of the problem
12111:                     if ($importedparts) {
12112:                         $metaentry{':partorder'}.=','.$origid;
12113:                     }
12114:                 } elsif ($origfiletagids[$index] eq 'import') {
12115:                     if ($importedparts) {
12116: # We have imported parts at this position
12117:                         $metaentry{':partorder'}.=','.$importedpartids{$origid};
12118:                     }
12119:                     if ($importedresponses) {
12120: # We have imported responses at this position
12121:                         if (ref($importedrespids{$origid}) eq 'ARRAY') {
12122:                             $metaentry{':responseorder'}.=','.join(',',map { $origid.'_'.$_ } @{$importedrespids{$origid}});
12123:                         }
12124:                     }
12125:                 } else {
12126: # Original response item, part of the problem
12127:                     if ($importedresponses) {
12128:                         $metaentry{':responseorder'}.=','.$origid;
12129:                     }
12130:                 }
12131:             }
12132:             if ($importedparts) {
12133:                 $metaentry{':partorder'}=~s/^\,//;
12134:             }
12135:             if ($importedresponses) {
12136:                 $metaentry{':responseorder'}=~s/^\,//;
12137:             }
12138:         }
12139: 
12140: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
12141: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
12142: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
12143: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
12144: # this is the end of "was not already recently cached
12145:     }
12146:     return $metaentry{':'.$what};
12147: }
12148: 
12149: sub metadata_create_package_def {
12150:     my ($uri,$key,$package,$metathesekeys)=@_;
12151:     my ($pack,$name,$subp)=split(/\&/,$key);
12152:     if ($subp eq 'default') { next; }
12153:     
12154:     if (defined($metaentry{':packages'})) {
12155: 	$metaentry{':packages'}.=','.$package;
12156:     } else {
12157: 	$metaentry{':packages'}=$package;
12158:     }
12159:     my $value=$packagetab{$key};
12160:     my $unikey;
12161:     $unikey='parameter_0_'.$name;
12162:     $metaentry{':'.$unikey.'.part'}=0;
12163:     $$metathesekeys{$unikey}=1;
12164:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
12165: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
12166:     }
12167:     if (defined($metaentry{':'.$unikey.'.default'})) {
12168: 	$metaentry{':'.$unikey}=
12169: 	    $metaentry{':'.$unikey.'.default'};
12170:     }
12171: }
12172: 
12173: sub metadata_generate_part0 {
12174:     my ($metadata,$metacache,$uri) = @_;
12175:     my %allnames;
12176:     foreach my $metakey (keys(%$metadata)) {
12177: 	if ($metakey=~/^parameter\_(.*)/) {
12178: 	  my $part=$$metacache{':'.$metakey.'.part'};
12179: 	  my $name=$$metacache{':'.$metakey.'.name'};
12180: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
12181: 	    $allnames{$name}=$part;
12182: 	  }
12183: 	}
12184:     }
12185:     foreach my $name (keys(%allnames)) {
12186:       $$metadata{"parameter_0_$name"}=1;
12187:       my $key=":parameter_0_$name";
12188:       $$metacache{"$key.part"}='0';
12189:       $$metacache{"$key.name"}=$name;
12190:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
12191: 					   $allnames{$name}.'_'.$name.
12192: 					   '.type'};
12193:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
12194: 			     '.display'};
12195:       my $expr='[Part: '.$allnames{$name}.']';
12196:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
12197:       $$metacache{"$key.display"}=$olddis;
12198:     }
12199: }
12200: 
12201: # ------------------------------------------------------ Devalidate title cache
12202: 
12203: sub devalidate_title_cache {
12204:     my ($url)=@_;
12205:     if (!$env{'request.course.id'}) { return; }
12206:     my $symb=&symbread($url);
12207:     if (!$symb) { return; }
12208:     my $key=$env{'request.course.id'}."\0".$symb;
12209:     &devalidate_cache_new('title',$key);
12210: }
12211: 
12212: # ------------------------------------------------- Get the title of a course
12213: 
12214: sub current_course_title {
12215:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
12216: }
12217: # ------------------------------------------------- Get the title of a resource
12218: 
12219: sub gettitle {
12220:     my $urlsymb=shift;
12221:     my $symb=&symbread($urlsymb);
12222:     if ($symb) {
12223: 	my $key=$env{'request.course.id'}."\0".$symb;
12224: 	my ($result,$cached)=&is_cached_new('title',$key);
12225: 	if (defined($cached)) { 
12226: 	    return $result;
12227: 	}
12228: 	my ($map,$resid,$url)=&decode_symb($symb);
12229: 	my $title='';
12230: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
12231: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
12232: 	} else {
12233: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12234: 		    &GDBM_READER(),0640)) {
12235: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
12236: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
12237: 		untie(%bighash);
12238: 	    }
12239: 	}
12240: 	$title=~s/\&colon\;/\:/gs;
12241: 	if ($title) {
12242: # Remember both $symb and $title for dynamic metadata
12243:             $accesshash{$symb.'___crstitle'}=$title;
12244:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
12245: # Cache this title and then return it
12246: 	    return &do_cache_new('title',$key,$title,600);
12247: 	}
12248: 	$urlsymb=$url;
12249:     }
12250:     my $title=&metadata($urlsymb,'title');
12251:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
12252:     return $title;
12253: }
12254: 
12255: sub get_slot {
12256:     my ($which,$cnum,$cdom)=@_;
12257:     if (!$cnum || !$cdom) {
12258: 	(undef,my $courseid)=&whichuser();
12259: 	$cdom=$env{'course.'.$courseid.'.domain'};
12260: 	$cnum=$env{'course.'.$courseid.'.num'};
12261:     }
12262:     my $key=join("\0",'slots',$cdom,$cnum,$which);
12263:     my %slotinfo;
12264:     if (exists($remembered{$key})) {
12265: 	$slotinfo{$which} = $remembered{$key};
12266:     } else {
12267: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
12268: 	&Apache::lonhomework::showhash(%slotinfo);
12269: 	my ($tmp)=keys(%slotinfo);
12270: 	if ($tmp=~/^error:/) { return (); }
12271: 	$remembered{$key} = $slotinfo{$which};
12272:     }
12273:     if (ref($slotinfo{$which}) eq 'HASH') {
12274: 	return %{$slotinfo{$which}};
12275:     }
12276:     return $slotinfo{$which};
12277: }
12278: 
12279: sub get_reservable_slots {
12280:     my ($cnum,$cdom,$uname,$udom) = @_;
12281:     my $now = time;
12282:     my $reservable_info;
12283:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
12284:     if (exists($remembered{$key})) {
12285:         $reservable_info = $remembered{$key};
12286:     } else {
12287:         my %resv;
12288:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
12289:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
12290:         $reservable_info = \%resv;
12291:         $remembered{$key} = $reservable_info;
12292:     }
12293:     return $reservable_info;
12294: }
12295: 
12296: sub get_course_slots {
12297:     my ($cnum,$cdom) = @_;
12298:     my $hashid=$cnum.':'.$cdom;
12299:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
12300:     if (defined($cached)) {
12301:         if (ref($result) eq 'HASH') {
12302:             return %{$result};
12303:         }
12304:     } else {
12305:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
12306:         my ($tmp) = keys(%slots);
12307:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
12308:             &do_cache_new('allslots',$hashid,\%slots,600);
12309:             return %slots;
12310:         }
12311:     }
12312:     return;
12313: }
12314: 
12315: sub devalidate_slots_cache {
12316:     my ($cnum,$cdom)=@_;
12317:     my $hashid=$cnum.':'.$cdom;
12318:     &devalidate_cache_new('allslots',$hashid);
12319: }
12320: 
12321: sub get_coursechange {
12322:     my ($cdom,$cnum) = @_;
12323:     if ($cdom eq '' || $cnum eq '') {
12324:         return unless ($env{'request.course.id'});
12325:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
12326:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
12327:     }
12328:     my $hashid=$cdom.'_'.$cnum;
12329:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
12330:     if ((defined($cached)) && ($change ne '')) {
12331:         return $change;
12332:     } else {
12333:         my %crshash;
12334:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
12335:         if ($crshash{'internal.contentchange'} eq '') {
12336:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
12337:             if ($change eq '') {
12338:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
12339:                 $change = $crshash{'internal.created'};
12340:             }
12341:         } else {
12342:             $change = $crshash{'internal.contentchange'};
12343:         }
12344:         my $cachetime = 600;
12345:         &do_cache_new('crschange',$hashid,$change,$cachetime);
12346:     }
12347:     return $change;
12348: }
12349: 
12350: sub devalidate_coursechange_cache {
12351:     my ($cnum,$cdom)=@_;
12352:     my $hashid=$cnum.':'.$cdom;
12353:     &devalidate_cache_new('crschange',$hashid);
12354: }
12355: 
12356: # ------------------------------------------------- Update symbolic store links
12357: 
12358: sub symblist {
12359:     my ($mapname,%newhash)=@_;
12360:     $mapname=&deversion(&declutter($mapname));
12361:     my %hash;
12362:     if (($env{'request.course.fn'}) && (%newhash)) {
12363:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
12364:                       &GDBM_WRCREAT(),0640)) {
12365: 	    foreach my $url (keys(%newhash)) {
12366: 		next if ($url eq 'last_known'
12367: 			 && $env{'form.no_update_last_known'});
12368: 		$hash{declutter($url)}=&encode_symb($mapname,
12369: 						    $newhash{$url}->[1],
12370: 						    $newhash{$url}->[0]);
12371:             }
12372:             if (untie(%hash)) {
12373: 		return 'ok';
12374:             }
12375:         }
12376:     }
12377:     return 'error';
12378: }
12379: 
12380: # --------------------------------------------------------------- Verify a symb
12381: 
12382: sub symbverify {
12383:     my ($symb,$thisurl,$encstate)=@_;
12384:     my $thisfn=$thisurl;
12385:     $thisfn=&declutter($thisfn);
12386: # direct jump to resource in page or to a sequence - will construct own symbs
12387:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
12388: # check URL part
12389:     my ($map,$resid,$url)=&decode_symb($symb);
12390: 
12391:     unless ($url eq $thisfn) { return 0; }
12392: 
12393:     $symb=&symbclean($symb);
12394:     $thisurl=&deversion($thisurl);
12395:     $thisfn=&deversion($thisfn);
12396: 
12397:     my %bighash;
12398:     my $okay=0;
12399: 
12400:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12401:                             &GDBM_READER(),0640)) {
12402:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
12403:             $thisurl =~ s/\?.+$//;
12404:             if ($map =~ m{^uploaded/.+\.page$}) {
12405:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
12406:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
12407:             }
12408:         }
12409:         my $ids;
12410:         if ($map =~ m{^uploaded/.+\.page$}) {
12411:             $ids=$bighash{'ids_'.&clutter_with_no_wrapper($thisurl)};
12412:         } else {
12413:             $ids=$bighash{'ids_'.&clutter($thisurl)};
12414:         }
12415:         unless ($ids) {
12416:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
12417:             $ids=$bighash{$idkey};
12418:         }
12419:         if ($ids) {
12420: # ------------------------------------------------------------------- Has ID(s)
12421:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
12422:                 $symb =~ s/\?.+$//;
12423:             }
12424: 	    foreach my $id (split(/\,/,$ids)) {
12425: 	       my ($mapid,$resid)=split(/\./,$id);
12426:                if (
12427:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
12428:    eq $symb) {
12429:                    if (ref($encstate)) {
12430:                        $$encstate = $bighash{'encrypted_'.$id};
12431:                    }
12432:                    if (($env{'request.role.adv'}) ||
12433:                        ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
12434:                        ($thisurl eq '/adm/navmaps')) {
12435:                        $okay=1;
12436:                        last;
12437:                    }
12438:                }
12439:            }
12440:         }
12441: 	untie(%bighash);
12442:     }
12443:     return $okay;
12444: }
12445: 
12446: # --------------------------------------------------------------- Clean-up symb
12447: 
12448: sub symbclean {
12449:     my $symb=shift;
12450:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
12451: # remove version from map
12452:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
12453: 
12454: # remove version from URL
12455:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
12456: 
12457: # remove wrapper
12458: 
12459:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
12460:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
12461:     return $symb;
12462: }
12463: 
12464: # ---------------------------------------------- Split symb to find map and url
12465: 
12466: sub encode_symb {
12467:     my ($map,$resid,$url)=@_;
12468:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
12469: }
12470: 
12471: sub decode_symb {
12472:     my $symb=shift;
12473:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
12474:     my ($map,$resid,$url)=split(/___/,$symb);
12475:     return (&fixversion($map),$resid,&fixversion($url));
12476: }
12477: 
12478: sub fixversion {
12479:     my $fn=shift;
12480:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
12481:     my %bighash;
12482:     my $uri=&clutter($fn);
12483:     my $key=$env{'request.course.id'}.'_'.$uri;
12484: # is this cached?
12485:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
12486:     if (defined($cached)) { return $result; }
12487: # unfortunately not cached, or expired
12488:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12489: 	    &GDBM_READER(),0640)) {
12490:  	if ($bighash{'version_'.$uri}) {
12491:  	    my $version=$bighash{'version_'.$uri};
12492:  	    unless (($version eq 'mostrecent') || 
12493: 		    ($version==&getversion($uri))) {
12494:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
12495:  	    }
12496:  	}
12497:  	untie %bighash;
12498:     }
12499:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
12500: }
12501: 
12502: sub deversion {
12503:     my $url=shift;
12504:     $url=~s/\.\d+\.(\w+)$/\.$1/;
12505:     return $url;
12506: }
12507: 
12508: # ------------------------------------------------------ Return symb list entry
12509: 
12510: sub symbread {
12511:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles,
12512:         $ignoresymbdb,$noenccheck)=@_;
12513:     my $cache_str='request.symbread.cached.'.$thisfn;
12514:     if (defined($env{$cache_str})) {
12515:         unless (ref($possibles) eq 'HASH') {
12516:             if ($ignorecachednull) {
12517:                 return $env{$cache_str} unless ($env{$cache_str} eq '');
12518:             } else {
12519:                 return $env{$cache_str};
12520:             }
12521:         }
12522:     }
12523: # no filename provided? try from environment
12524:     unless ($thisfn) {
12525:         if ($env{'request.symb'}) {
12526:             return $env{$cache_str}=&symbclean($env{'request.symb'});
12527:         }
12528:         $thisfn=$env{'request.filename'};
12529:     }
12530:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
12531: # is that filename actually a symb? Verify, clean, and return
12532:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
12533: 	if (&symbverify($thisfn,$1)) {
12534: 	    return $env{$cache_str}=&symbclean($thisfn);
12535: 	}
12536:     }
12537:     $thisfn=declutter($thisfn);
12538:     my %hash;
12539:     my %bighash;
12540:     my $syval='';
12541:     if (($env{'request.course.fn'}) && ($thisfn)) {
12542:         my $targetfn = $thisfn;
12543:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
12544:             $targetfn = 'adm/wrapper/'.$thisfn;
12545:         }
12546: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
12547: 	    $targetfn=$1;
12548: 	}
12549:         unless ($ignoresymbdb) {
12550:             if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
12551:                           &GDBM_READER(),0640)) {
12552: 	        $syval=$hash{$targetfn};
12553:                 untie(%hash);
12554:             }
12555:             if ($syval && $checkforblock) {
12556:                 my @blockers = &has_comm_blocking('bre',$syval,$thisfn,$ignoresymbdb,$noenccheck);
12557:                 if (@blockers) {
12558:                     $syval='';
12559:                 }
12560:             }
12561:         }
12562: # ---------------------------------------------------------- There was an entry
12563:         if ($syval) {
12564: 	    #unless ($syval=~/\_\d+$/) {
12565: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
12566: 		    #&appenv({'request.ambiguous' => $thisfn});
12567: 		    #return $env{$cache_str}='';
12568: 		#}    
12569: 		#$syval.=$1;
12570: 	    #}
12571:         } else {
12572: # ------------------------------------------------------- Was not in symb table
12573:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12574:                             &GDBM_READER(),0640)) {
12575: # ---------------------------------------------- Get ID(s) for current resource
12576:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
12577:               unless ($ids) { 
12578:                  $ids=$bighash{'ids_/'.$thisfn};
12579:               }
12580:               unless ($ids) {
12581: # alias?
12582: 		  $ids=$bighash{'mapalias_'.$thisfn};
12583:               }
12584:               if ($ids) {
12585: # ------------------------------------------------------------------- Has ID(s)
12586:                  my @possibilities=split(/\,/,$ids);
12587:                  if ($#possibilities==0) {
12588: # ----------------------------------------------- There is only one possibility
12589: 		     my ($mapid,$resid)=split(/\./,$ids);
12590: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
12591: 						    $resid,$thisfn);
12592:                      if (ref($possibles) eq 'HASH') {
12593:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
12594:                              $possibles->{$syval} = 1;
12595:                          }
12596:                      }
12597:                      if ($checkforblock) {
12598:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
12599:                              my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids},'',$noenccheck);
12600:                              if (@blockers) {
12601:                                  $syval = '';
12602:                                  untie(%bighash);
12603:                                  return $env{$cache_str}='';
12604:                              }
12605:                          }
12606:                      }
12607:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
12608: # ------------------------------------------ There is more than one possibility
12609:                      my $realpossible=0;
12610:                      foreach my $id (@possibilities) {
12611: 			 my $file=$bighash{'src_'.$id};
12612:                          my $canaccess;
12613:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
12614:                              $canaccess = 1;
12615:                          } else {
12616:                              $canaccess = &allowed('bre',$file);
12617:                          }
12618:                          if ($canaccess) {
12619:          		     my ($mapid,$resid)=split(/\./,$id);
12620:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
12621:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
12622:                                                              $resid,$thisfn);
12623:                                  next if ($bighash{'randomout_'.$id} && !$env{'request.role.adv'});
12624:                                  next unless (($noenccheck) || ($bighash{'encrypted_'.$id} eq $env{'request.enc'}));
12625:                                  if ($checkforblock) {
12626:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file,'',$noenccheck);
12627:                                      if (@blockers > 0) {
12628:                                          $syval = '';
12629:                                      } else {
12630:                                          $syval = $poss_syval;
12631:                                          $realpossible++;
12632:                                      }
12633:                                  } else {
12634:                                      $syval = $poss_syval;
12635:                                      $realpossible++;
12636:                                  }
12637:                                  if ($syval) {
12638:                                      if (ref($possibles) eq 'HASH') {
12639:                                          $possibles->{$syval} = 1;
12640:                                      }
12641:                                  }
12642:                              }
12643: 			 }
12644:                      }
12645: 		     if ($realpossible!=1) { $syval=''; }
12646:                  } else {
12647:                      $syval='';
12648:                  }
12649: 	      }
12650:               untie(%bighash);
12651:            }
12652:         }
12653:         if ($syval) {
12654: 	    return $env{$cache_str}=$syval;
12655:         }
12656:     }
12657:     &appenv({'request.ambiguous' => $thisfn});
12658:     return $env{$cache_str}='';
12659: }
12660: 
12661: # ---------------------------------------------------------- Return random seed
12662: 
12663: sub numval {
12664:     my $txt=shift;
12665:     $txt=~tr/A-J/0-9/;
12666:     $txt=~tr/a-j/0-9/;
12667:     $txt=~tr/K-T/0-9/;
12668:     $txt=~tr/k-t/0-9/;
12669:     $txt=~tr/U-Z/0-5/;
12670:     $txt=~tr/u-z/0-5/;
12671:     $txt=~s/\D//g;
12672:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
12673:     return int($txt);
12674: }
12675: 
12676: sub numval2 {
12677:     my $txt=shift;
12678:     $txt=~tr/A-J/0-9/;
12679:     $txt=~tr/a-j/0-9/;
12680:     $txt=~tr/K-T/0-9/;
12681:     $txt=~tr/k-t/0-9/;
12682:     $txt=~tr/U-Z/0-5/;
12683:     $txt=~tr/u-z/0-5/;
12684:     $txt=~s/\D//g;
12685:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
12686:     my $total;
12687:     foreach my $val (@txts) { $total+=$val; }
12688:     if ($_64bit) { if ($total > 2**32) { return -1; } }
12689:     return int($total);
12690: }
12691: 
12692: sub numval3 {
12693:     use integer;
12694:     my $txt=shift;
12695:     $txt=~tr/A-J/0-9/;
12696:     $txt=~tr/a-j/0-9/;
12697:     $txt=~tr/K-T/0-9/;
12698:     $txt=~tr/k-t/0-9/;
12699:     $txt=~tr/U-Z/0-5/;
12700:     $txt=~tr/u-z/0-5/;
12701:     $txt=~s/\D//g;
12702:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
12703:     my $total;
12704:     foreach my $val (@txts) { $total+=$val; }
12705:     if ($_64bit) { $total=(($total<<32)>>32); }
12706:     return $total;
12707: }
12708: 
12709: sub digest {
12710:     my ($data)=@_;
12711:     my $digest=&Digest::MD5::md5($data);
12712:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
12713:     my ($e,$f);
12714:     {
12715:         use integer;
12716:         $e=($a+$b);
12717:         $f=($c+$d);
12718:         if ($_64bit) {
12719:             $e=(($e<<32)>>32);
12720:             $f=(($f<<32)>>32);
12721:         }
12722:     }
12723:     if (wantarray) {
12724: 	return ($e,$f);
12725:     } else {
12726: 	my $g;
12727: 	{
12728: 	    use integer;
12729: 	    $g=($e+$f);
12730: 	    if ($_64bit) {
12731: 		$g=(($g<<32)>>32);
12732: 	    }
12733: 	}
12734: 	return $g;
12735:     }
12736: }
12737: 
12738: sub latest_rnd_algorithm_id {
12739:     return '64bit5';
12740: }
12741: 
12742: sub get_rand_alg {
12743:     my ($courseid)=@_;
12744:     if (!$courseid) { $courseid=(&whichuser())[1]; }
12745:     if ($courseid) {
12746: 	return $env{"course.$courseid.rndseed"};
12747:     }
12748:     return &latest_rnd_algorithm_id();
12749: }
12750: 
12751: sub validCODE {
12752:     my ($CODE)=@_;
12753:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
12754:     return 0;
12755: }
12756: 
12757: sub getCODE {
12758:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
12759:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
12760: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
12761: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
12762: 	return $Apache::lonhomework::history{'resource.CODE'};
12763:     }
12764:     return undef;
12765: }
12766: #
12767: #  Determines the random seed for a specific context:
12768: #
12769: # parameters:
12770: #   symb      - in course context the symb for the seed.
12771: #   course_id - The course id of the form domain_coursenum.
12772: #   domain    - Domain for the user.
12773: #   course    - Course for the user.
12774: #   cenv      - environment of the course.
12775: #
12776: # NOTE:
12777: #   All parameters are picked out of the environment if missing
12778: #   or not defined.
12779: #   If a symb cannot be determined the current time is used instead.
12780: #
12781: #  For a given well defined symb, courside, domain, username,
12782: #  and course environment, the seed is reproducible.
12783: #
12784: sub rndseed {
12785:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
12786:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
12787:     if (!defined($symb)) {
12788: 	unless ($symb=$wsymb) { return time; }
12789:     }
12790:     if (!defined $courseid) { 
12791: 	$courseid=$wcourseid; 
12792:     }
12793:     if (!defined $domain) { $domain=$wdomain; }
12794:     if (!defined $username) { $username=$wusername }
12795: 
12796:     my $which;
12797:     if (defined($cenv->{'rndseed'})) {
12798: 	$which = $cenv->{'rndseed'};
12799:     } else {
12800: 	$which =&get_rand_alg($courseid);
12801:     }
12802:     if (defined(&getCODE())) {
12803: 	if ($which eq '64bit5') {
12804: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
12805: 	} elsif ($which eq '64bit4') {
12806: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
12807: 	} else {
12808: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
12809: 	}
12810:     } elsif ($which eq '64bit5') {
12811: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
12812:     } elsif ($which eq '64bit4') {
12813: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
12814:     } elsif ($which eq '64bit3') {
12815: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
12816:     } elsif ($which eq '64bit2') {
12817: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
12818:     } elsif ($which eq '64bit') {
12819: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
12820:     }
12821:     return &rndseed_32bit($symb,$courseid,$domain,$username);
12822: }
12823: 
12824: sub rndseed_32bit {
12825:     my ($symb,$courseid,$domain,$username)=@_;
12826:     {
12827: 	use integer;
12828: 	my $symbchck=unpack("%32C*",$symb) << 27;
12829: 	my $symbseed=numval($symb) << 22;
12830: 	my $namechck=unpack("%32C*",$username) << 17;
12831: 	my $nameseed=numval($username) << 12;
12832: 	my $domainseed=unpack("%32C*",$domain) << 7;
12833: 	my $courseseed=unpack("%32C*",$courseid);
12834: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
12835: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12836: 	#&logthis("rndseed :$num:$symb");
12837: 	if ($_64bit) { $num=(($num<<32)>>32); }
12838: 	return $num;
12839:     }
12840: }
12841: 
12842: sub rndseed_64bit {
12843:     my ($symb,$courseid,$domain,$username)=@_;
12844:     {
12845: 	use integer;
12846: 	my $symbchck=unpack("%32S*",$symb) << 21;
12847: 	my $symbseed=numval($symb) << 10;
12848: 	my $namechck=unpack("%32S*",$username);
12849: 	
12850: 	my $nameseed=numval($username) << 21;
12851: 	my $domainseed=unpack("%32S*",$domain) << 10;
12852: 	my $courseseed=unpack("%32S*",$courseid);
12853: 	
12854: 	my $num1=$symbchck+$symbseed+$namechck;
12855: 	my $num2=$nameseed+$domainseed+$courseseed;
12856: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12857: 	#&logthis("rndseed :$num:$symb");
12858: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
12859: 	return "$num1,$num2";
12860:     }
12861: }
12862: 
12863: sub rndseed_64bit2 {
12864:     my ($symb,$courseid,$domain,$username)=@_;
12865:     {
12866: 	use integer;
12867: 	# strings need to be an even # of cahracters long, it it is odd the
12868:         # last characters gets thrown away
12869: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
12870: 	my $symbseed=numval($symb) << 10;
12871: 	my $namechck=unpack("%32S*",$username.' ');
12872: 	
12873: 	my $nameseed=numval($username) << 21;
12874: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
12875: 	my $courseseed=unpack("%32S*",$courseid.' ');
12876: 	
12877: 	my $num1=$symbchck+$symbseed+$namechck;
12878: 	my $num2=$nameseed+$domainseed+$courseseed;
12879: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12880: 	#&logthis("rndseed :$num:$symb");
12881: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
12882: 	return "$num1,$num2";
12883:     }
12884: }
12885: 
12886: sub rndseed_64bit3 {
12887:     my ($symb,$courseid,$domain,$username)=@_;
12888:     {
12889: 	use integer;
12890: 	# strings need to be an even # of cahracters long, it it is odd the
12891:         # last characters gets thrown away
12892: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
12893: 	my $symbseed=numval2($symb) << 10;
12894: 	my $namechck=unpack("%32S*",$username.' ');
12895: 	
12896: 	my $nameseed=numval2($username) << 21;
12897: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
12898: 	my $courseseed=unpack("%32S*",$courseid.' ');
12899: 	
12900: 	my $num1=$symbchck+$symbseed+$namechck;
12901: 	my $num2=$nameseed+$domainseed+$courseseed;
12902: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12903: 	#&logthis("rndseed :$num1:$num2:$_64bit");
12904: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
12905: 	
12906: 	return "$num1:$num2";
12907:     }
12908: }
12909: 
12910: sub rndseed_64bit4 {
12911:     my ($symb,$courseid,$domain,$username)=@_;
12912:     {
12913: 	use integer;
12914: 	# strings need to be an even # of cahracters long, it it is odd the
12915:         # last characters gets thrown away
12916: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
12917: 	my $symbseed=numval3($symb) << 10;
12918: 	my $namechck=unpack("%32S*",$username.' ');
12919: 	
12920: 	my $nameseed=numval3($username) << 21;
12921: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
12922: 	my $courseseed=unpack("%32S*",$courseid.' ');
12923: 	
12924: 	my $num1=$symbchck+$symbseed+$namechck;
12925: 	my $num2=$nameseed+$domainseed+$courseseed;
12926: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12927: 	#&logthis("rndseed :$num1:$num2:$_64bit");
12928: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
12929: 	
12930: 	return "$num1:$num2";
12931:     }
12932: }
12933: 
12934: sub rndseed_64bit5 {
12935:     my ($symb,$courseid,$domain,$username)=@_;
12936:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
12937:     return "$num1:$num2";
12938: }
12939: 
12940: sub rndseed_CODE_64bit {
12941:     my ($symb,$courseid,$domain,$username)=@_;
12942:     {
12943: 	use integer;
12944: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
12945: 	my $symbseed=numval2($symb);
12946: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
12947: 	my $CODEseed=numval(&getCODE());
12948: 	my $courseseed=unpack("%32S*",$courseid.' ');
12949: 	my $num1=$symbseed+$CODEchck;
12950: 	my $num2=$CODEseed+$courseseed+$symbchck;
12951: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
12952: 	#&logthis("rndseed :$num1:$num2:$symb");
12953: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
12954: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
12955: 	return "$num1:$num2";
12956:     }
12957: }
12958: 
12959: sub rndseed_CODE_64bit4 {
12960:     my ($symb,$courseid,$domain,$username)=@_;
12961:     {
12962: 	use integer;
12963: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
12964: 	my $symbseed=numval3($symb);
12965: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
12966: 	my $CODEseed=numval3(&getCODE());
12967: 	my $courseseed=unpack("%32S*",$courseid.' ');
12968: 	my $num1=$symbseed+$CODEchck;
12969: 	my $num2=$CODEseed+$courseseed+$symbchck;
12970: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
12971: 	#&logthis("rndseed :$num1:$num2:$symb");
12972: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
12973: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
12974: 	return "$num1:$num2";
12975:     }
12976: }
12977: 
12978: sub rndseed_CODE_64bit5 {
12979:     my ($symb,$courseid,$domain,$username)=@_;
12980:     my $code = &getCODE();
12981:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
12982:     return "$num1:$num2";
12983: }
12984: 
12985: sub setup_random_from_rndseed {
12986:     my ($rndseed)=@_;
12987:     if ($rndseed =~/([,:])/) {
12988: 	my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
12989:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
12990:             &Math::Random::random_set_seed_from_phrase($rndseed);
12991:         } else {
12992:             &Math::Random::random_set_seed($num1,$num2);
12993:         }
12994:     } else {
12995: 	&Math::Random::random_set_seed_from_phrase($rndseed);
12996:     }
12997: }
12998: 
12999: sub latest_receipt_algorithm_id {
13000:     return 'receipt3';
13001: }
13002: 
13003: sub recunique {
13004:     my $fucourseid=shift;
13005:     my $unique;
13006:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
13007: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
13008: 	$unique=$env{"course.$fucourseid.internal.encseed"};
13009:     } else {
13010: 	$unique=$perlvar{'lonReceipt'};
13011:     }
13012:     return unpack("%32C*",$unique);
13013: }
13014: 
13015: sub recprefix {
13016:     my $fucourseid=shift;
13017:     my $prefix;
13018:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
13019: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
13020: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
13021:     } else {
13022: 	$prefix=$perlvar{'lonHostID'};
13023:     }
13024:     return unpack("%32C*",$prefix);
13025: }
13026: 
13027: sub ireceipt {
13028:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
13029: 
13030:     my $return =&recprefix($fucourseid).'-';
13031: 
13032:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
13033: 	$env{'request.state'} eq 'construct') {
13034: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
13035: 	return $return;
13036:     }
13037: 
13038:     my $cuname=unpack("%32C*",$funame);
13039:     my $cudom=unpack("%32C*",$fudom);
13040:     my $cucourseid=unpack("%32C*",$fucourseid);
13041:     my $cusymb=unpack("%32C*",$fusymb);
13042:     my $cunique=&recunique($fucourseid);
13043:     my $cpart=unpack("%32S*",$part);
13044:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
13045: 
13046: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
13047: 			       
13048: 	$return.= ($cunique%$cuname+
13049: 		   $cunique%$cudom+
13050: 		   $cusymb%$cuname+
13051: 		   $cusymb%$cudom+
13052: 		   $cucourseid%$cuname+
13053: 		   $cucourseid%$cudom+
13054: 		   $cpart%$cuname+
13055: 		   $cpart%$cudom);
13056:     } else {
13057: 	$return.= ($cunique%$cuname+
13058: 		   $cunique%$cudom+
13059: 		   $cusymb%$cuname+
13060: 		   $cusymb%$cudom+
13061: 		   $cucourseid%$cuname+
13062: 		   $cucourseid%$cudom);
13063:     }
13064:     return $return;
13065: }
13066: 
13067: sub receipt {
13068:     my ($part)=@_;
13069:     my ($symb,$courseid,$domain,$name) = &whichuser();
13070:     return &ireceipt($name,$domain,$courseid,$symb,$part);
13071: }
13072: 
13073: sub whichuser {
13074:     my ($passedsymb)=@_;
13075:     my ($symb,$courseid,$domain,$name,$publicuser);
13076:     if (defined($env{'form.grade_symb'})) {
13077: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
13078: 	my $allowed=&allowed('vgr',$tmp_courseid);
13079: 	if (!$allowed &&
13080: 	    exists($env{'request.course.sec'}) &&
13081: 	    $env{'request.course.sec'} !~ /^\s*$/) {
13082: 	    $allowed=&allowed('vgr',$tmp_courseid.
13083: 			      '/'.$env{'request.course.sec'});
13084: 	}
13085: 	if ($allowed) {
13086: 	    ($symb)=&get_env_multiple('form.grade_symb');
13087: 	    $courseid=$tmp_courseid;
13088: 	    ($domain)=&get_env_multiple('form.grade_domain');
13089: 	    ($name)=&get_env_multiple('form.grade_username');
13090: 	    return ($symb,$courseid,$domain,$name,$publicuser);
13091: 	}
13092:     }
13093:     if (!$passedsymb) {
13094: 	$symb=&symbread();
13095:     } else {
13096: 	$symb=$passedsymb;
13097:     }
13098:     $courseid=$env{'request.course.id'};
13099:     $domain=$env{'user.domain'};
13100:     $name=$env{'user.name'};
13101:     if ($name eq 'public' && $domain eq 'public') {
13102: 	if (!defined($env{'form.username'})) {
13103: 	    $env{'form.username'}.=time.rand(10000000);
13104: 	}
13105: 	$name.=$env{'form.username'};
13106:     }
13107:     return ($symb,$courseid,$domain,$name,$publicuser);
13108: 
13109: }
13110: 
13111: # ------------------------------------------------------------ Serves up a file
13112: # returns either the contents of the file or 
13113: # -1 if the file doesn't exist
13114: #
13115: # if the target is a file that was uploaded via DOCS, 
13116: # a check will be made to see if a current copy exists on the local server,
13117: # if it does this will be served, otherwise a copy will be retrieved from
13118: # the home server for the course and stored in /home/httpd/html/userfiles on
13119: # the local server.   
13120: 
13121: sub getfile {
13122:     my ($file) = @_;
13123:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
13124:     &repcopy($file);
13125:     return &readfile($file);
13126: }
13127: 
13128: sub repcopy_userfile {
13129:     my ($file)=@_;
13130:     my $londocroot = $perlvar{'lonDocRoot'};
13131:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
13132:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
13133:     my ($cdom,$cnum,$filename) = 
13134: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
13135:     my $uri="/uploaded/$cdom/$cnum/$filename";
13136:     if (-e "$file") {
13137: # we already have a local copy, check it out
13138: 	my @fileinfo = stat($file);
13139: 	my $rtncode;
13140: 	my $info;
13141: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
13142: 	if ($lwpresp ne 'ok') {
13143: # there is no such file anymore, even though we had a local copy
13144: 	    if ($rtncode eq '404') {
13145: 		unlink($file);
13146: 	    }
13147: 	    return -1;
13148: 	}
13149: 	if ($info < $fileinfo[9]) {
13150: # nice, the file we have is up-to-date, just say okay
13151: 	    return 'ok';
13152: 	} else {
13153: # the file is outdated, get rid of it
13154: 	    unlink($file);
13155: 	}
13156:     }
13157: # one way or the other, at this point, we don't have the file
13158: # construct the correct path for the file
13159:     my @parts = ($cdom,$cnum); 
13160:     if ($filename =~ m|^(.+)/[^/]+$|) {
13161: 	push @parts, split(/\//,$1);
13162:     }
13163:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
13164:     foreach my $part (@parts) {
13165: 	$path .= '/'.$part;
13166: 	if (!-e $path) {
13167: 	    mkdir($path,0770);
13168: 	}
13169:     }
13170: # now the path exists for sure
13171: # get a user agent
13172:     my $ua=new LWP::UserAgent;
13173:     my $transferfile=$file.'.in.transfer';
13174: # FIXME: this should flock
13175:     if (-e $transferfile) { return 'ok'; }
13176:     my $request;
13177:     $uri=~s/^\///;
13178:     my $homeserver = &homeserver($cnum,$cdom);
13179:     my $hostname = &hostname($homeserver);
13180:     my $protocol = $protocol{$homeserver};
13181:     $protocol = 'http' if ($protocol ne 'https');
13182:     $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
13183:     my $response=$ua->request($request,$transferfile);
13184: # did it work?
13185:     if ($response->is_error()) {
13186: 	unlink($transferfile);
13187: 	&logthis("Userfile repcopy failed for $uri");
13188: 	return -1;
13189:     }
13190: # worked, rename the transfer file
13191:     rename($transferfile,$file);
13192:     return 'ok';
13193: }
13194: 
13195: sub tokenwrapper {
13196:     my $uri=shift;
13197:     $uri=~s|^https?\://([^/]+)||;
13198:     $uri=~s|^/||;
13199:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
13200:     my $token=$1;
13201:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
13202:     if ($udom && $uname && $file) {
13203: 	$file=~s|(\?\.*)*$||;
13204:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
13205:         my $homeserver = &homeserver($uname,$udom);
13206:         my $hostname = &hostname($homeserver);
13207:         my $protocol = $protocol{$homeserver};
13208:         $protocol = 'http' if ($protocol ne 'https');
13209:         return $protocol.'://'.$hostname.'/'.$uri.
13210:                (($uri=~/\?/)?'&':'?').'token='.$token.
13211:                                '&tokenissued='.$perlvar{'lonHostID'};
13212:     } else {
13213:         return '/adm/notfound.html';
13214:     }
13215: }
13216: 
13217: # call with reqtype HEAD: get last modification time
13218: # call with reqtype GET: get the file contents
13219: # Do not call this with reqtype GET for large files! It loads everything into memory
13220: #
13221: sub getuploaded {
13222:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
13223:     $uri=~s/^\///;
13224:     my $homeserver = &homeserver($cnum,$cdom);
13225:     my $hostname = &hostname($homeserver);
13226:     my $protocol = $protocol{$homeserver};
13227:     $protocol = 'http' if ($protocol ne 'https');
13228:     $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
13229:     my $ua=new LWP::UserAgent;
13230:     my $request=new HTTP::Request($reqtype,$uri);
13231:     my $response=$ua->request($request);
13232:     $$rtncode = $response->code;
13233:     if (! $response->is_success()) {
13234: 	return 'failed';
13235:     }      
13236:     if ($reqtype eq 'HEAD') {
13237: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
13238:     } elsif ($reqtype eq 'GET') {
13239: 	$$info = $response->content;
13240:     }
13241:     return 'ok';
13242: }
13243: 
13244: sub readfile {
13245:     my $file = shift;
13246:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
13247:     my $fh;
13248:     open($fh,"<",$file);
13249:     my $a='';
13250:     while (my $line = <$fh>) { $a .= $line; }
13251:     return $a;
13252: }
13253: 
13254: sub filelocation {
13255:     my ($dir,$file) = @_;
13256:     my $location;
13257:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
13258: 
13259:     if ($file =~ m-^/adm/-) {
13260: 	$file=~s-^/adm/wrapper/-/-;
13261: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
13262:     }
13263: 
13264:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
13265:         $location = $file;
13266:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
13267:         my ($udom,$uname,$filename)=
13268:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
13269:         my $home=&homeserver($uname,$udom);
13270:         my $is_me=0;
13271:         my @ids=&current_machine_ids();
13272:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
13273:         if ($is_me) {
13274:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
13275:         } else {
13276:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
13277:   	      $udom.'/'.$uname.'/'.$filename;
13278:         }
13279:     } elsif ($file =~ m-^/adm/-) {
13280: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
13281:     } else {
13282:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
13283:         $file=~s:^/(res|priv)/:/:;
13284:         my $space=$1;
13285:         if ( !( $file =~ m:^/:) ) {
13286:             $location = $dir. '/'.$file;
13287:         } else {
13288:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
13289:         }
13290:     }
13291:     $location=~s://+:/:g; # remove duplicate /
13292:     while ($location=~m{/\.\./}) {
13293: 	if ($location =~ m{/[^/]+/\.\./}) {
13294: 	    $location=~ s{/[^/]+/\.\./}{/}g;
13295: 	} else {
13296: 	    $location=~ s{/\.\./}{/}g;
13297: 	}
13298:     } #remove dir/..
13299:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
13300:     return $location;
13301: }
13302: 
13303: sub hreflocation {
13304:     my ($dir,$file)=@_;
13305:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
13306: 	$file=filelocation($dir,$file);
13307:     } elsif ($file=~m-^/adm/-) {
13308: 	$file=~s-^/adm/wrapper/-/-;
13309: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
13310:     }
13311:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
13312: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
13313:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
13314: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
13315: 	        {/uploaded/$1/$2/}x;
13316:     }
13317:     if ($file=~ m{^/userfiles/}) {
13318: 	$file =~ s{^/userfiles/}{/uploaded/};
13319:     }
13320:     return $file;
13321: }
13322: 
13323: 
13324: 
13325: 
13326: 
13327: sub current_machine_domains {
13328:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
13329: }
13330: 
13331: sub machine_domains {
13332:     my ($hostname) = @_;
13333:     my @domains;
13334:     my %hostname = &all_hostnames();
13335:     while( my($id, $name) = each(%hostname)) {
13336: #	&logthis("-$id-$name-$hostname-");
13337: 	if ($hostname eq $name) {
13338: 	    push(@domains,&host_domain($id));
13339: 	}
13340:     }
13341:     return @domains;
13342: }
13343: 
13344: sub current_machine_ids {
13345:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
13346: }
13347: 
13348: sub machine_ids {
13349:     my ($hostname) = @_;
13350:     $hostname ||= &hostname($perlvar{'lonHostID'});
13351:     my @ids;
13352:     my %name_to_host = &all_names();
13353:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
13354: 	return @{ $name_to_host{$hostname} };
13355:     }
13356:     return;
13357: }
13358: 
13359: sub additional_machine_domains {
13360:     my @domains;
13361:     open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab");
13362:     while( my $line = <$fh>) {
13363:         $line =~ s/\s//g;
13364:         push(@domains,$line);
13365:     }
13366:     return @domains;
13367: }
13368: 
13369: sub default_login_domain {
13370:     my $domain = $perlvar{'lonDefDomain'};
13371:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
13372:     foreach my $posdom (&current_machine_domains(),
13373:                         &additional_machine_domains()) {
13374:         if (lc($posdom) eq lc($testdomain)) {
13375:             $domain=$posdom;
13376:             last;
13377:         }
13378:     }
13379:     return $domain;
13380: }
13381: 
13382: sub shared_institution {
13383:     my ($dom,$lonhost) = @_;
13384:     if ($lonhost eq '') {
13385:         $lonhost = $perlvar{'lonHostID'};
13386:     }
13387:     my $same_intdom;
13388:     my $hostintdom = &internet_dom($lonhost);
13389:     if ($hostintdom ne '') {
13390:         my %iphost = &get_iphost();
13391:         my $primary_id = &domain($dom,'primary');
13392:         my $primary_ip = &get_host_ip($primary_id);
13393:         if (ref($iphost{$primary_ip}) eq 'ARRAY') {
13394:             foreach my $id (@{$iphost{$primary_ip}}) {
13395:                 my $intdom = &internet_dom($id);
13396:                 if ($intdom eq $hostintdom) {
13397:                     $same_intdom = 1;
13398:                     last;
13399:                 }
13400:             }
13401:         }
13402:     }
13403:     return $same_intdom;
13404: }
13405: 
13406: sub uses_sts {
13407:     my ($ignore_cache) = @_;
13408:     my $lonhost = $perlvar{'lonHostID'};
13409:     my $hostname = &hostname($lonhost);
13410:     my $sts_on;
13411:     if ($protocol{$lonhost} eq 'https') {
13412:         my $cachetime = 12*3600;
13413:         if (!$ignore_cache) {
13414:             ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
13415:             if (defined($cached)) {
13416:                 return $sts_on;
13417:             }
13418:         }
13419:         my $ua=new LWP::UserAgent;
13420:         my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
13421:         my $request=new HTTP::Request('HEAD',$url);
13422:         my $response=$ua->request($request);
13423:         if ($response->is_success) {
13424:             my $has_sts = $response->header('Strict-Transport-Security');
13425:             if ($has_sts eq '') {
13426:                 $sts_on = 0;
13427:             } else {
13428:                 if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
13429:                     my $maxage = $1;
13430:                     if ($maxage) {
13431:                         $sts_on = 1;
13432:                     } else {
13433:                         $sts_on = 0;
13434:                     }
13435:                 } else {
13436:                     $sts_on = 0;
13437:                 }
13438:             }
13439:             return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
13440:         }
13441:     }
13442:     return;
13443: }
13444: 
13445: sub get_requestor_ip {
13446:     my ($r,$nolookup,$noproxy) = @_;
13447:     my $from_ip;
13448:     if (ref($r)) {
13449:         $from_ip = $r->get_remote_host($nolookup);
13450:     } else {
13451:         $from_ip = $ENV{'REMOTE_ADDR'};
13452:     }
13453:     return $from_ip;
13454: }
13455: 
13456: # ------------------------------------------------------------- Declutters URLs
13457: 
13458: sub declutter {
13459:     my $thisfn=shift;
13460:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
13461:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
13462:         $thisfn=~s{^/home/httpd/html}{};
13463:     }
13464:     $thisfn=~s/^\///;
13465:     $thisfn=~s|^adm/wrapper/||;
13466:     $thisfn=~s|^adm/coursedocs/showdoc/||;
13467:     $thisfn=~s/^res\///;
13468:     $thisfn=~s/^priv\///;
13469:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
13470:         $thisfn=~s/\?.+$//;
13471:     }
13472:     return $thisfn;
13473: }
13474: 
13475: # ------------------------------------------------------------- Clutter up URLs
13476: 
13477: sub clutter {
13478:     my $thisfn='/'.&declutter(shift);
13479:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
13480: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
13481:        $thisfn='/res'.$thisfn; 
13482:     }
13483:     if ($thisfn !~m|^/adm|) {
13484: 	if ($thisfn =~ m|^/ext/|) {
13485: 	    $thisfn='/adm/wrapper'.$thisfn;
13486: 	} else {
13487: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
13488: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
13489: 	    if ($embstyle eq 'ssi'
13490: 		|| ($embstyle eq 'hdn')
13491: 		|| ($embstyle eq 'rat')
13492: 		|| ($embstyle eq 'prv')
13493: 		|| ($embstyle eq 'ign')) {
13494: 		#do nothing with these
13495: 	    } elsif (($embstyle eq 'img') 
13496: 		|| ($embstyle eq 'emb')
13497: 		|| ($embstyle eq 'wrp')) {
13498: 		$thisfn='/adm/wrapper'.$thisfn;
13499: 	    } elsif ($embstyle eq 'unk'
13500: 		     && $thisfn!~/\.(sequence|page)$/) {
13501: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
13502: 	    } else {
13503: #		&logthis("Got a blank emb style");
13504: 	    }
13505: 	}
13506:     }
13507:     return $thisfn;
13508: }
13509: 
13510: sub clutter_with_no_wrapper {
13511:     my $uri = &clutter(shift);
13512:     if ($uri =~ m-^/adm/-) {
13513: 	$uri =~ s-^/adm/wrapper/-/-;
13514: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
13515:     }
13516:     return $uri;
13517: }
13518: 
13519: sub freeze_escape {
13520:     my ($value)=@_;
13521:     if (ref($value)) {
13522: 	$value=&nfreeze($value);
13523: 	return '__FROZEN__'.&escape($value);
13524:     }
13525:     return &escape($value);
13526: }
13527: 
13528: 
13529: sub thaw_unescape {
13530:     my ($value)=@_;
13531:     if ($value =~ /^__FROZEN__/) {
13532: 	substr($value,0,10,undef);
13533: 	$value=&unescape($value);
13534: 	return &thaw($value);
13535:     }
13536:     return &unescape($value);
13537: }
13538: 
13539: sub correct_line_ends {
13540:     my ($result)=@_;
13541:     $$result =~s/\r\n/\n/mg;
13542:     $$result =~s/\r/\n/mg;
13543: }
13544: # ================================================================ Main Program
13545: 
13546: sub goodbye {
13547:    &logthis("Starting Shut down");
13548: #not converted to using infrastruture and probably shouldn't be
13549:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
13550: #converted
13551: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
13552:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
13553: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
13554: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
13555: #1.1 only
13556: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
13557: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
13558: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
13559: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
13560:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
13561:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
13562:    &logthis(sprintf("%-20s is %s",'hits',$hits));
13563:    &flushcourselogs();
13564:    &logthis("Shutting down");
13565: }
13566: 
13567: sub get_dns {
13568:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
13569:     if (!$ignore_cache) {
13570: 	my ($content,$cached)=
13571: 	    &Apache::lonnet::is_cached_new('dns',$url);
13572: 	if ($cached) {
13573: 	    &$func($content,$hashref);
13574: 	    return;
13575: 	}
13576:     }
13577: 
13578:     my %alldns;
13579:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
13580:         foreach my $dns (<$config>) {
13581: 	    next if ($dns !~ /^\^(\S*)/x);
13582:             my $line = $1;
13583:             my ($host,$protocol) = split(/:/,$line);
13584:             if ($protocol ne 'https') {
13585:                 $protocol = 'http';
13586:             }
13587: 	    $alldns{$host} = $protocol;
13588:         }
13589:         close($config);
13590:     }
13591:     while (%alldns) {
13592: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
13593: 	my $ua=new LWP::UserAgent;
13594:         $ua->timeout(30);
13595: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
13596: 	my $response=$ua->request($request);
13597:         delete($alldns{$dns});
13598: 	next if ($response->is_error());
13599: 	my @content = split("\n",$response->content);
13600:         unless ($nocache) {
13601: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
13602:         }
13603: 	&$func(\@content,$hashref);
13604: 	return;
13605:     }
13606:     my $which = (split('/',$url))[3];
13607:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
13608:     if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
13609:         my @content = <$config>;
13610:         &$func(\@content,$hashref);
13611:     }
13612:     return;
13613: }
13614: 
13615: # ------------------------------------------------------Get DNS checksums file
13616: sub parse_dns_checksums_tab {
13617:     my ($lines,$hashref) = @_;
13618:     my $lonhost = $perlvar{'lonHostID'};
13619:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
13620:     my $loncaparev = &get_server_loncaparev($machine_dom);
13621:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
13622:     my $webconfdir = '/etc/httpd/conf';
13623:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
13624:         $webconfdir = '/etc/apache2';
13625:     } elsif ($distro =~ /^sles(\d+)$/) {
13626:         if ($1 >= 10) {
13627:             $webconfdir = '/etc/apache2';
13628:         }
13629:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
13630:         if ($1 >= 10.0) {
13631:             $webconfdir = '/etc/apache2';
13632:         }
13633:     }
13634:     my ($release,$timestamp) = split(/\-/,$loncaparev);
13635:     my (%chksum,%revnum);
13636:     if (ref($lines) eq 'ARRAY') {
13637:         chomp(@{$lines});
13638:         my $version = shift(@{$lines});
13639:         if ($version eq $release) {
13640:             foreach my $line (@{$lines}) {
13641:                 my ($file,$version,$shasum) = split(/,/,$line);
13642:                 if ($file =~ m{^/etc/httpd/conf}) {
13643:                     if ($webconfdir eq '/etc/apache2') {
13644:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
13645:                     }
13646:                 }
13647:                 $chksum{$file} = $shasum;
13648:                 $revnum{$file} = $version;
13649:             }
13650:             if (ref($hashref) eq 'HASH') {
13651:                 %{$hashref} = (
13652:                                 sums     => \%chksum,
13653:                                 versions => \%revnum,
13654:                               );
13655:             }
13656:         }
13657:     }
13658:     return;
13659: }
13660: 
13661: sub fetch_dns_checksums {
13662:     my %checksums;
13663:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
13664:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
13665:     my ($release,$timestamp) = split(/\-/,$loncaparev);
13666:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
13667:              \%checksums);
13668:     return \%checksums;
13669: }
13670: 
13671: # ------------------------------------------------------------ Read domain file
13672: {
13673:     my $loaded;
13674:     my %domain;
13675: 
13676:     sub parse_domain_tab {
13677: 	my ($lines) = @_;
13678: 	foreach my $line (@$lines) {
13679: 	    next if ($line =~ /^(\#|\s*$ )/x);
13680: 
13681: 	    chomp($line);
13682: 	    my ($name,@elements) = split(/:/,$line,9);
13683: 	    my %this_domain;
13684: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
13685: 			       'lang_def', 'city', 'longi', 'lati',
13686: 			       'primary') {
13687: 		$this_domain{$field} = shift(@elements);
13688: 	    }
13689: 	    $domain{$name} = \%this_domain;
13690: 	}
13691:     }
13692: 
13693:     sub reset_domain_info {
13694: 	undef($loaded);
13695: 	undef(%domain);
13696:     }
13697: 
13698:     sub load_domain_tab {
13699: 	my ($ignore_cache,$nocache) = @_;
13700: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
13701: 	my $fh;
13702: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
13703: 	    my @lines = <$fh>;
13704: 	    &parse_domain_tab(\@lines);
13705: 	}
13706: 	close($fh);
13707: 	$loaded = 1;
13708:     }
13709: 
13710:     sub domain {
13711: 	&load_domain_tab() if (!$loaded);
13712: 
13713: 	my ($name,$what) = @_;
13714: 	return if ( !exists($domain{$name}) );
13715: 
13716: 	if (!$what) {
13717: 	    return $domain{$name}{'description'};
13718: 	}
13719: 	return $domain{$name}{$what};
13720:     }
13721: 
13722:     sub domain_info {
13723:         &load_domain_tab() if (!$loaded);
13724:         return %domain;
13725:     }
13726: 
13727: }
13728: 
13729: 
13730: # ------------------------------------------------------------- Read hosts file
13731: {
13732:     my %hostname;
13733:     my %hostdom;
13734:     my %libserv;
13735:     my $loaded;
13736:     my %name_to_host;
13737:     my %internetdom;
13738:     my %LC_dns_serv;
13739: 
13740:     sub parse_hosts_tab {
13741: 	my ($file) = @_;
13742: 	foreach my $configline (@$file) {
13743: 	    next if ($configline =~ /^(\#|\s*$ )/x);
13744:             chomp($configline);
13745: 	    if ($configline =~ /^\^/) {
13746:                 if ($configline =~ /^\^([\w.\-]+)/) {
13747:                     $LC_dns_serv{$1} = 1;
13748:                 }
13749:                 next;
13750:             }
13751: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
13752: 	    $name=~s/\s//g;
13753: 	    if ($id && $domain && $role && $name) {
13754:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
13755:                     my $curr = $hostname{$id};
13756:                     my $skip;
13757:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
13758:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
13759:                             $skip = 1;
13760:                         } else {
13761:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
13762:                         }
13763:                     }
13764:                     unless ($skip) {
13765:                         push(@{$name_to_host{$name}},$id);
13766:                     }
13767:                 } else {
13768:                     push(@{$name_to_host{$name}},$id);
13769:                 }
13770: 		$hostname{$id}=$name;
13771: 		$hostdom{$id}=$domain;
13772: 		if ($role eq 'library') { $libserv{$id}=$name; }
13773:                 if (defined($protocol)) {
13774:                     if ($protocol eq 'https') {
13775:                         $protocol{$id} = $protocol;
13776:                     } else {
13777:                         $protocol{$id} = 'http'; 
13778:                     }
13779:                 } else {
13780:                     $protocol{$id} = 'http';
13781:                 }
13782:                 if (defined($intdom)) {
13783:                     $internetdom{$id} = $intdom;
13784:                 }
13785: 	    }
13786: 	}
13787:     }
13788:     
13789:     sub reset_hosts_info {
13790: 	&purge_remembered();
13791: 	&reset_domain_info();
13792: 	&reset_hosts_ip_info();
13793: 	undef(%name_to_host);
13794: 	undef(%hostname);
13795: 	undef(%hostdom);
13796: 	undef(%libserv);
13797: 	undef($loaded);
13798:     }
13799: 
13800:     sub load_hosts_tab {
13801: 	my ($ignore_cache,$nocache) = @_;
13802: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
13803: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
13804: 	my @config = <$config>;
13805: 	&parse_hosts_tab(\@config);
13806: 	close($config);
13807: 	$loaded=1;
13808:     }
13809: 
13810:     sub hostname {
13811: 	&load_hosts_tab() if (!$loaded);
13812: 
13813: 	my ($lonid) = @_;
13814: 	return $hostname{$lonid};
13815:     }
13816: 
13817:     sub all_hostnames {
13818: 	&load_hosts_tab() if (!$loaded);
13819: 
13820: 	return %hostname;
13821:     }
13822: 
13823:     sub all_names {
13824:         my ($ignore_cache,$nocache) = @_;
13825: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
13826: 
13827: 	return %name_to_host;
13828:     }
13829: 
13830:     sub all_host_domain {
13831:         &load_hosts_tab() if (!$loaded);
13832:         return %hostdom;
13833:     }
13834: 
13835:     sub is_library {
13836: 	&load_hosts_tab() if (!$loaded);
13837: 
13838: 	return exists($libserv{$_[0]});
13839:     }
13840: 
13841:     sub all_library {
13842: 	&load_hosts_tab() if (!$loaded);
13843: 
13844: 	return %libserv;
13845:     }
13846: 
13847:     sub unique_library {
13848: 	#2x reverse removes all hostnames that appear more than once
13849:         my %unique = reverse &all_library();
13850:         return reverse %unique;
13851:     }
13852: 
13853:     sub get_servers {
13854: 	&load_hosts_tab() if (!$loaded);
13855: 
13856: 	my ($domain,$type) = @_;
13857: 	my %possible_hosts = ($type eq 'library') ? %libserv
13858: 	                                          : %hostname;
13859: 	my %result;
13860: 	if (ref($domain) eq 'ARRAY') {
13861: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
13862: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
13863: 		    $result{$host} = $hostname;
13864: 		}
13865: 	    }
13866: 	} else {
13867: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
13868: 		if ($hostdom{$host} eq $domain) {
13869: 		    $result{$host} = $hostname;
13870: 		}
13871: 	    }
13872: 	}
13873: 	return %result;
13874:     }
13875: 
13876:     sub get_unique_servers {
13877:         my %unique = reverse &get_servers(@_);
13878: 	return reverse %unique;
13879:     }
13880: 
13881:     sub host_domain {
13882: 	&load_hosts_tab() if (!$loaded);
13883: 
13884: 	my ($lonid) = @_;
13885: 	return $hostdom{$lonid};
13886:     }
13887: 
13888:     sub all_domains {
13889: 	&load_hosts_tab() if (!$loaded);
13890: 
13891: 	my %seen;
13892: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
13893: 	return @uniq;
13894:     }
13895: 
13896:     sub internet_dom {
13897:         &load_hosts_tab() if (!$loaded);
13898: 
13899:         my ($lonid) = @_;
13900:         return $internetdom{$lonid};
13901:     }
13902: 
13903:     sub is_LC_dns {
13904:         &load_hosts_tab() if (!$loaded);
13905: 
13906:         my ($hostname) = @_;
13907:         return exists($LC_dns_serv{$hostname});
13908:     }
13909: 
13910: }
13911: 
13912: { 
13913:     my %iphost;
13914:     my %name_to_ip;
13915:     my %lonid_to_ip;
13916: 
13917:     sub get_hosts_from_ip {
13918: 	my ($ip) = @_;
13919: 	my %iphosts = &get_iphost();
13920: 	if (ref($iphosts{$ip})) {
13921: 	    return @{$iphosts{$ip}};
13922: 	}
13923: 	return;
13924:     }
13925:     
13926:     sub reset_hosts_ip_info {
13927: 	undef(%iphost);
13928: 	undef(%name_to_ip);
13929: 	undef(%lonid_to_ip);
13930:     }
13931: 
13932:     sub get_host_ip {
13933: 	my ($lonid) = @_;
13934: 	if (exists($lonid_to_ip{$lonid})) {
13935: 	    return $lonid_to_ip{$lonid};
13936: 	}
13937: 	my $name=&hostname($lonid);
13938:    	my $ip = gethostbyname($name);
13939: 	return if (!$ip || length($ip) ne 4);
13940: 	$ip=inet_ntoa($ip);
13941: 	$name_to_ip{$name}   = $ip;
13942: 	$lonid_to_ip{$lonid} = $ip;
13943: 	return $ip;
13944:     }
13945:     
13946:     sub get_iphost {
13947: 	my ($ignore_cache,$nocache) = @_;
13948: 
13949: 	if (!$ignore_cache) {
13950: 	    if (%iphost) {
13951: 		return %iphost;
13952: 	    }
13953: 	    my ($ip_info,$cached)=
13954: 		&Apache::lonnet::is_cached_new('iphost','iphost');
13955: 	    if ($cached) {
13956: 		%iphost      = %{$ip_info->[0]};
13957: 		%name_to_ip  = %{$ip_info->[1]};
13958: 		%lonid_to_ip = %{$ip_info->[2]};
13959: 		return %iphost;
13960: 	    }
13961: 	}
13962: 
13963: 	# get yesterday's info for fallback
13964: 	my %old_name_to_ip;
13965: 	my ($ip_info,$cached)=
13966: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
13967: 	if ($cached) {
13968: 	    %old_name_to_ip = %{$ip_info->[1]};
13969: 	}
13970: 
13971: 	my %name_to_host = &all_names($ignore_cache,$nocache);
13972: 	foreach my $name (keys(%name_to_host)) {
13973: 	    my $ip;
13974: 	    if (!exists($name_to_ip{$name})) {
13975: 		$ip = gethostbyname($name);
13976: 		if (!$ip || length($ip) ne 4) {
13977: 		    if (defined($old_name_to_ip{$name})) {
13978: 			$ip = $old_name_to_ip{$name};
13979: 			&logthis("Can't find $name defaulting to old $ip");
13980: 		    } else {
13981: 			&logthis("Name $name no IP found");
13982: 			next;
13983: 		    }
13984: 		} else {
13985: 		    $ip=inet_ntoa($ip);
13986: 		}
13987: 		$name_to_ip{$name} = $ip;
13988: 	    } else {
13989: 		$ip = $name_to_ip{$name};
13990: 	    }
13991: 	    foreach my $id (@{ $name_to_host{$name} }) {
13992: 		$lonid_to_ip{$id} = $ip;
13993: 	    }
13994: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
13995: 	}
13996:         unless ($nocache) {
13997: 	    &do_cache_new('iphost','iphost',
13998: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
13999: 		          48*60*60);
14000:         }
14001: 
14002: 	return %iphost;
14003:     }
14004: 
14005:     #
14006:     #  Given a DNS returns the loncapa host name for that DNS 
14007:     # 
14008:     sub host_from_dns {
14009:         my ($dns) = @_;
14010:         my @hosts;
14011:         my $ip;
14012: 
14013:         if (exists($name_to_ip{$dns})) {
14014:             $ip = $name_to_ip{$dns};
14015:         }
14016:         if (!$ip) {
14017:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
14018:             if (length($ip) == 4) { 
14019: 	        $ip   = &IO::Socket::inet_ntoa($ip);
14020:             }
14021:         }
14022:         if ($ip) {
14023: 	    @hosts = get_hosts_from_ip($ip);
14024: 	    return $hosts[0];
14025:         }
14026:         return undef;
14027:     }
14028: 
14029:     sub get_internet_names {
14030:         my ($lonid) = @_;
14031:         return if ($lonid eq '');
14032:         my ($idnref,$cached)=
14033:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
14034:         if ($cached) {
14035:             return $idnref;
14036:         }
14037:         my $ip = &get_host_ip($lonid);
14038:         my @hosts = &get_hosts_from_ip($ip);
14039:         my %iphost = &get_iphost();
14040:         my (@idns,%seen);
14041:         foreach my $id (@hosts) {
14042:             my $dom = &host_domain($id);
14043:             my $prim_id = &domain($dom,'primary');
14044:             my $prim_ip = &get_host_ip($prim_id);
14045:             next if ($seen{$prim_ip});
14046:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
14047:                 foreach my $id (@{$iphost{$prim_ip}}) {
14048:                     my $intdom = &internet_dom($id);
14049:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
14050:                         push(@idns,$intdom);
14051:                     }
14052:                 }
14053:             }
14054:             $seen{$prim_ip} = 1;
14055:         }
14056:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
14057:     }
14058: 
14059: }
14060: 
14061: sub all_loncaparevs {
14062:     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);
14063: }
14064: 
14065: # ------------------------------------------------------- Read loncaparev table
14066: {
14067:     sub load_loncaparevs {
14068:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
14069:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
14070:                 while (my $configline=<$config>) {
14071:                     chomp($configline);
14072:                     my ($hostid,$loncaparev)=split(/:/,$configline);
14073:                     $loncaparevs{$hostid}=$loncaparev;
14074:                 }
14075:                 close($config);
14076:             }
14077:         }
14078:     }
14079: }
14080: 
14081: # ----------------------------------------------------- Read serverhostID table
14082: {
14083:     sub load_serverhomeIDs {
14084:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
14085:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
14086:                 while (my $configline=<$config>) {
14087:                     chomp($configline);
14088:                     my ($name,$id)=split(/:/,$configline);
14089:                     $serverhomeIDs{$name}=$id;
14090:                 }
14091:                 close($config);
14092:             }
14093:         }
14094:     }
14095: }
14096: 
14097: 
14098: BEGIN {
14099: 
14100: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
14101:     unless ($readit) {
14102: {
14103:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
14104:     %perlvar = (%perlvar,%{$configvars});
14105: }
14106: 
14107: 
14108: # ------------------------------------------------------ Read spare server file
14109: {
14110:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
14111: 
14112:     while (my $configline=<$config>) {
14113:        chomp($configline);
14114:        if ($configline) {
14115: 	   my ($host,$type) = split(':',$configline,2);
14116: 	   if (!defined($type) || $type eq '') { $type = 'default' };
14117: 	   push(@{ $spareid{$type} }, $host);
14118:        }
14119:     }
14120:     close($config);
14121: }
14122: # ------------------------------------------------------------ Read permissions
14123: {
14124:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
14125: 
14126:     while (my $configline=<$config>) {
14127: 	chomp($configline);
14128: 	if ($configline) {
14129: 	    my ($role,$perm)=split(/ /,$configline);
14130: 	    if ($perm ne '') { $pr{$role}=$perm; }
14131: 	}
14132:     }
14133:     close($config);
14134: }
14135: 
14136: # -------------------------------------------- Read plain texts for permissions
14137: {
14138:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
14139: 
14140:     while (my $configline=<$config>) {
14141: 	chomp($configline);
14142: 	if ($configline) {
14143: 	    my ($short,@plain)=split(/:/,$configline);
14144:             %{$prp{$short}} = ();
14145: 	    if (@plain > 0) {
14146:                 $prp{$short}{'std'} = $plain[0];
14147:                 for (my $i=1; $i<@plain; $i++) {
14148:                     $prp{$short}{'alt'.$i} = $plain[$i];  
14149:                 }
14150:             }
14151: 	}
14152:     }
14153:     close($config);
14154: }
14155: 
14156: # ---------------------------------------------------------- Read package table
14157: {
14158:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
14159: 
14160:     while (my $configline=<$config>) {
14161: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
14162: 	chomp($configline);
14163: 	my ($short,$plain)=split(/:/,$configline);
14164: 	my ($pack,$name)=split(/\&/,$short);
14165: 	if ($plain ne '') {
14166: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
14167: 	    $packagetab{$short}=$plain; 
14168: 	}
14169:     }
14170:     close($config);
14171: }
14172: 
14173: # --------------------------------------------------------- Read loncaparev table
14174: 
14175: &load_loncaparevs();
14176: 
14177: # ------------------------------------------------------- Read serverhostID table
14178: 
14179: &load_serverhomeIDs();
14180: 
14181: # ---------------------------------------------------------- Read releaseslist XML
14182: {
14183:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
14184:     if (-e $file) {
14185:         my $parser = HTML::LCParser->new($file);
14186:         while (my $token = $parser->get_token()) {
14187:             if ($token->[0] eq 'S') {
14188:                 my $item = $token->[1];
14189:                 my $name = $token->[2]{'name'};
14190:                 my $value = $token->[2]{'value'};
14191:                 if ($item ne '' && $name ne '' && $value ne '') {
14192:                     my $release = $parser->get_text();
14193:                     $release =~ s/(^\s*|\s*$ )//gx;
14194:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
14195:                 }
14196:             }
14197:         }
14198:     }
14199: }
14200: 
14201: # ---------------------------------------------------------- Read managers table
14202: {
14203:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
14204:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
14205:             while (my $configline=<$config>) {
14206:                 chomp($configline);
14207:                 next if ($configline =~ /^\#/);
14208:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
14209:                     $managerstab{$configline} = 1;
14210:                 }
14211:             }
14212:             close($config);
14213:         }
14214:     }
14215: }
14216: 
14217: # ------------- set up temporary directory
14218: {
14219:     $tmpdir = LONCAPA::tempdir();
14220: 
14221: }
14222: 
14223: # ------------- set default texengine (domain default overrides this)
14224: {
14225:     $deftex = LONCAPA::texengine();
14226: }
14227: 
14228: # ------------- set default minimum length for passwords for internal auth users
14229: {
14230:     $passwdmin = LONCAPA::passwd_min();
14231: }
14232: 
14233: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
14234: 				'compress_threshold'=> 20_000,
14235:  			        });
14236: 
14237: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
14238: $dumpcount=0;
14239: $locknum=0;
14240: 
14241: &logtouch();
14242: &logthis('<font color="yellow">INFO: Read configuration</font>');
14243: $readit=1;
14244:     {
14245: 	use integer;
14246: 	my $test=(2**32)+1;
14247: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
14248: 	&logthis(" Detected 64bit platform ($_64bit)");
14249:     }
14250: }
14251: }
14252: 
14253: 1;
14254: __END__
14255: 
14256: =pod
14257: 
14258: =head1 NAME
14259: 
14260: Apache::lonnet - Subroutines to ask questions about things in the network.
14261: 
14262: =head1 SYNOPSIS
14263: 
14264: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
14265: 
14266:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
14267: 
14268: Common parameters:
14269: 
14270: =over 4
14271: 
14272: =item *
14273: 
14274: $uname : an internal username (if $cname expecting a course Id specifically)
14275: 
14276: =item *
14277: 
14278: $udom : a domain (if $cdom expecting a course's domain specifically)
14279: 
14280: =item *
14281: 
14282: $symb : a resource instance identifier
14283: 
14284: =item *
14285: 
14286: $namespace : the name of a .db file that contains the data needed or
14287: being set.
14288: 
14289: =back
14290: 
14291: =head1 OVERVIEW
14292: 
14293: lonnet provides subroutines which interact with the
14294: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
14295: about classes, users, and resources.
14296: 
14297: For many of these objects you can also use this to store data about
14298: them or modify them in various ways.
14299: 
14300: =head2 Symbs
14301: 
14302: To identify a specific instance of a resource, LON-CAPA uses symbols
14303: or "symbs"X<symb>. These identifiers are built from the URL of the
14304: map, the resource number of the resource in the map, and the URL of
14305: the resource itself. The latter is somewhat redundant, but might help
14306: if maps change.
14307: 
14308: An example is
14309: 
14310:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
14311: 
14312: The respective map entry is
14313: 
14314:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
14315:   title="Problem 2">
14316:  </resource>
14317: 
14318: Symbs are used by the random number generator, as well as to store and
14319: restore data specific to a certain instance of for example a problem.
14320: 
14321: =head2 Storing And Retrieving Data
14322: 
14323: X<store()>X<cstore()>X<restore()>Three of the most important functions
14324: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
14325: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
14326: is is the non-critical message twin of cstore. These functions are for
14327: handlers to store a perl hash to a user's permanent data space in an
14328: easy manner, and to retrieve it again on another call. It is expected
14329: that a handler would use this once at the beginning to retrieve data,
14330: and then again once at the end to send only the new data back.
14331: 
14332: The data is stored in the user's data directory on the user's
14333: homeserver under the ID of the course.
14334: 
14335: The hash that is returned by restore will have all of the previous
14336: value for all of the elements of the hash.
14337: 
14338: Example:
14339: 
14340:  #creating a hash
14341:  my %hash;
14342:  $hash{'foo'}='bar';
14343: 
14344:  #storing it
14345:  &Apache::lonnet::cstore(\%hash);
14346: 
14347:  #changing a value
14348:  $hash{'foo'}='notbar';
14349: 
14350:  #adding a new value
14351:  $hash{'bar'}='foo';
14352:  &Apache::lonnet::cstore(\%hash);
14353: 
14354:  #retrieving the hash
14355:  my %history=&Apache::lonnet::restore();
14356: 
14357:  #print the hash
14358:  foreach my $key (sort(keys(%history))) {
14359:    print("\%history{$key} = $history{$key}");
14360:  }
14361: 
14362: Will print out:
14363: 
14364:  %history{1:foo} = bar
14365:  %history{1:keys} = foo:timestamp
14366:  %history{1:timestamp} = 990455579
14367:  %history{2:bar} = foo
14368:  %history{2:foo} = notbar
14369:  %history{2:keys} = foo:bar:timestamp
14370:  %history{2:timestamp} = 990455580
14371:  %history{bar} = foo
14372:  %history{foo} = notbar
14373:  %history{timestamp} = 990455580
14374:  %history{version} = 2
14375: 
14376: Note that the special hash entries C<keys>, C<version> and
14377: C<timestamp> were added to the hash. C<version> will be equal to the
14378: total number of versions of the data that have been stored. The
14379: C<timestamp> attribute will be the UNIX time the hash was
14380: stored. C<keys> is available in every historical section to list which
14381: keys were added or changed at a specific historical revision of a
14382: hash.
14383: 
14384: B<Warning>: do not store the hash that restore returns directly. This
14385: will cause a mess since it will restore the historical keys as if the
14386: were new keys. I.E. 1:foo will become 1:1:foo etc.
14387: 
14388: Calling convention:
14389: 
14390:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
14391:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
14392: 
14393: For more detailed information, see lonnet specific documentation.
14394: 
14395: =head1 RETURN MESSAGES
14396: 
14397: =over 4
14398: 
14399: =item * B<con_lost>: unable to contact remote host
14400: 
14401: =item * B<con_delayed>: unable to contact remote host, message will be delivered
14402: when the connection is brought back up
14403: 
14404: =item * B<con_failed>: unable to contact remote host and unable to save message
14405: for later delivery
14406: 
14407: =item * B<error:>: an error a occurred, a description of the error follows the :
14408: 
14409: =item * B<no_such_host>: unable to fund a host associated with the user/domain
14410: that was requested
14411: 
14412: =back
14413: 
14414: =head1 PUBLIC SUBROUTINES
14415: 
14416: =head2 Session Environment Functions
14417: 
14418: =over 4
14419: 
14420: =item * 
14421: X<appenv()>
14422: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
14423: the user envirnoment file, and will be restored for each access this
14424: user makes during this session, also modifies the %env for the current
14425: process. Optional rolesarrayref - if defined contains a reference to an array
14426: of roles which are exempt from the restriction on modifying user.role entries 
14427: in the user's environment.db and in %env.    
14428: 
14429: =item *
14430: X<delenv()>
14431: B<delenv($delthis,$regexp)>: removes all items from the session
14432: environment file that begin with $delthis. If the 
14433: optional second arg - $regexp - is true, $delthis is treated as a 
14434: regular expression, otherwise \Q$delthis\E is used. 
14435: The values are also deleted from the current processes %env.
14436: 
14437: =item * get_env_multiple($name) 
14438: 
14439: gets $name from the %env hash, it seemlessly handles the cases where multiple
14440: values may be defined and end up as an array ref.
14441: 
14442: returns an array of values
14443: 
14444: =back
14445: 
14446: =head2 User Information
14447: 
14448: =over 4
14449: 
14450: =item *
14451: X<queryauthenticate()>
14452: B<queryauthenticate($uname,$udom)>: try to determine user's current 
14453: authentication scheme
14454: 
14455: =item *
14456: X<authenticate()>
14457: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
14458: authenticate user from domain's lib servers (first use the current
14459: one). C<$upass> should be the users password.
14460: $checkdefauth is optional (value is 1 if a check should be made to
14461:    authenticate user using default authentication method, and allow
14462:    account creation if username does not have account in the domain).
14463: $clientcancheckhost is optional (value is 1 if checking whether the
14464:    server can host will occur on the client side in lonauth.pm).   
14465: 
14466: =item *
14467: X<homeserver()>
14468: B<homeserver($uname,$udom)>: find the server which has
14469: the user's directory and files (there must be only one), this caches
14470: the answer, and also caches if there is a borken connection.
14471: 
14472: =item *
14473: X<idget()>
14474: B<idget($udom,@ids)>: find the usernames behind a list of IDs
14475: (IDs are a unique resource in a domain, there must be only 1 ID per
14476: username, and only 1 username per ID in a specific domain) (returns
14477: hash: id=>name,id=>name)
14478: 
14479: =item *
14480: X<idrget()>
14481: B<idrget($udom,@unames)>: find the IDs behind a list of
14482: usernames (returns hash: name=>id,name=>id)
14483: 
14484: =item *
14485: X<idput()>
14486: B<idput($udom,%ids)>: store away a list of names and associated IDs
14487: 
14488: =item *
14489: X<rolesinit()>
14490: B<rolesinit($udom,$username)>: get user privileges.
14491: returns user role, first access and timer interval hashes
14492: 
14493: =item *
14494: X<privileged()>
14495: B<privileged($username,$domain)>: returns a true if user has a
14496: privileged and active role (i.e. su or dc), false otherwise.
14497: 
14498: =item *
14499: X<getsection()>
14500: B<getsection($udom,$uname,$cname)>: finds the section of student in the
14501: course $cname, return section name/number or '' for "not in course"
14502: and '-1' for "no section"
14503: 
14504: =item *
14505: X<userenvironment()>
14506: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
14507: passed in @what from the requested user's environment, returns a hash
14508: 
14509: =item * 
14510: X<userlog_query()>
14511: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
14512: activity.log file. %filters defines filters applied when parsing the
14513: log file. These can be start or end timestamps, or the type of action
14514: - log to look for Login or Logout events, check for Checkin or
14515: Checkout, role for role selection. The response is in the form
14516: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
14517: escaped strings of the action recorded in the activity.log file.
14518: 
14519: =back
14520: 
14521: =head2 User Roles
14522: 
14523: =over 4
14524: 
14525: =item *
14526: 
14527: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
14528: returns codes for allowed actions.
14529: 
14530: The first argument is required, all others are optional.
14531: 
14532: $priv is the privilege being checked.
14533: $uri contains additional information about what is being checked for access (e.g.,
14534: URL, course ID etc.).
14535: $symb is the unique resource instance identifier in a course; if needed,
14536: but not provided, it will be retrieved via a call to &symbread().
14537: $role is the role for which a priv is being checked (only used if priv is evb).
14538: $clientip is the user's IP address (only used when checking for access to portfolio
14539: files).
14540: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
14541: prevents recursive calls to &allowed.
14542: 
14543:  F: full access
14544:  U,I,K: authentication modes (cxx only)
14545:  '': forbidden
14546:  1: user needs to choose course
14547:  2: browse allowed
14548:  A: passphrase authentication needed
14549:  B: access temporarily blocked because of a blocking event in a course.
14550: 
14551: =item *
14552: 
14553: constructaccess($url,$setpriv) : check for access to construction space URL
14554: 
14555: See if the owner domain and name in the URL match those in the
14556: expected environment.  If so, return three element list
14557: ($ownername,$ownerdomain,$ownerhome).
14558: 
14559: Otherwise return the null string.
14560: 
14561: If second argument 'setpriv' is true, it assigns the privileges,
14562: and returns the same three element list, unless the owner has
14563: blocked "ad hoc" Domain Coordinator access to the Author Space,
14564: in which case the null string is returned.
14565: 
14566: =item *
14567: 
14568: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
14569: define a custom role rolename set privileges in format of lonTabs/roles.tab
14570: for system, domain, and course level. $uname and $udom are optional (current
14571: user's username and domain will be used when either of $uname or $udom are absent.
14572: 
14573: =item *
14574: 
14575: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
14576: (rolesplain.tab); plain text explanation of a user role term.
14577: $type is Course (default) or Community.
14578: If $forcedefault evaluates to true, text returned will be default 
14579: text for $type. Otherwise, if this is a course, the text returned 
14580: will be a custom name for the role (if defined in the course's 
14581: environment).  If no custom name is defined the default is returned.
14582:    
14583: =item *
14584: 
14585: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
14586: All arguments are optional. Returns a hash of a roles, either for
14587: co-author/assistant author roles for a user's Construction Space
14588: (default), or if $context is 'userroles', roles for the user himself,
14589: In the hash, keys are set to colon-separated $uname,$udom,$role, and
14590: (optionally) if $withsec is true, a fourth colon-separated item - $section.
14591: For each key, value is set to colon-separated start and end times for
14592: the role.  If no username and domain are specified, will default to
14593: current user/domain. Types, roles, and roledoms are references to arrays
14594: of role statuses (active, future or previous), roles 
14595: (e.g., cc,in, st etc.) and domains of the roles which can be used
14596: to restrict the list of roles reported. If no array ref is 
14597: provided for types, will default to return only active roles.
14598: 
14599: =item *
14600: 
14601: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
14602: user: $uname:$udom has a role in the course: $cdom_$cnum.
14603: 
14604: Additional optional arguments are: $type (if role checking is to be restricted
14605: to certain user status types -- previous (expired roles), active (currently
14606: available roles) or future (roles available in the future), and
14607: $hideprivileged -- if true will not report course roles for users who
14608: have active Domain Coordinator role in course's domain or in additional
14609: domains (specified in 'Domains to check for privileged users' in course
14610: environment -- set via:  Course Settings -> Classlists and staff listing).
14611: 
14612: =item *
14613: 
14614: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
14615: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
14616: $possdomains and $possroles are optional array refs -- to domains to check and
14617: roles to check.  If $possdomains is not specified, a dump will be done of the
14618: users' roles.db to check for a dc or su role in any domain. This can be
14619: time consuming if &privileged is called repeatedly (e.g., when displaying a
14620: classlist), so in such cases, supplying a $possdomains array is preferred, as
14621: this then allows &privileged_by_domain() to be used, which caches the identity
14622: of privileged users, eliminating the need for repeated calls to &dump().
14623: 
14624: =item *
14625: 
14626: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
14627: where the outer hash keys are domains specified in the $possdomains array ref,
14628: next inner hash keys are privileged roles specified in the $roles array ref,
14629: and the innermost hash contains key = value pairs for username:domain = end:start
14630: for active or future "privileged" users with that role in that domain. To avoid
14631: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
14632: innerhash are cached using priv_$role and $dom as the identifiers.
14633: 
14634: =back
14635: 
14636: =head2 User Modification
14637: 
14638: =over 4
14639: 
14640: =item *
14641: 
14642: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
14643: user for the level given by URL.  Optional start and end dates (leave empty
14644: string or zero for "no date")
14645: 
14646: =item *
14647: 
14648: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
14649: change a users, password, possible return values are: ok,
14650: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
14651: refused
14652: 
14653: =item *
14654: 
14655: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
14656: 
14657: =item *
14658: 
14659: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
14660:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
14661: 
14662: will update user information (firstname,middlename,lastname,generation,
14663: permanentemail), and if forceid is true, student/employee ID also.
14664: A user's institutional affiliation(s) can also be updated.
14665: User information fields will not be overwritten with empty entries 
14666: unless the field is included in the $candelete array reference.
14667: This array is included when a single user is modified via "Manage Users",
14668: or when Autoupdate.pl is run by cron in a domain.
14669: 
14670: =item *
14671: 
14672: modifystudent
14673: 
14674: modify a student's enrollment and identification information.
14675: The course id is resolved based on the current user's environment.  
14676: This means the invoking user must be a course coordinator or otherwise
14677: associated with a course.
14678: 
14679: This call is essentially a wrapper for lonnet::modifyuser and
14680: lonnet::modify_student_enrollment
14681: 
14682: Inputs: 
14683: 
14684: =over 4
14685: 
14686: =item B<$udom> Student's loncapa domain
14687: 
14688: =item B<$uname> Student's loncapa login name
14689: 
14690: =item B<$uid> Student/Employee ID
14691: 
14692: =item B<$umode> Student's authentication mode
14693: 
14694: =item B<$upass> Student's password
14695: 
14696: =item B<$first> Student's first name
14697: 
14698: =item B<$middle> Student's middle name
14699: 
14700: =item B<$last> Student's last name
14701: 
14702: =item B<$gene> Student's generation
14703: 
14704: =item B<$usec> Student's section in course
14705: 
14706: =item B<$end> Unix time of the roles expiration
14707: 
14708: =item B<$start> Unix time of the roles start date
14709: 
14710: =item B<$forceid> If defined, allow $uid to be changed
14711: 
14712: =item B<$desiredhome> server to use as home server for student
14713: 
14714: =item B<$email> Student's permanent e-mail address
14715: 
14716: =item B<$type> Type of enrollment (auto or manual)
14717: 
14718: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
14719: 
14720: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
14721: 
14722: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
14723: 
14724: =item B<$context> role change context (shown in User Management Logs display in a course)
14725: 
14726: =item B<$inststatus> institutional status of user - : separated string of escaped status types
14727: 
14728: =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.
14729: 
14730: =back
14731: 
14732: =item *
14733: 
14734: modify_student_enrollment
14735: 
14736: Change a student's enrollment status in a class.  The environment variable
14737: 'role.request.course' must be defined for this function to proceed.
14738: 
14739: Inputs:
14740: 
14741: =over 4
14742: 
14743: =item $udom, student's domain
14744: 
14745: =item $uname, student's name
14746: 
14747: =item $uid, student's user id
14748: 
14749: =item $first, student's first name
14750: 
14751: =item $middle
14752: 
14753: =item $last
14754: 
14755: =item $gene
14756: 
14757: =item $usec
14758: 
14759: =item $end
14760: 
14761: =item $start
14762: 
14763: =item $type
14764: 
14765: =item $locktype
14766: 
14767: =item $cid
14768: 
14769: =item $selfenroll
14770: 
14771: =item $context
14772: 
14773: =item $credits, number of credits student will earn from this class
14774: 
14775: =item $instsec, institutional course section code for student
14776: 
14777: =back
14778: 
14779: 
14780: =item *
14781: 
14782: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
14783: custom role; give a custom role to a user for the level given by URL.  Specify
14784: name and domain of role author, and role name
14785: 
14786: =item *
14787: 
14788: revokerole($udom,$uname,$url,$role) : revoke a role for url
14789: 
14790: =item *
14791: 
14792: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
14793: 
14794: =back
14795: 
14796: =head2 Course Infomation
14797: 
14798: =over 4
14799: 
14800: =item *
14801: 
14802: coursedescription($courseid,$options) : returns a hash of information about the
14803: specified course id, including all environment settings for the
14804: course, the description of the course will be in the hash under the
14805: key 'description'
14806: 
14807: $options is an optional parameter that if supplied is a hash reference that controls
14808: what how this function works.  It has the following key/values:
14809: 
14810: =over 4
14811: 
14812: =item freshen_cache
14813: 
14814: If defined, and the environment cache for the course is valid, it is 
14815: returned in the returned hash.
14816: 
14817: =item one_time
14818: 
14819: If defined, the last cache time is set to _now_
14820: 
14821: =item user
14822: 
14823: If defined, the supplied username is used instead of the current user.
14824: 
14825: 
14826: =back
14827: 
14828: =item *
14829: 
14830: resdata($name,$domain,$type,@which) : request for current parameter
14831: setting for a specific $type, where $type is either 'course' or 'user',
14832: @what should be a list of parameters to ask about. This routine caches
14833: answers for 10 minutes.
14834: 
14835: =item *
14836: 
14837: get_courseresdata($courseid, $domain) : dump the entire course resource
14838: data base, returning a hash that is keyed by the resource name and has
14839: values that are the resource value.  I believe that the timestamps and
14840: versions are also returned.
14841: 
14842: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
14843: supplemental content area. This routine caches the number of files for
14844: 10 minutes.
14845: 
14846: =back
14847: 
14848: =head2 Course Modification
14849: 
14850: =over 4
14851: 
14852: =item *
14853: 
14854: writecoursepref($courseid,%prefs) : write preferences (environment
14855: database) for a course
14856: 
14857: =item *
14858: 
14859: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
14860: 
14861: =item *
14862: 
14863: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
14864: 
14865: =item *
14866: 
14867: is_course($courseid), is_course($cdom, $cnum)
14868: 
14869: Accepts either a combined $courseid (in the form of domain_courseid) or the
14870: two component version $cdom, $cnum. It checks if the specified course exists.
14871: 
14872: Returns:
14873:     undef if the course doesn't exist, otherwise
14874:     in scalar context the combined courseid.
14875:     in list context the two components of the course identifier, domain and 
14876:     courseid.    
14877: 
14878: =back
14879: 
14880: =head2 Bubblesheet Configuration
14881: 
14882: =over 4
14883: 
14884: =item *
14885: 
14886: get_scantron_config($which)
14887: 
14888: $which - the name of the configuration to parse from the file.
14889: 
14890: Parses and returns the bubblesheet configuration line selected as a
14891: hash of configuration file fields.
14892: 
14893: 
14894: Returns:
14895:     If the named configuration is not in the file, an empty
14896:     hash is returned.
14897: 
14898:     a hash with the fields
14899:       name         - internal name for the this configuration setup
14900:       description  - text to display to operator that describes this config
14901:       CODElocation - if 0 or the string 'none'
14902:                           - no CODE exists for this config
14903:                      if -1 || the string 'letter'
14904:                           - a CODE exists for this config and is
14905:                             a string of letters
14906:                      Unsupported value (but planned for future support)
14907:                           if a positive integer
14908:                                - The CODE exists as the first n items from
14909:                                  the question section of the form
14910:                           if the string 'number'
14911:                                - The CODE exists for this config and is
14912:                                  a string of numbers
14913:       CODEstart   - (only matter if a CODE exists) column in the line where
14914:                      the CODE starts
14915:       CODElength  - length of the CODE
14916:       IDstart     - column where the student/employee ID starts
14917:       IDlength    - length of the student/employee ID info
14918:       Qstart      - column where the information from the bubbled
14919:                     'questions' start
14920:       Qlength     - number of columns comprising a single bubble line from
14921:                     the sheet. (usually either 1 or 10)
14922:       Qon         - either a single character representing the character used
14923:                     to signal a bubble was chosen in the positional setup, or
14924:                     the string 'letter' if the letter of the chosen bubble is
14925:                     in the final, or 'number' if a number representing the
14926:                     chosen bubble is in the file (1->A 0->J)
14927:       Qoff        - the character used to represent that a bubble was
14928:                     left blank
14929:       PaperID     - if the scanning process generates a unique number for each
14930:                     sheet scanned the column that this ID number starts in
14931:       PaperIDlength - number of columns that comprise the unique ID number
14932:                       for the sheet of paper
14933:       FirstName   - column that the first name starts in
14934:       FirstNameLength - number of columns that the first name spans
14935:       LastName    - column that the last name starts in
14936:       LastNameLength - number of columns that the last name spans
14937:       BubblesPerRow - number of bubbles available in each row used to
14938:                       bubble an answer. (If not specified, 10 assumed).
14939: 
14940: 
14941: =item *
14942: 
14943: get_scantronformat_file($cdom)
14944: 
14945: $cdom - the course's domain (optional); if not supplied, uses
14946: domain for current $env{'request.course.id'}.
14947: 
14948: Returns an array containing lines from the scantron format file for
14949: the domain of the course.
14950: 
14951: If a url for a custom.tab file is listed in domain's configuration.db,
14952: lines are from this file.
14953: 
14954: Otherwise, if a default.tab has been published in RES space by the
14955: domainconfig user, lines are from this file.
14956: 
14957: Otherwise, fall back to getting lines from the legacy file on the
14958: local server:  /home/httpd/lonTabs/default_scantronformat.tab
14959: 
14960: =back
14961: 
14962: =head2 Resource Subroutines
14963: 
14964: =over 4
14965: 
14966: =item *
14967: 
14968: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
14969: 
14970: =item *
14971: 
14972: repcopy($filename) : subscribes to the requested file, and attempts to
14973: replicate from the owning library server, Might return
14974: 'unavailable', 'not_found', 'forbidden', 'ok', or
14975: 'bad_request', also attempts to grab the metadata for the
14976: resource. Expects the local filesystem pathname
14977: (/home/httpd/html/res/....)
14978: 
14979: =back
14980: 
14981: =head2 Resource Information
14982: 
14983: =over 4
14984: 
14985: =item *
14986: 
14987: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
14988: and returns the value of a variety of different possible values,
14989: $varname should be a request string, and the other parameters can be
14990: used to specify who and what one is asking about. Ordinarily, $cid 
14991: does not need to be specified, as it is retrived from 
14992: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
14993: within lonuserstate::loadmap() when initializing a course, before
14994: $env{'request.course.id'} has been set, so it needs to be provided
14995: in that one case.
14996: 
14997: Possible values for $varname are environment.lastname (or other item
14998: from the envirnment hash), user.name (or someother aspect about the
14999: user), resource.0.maxtries (or some other part and parameter of a
15000: resource)
15001: 
15002: =item *
15003: 
15004: directcondval($number) : get current value of a condition; reads from a state
15005: string
15006: 
15007: =item *
15008: 
15009: condval($condidx) : value of condition index based on state
15010: 
15011: =item *
15012: 
15013: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
15014: resource's metadata, $what should be either a specific key, or either
15015: 'keys' (to get a list of possible keys) or 'packages' to get a list of
15016: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
15017: 
15018: this function automatically caches all requests
15019: 
15020: =item *
15021: 
15022: metadata_query($query,$custom,$customshow) : make a metadata query against the
15023: network of library servers; returns file handle of where SQL and regex results
15024: will be stored for query
15025: 
15026: =item *
15027: 
15028: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
15029: return symbolic list entry (all arguments optional).
15030: 
15031: Args: filename is the filename (including path) for the file for which a symb
15032: is required; donotrecurse, if true will prevent calls to allowed() being made
15033: to check access status if more than one resource was found in the bighash
15034: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
15035: a randompick); ignorecachednull, if true will prevent a symb of '' being
15036: returned if $env{$cache_str} is defined as ''; checkforblock if true will
15037: cause possible symbs to be checked to determine if they are subject to content
15038: blocking, if so they will not be included as possible symbs; possibles is a
15039: ref to a hash, which, as a side effect, will be populated with all possible
15040: symbs (content blocking not tested).
15041: 
15042: returns the data handle
15043: 
15044: =item *
15045: 
15046: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
15047: and is a possible symb for the URL in $thisfn, and if is an encrypted
15048: resource that the user accessed using /enc/ returns a 1 on success, 0
15049: on failure, user must be in a course, as it assumes the existence of
15050: the course initial hash, and uses $env('request.course.id'}.  The third
15051: arg is an optional reference to a scalar.  If this arg is passed in the
15052: call to symbverify, it will be set to 1 if the symb has been set to be 
15053: encrypted; otherwise it will be null.
15054: 
15055: =item *
15056: 
15057: symbclean($symb) : removes versions numbers from a symb, returns the
15058: cleaned symb
15059: 
15060: =item *
15061: 
15062: is_on_map($uri) : checks if the $uri is somewhere on the current
15063: course map, user must be in a course for it to work.
15064: 
15065: =item *
15066: 
15067: numval($salt) : return random seed value (addend for rndseed)
15068: 
15069: =item *
15070: 
15071: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
15072: a random seed, all arguments are optional, if they aren't sent it uses the
15073: environment to derive them. Note: if symb isn't sent and it can't get one
15074: from &symbread it will use the current time as its return value
15075: 
15076: =item *
15077: 
15078: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
15079: unfakeable, receipt
15080: 
15081: =item *
15082: 
15083: receipt() : API to ireceipt working off of env values; given out to users
15084: 
15085: =item *
15086: 
15087: countacc($url) : count the number of accesses to a given URL
15088: 
15089: =item *
15090: 
15091: 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
15092: 
15093: =item *
15094: 
15095: 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)
15096: 
15097: =item *
15098: 
15099: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
15100: 
15101: =item *
15102: 
15103: devalidate($symb) : devalidate temporary spreadsheet calculations,
15104: forcing spreadsheet to reevaluate the resource scores next time.
15105: 
15106: =item *
15107: 
15108: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
15109: when viewing in course context.
15110: 
15111:  input: six args -- filename (decluttered), course number, course domain,
15112:                     url, symb (if registered) and group (if this is a
15113:                     group item -- e.g., bulletin board, group page etc.).
15114: 
15115:  output: array of five scalars --
15116:          $cfile -- url for file editing if editable on current server
15117:          $home -- homeserver of resource (i.e., for author if published,
15118:                                           or course if uploaded.).
15119:          $switchserver --  1 if server switch will be needed.
15120:          $forceedit -- 1 if icon/link should be to go to edit mode
15121:          $forceview -- 1 if icon/link should be to go to view mode
15122: 
15123: =item *
15124: 
15125: is_course_upload($file,$cnum,$cdom)
15126: 
15127: Used in course context to determine if current file was uploaded to
15128: the course (i.e., would be found in /userfiles/docs on the course's
15129: homeserver.
15130: 
15131:   input: 3 args -- filename (decluttered), course number and course domain.
15132:   output: boolean -- 1 if file was uploaded.
15133: 
15134: =back
15135: 
15136: =head2 Storing/Retreiving Data
15137: 
15138: =over 4
15139: 
15140: =item *
15141: 
15142: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash 
15143: permanently for this url; hashref needs to be given and should be a \%hashname;
15144: the remaining args aren't required and if they aren't passed or are '' they will
15145: be derived from the env (with the exception of $laststore, which is an
15146: optional arg used when a user's submission is stored in grading).
15147: $laststore is $version=$timestamp, where $version is the most recent version
15148: number retrieved for the corresponding $symb in the $namespace db file, and
15149: $timestamp is the timestamp for that transaction (UNIX time).
15150: $laststore is currently only passed when cstore() is called by
15151: structuretags::finalize_storage().
15152: 
15153: =item *
15154: 
15155: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store 
15156: but uses critical subroutine
15157: 
15158: =item *
15159: 
15160: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
15161: all args are optional
15162: 
15163: =item *
15164: 
15165: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
15166: dumps the complete (or key matching regexp) namespace into a hash
15167: ($udom, $uname, $regexp, $range are optional) for a namespace that is
15168: normally &store()ed into
15169: 
15170: $range should be either an integer '100' (give me the first 100
15171:                                            matching records)
15172:               or be  two integers sperated by a - with no spaces
15173:                  '30-50' (give me the 30th through the 50th matching
15174:                           records)
15175: 
15176: 
15177: =item *
15178: 
15179: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
15180: replaces a &store() version of data with a replacement set of data
15181: for a particular resource in a namespace passed in the $storehash hash 
15182: reference. If $tolog is true, the transaction is logged in the courselog
15183: with an action=PUTSTORE.
15184: 
15185: =item *
15186: 
15187: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
15188: works very similar to store/cstore, but all data is stored in a
15189: temporary location and can be reset using tmpreset, $storehash should
15190: be a hash reference, returns nothing on success
15191: 
15192: =item *
15193: 
15194: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
15195: similar to restore, but all data is stored in a temporary location and
15196: can be reset using tmpreset. Returns a hash of values on success,
15197: error string otherwise.
15198: 
15199: =item *
15200: 
15201: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
15202: deltes all keys for $symb form the temporary storage hash.
15203: 
15204: =item *
15205: 
15206: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
15207: reference filled in from namesp ($udom and $uname are optional)
15208: 
15209: =item *
15210: 
15211: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
15212: namesp ($udom and $uname are optional)
15213: 
15214: =item *
15215: 
15216: dump($namespace,$udom,$uname,$regexp,$range) : 
15217: dumps the complete (or key matching regexp) namespace into a hash
15218: ($udom, $uname, $regexp, $range are optional)
15219: 
15220: $range should be either an integer '100' (give me the first 100
15221:                                            matching records)
15222:               or be  two integers sperated by a - with no spaces
15223:                  '30-50' (give me the 30th through the 50th matching
15224:                           records)
15225: =item *
15226: 
15227: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
15228: $store can be a scalar, an array reference, or if the amount to be 
15229: incremented is > 1, a hash reference.
15230: 
15231: ($udom and $uname are optional)
15232: 
15233: =item *
15234: 
15235: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
15236: ($udom and $uname are optional)
15237: 
15238: =item *
15239: 
15240: cput($namespace,$storehash,$udom,$uname) : critical put
15241: ($udom and $uname are optional)
15242: 
15243: =item *
15244: 
15245: newput($namespace,$storehash,$udom,$uname) :
15246: 
15247: Attempts to store the items in the $storehash, but only if they don't
15248: currently exist, if this succeeds you can be certain that you have 
15249: successfully created a new key value pair in the $namespace db.
15250: 
15251: 
15252: Args:
15253:  $namespace: name of database to store values to
15254:  $storehash: hashref to store to the db
15255:  $udom: (optional) domain of user containing the db
15256:  $uname: (optional) name of user caontaining the db
15257: 
15258: Returns:
15259:  'ok' -> succeeded in storing all keys of $storehash
15260:  'key_exists: <key>' -> failed to anything out of $storehash, as at
15261:                         least <key> already existed in the db (other
15262:                         requested keys may also already exist)
15263:  'error: <msg>' -> unable to tie the DB or other error occurred
15264:  'con_lost' -> unable to contact request server
15265:  'refused' -> action was not allowed by remote machine
15266: 
15267: 
15268: =item *
15269: 
15270: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
15271: reference filled in from namesp (encrypts the return communication)
15272: ($udom and $uname are optional)
15273: 
15274: =item *
15275: 
15276: log($udom,$name,$home,$message) : write to permanent log for user; use
15277: critical subroutine
15278: 
15279: =item *
15280: 
15281: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
15282: array reference filled in from namespace found in domain level on either
15283: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
15284: 
15285: =item *
15286: 
15287: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
15288: domain level either on specified domain server ($uhome) or primary domain 
15289: server ($udom and $uhome are optional)
15290: 
15291: =item * 
15292: 
15293: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
15294: for: authentication, language, quotas, timezone, date locale, and portal URL in
15295: the target domain.
15296: 
15297: May also include additional key => value pairs for the following groups:
15298: 
15299: =over
15300: 
15301: =item
15302: disk quotas (MB allocated by default to portfolios and authoring spaces).
15303: 
15304: =over
15305: 
15306: =item defaultquota, authorquota
15307: 
15308: =back
15309: 
15310: =item
15311: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
15312: portfolio for users).
15313: 
15314: =over
15315: 
15316: =item
15317: aboutme, blog, webdav, portfolio
15318: 
15319: =back
15320: 
15321: =item
15322: requestcourses: ability to request courses, and how requests are processed.
15323: 
15324: =over
15325: 
15326: =item
15327: official, unofficial, community, textbook
15328: 
15329: =back
15330: 
15331: =item
15332: inststatus: types of institutional affiliation, and order in which they are displayed.
15333: 
15334: =over
15335: 
15336: =item
15337: inststatustypes, inststatusorder, inststatusguest
15338: 
15339: =back
15340: 
15341: =item
15342: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
15343: for course's uploaded content.
15344: 
15345: =over
15346: 
15347: =item
15348: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
15349: communityquota, textbookquota
15350: 
15351: =back
15352: 
15353: =item
15354: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
15355: on your servers.
15356: 
15357: =over
15358: 
15359: =item
15360: remotesessions, hostedsessions
15361: 
15362: =back
15363: 
15364: =back
15365: 
15366: In cases where a domain coordinator has never used the "Set Domain Configuration"
15367: utility to create a configuration.db file on a domain's primary library server
15368: only the following domain defaults: auth_def, auth_arg_def, lang_def
15369: -- corresponding values are authentication type (internal, krb4, krb5,
15370: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
15371: will be available. Values are retrieved from cache (if current), unless the
15372: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
15373: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
15374: 
15375: Typical usage:
15376: 
15377: %domdefaults = &get_domain_defaults($target_domain);
15378: 
15379: =back
15380: 
15381: =head2 Network Status Functions
15382: 
15383: =over 4
15384: 
15385: =item *
15386: 
15387: dirlist() : return directory list based on URI (first arg).
15388: 
15389: Inputs: 1 required, 5 optional.
15390: 
15391: =over
15392: 
15393: =item 
15394: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
15395: 
15396: =item
15397: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
15398: 
15399: =item
15400: $username -  username of user/course to be listed. Extracted from $uri if absent. 
15401: 
15402: =item
15403: $getpropath - boolean: 1 if prepend path using &propath(). 
15404: 
15405: =item
15406: $getuserdir - boolean: 1 if prepend path for "userfiles".
15407: 
15408: =item 
15409: $alternateRoot - path to prepend in place of path from $uri.
15410: 
15411: =back
15412: 
15413: Returns: Array of up to two items.
15414: 
15415: =over
15416: 
15417: a reference to an array of files/subdirectories
15418: 
15419: =over
15420: 
15421: Each element in the array of files/subdirectories is a & separated list of
15422: item name and the result of running stat on the item.  If dirlist was requested
15423: for a file instead of a directory, the item name will be ''. For a directory 
15424: listing, if the item is a metadata file, the element will end &N&M 
15425: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
15426: default copyright set (1).  
15427: 
15428: =back
15429: 
15430: a scalar containing error condition (if encountered).
15431: 
15432: =over
15433: 
15434: =item 
15435: no_host (no homeserver identified for $username:$domain).
15436: 
15437: =item 
15438: no_such_host (server contacted for listing not identified as valid host).
15439: 
15440: =item 
15441: con_lost (connection to remote server failed).
15442: 
15443: =item 
15444: refused (invalid $username:$domain received on lond side).
15445: 
15446: =item 
15447: no_such_dir (directory at specified path on lond side does not exist). 
15448: 
15449: =item 
15450: empty (directory at specified path on lond side is empty).
15451: 
15452: =over
15453: 
15454: This is currently not encountered because the &ls3, &ls2, 
15455: &ls (_handler) routines on the lond side do not filter out
15456: . and .. from a directory listing. 
15457: 
15458: =back
15459: 
15460: =back
15461: 
15462: =back
15463: 
15464: =item *
15465: 
15466: spareserver() : find server with least workload from spare.tab
15467: 
15468: 
15469: =item *
15470: 
15471: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
15472: if there is no corresponding loncapa host.
15473: 
15474: =back
15475: 
15476: 
15477: =head2 Apache Request
15478: 
15479: =over 4
15480: 
15481: =item *
15482: 
15483: ssi($url,%hash) : server side include, does a complete request cycle on url to
15484: localhost, posts hash
15485: 
15486: =back
15487: 
15488: =head2 Data to String to Data
15489: 
15490: =over 4
15491: 
15492: =item *
15493: 
15494: hash2str(%hash) : convert a hash into a string complete with escaping and '='
15495: and '&' separators, supports elements that are arrayrefs and hashrefs
15496: 
15497: =item *
15498: 
15499: hashref2str($hashref) : convert a hashref into a string complete with
15500: escaping and '=' and '&' separators, supports elements that are
15501: arrayrefs and hashrefs
15502: 
15503: =item *
15504: 
15505: arrayref2str($arrayref) : convert an arrayref into a string complete
15506: with escaping and '&' separators, supports elements that are arrayrefs
15507: and hashrefs
15508: 
15509: =item *
15510: 
15511: str2hash($string) : convert string to hash using unescaping and
15512: splitting on '=' and '&', supports elements that are arrayrefs and
15513: hashrefs
15514: 
15515: =item *
15516: 
15517: str2array($string) : convert string to hash using unescaping and
15518: splitting on '&', supports elements that are arrayrefs and hashrefs
15519: 
15520: =back
15521: 
15522: =head2 Logging Routines
15523: 
15524: 
15525: These routines allow one to make log messages in the lonnet.log and
15526: lonnet.perm logfiles.
15527: 
15528: =over 4
15529: 
15530: =item *
15531: 
15532: logtouch() : make sure the logfile, lonnet.log, exists
15533: 
15534: =item *
15535: 
15536: logthis() : append message to the normal lonnet.log file, it gets
15537: preiodically rolled over and deleted.
15538: 
15539: =item *
15540: 
15541: logperm() : append a permanent message to lonnet.perm.log, this log
15542: file never gets deleted by any automated portion of the system, only
15543: messages of critical importance should go in here.
15544: 
15545: 
15546: =back
15547: 
15548: =head2 General File Helper Routines
15549: 
15550: =over 4
15551: 
15552: =item *
15553: 
15554: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
15555: (a) files in /uploaded
15556:   (i) If a local copy of the file exists - 
15557:       compares modification date of local copy with last-modified date for 
15558:       definitive version stored on home server for course. If local copy is 
15559:       stale, requests a new version from the home server and stores it. 
15560:       If the original has been removed from the home server, then local copy 
15561:       is unlinked.
15562:   (ii) If local copy does not exist -
15563:       requests the file from the home server and stores it. 
15564:   
15565:   If $caller is 'uploadrep':  
15566:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
15567:     for request for files originally uploaded via DOCS. 
15568:      - returns 'ok' if fresh local copy now available, -1 otherwise.
15569:   
15570:   Otherwise:
15571:      This indicates a call from the content generation phase of the request.
15572:      -  returns the entire contents of the file or -1.
15573:      
15574: (b) files in /res
15575:    - returns the entire contents of a file or -1; 
15576:    it properly subscribes to and replicates the file if neccessary.
15577: 
15578: 
15579: =item *
15580: 
15581: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
15582:                   reference
15583: 
15584: returns either a stat() list of data about the file or an empty list
15585: if the file doesn't exist or couldn't find out about it (connection
15586: problems or user unknown)
15587: 
15588: =item *
15589: 
15590: filelocation($dir,$file) : returns file system location of a file
15591: based on URI; meant to be "fairly clean" absolute reference, $dir is a
15592: directory that relative $file lookups are to looked in ($dir of /a/dir
15593: and a file of ../bob will become /a/bob)
15594: 
15595: =item *
15596: 
15597: hreflocation($dir,$file) : returns file system location or a URL; same as
15598: filelocation except for hrefs
15599: 
15600: =item *
15601: 
15602: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
15603: also removes beginning /home/httpd/html unless /priv/ follows it.
15604: 
15605: =back
15606: 
15607: =head2 Usererfile file routines (/uploaded*)
15608: 
15609: =over 4
15610: 
15611: =item *
15612: 
15613: userfileupload(): main rotine for putting a file in a user or course's
15614:                   filespace, arguments are,
15615: 
15616:  formname - required - this is the name of the element in $env where the
15617:            filename, and the contents of the file to create/modifed exist
15618:            the filename is in $env{'form.'.$formname.'.filename'} and the
15619:            contents of the file is located in $env{'form.'.$formname}
15620:  context - if coursedoc, store the file in the course of the active role
15621:              of the current user; 
15622:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
15623:            if 'canceloverwrite': delete file in tmp/overwrites directory
15624:  subdir - required - subdirectory to put the file in under ../userfiles/
15625:          if undefined, it will be placed in "unknown"
15626: 
15627:  (This routine calls clean_filename() to remove any dangerous
15628:  characters from the filename, and then calls finuserfileupload() to
15629:  complete the transaction)
15630: 
15631:  returns either the url of the uploaded file (/uploaded/....) if successful
15632:  and /adm/notfound.html if unsuccessful
15633: 
15634: =item *
15635: 
15636: clean_filename(): routine for cleaing a filename up for storage in
15637:                  userfile space, argument is:
15638: 
15639:  filename - proposed filename
15640: 
15641: returns: the new clean filename
15642: 
15643: =item *
15644: 
15645: finishuserfileupload(): routine that creates and sends the file to
15646: userspace, probably shouldn't be called directly
15647: 
15648:   docuname: username or courseid of destination for the file
15649:   docudom: domain of user/course of destination for the file
15650:   formname: same as for userfileupload()
15651:   fname: filename (including subdirectories) for the file
15652:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
15653:           if hashref, and context is scantron, will convert csv format to standard format
15654:   allfiles: reference to hash used to store objects found by parser
15655:   codebase: reference to hash used for codebases of java objects found by parser
15656:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
15657:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
15658:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
15659:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
15660:   context: if 'overwrite', will move the uploaded file from its temporary location to
15661:             userfiles to facilitate overwriting a previously uploaded file with same name.
15662:   mimetype: reference to scalar to accommodate mime type determined
15663:             from File::MMagic if $parser = parse.
15664: 
15665:  returns either the url of the uploaded file (/uploaded/....) if successful
15666:  and /adm/notfound.html if unsuccessful (or an error message if context 
15667:  was 'overwrite').
15668:  
15669: 
15670: =item *
15671: 
15672: renameuserfile(): renames an existing userfile to a new name
15673: 
15674:   Args:
15675:    docuname: username or courseid of destination for the file
15676:    docudom: domain of user/course of destination for the file
15677:    old: current file name (including any subdirs under userfiles)
15678:    new: desired file name (including any subdirs under userfiles)
15679: 
15680: =item *
15681: 
15682: mkdiruserfile(): creates a directory is a userfiles dir
15683: 
15684:   Args:
15685:    docuname: username or courseid of destination for the file
15686:    docudom: domain of user/course of destination for the file
15687:    dir: dir to create (including any subdirs under userfiles)
15688: 
15689: =item *
15690: 
15691: removeuserfile(): removes a file that exists in userfiles
15692: 
15693:   Args:
15694:    docuname: username or courseid of destination for the file
15695:    docudom: domain of user/course of destination for the file
15696:    fname: filname to delete (including any subdirs under userfiles)
15697: 
15698: =item *
15699: 
15700: removeuploadedurl(): convience function for removeuserfile()
15701: 
15702:   Args:
15703:    url:  a full /uploaded/... url to delete
15704: 
15705: =item * 
15706: 
15707: get_portfile_permissions():
15708:   Args:
15709:     domain: domain of user or course contain the portfolio files
15710:     user: name of user or num of course contain the portfolio files
15711:   Returns:
15712:     hashref of a dump of the proper file_permissions.db
15713:    
15714: 
15715: =item * 
15716: 
15717: get_access_controls():
15718: 
15719: Args:
15720:   current_permissions: the hash ref returned from get_portfile_permissions()
15721:   group: (optional) the group you want the files associated with
15722:   file: (optional) the file you want access info on
15723: 
15724: Returns:
15725:     a hash (keys are file names) of hashes containing
15726:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
15727:         values are XML containing access control settings (see below) 
15728: 
15729: Internal notes:
15730: 
15731:  access controls are stored in file_permissions.db as key=value pairs.
15732:     key -> path to file/file_name\0uniqueID:scope_end_start
15733:         where scope -> public,guest,course,group,domains or users.
15734:               end -> UNIX time for end of access (0 -> no end date)
15735:               start -> UNIX time for start of access
15736: 
15737:     value -> XML description of access control
15738:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
15739:             <start></start>
15740:             <end></end>
15741: 
15742:             <password></password>  for scope type = guest
15743: 
15744:             <domain></domain>     for scope type = course or group
15745:             <number></number>
15746:             <roles id="">
15747:              <role></role>
15748:              <access></access>
15749:              <section></section>
15750:              <group></group>
15751:             </roles>
15752: 
15753:             <dom></dom>         for scope type = domains
15754: 
15755:             <users>             for scope type = users
15756:              <user>
15757:               <uname></uname>
15758:               <udom></udom>
15759:              </user>
15760:             </users>
15761:            </scope> 
15762:               
15763:  Access data is also aggregated for each file in an additional key=value pair:
15764:  key -> path to file/file_name\0accesscontrol 
15765:  value -> reference to hash
15766:           hash contains key = value pairs
15767:           where key = uniqueID:scope_end_start
15768:                 value = UNIX time record was last updated
15769: 
15770:           Used to improve speed of look-ups of access controls for each file.  
15771:  
15772:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
15773: 
15774: =item *
15775: 
15776: modify_access_controls():
15777: 
15778: Modifies access controls for a portfolio file
15779: Args
15780: 1. file name
15781: 2. reference to hash of required changes,
15782: 3. domain
15783: 4. username
15784:   where domain,username are the domain of the portfolio owner 
15785:   (either a user or a course) 
15786: 
15787: Returns:
15788: 1. result of additions or updates ('ok' or 'error', with error message). 
15789: 2. result of deletions ('ok' or 'error', with error message).
15790: 3. reference to hash of any new or updated access controls.
15791: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
15792:    key = integer (inbound ID)
15793:    value = uniqueID
15794: 
15795: =item *
15796: 
15797: get_timebased_id():
15798: 
15799: Attempts to get a unique timestamp-based suffix for use with items added to a
15800: course via the Course Editor (e.g., folders, composite pages,
15801: group bulletin boards).
15802: 
15803: Args: (first three required; six others optional)
15804: 
15805: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
15806:    docssequence, or name of group
15807: 
15808: 2. keyid (alphanumeric): name of temporary locking key in hash,
15809:    e.g., num, boardids
15810: 
15811: 3. namespace: name of gdbm file used to store suffixes already assigned;
15812:    file will be named nohist_namespace.db
15813: 
15814: 4. cdom: domain of course; default is current course domain from %env
15815: 
15816: 5. cnum: course number; default is current course number from %env
15817: 
15818: 6. idtype: set to concat if an additional digit is to be appended to the
15819:    unix timestamp to form the suffix, if the plain timestamp is already
15820:    in use.  Default is to not do this, but simply increment the unix
15821:    timestamp by 1 until a unique key is obtained.
15822: 
15823: 7. who: holder of locking key; defaults to user:domain for user.
15824: 
15825: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
15826:    retrying); default is 3.
15827: 
15828: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
15829: 
15830: Returns:
15831: 
15832: 1. suffix obtained (numeric)
15833: 
15834: 2. result of deleting locking key (ok if deleted, or lock never obtained)
15835: 
15836: 3. error: contains (localized) error message if an error occurred.
15837: 
15838: 
15839: =back
15840: 
15841: =head2 HTTP Helper Routines
15842: 
15843: =over 4
15844: 
15845: =item *
15846: 
15847: escape() : unpack non-word characters into CGI-compatible hex codes
15848: 
15849: =item *
15850: 
15851: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
15852: 
15853: =back
15854: 
15855: =head1 PRIVATE SUBROUTINES
15856: 
15857: =head2 Underlying communication routines (Shouldn't call)
15858: 
15859: =over 4
15860: 
15861: =item *
15862: 
15863: subreply() : tries to pass a message to lonc, returns con_lost if incapable
15864: 
15865: =item *
15866: 
15867: reply() : uses subreply to send a message to remote machine, logs all failures
15868: 
15869: =item *
15870: 
15871: critical() : passes a critical message to another server; if cannot
15872: get through then place message in connection buffer directory and
15873: returns con_delayed, if incapable of saving message, returns
15874: con_failed
15875: 
15876: =item *
15877: 
15878: reconlonc() : tries to reconnect lonc client processes.
15879: 
15880: =back
15881: 
15882: =head2 Resource Access Logging
15883: 
15884: =over 4
15885: 
15886: =item *
15887: 
15888: flushcourselogs() : flush (save) buffer logs and access logs
15889: 
15890: =item *
15891: 
15892: courselog($what) : save message for course in hash
15893: 
15894: =item *
15895: 
15896: courseacclog($what) : save message for course using &courselog().  Perform
15897: special processing for specific resource types (problems, exams, quizzes, etc).
15898: 
15899: =item *
15900: 
15901: goodbye() : flush course logs and log shutting down; it is called in srm.conf
15902: as a PerlChildExitHandler
15903: 
15904: =back
15905: 
15906: =head2 Other
15907: 
15908: =over 4
15909: 
15910: =item *
15911: 
15912: symblist($mapname,%newhash) : update symbolic storage links
15913: 
15914: =back
15915: 
15916: =cut
15917: 

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