File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1246: download - view: text, annotated - select for diffs
Fri Dec 27 23:31:01 2013 UTC (10 years, 6 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- "textbook" is a course request type.
- courses of type "textbook" have specific default credits and upload quota,
  set via domain configuration.

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1246 2013/12/27 23:31:01 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: 
   78: 
   79: use Encode;
   80: 
   81: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
   82:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
   83:             %managerstab);
   84: 
   85: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
   86:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
   87:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
   88:     %courseownerbuf, %coursetypebuf,$locknum);
   89: 
   90: use IO::Socket;
   91: use GDBM_File;
   92: use HTML::LCParser;
   93: use Fcntl qw(:flock);
   94: use Storable qw(thaw nfreeze);
   95: use Time::HiRes qw( gettimeofday tv_interval );
   96: use Cache::Memcached;
   97: use Digest::MD5;
   98: use Math::Random;
   99: use File::MMagic;
  100: use LONCAPA qw(:DEFAULT :match);
  101: use LONCAPA::Configuration;
  102: use LONCAPA::lonmetadata;
  103: use LONCAPA::Lond;
  104: 
  105: use File::Copy;
  106: 
  107: my $readit;
  108: my $max_connection_retries = 10;     # Or some such value.
  109: 
  110: require Exporter;
  111: 
  112: our @ISA = qw (Exporter);
  113: our @EXPORT = qw(%env);
  114: 
  115: 
  116: # ------------------------------------ Logging (parameters, docs, slots, roles)
  117: {
  118:     my $logid;
  119:     sub write_log {
  120: 	my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
  121:         if ($context eq 'course') {
  122:             if (($cnum eq '') || ($cdom eq '')) {
  123:                 $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
  124:                 $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
  125:             }
  126:         }
  127: 	$logid ++;
  128:         my $now = time();
  129: 	my $id=$now.'00000'.$$.'00000'.$logid;
  130:         my $logentry = { 
  131:                           $id => {
  132:                                    'exe_uname' => $env{'user.name'},
  133:                                    'exe_udom'  => $env{'user.domain'},
  134:                                    'exe_time'  => $now,
  135:                                    'exe_ip'    => $ENV{'REMOTE_ADDR'},
  136:                                    'delflag'   => $delflag,
  137:                                    'logentry'  => $storehash,
  138:                                    'uname'     => $uname,
  139:                                    'udom'      => $udom,
  140:                                   }
  141:                        };
  142: 	return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
  143:     }
  144: }
  145: 
  146: sub logtouch {
  147:     my $execdir=$perlvar{'lonDaemons'};
  148:     unless (-e "$execdir/logs/lonnet.log") {	
  149: 	open(my $fh,">>$execdir/logs/lonnet.log");
  150: 	close $fh;
  151:     }
  152:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
  153:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
  154: }
  155: 
  156: sub logthis {
  157:     my $message=shift;
  158:     my $execdir=$perlvar{'lonDaemons'};
  159:     my $now=time;
  160:     my $local=localtime($now);
  161:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
  162: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
  163: 	print $fh $logstring;
  164: 	close($fh);
  165:     }
  166:     return 1;
  167: }
  168: 
  169: sub logperm {
  170:     my $message=shift;
  171:     my $execdir=$perlvar{'lonDaemons'};
  172:     my $now=time;
  173:     my $local=localtime($now);
  174:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
  175: 	print $fh "$now:$message:$local\n";
  176: 	close($fh);
  177:     }
  178:     return 1;
  179: }
  180: 
  181: sub create_connection {
  182:     my ($hostname,$lonid) = @_;
  183:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
  184: 				     Type    => SOCK_STREAM,
  185: 				     Timeout => 10);
  186:     return 0 if (!$client);
  187:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
  188:     my $result = <$client>;
  189:     chomp($result);
  190:     return 1 if ($result eq 'done');
  191:     return 0;
  192: }
  193: 
  194: sub get_server_timezone {
  195:     my ($cnum,$cdom) = @_;
  196:     my $home=&homeserver($cnum,$cdom);
  197:     if ($home ne 'no_host') {
  198:         my $cachetime = 24*3600;
  199:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
  200:         if (defined($cached)) {
  201:             return $timezone;
  202:         } else {
  203:             my $timezone = &reply('servertimezone',$home);
  204:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
  205:         }
  206:     }
  207: }
  208: 
  209: sub get_server_distarch {
  210:     my ($lonhost,$ignore_cache) = @_;
  211:     if (defined($lonhost)) {
  212:         if (!defined(&hostname($lonhost))) {
  213:             return;
  214:         }
  215:         my $cachetime = 12*3600;
  216:         if (!$ignore_cache) {
  217:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
  218:             if (defined($cached)) {
  219:                 return $distarch;
  220:             }
  221:         }
  222:         my $rep = &reply('serverdistarch',$lonhost);
  223:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
  224:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
  225:                 $rep eq '') {
  226:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
  227:         }
  228:     }
  229:     return;
  230: }
  231: 
  232: sub get_server_loncaparev {
  233:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
  234:     if (defined($lonhost)) {
  235:         if (!defined(&hostname($lonhost))) {
  236:             undef($lonhost);
  237:         }
  238:     }
  239:     if (!defined($lonhost)) {
  240:         if (defined(&domain($dom,'primary'))) {
  241:             $lonhost=&domain($dom,'primary');
  242:             if ($lonhost eq 'no_host') {
  243:                 undef($lonhost);
  244:             }
  245:         }
  246:     }
  247:     if (defined($lonhost)) {
  248:         my $cachetime = 12*3600;
  249:         if (!$ignore_cache) {
  250:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
  251:             if (defined($cached)) {
  252:                 return $loncaparev;
  253:             }
  254:         }
  255:         my ($answer,$loncaparev);
  256:         my @ids=&current_machine_ids();
  257:         if (grep(/^\Q$lonhost\E$/,@ids)) {
  258:             $answer = $perlvar{'lonVersion'};
  259:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  260:                 $loncaparev = $1;
  261:             }
  262:         } else {
  263:             $answer = &reply('serverloncaparev',$lonhost);
  264:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
  265:                 if ($caller eq 'loncron') {
  266:                     my $ua=new LWP::UserAgent;
  267:                     $ua->timeout(4);
  268:                     my $protocol = $protocol{$lonhost};
  269:                     $protocol = 'http' if ($protocol ne 'https');
  270:                     my $url = $protocol.'://'.&hostname($lonhost).'/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:     my $response = &reply('devalidatecache:'.&escape($cachestr),$lonhost);
  364:     return $response;
  365: }
  366: 
  367: # -------------------------------------------------- Non-critical communication
  368: sub subreply {
  369:     my ($cmd,$server)=@_;
  370:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
  371:     #
  372:     #  With loncnew process trimming, there's a timing hole between lonc server
  373:     #  process exit and the master server picking up the listen on the AF_UNIX
  374:     #  socket.  In that time interval, a lock file will exist:
  375: 
  376:     my $lockfile=$peerfile.".lock";
  377:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
  378: 	sleep(1);
  379:     }
  380:     # At this point, either a loncnew parent is listening or an old lonc
  381:     # or loncnew child is listening so we can connect or everything's dead.
  382:     #
  383:     #   We'll give the connection a few tries before abandoning it.  If
  384:     #   connection is not possible, we'll con_lost back to the client.
  385:     #   
  386:     my $client;
  387:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
  388: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  389: 				      Type    => SOCK_STREAM,
  390: 				      Timeout => 10);
  391: 	if ($client) {
  392: 	    last;		# Connected!
  393: 	} else {
  394: 	    &create_connection(&hostname($server),$server);
  395: 	}
  396:         sleep(1);		# Try again later if failed connection.
  397:     }
  398:     my $answer;
  399:     if ($client) {
  400: 	print $client "sethost:$server:$cmd\n";
  401: 	$answer=<$client>;
  402: 	if (!$answer) { $answer="con_lost"; }
  403: 	chomp($answer);
  404:     } else {
  405: 	$answer = 'con_lost';	# Failed connection.
  406:     }
  407:     return $answer;
  408: }
  409: 
  410: sub reply {
  411:     my ($cmd,$server)=@_;
  412:     unless (defined(&hostname($server))) { return 'no_such_host'; }
  413:     my $answer=subreply($cmd,$server);
  414:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
  415:        &logthis("<font color=\"blue\">WARNING:".
  416:                 " $cmd to $server returned $answer</font>");
  417:     }
  418:     return $answer;
  419: }
  420: 
  421: # ----------------------------------------------------------- Send USR1 to lonc
  422: 
  423: sub reconlonc {
  424:     my ($lonid) = @_;
  425:     my $hostname = &hostname($lonid);
  426:     if ($lonid) {
  427: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
  428: 	if ($hostname && -e $peerfile) {
  429: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
  430: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
  431: 					     Type    => SOCK_STREAM,
  432: 					     Timeout => 10);
  433: 	    if ($client) {
  434: 		print $client ("reset_retries\n");
  435: 		my $answer=<$client>;
  436: 		#reset just this one.
  437: 	    }
  438: 	}
  439: 	return;
  440:     }
  441: 
  442:     &logthis("Trying to reconnect lonc");
  443:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  444:     if (open(my $fh,"<$loncfile")) {
  445: 	my $loncpid=<$fh>;
  446:         chomp($loncpid);
  447:         if (kill 0 => $loncpid) {
  448: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  449:             kill USR1 => $loncpid;
  450:             sleep 1;
  451:          } else {
  452: 	    &logthis(
  453:                "<font color=\"blue\">WARNING:".
  454:                " lonc at pid $loncpid not responding, giving up</font>");
  455:         }
  456:     } else {
  457: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
  458:     }
  459: }
  460: 
  461: # ------------------------------------------------------ Critical communication
  462: 
  463: sub critical {
  464:     my ($cmd,$server)=@_;
  465:     unless (&hostname($server)) {
  466:         &logthis("<font color=\"blue\">WARNING:".
  467:                " Critical message to unknown server ($server)</font>");
  468:         return 'no_such_host';
  469:     }
  470:     my $answer=reply($cmd,$server);
  471:     if ($answer eq 'con_lost') {
  472: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
  473: 	my $answer=reply($cmd,$server);
  474:         if ($answer eq 'con_lost') {
  475:             my $now=time;
  476:             my $middlename=$cmd;
  477:             $middlename=substr($middlename,0,16);
  478:             $middlename=~s/\W//g;
  479:             my $dfilename=
  480:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
  481:             $dumpcount++;
  482:             {
  483: 		my $dfh;
  484: 		if (open($dfh,">$dfilename")) {
  485: 		    print $dfh "$cmd\n"; 
  486: 		    close($dfh);
  487: 		}
  488:             }
  489:             sleep 2;
  490:             my $wcmd='';
  491:             {
  492: 		my $dfh;
  493: 		if (open($dfh,"<$dfilename")) {
  494: 		    $wcmd=<$dfh>; 
  495: 		    close($dfh);
  496: 		}
  497:             }
  498:             chomp($wcmd);
  499:             if ($wcmd eq $cmd) {
  500: 		&logthis("<font color=\"blue\">WARNING: ".
  501:                          "Connection buffer $dfilename: $cmd</font>");
  502:                 &logperm("D:$server:$cmd");
  503: 	        return 'con_delayed';
  504:             } else {
  505:                 &logthis("<font color=\"red\">CRITICAL:"
  506:                         ." Critical connection failed: $server $cmd</font>");
  507:                 &logperm("F:$server:$cmd");
  508:                 return 'con_failed';
  509:             }
  510:         }
  511:     }
  512:     return $answer;
  513: }
  514: 
  515: # ------------------------------------------- check if return value is an error
  516: 
  517: sub error {
  518:     my ($result) = @_;
  519:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
  520: 	if ($2 == 2) { return undef; }
  521: 	return $1;
  522:     }
  523:     return undef;
  524: }
  525: 
  526: sub convert_and_load_session_env {
  527:     my ($lonidsdir,$handle)=@_;
  528:     my @profile;
  529:     {
  530: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  531: 	if (!$opened) {
  532: 	    return 0;
  533: 	}
  534: 	flock($idf,LOCK_SH);
  535: 	@profile=<$idf>;
  536: 	close($idf);
  537:     }
  538:     my %temp_env;
  539:     foreach my $line (@profile) {
  540: 	if ($line !~ m/=/) {
  541: 	    return 0;
  542: 	}
  543: 	chomp($line);
  544: 	my ($envname,$envvalue)=split(/=/,$line,2);
  545: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
  546:     }
  547:     unlink("$lonidsdir/$handle.id");
  548:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
  549: 	    0640)) {
  550: 	%disk_env = %temp_env;
  551: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
  552: 	untie(%disk_env);
  553:     }
  554:     return 1;
  555: }
  556: 
  557: # ------------------------------------------- Transfer profile into environment
  558: my $env_loaded;
  559: sub transfer_profile_to_env {
  560:     my ($lonidsdir,$handle,$force_transfer) = @_;
  561:     if (!$force_transfer && $env_loaded) { return; } 
  562: 
  563:     if (!defined($lonidsdir)) {
  564: 	$lonidsdir = $perlvar{'lonIDsDir'};
  565:     }
  566:     if (!defined($handle)) {
  567:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
  568:     }
  569: 
  570:     my $convert;
  571:     {
  572:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  573: 	if (!$opened) {
  574: 	    return;
  575: 	}
  576: 	flock($idf,LOCK_SH);
  577: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  578: 		&GDBM_READER(),0640)) {
  579: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
  580: 	    untie(%disk_env);
  581: 	} else {
  582: 	    $convert = 1;
  583: 	}
  584:     }
  585:     if ($convert) {
  586: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
  587: 	    &logthis("Failed to load session, or convert session.");
  588: 	}
  589:     }
  590: 
  591:     my %remove;
  592:     while ( my $envname = each(%env) ) {
  593:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  594:             if ($time < time-300) {
  595:                 $remove{$key}++;
  596:             }
  597:         }
  598:     }
  599: 
  600:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  601:     $env_loaded=1;
  602:     foreach my $expired_key (keys(%remove)) {
  603:         &delenv($expired_key);
  604:     }
  605: }
  606: 
  607: # ---------------------------------------------------- Check for valid session 
  608: sub check_for_valid_session {
  609:     my ($r,$name,$userhashref) = @_;
  610:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
  611:     if ($name eq '') {
  612:         $name = 'lonID';
  613:     }
  614:     my $lonid=$cookies{$name};
  615:     return undef if (!$lonid);
  616: 
  617:     my $handle=&LONCAPA::clean_handle($lonid->value);
  618:     my $lonidsdir;
  619:     if ($name eq 'lonDAV') {
  620:         $lonidsdir=$r->dir_config('lonDAVsessDir');
  621:     } else {
  622:         $lonidsdir=$r->dir_config('lonIDsDir');
  623:     }
  624:     return undef if (!-e "$lonidsdir/$handle.id");
  625: 
  626:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  627:     return undef if (!$opened);
  628: 
  629:     flock($idf,LOCK_SH);
  630:     my %disk_env;
  631:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  632: 	    &GDBM_READER(),0640)) {
  633: 	return undef;	
  634:     }
  635: 
  636:     if (!defined($disk_env{'user.name'})
  637: 	|| !defined($disk_env{'user.domain'})) {
  638: 	return undef;
  639:     }
  640: 
  641:     if (ref($userhashref) eq 'HASH') {
  642:         $userhashref->{'name'} = $disk_env{'user.name'};
  643:         $userhashref->{'domain'} = $disk_env{'user.domain'};
  644:     }
  645: 
  646:     return $handle;
  647: }
  648: 
  649: sub timed_flock {
  650:     my ($file,$lock_type) = @_;
  651:     my $failed=0;
  652:     eval {
  653: 	local $SIG{__DIE__}='DEFAULT';
  654: 	local $SIG{ALRM}=sub {
  655: 	    $failed=1;
  656: 	    die("failed lock");
  657: 	};
  658: 	alarm(13);
  659: 	flock($file,$lock_type);
  660: 	alarm(0);
  661:     };
  662:     if ($failed) {
  663: 	return undef;
  664:     } else {
  665: 	return 1;
  666:     }
  667: }
  668: 
  669: # ---------------------------------------------------------- Append Environment
  670: 
  671: sub appenv {
  672:     my ($newenv,$roles) = @_;
  673:     if (ref($newenv) eq 'HASH') {
  674:         foreach my $key (keys(%{$newenv})) {
  675:             my $refused = 0;
  676: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
  677:                 $refused = 1;
  678:                 if (ref($roles) eq 'ARRAY') {
  679:                     my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
  680:                     if (grep(/^\Q$role\E$/,@{$roles})) {
  681:                         $refused = 0;
  682:                     }
  683:                 }
  684:             }
  685:             if ($refused) {
  686:                 &logthis("<font color=\"blue\">WARNING: ".
  687:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
  688:                          .'</font>');
  689: 	        delete($newenv->{$key});
  690:             } else {
  691:                 $env{$key}=$newenv->{$key};
  692:             }
  693:         }
  694:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
  695:         if ($opened
  696: 	    && &timed_flock($env_file,LOCK_EX)
  697: 	    &&
  698: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  699: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  700: 	    while (my ($key,$value) = each(%{$newenv})) {
  701: 	        $disk_env{$key} = $value;
  702: 	    }
  703: 	    untie(%disk_env);
  704:         }
  705:     }
  706:     return 'ok';
  707: }
  708: # ----------------------------------------------------- Delete from Environment
  709: 
  710: sub delenv {
  711:     my ($delthis,$regexp,$roles) = @_;
  712:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
  713:         my $refused = 1;
  714:         if (ref($roles) eq 'ARRAY') {
  715:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
  716:             if (grep(/^\Q$role\E$/,@{$roles})) {
  717:                 $refused = 0;
  718:             }
  719:         }
  720:         if ($refused) {
  721:             &logthis("<font color=\"blue\">WARNING: ".
  722:                      "Attempt to delete from environment ".$delthis);
  723:             return 'error';
  724:         }
  725:     }
  726:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
  727:     if ($opened
  728: 	&& &timed_flock($env_file,LOCK_EX)
  729: 	&&
  730: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  731: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  732: 	foreach my $key (keys(%disk_env)) {
  733: 	    if ($regexp) {
  734:                 if ($key=~/^$delthis/) {
  735:                     delete($env{$key});
  736:                     delete($disk_env{$key});
  737:                 } 
  738:             } else {
  739:                 if ($key=~/^\Q$delthis\E/) {
  740: 		    delete($env{$key});
  741: 		    delete($disk_env{$key});
  742: 	        }
  743:             }
  744: 	}
  745: 	untie(%disk_env);
  746:     }
  747:     return 'ok';
  748: }
  749: 
  750: sub get_env_multiple {
  751:     my ($name) = @_;
  752:     my @values;
  753:     if (defined($env{$name})) {
  754:         # exists is it an array
  755:         if (ref($env{$name})) {
  756:             @values=@{ $env{$name} };
  757:         } else {
  758:             $values[0]=$env{$name};
  759:         }
  760:     }
  761:     return(@values);
  762: }
  763: 
  764: # ------------------------------------------------------------------- Locking
  765: 
  766: sub set_lock {
  767:     my ($text)=@_;
  768:     $locknum++;
  769:     my $id=$$.'-'.$locknum;
  770:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
  771:              'session.lock.'.$id => $text});
  772:     return $id;
  773: }
  774: 
  775: sub get_locks {
  776:     my $num=0;
  777:     my %texts=();
  778:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  779:        if ($lock=~/\w/) {
  780:           $num++;
  781:           $texts{$lock}=$env{'session.lock.'.$lock};
  782:        }
  783:    }
  784:    return ($num,%texts);
  785: }
  786: 
  787: sub remove_lock {
  788:     my ($id)=@_;
  789:     my $newlocks='';
  790:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  791:        if (($lock=~/\w/) && ($lock ne $id)) {
  792:           $newlocks.=','.$lock;
  793:        }
  794:     }
  795:     &appenv({'session.locks' => $newlocks});
  796:     &delenv('session.lock.'.$id);
  797: }
  798: 
  799: sub remove_all_locks {
  800:     my $activelocks=$env{'session.locks'};
  801:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  802:        if ($lock=~/\w/) {
  803:           &remove_lock($lock);
  804:        }
  805:     }
  806: }
  807: 
  808: 
  809: # ------------------------------------------ Find out current server userload
  810: sub userload {
  811:     my $numusers=0;
  812:     {
  813: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  814: 	my $filename;
  815: 	my $curtime=time;
  816: 	while ($filename=readdir(LONIDS)) {
  817: 	    next if ($filename eq '.' || $filename eq '..');
  818: 	    next if ($filename =~ /publicuser_\d+\.id/);
  819: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  820: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  821: 	}
  822: 	closedir(LONIDS);
  823:     }
  824:     my $userloadpercent=0;
  825:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  826:     if ($maxuserload) {
  827: 	$userloadpercent=100*$numusers/$maxuserload;
  828:     }
  829:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  830:     return $userloadpercent;
  831: }
  832: 
  833: # ------------------------------ Find server with least workload from spare.tab
  834: 
  835: sub spareserver {
  836:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
  837:     my $spare_server;
  838:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  839:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
  840:                                                      :  $userloadpercent;
  841:     my ($uint_dom,$remotesessions);
  842:     if (($udom ne '') && (&domain($udom) ne '')) {
  843:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
  844:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
  845:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
  846:         $remotesessions = $udomdefaults{'remotesessions'};
  847:     }
  848:     my $spareshash = &this_host_spares($udom);
  849:     if (ref($spareshash) eq 'HASH') {
  850:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
  851:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
  852:                 if ($uint_dom) {
  853:                     next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
  854:                                                  $try_server));
  855:                 }
  856: 	        ($spare_server, $lowest_load) =
  857: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
  858:             }
  859:         }
  860: 
  861:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
  862: 
  863:         if (!$found_server) {
  864:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
  865: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
  866:                     if ($uint_dom) {
  867:                         next unless (&spare_can_host($udom,$uint_dom,
  868:                                                      $remotesessions,$try_server));
  869:                     }
  870: 	            ($spare_server, $lowest_load) =
  871: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
  872:                 }
  873: 	    }
  874:         }
  875:     }
  876: 
  877:     if (!$want_server_name) {
  878:         my $protocol = 'http';
  879:         if ($protocol{$spare_server} eq 'https') {
  880:             $protocol = $protocol{$spare_server};
  881:         }
  882:         if (defined($spare_server)) {
  883:             my $hostname = &hostname($spare_server);
  884:             if (defined($hostname)) {
  885: 	        $spare_server = $protocol.'://'.$hostname;
  886:             }
  887:         }
  888:     }
  889:     return $spare_server;
  890: }
  891: 
  892: sub compare_server_load {
  893:     my ($try_server, $spare_server, $lowest_load) = @_;
  894: 
  895:     my $loadans     = &reply('load',    $try_server);
  896:     my $userloadans = &reply('userload',$try_server);
  897: 
  898:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
  899: 	return ($spare_server, $lowest_load); #didn't get a number from the server
  900:     }
  901: 
  902:     my $load;
  903:     if ($loadans =~ /\d/) {
  904: 	if ($userloadans =~ /\d/) {
  905: 	    #both are numbers, pick the bigger one
  906: 	    $load = ($loadans > $userloadans) ? $loadans 
  907: 		                              : $userloadans;
  908: 	} else {
  909: 	    $load = $loadans;
  910: 	}
  911:     } else {
  912: 	$load = $userloadans;
  913:     }
  914: 
  915:     if (($load =~ /\d/) && ($load < $lowest_load)) {
  916: 	$spare_server = $try_server;
  917: 	$lowest_load  = $load;
  918:     }
  919:     return ($spare_server,$lowest_load);
  920: }
  921: 
  922: # --------------------------- ask offload servers if user already has a session
  923: sub find_existing_session {
  924:     my ($udom,$uname) = @_;
  925:     my $spareshash = &this_host_spares($udom);
  926:     if (ref($spareshash) eq 'HASH') {
  927:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
  928:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
  929:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
  930:             }
  931:         }
  932:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
  933:             foreach my $try_server (@{ $spareshash->{'default'} }) {
  934:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
  935:             }
  936:         }
  937:     }
  938:     return;
  939: }
  940: 
  941: # -------------------------------- ask if server already has a session for user
  942: sub has_user_session {
  943:     my ($lonid,$udom,$uname) = @_;
  944:     my $result = &reply(join(':','userhassession',
  945: 			     map {&escape($_)} ($udom,$uname)),$lonid);
  946:     return 1 if ($result eq 'ok');
  947: 
  948:     return 0;
  949: }
  950: 
  951: # --------- determine least loaded server in a user's domain which allows login
  952: 
  953: sub choose_server {
  954:     my ($udom,$checkloginvia) = @_;
  955:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
  956:     my %servers = &get_servers($udom);
  957:     my $lowest_load = 30000;
  958:     my ($login_host,$hostname,$portal_path,$isredirect);
  959:     foreach my $lonhost (keys(%servers)) {
  960:         my $loginvia;
  961:         if ($checkloginvia) {
  962:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
  963:             if ($loginvia) {
  964:                 my ($server,$path) = split(/:/,$loginvia);
  965:                 ($login_host, $lowest_load) =
  966:                     &compare_server_load($server, $login_host, $lowest_load);
  967:                 if ($login_host eq $server) {
  968:                     $portal_path = $path;
  969:                     $isredirect = 1;
  970:                 }
  971:             } else {
  972:                 ($login_host, $lowest_load) =
  973:                     &compare_server_load($lonhost, $login_host, $lowest_load);
  974:                 if ($login_host eq $lonhost) {
  975:                     $portal_path = '';
  976:                     $isredirect = ''; 
  977:                 }
  978:             }
  979:         } else {
  980:             ($login_host, $lowest_load) =
  981:                 &compare_server_load($lonhost, $login_host, $lowest_load);
  982:         }
  983:     }
  984:     if ($login_host ne '') {
  985:         $hostname = &hostname($login_host);
  986:     }
  987:     return ($login_host,$hostname,$portal_path,$isredirect);
  988: }
  989: 
  990: # --------------------------------------------- Try to change a user's password
  991: 
  992: sub changepass {
  993:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
  994:     $currentpass = &escape($currentpass);
  995:     $newpass     = &escape($newpass);
  996:     my $lonhost = $perlvar{'lonHostID'};
  997:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
  998: 		       $server);
  999:     if (! $answer) {
 1000: 	&logthis("No reply on password change request to $server ".
 1001: 		 "by $uname in domain $udom.");
 1002:     } elsif ($answer =~ "^ok") {
 1003:         &logthis("$uname in $udom successfully changed their password ".
 1004: 		 "on $server.");
 1005:     } elsif ($answer =~ "^pwchange_failure") {
 1006: 	&logthis("$uname in $udom was unable to change their password ".
 1007: 		 "on $server.  The action was blocked by either lcpasswd ".
 1008: 		 "or pwchange");
 1009:     } elsif ($answer =~ "^non_authorized") {
 1010:         &logthis("$uname in $udom did not get their password correct when ".
 1011: 		 "attempting to change it on $server.");
 1012:     } elsif ($answer =~ "^auth_mode_error") {
 1013:         &logthis("$uname in $udom attempted to change their password despite ".
 1014: 		 "not being locally or internally authenticated on $server.");
 1015:     } elsif ($answer =~ "^unknown_user") {
 1016:         &logthis("$uname in $udom attempted to change their password ".
 1017: 		 "on $server but were unable to because $server is not ".
 1018: 		 "their home server.");
 1019:     } elsif ($answer =~ "^refused") {
 1020: 	&logthis("$server refused to change $uname in $udom password because ".
 1021: 		 "it was sent an unencrypted request to change the password.");
 1022:     } elsif ($answer =~ "invalid_client") {
 1023:         &logthis("$server refused to change $uname in $udom password because ".
 1024:                  "it was a reset by e-mail originating from an invalid server.");
 1025:     }
 1026:     return $answer;
 1027: }
 1028: 
 1029: # ----------------------- Try to determine user's current authentication scheme
 1030: 
 1031: sub queryauthenticate {
 1032:     my ($uname,$udom)=@_;
 1033:     my $uhome=&homeserver($uname,$udom);
 1034:     if (!$uhome) {
 1035: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
 1036: 	return 'no_host';
 1037:     }
 1038:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
 1039:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
 1040: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1041:     }
 1042:     return $answer;
 1043: }
 1044: 
 1045: # --------- Try to authenticate user from domain's lib servers (first this one)
 1046: 
 1047: sub authenticate {
 1048:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
 1049:     $upass=&escape($upass);
 1050:     $uname= &LONCAPA::clean_username($uname);
 1051:     my $uhome=&homeserver($uname,$udom,1);
 1052:     my $newhome;
 1053:     if ((!$uhome) || ($uhome eq 'no_host')) {
 1054: # Maybe the machine was offline and only re-appeared again recently?
 1055:         &reconlonc();
 1056: # One more
 1057: 	$uhome=&homeserver($uname,$udom,1);
 1058:         if (($uhome eq 'no_host') && $checkdefauth) {
 1059:             if (defined(&domain($udom,'primary'))) {
 1060:                 $newhome=&domain($udom,'primary');
 1061:             }
 1062:             if ($newhome ne '') {
 1063:                 $uhome = $newhome;
 1064:             }
 1065:         }
 1066: 	if ((!$uhome) || ($uhome eq 'no_host')) {
 1067: 	    &logthis("User $uname at $udom is unknown in authenticate");
 1068: 	    return 'no_host';
 1069:         }
 1070:     }
 1071:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
 1072:     if ($answer eq 'authorized') {
 1073:         if ($newhome) {
 1074:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
 1075:             return 'no_account_on_host'; 
 1076:         } else {
 1077:             &logthis("User $uname at $udom authorized by $uhome");
 1078:             return $uhome;
 1079:         }
 1080:     }
 1081:     if ($answer eq 'non_authorized') {
 1082: 	&logthis("User $uname at $udom rejected by $uhome");
 1083: 	return 'no_host'; 
 1084:     }
 1085:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1086:     return 'no_host';
 1087: }
 1088: 
 1089: sub can_host_session {
 1090:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
 1091:     my $canhost = 1;
 1092:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
 1093:     if (ref($remotesessions) eq 'HASH') {
 1094:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
 1095:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
 1096:                 $canhost = 0;
 1097:             } else {
 1098:                 $canhost = 1;
 1099:             }
 1100:         }
 1101:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
 1102:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
 1103:                 $canhost = 1;
 1104:             } else {
 1105:                 $canhost = 0;
 1106:             }
 1107:         }
 1108:         if ($canhost) {
 1109:             if ($remotesessions->{'version'} ne '') {
 1110:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
 1111:                 if ($reqmajor ne '' && $reqminor ne '') {
 1112:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
 1113:                         my $major = $1;
 1114:                         my $minor = $2;
 1115:                         if (($major < $reqmajor ) ||
 1116:                             (($major == $reqmajor) && ($minor < $reqminor))) {
 1117:                             $canhost = 0;
 1118:                         }
 1119:                     } else {
 1120:                         $canhost = 0;
 1121:                     }
 1122:                 }
 1123:             }
 1124:         }
 1125:     }
 1126:     if ($canhost) {
 1127:         if (ref($hostedsessions) eq 'HASH') {
 1128:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1129:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
 1130:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
 1131:                 if (($uint_dom ne '') && 
 1132:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
 1133:                     $canhost = 0;
 1134:                 } else {
 1135:                     $canhost = 1;
 1136:                 }
 1137:             }
 1138:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
 1139:                 if (($uint_dom ne '') && 
 1140:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
 1141:                     $canhost = 1;
 1142:                 } else {
 1143:                     $canhost = 0;
 1144:                 }
 1145:             }
 1146:         }
 1147:     }
 1148:     return $canhost;
 1149: }
 1150: 
 1151: sub spare_can_host {
 1152:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
 1153:     my $canhost=1;
 1154:     my @intdoms;
 1155:     my $internet_names = &Apache::lonnet::get_internet_names($try_server);
 1156:     if (ref($internet_names) eq 'ARRAY') {
 1157:         @intdoms = @{$internet_names};
 1158:     }
 1159:     unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
 1160:         my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
 1161:         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
 1162:         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
 1163:         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
 1164:         $canhost = &can_host_session($udom,$try_server,$remoterev,
 1165:                                      $remotesessions,
 1166:                                      $defdomdefaults{'hostedsessions'});
 1167:     }
 1168:     return $canhost;
 1169: }
 1170: 
 1171: sub this_host_spares {
 1172:     my ($dom) = @_;
 1173:     my ($dom_in_use,$lonhost_in_use,$result);
 1174:     my @hosts = &current_machine_ids();
 1175:     foreach my $lonhost (@hosts) {
 1176:         if (&host_domain($lonhost) eq $dom) {
 1177:             $dom_in_use = $dom;
 1178:             $lonhost_in_use = $lonhost;
 1179:             last;
 1180:         }
 1181:     }
 1182:     if ($dom_in_use ne '') {
 1183:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1184:     }
 1185:     if (ref($result) ne 'HASH') {
 1186:         $lonhost_in_use = $perlvar{'lonHostID'};
 1187:         $dom_in_use = &host_domain($lonhost_in_use);
 1188:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1189:         if (ref($result) ne 'HASH') {
 1190:             $result = \%spareid;
 1191:         }
 1192:     }
 1193:     return $result;
 1194: }
 1195: 
 1196: sub spares_for_offload  {
 1197:     my ($dom_in_use,$lonhost_in_use) = @_;
 1198:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
 1199:     if (defined($cached)) {
 1200:         return $result;
 1201:     } else {
 1202:         my $cachetime = 60*60*24;
 1203:         my %domconfig =
 1204:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
 1205:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
 1206:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
 1207:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
 1208:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
 1209:                 }
 1210:             }
 1211:         }
 1212:     }
 1213:     return;
 1214: }
 1215: 
 1216: sub get_lonbalancer_config {
 1217:     my ($servers) = @_;
 1218:     my ($currbalancer,$currtargets);
 1219:     if (ref($servers) eq 'HASH') {
 1220:         foreach my $server (keys(%{$servers})) {
 1221:             my %what = (
 1222:                          spareid => 1,
 1223:                          perlvar => 1,
 1224:                        );
 1225:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
 1226:             if ($result eq 'ok') {
 1227:                 if (ref($returnhash) eq 'HASH') {
 1228:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
 1229:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
 1230:                             $currbalancer = $server;
 1231:                             $currtargets = {};
 1232:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
 1233:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
 1234:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
 1235:                                 }
 1236:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
 1237:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
 1238:                                 }
 1239:                             }
 1240:                             last;
 1241:                         }
 1242:                     }
 1243:                 }
 1244:             }
 1245:         }
 1246:     }
 1247:     return ($currbalancer,$currtargets);
 1248: }
 1249: 
 1250: sub check_loadbalancing {
 1251:     my ($uname,$udom) = @_;
 1252:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
 1253:         $rule_in_effect,$offloadto,$otherserver);
 1254:     my $lonhost = $perlvar{'lonHostID'};
 1255:     my @hosts = &current_machine_ids();
 1256:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1257:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
 1258:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
 1259:     my $serverhomedom = &host_domain($lonhost);
 1260: 
 1261:     my $cachetime = 60*60*24;
 1262: 
 1263:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1264:         $dom_in_use = $udom;
 1265:         $homeintdom = 1;
 1266:     } else {
 1267:         $dom_in_use = $serverhomedom;
 1268:     }
 1269:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
 1270:     unless (defined($cached)) {
 1271:         my %domconfig =
 1272:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
 1273:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1274:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1275:         }
 1276:     }
 1277:     if (ref($result) eq 'HASH') {
 1278:         ($is_balancer,$currtargets,$currrules) = 
 1279:             &check_balancer_result($result,@hosts);
 1280:         if ($is_balancer) {
 1281:             if (ref($currrules) eq 'HASH') {
 1282:                 if ($homeintdom) {
 1283:                     if ($uname ne '') {
 1284:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
 1285:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
 1286:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
 1287:                                 $rule_in_effect = $currrules->{'_LC_author'};
 1288:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
 1289:                                 $rule_in_effect = $currrules->{'_LC_adv'}
 1290:                             }
 1291:                         }
 1292:                         if ($rule_in_effect eq '') {
 1293:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
 1294:                             if ($userenv{'inststatus'} ne '') {
 1295:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
 1296:                                 my ($othertitle,$usertypes,$types) =
 1297:                                     &Apache::loncommon::sorted_inst_types($udom);
 1298:                                 if (ref($types) eq 'ARRAY') {
 1299:                                     foreach my $type (@{$types}) {
 1300:                                         if (grep(/^\Q$type\E$/,@statuses)) {
 1301:                                             if (exists($currrules->{$type})) {
 1302:                                                 $rule_in_effect = $currrules->{$type};
 1303:                                             }
 1304:                                         }
 1305:                                     }
 1306:                                 }
 1307:                             } else {
 1308:                                 if (exists($currrules->{'default'})) {
 1309:                                     $rule_in_effect = $currrules->{'default'};
 1310:                                 }
 1311:                             }
 1312:                         }
 1313:                     } else {
 1314:                         if (exists($currrules->{'default'})) {
 1315:                             $rule_in_effect = $currrules->{'default'};
 1316:                         }
 1317:                     }
 1318:                 } else {
 1319:                     if ($currrules->{'_LC_external'} ne '') {
 1320:                         $rule_in_effect = $currrules->{'_LC_external'};
 1321:                     }
 1322:                 }
 1323:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1324:                                                        $uname,$udom);
 1325:             }
 1326:         }
 1327:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
 1328:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
 1329:         unless (defined($cached)) {
 1330:             my %domconfig =
 1331:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
 1332:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1333:                 $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1334:             }
 1335:         }
 1336:         if (ref($result) eq 'HASH') {
 1337:             ($is_balancer,$currtargets,$currrules) = 
 1338:                 &check_balancer_result($result,@hosts);
 1339:             if ($is_balancer) {
 1340:                 if (ref($currrules) eq 'HASH') {
 1341:                     if ($currrules->{'_LC_internetdom'} ne '') {
 1342:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
 1343:                     }
 1344:                 }
 1345:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1346:                                                        $uname,$udom);
 1347:             }
 1348:         } else {
 1349:             if ($perlvar{'lonBalancer'} eq 'yes') {
 1350:                 $is_balancer = 1;
 1351:                 $offloadto = &this_host_spares($dom_in_use);
 1352:             }
 1353:         }
 1354:     } else {
 1355:         if ($perlvar{'lonBalancer'} eq 'yes') {
 1356:             $is_balancer = 1;
 1357:             $offloadto = &this_host_spares($dom_in_use);
 1358:         }
 1359:     }
 1360:     if ($is_balancer) {
 1361:         my $lowest_load = 30000;
 1362:         if (ref($offloadto) eq 'HASH') {
 1363:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
 1364:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
 1365:                     ($otherserver,$lowest_load) =
 1366:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1367:                 }
 1368:             }
 1369:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
 1370: 
 1371:             if (!$found_server) {
 1372:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
 1373:                     foreach my $try_server (@{$offloadto->{'default'}}) {
 1374:                         ($otherserver,$lowest_load) =
 1375:                             &compare_server_load($try_server,$otherserver,$lowest_load);
 1376:                     }
 1377:                 }
 1378:             }
 1379:         } elsif (ref($offloadto) eq 'ARRAY') {
 1380:             if (@{$offloadto} == 1) {
 1381:                 $otherserver = $offloadto->[0];
 1382:             } elsif (@{$offloadto} > 1) {
 1383:                 foreach my $try_server (@{$offloadto}) {
 1384:                     ($otherserver,$lowest_load) =
 1385:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1386:                 }
 1387:             }
 1388:         }
 1389:         if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
 1390:             $is_balancer = 0;
 1391:             if ($uname ne '' && $udom ne '') {
 1392:                 if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
 1393:                     
 1394:                     &appenv({'user.loadbalexempt'     => $lonhost,  
 1395:                              'user.loadbalcheck.time' => time});
 1396:                 }
 1397:             }
 1398:         }
 1399:     }
 1400:     return ($is_balancer,$otherserver);
 1401: }
 1402: 
 1403: sub check_balancer_result {
 1404:     my ($result,@hosts) = @_;
 1405:     my ($is_balancer,$currtargets,$currrules);
 1406:     if (ref($result) eq 'HASH') {
 1407:         if ($result->{'lonhost'} ne '') {
 1408:             my $currbalancer = $result->{'lonhost'};
 1409:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
 1410:                 $is_balancer = 1;
 1411:                 $currtargets = $result->{'targets'};
 1412:                 $currrules = $result->{'rules'};
 1413:             }
 1414:         } else {
 1415:             foreach my $key (keys(%{$result})) {
 1416:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
 1417:                     (ref($result->{$key}) eq 'HASH')) {
 1418:                     $is_balancer = 1;
 1419:                     $currrules = $result->{$key}{'rules'};
 1420:                     $currtargets = $result->{$key}{'targets'};
 1421:                     last;
 1422:                 }
 1423:             }
 1424:         }
 1425:     }
 1426:     return ($is_balancer,$currtargets,$currrules);
 1427: }
 1428: 
 1429: sub get_loadbalancer_targets {
 1430:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
 1431:     my $offloadto;
 1432:     if ($rule_in_effect eq 'none') {
 1433:         return [$perlvar{'lonHostID'}];
 1434:     } elsif ($rule_in_effect eq '') {
 1435:         $offloadto = $currtargets;
 1436:     } else {
 1437:         if ($rule_in_effect eq 'homeserver') {
 1438:             my $homeserver = &homeserver($uname,$udom);
 1439:             if ($homeserver ne 'no_host') {
 1440:                 $offloadto = [$homeserver];
 1441:             }
 1442:         } elsif ($rule_in_effect eq 'externalbalancer') {
 1443:             my %domconfig =
 1444:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
 1445:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1446:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
 1447:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
 1448:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
 1449:                     }
 1450:                 }
 1451:             } else {
 1452:                 my %servers = &internet_dom_servers($udom);
 1453:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
 1454:                 if (&hostname($remotebalancer) ne '') {
 1455:                     $offloadto = [$remotebalancer];
 1456:                 }
 1457:             }
 1458:         } elsif (&hostname($rule_in_effect) ne '') {
 1459:             $offloadto = [$rule_in_effect];
 1460:         }
 1461:     }
 1462:     return $offloadto;
 1463: }
 1464: 
 1465: sub internet_dom_servers {
 1466:     my ($dom) = @_;
 1467:     my (%uniqservers,%servers);
 1468:     my $primaryserver = &hostname(&domain($dom,'primary'));
 1469:     my @machinedoms = &machine_domains($primaryserver);
 1470:     foreach my $mdom (@machinedoms) {
 1471:         my %currservers = %servers;
 1472:         my %server = &get_servers($mdom);
 1473:         %servers = (%currservers,%server);
 1474:     }
 1475:     my %by_hostname;
 1476:     foreach my $id (keys(%servers)) {
 1477:         push(@{$by_hostname{$servers{$id}}},$id);
 1478:     }
 1479:     foreach my $hostname (sort(keys(%by_hostname))) {
 1480:         if (@{$by_hostname{$hostname}} > 1) {
 1481:             my $match = 0;
 1482:             foreach my $id (@{$by_hostname{$hostname}}) {
 1483:                 if (&host_domain($id) eq $dom) {
 1484:                     $uniqservers{$id} = $hostname;
 1485:                     $match = 1;
 1486:                 }
 1487:             }
 1488:             unless ($match) {
 1489:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1490:             }
 1491:         } else {
 1492:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1493:         }
 1494:     }
 1495:     return %uniqservers;
 1496: }
 1497: 
 1498: # ---------------------- Find the homebase for a user from domain's lib servers
 1499: 
 1500: my %homecache;
 1501: sub homeserver {
 1502:     my ($uname,$udom,$ignoreBadCache)=@_;
 1503:     my $index="$uname:$udom";
 1504: 
 1505:     if (exists($homecache{$index})) { return $homecache{$index}; }
 1506: 
 1507:     my %servers = &get_servers($udom,'library');
 1508:     foreach my $tryserver (keys(%servers)) {
 1509:         next if ($ignoreBadCache ne 'true' && 
 1510: 		 exists($badServerCache{$tryserver}));
 1511: 
 1512: 	my $answer=reply("home:$udom:$uname",$tryserver);
 1513: 	if ($answer eq 'found') {
 1514: 	    delete($badServerCache{$tryserver}); 
 1515: 	    return $homecache{$index}=$tryserver;
 1516: 	} elsif ($answer eq 'no_host') {
 1517: 	    $badServerCache{$tryserver}=1;
 1518: 	}
 1519:     }    
 1520:     return 'no_host';
 1521: }
 1522: 
 1523: # ------------------------------------- Find the usernames behind a list of IDs
 1524: 
 1525: sub idget {
 1526:     my ($udom,@ids)=@_;
 1527:     my %returnhash=();
 1528:     
 1529:     my %servers = &get_servers($udom,'library');
 1530:     foreach my $tryserver (keys(%servers)) {
 1531: 	my $idlist=join('&',@ids);
 1532: 	$idlist=~tr/A-Z/a-z/; 
 1533: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
 1534: 	my @answer=();
 1535: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
 1536: 	    @answer=split(/\&/,$reply);
 1537: 	}                    ;
 1538: 	my $i;
 1539: 	for ($i=0;$i<=$#ids;$i++) {
 1540: 	    if ($answer[$i]) {
 1541: 		$returnhash{$ids[$i]}=$answer[$i];
 1542: 	    } 
 1543: 	}
 1544:     } 
 1545:     return %returnhash;
 1546: }
 1547: 
 1548: # ------------------------------------- Find the IDs behind a list of usernames
 1549: 
 1550: sub idrget {
 1551:     my ($udom,@unames)=@_;
 1552:     my %returnhash=();
 1553:     foreach my $uname (@unames) {
 1554:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
 1555:     }
 1556:     return %returnhash;
 1557: }
 1558: 
 1559: # ------------------------------- Store away a list of names and associated IDs
 1560: 
 1561: sub idput {
 1562:     my ($udom,%ids)=@_;
 1563:     my %servers=();
 1564:     foreach my $uname (keys(%ids)) {
 1565: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
 1566:         my $uhom=&homeserver($uname,$udom);
 1567:         if ($uhom ne 'no_host') {
 1568:             my $id=&escape($ids{$uname});
 1569:             $id=~tr/A-Z/a-z/;
 1570:             my $esc_unam=&escape($uname);
 1571: 	    if ($servers{$uhom}) {
 1572: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
 1573:             } else {
 1574:                 $servers{$uhom}=$id.'='.$esc_unam;
 1575:             }
 1576:         }
 1577:     }
 1578:     foreach my $server (keys(%servers)) {
 1579:         &critical('idput:'.$udom.':'.$servers{$server},$server);
 1580:     }
 1581: }
 1582: 
 1583: # ---------------------------------------- Delete unwanted IDs from ids.db file 
 1584: 
 1585: sub iddel {
 1586:     my ($udom,$idshashref,$uhome)=@_;
 1587:     my %result=();
 1588:     unless (ref($idshashref) eq 'HASH') {
 1589:         return %result;
 1590:     }
 1591:     my %servers=();
 1592:     while (my ($id,$uname) = each(%{$idshashref})) {
 1593:         my $uhom;
 1594:         if ($uhome) {
 1595:             $uhom = $uhome;
 1596:         } else {
 1597:             $uhom=&homeserver($uname,$udom);
 1598:         }
 1599:         if ($uhom ne 'no_host') {
 1600:             if ($servers{$uhom}) {
 1601:                 $servers{$uhom}.='&'.&escape($id);
 1602:             } else {
 1603:                 $servers{$uhom}=&escape($id);
 1604:             }
 1605:         }
 1606:     }
 1607:     foreach my $server (keys(%servers)) {
 1608:         $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
 1609:     }
 1610:     return %result;
 1611: }
 1612: 
 1613: # ------------------------------dump from db file owned by domainconfig user
 1614: sub dump_dom {
 1615:     my ($namespace, $udom, $regexp) = @_;
 1616: 
 1617:     $udom ||= $env{'user.domain'};
 1618: 
 1619:     return () unless $udom;
 1620: 
 1621:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
 1622: }
 1623: 
 1624: # ------------------------------------------ get items from domain db files   
 1625: 
 1626: sub get_dom {
 1627:     my ($namespace,$storearr,$udom,$uhome)=@_;
 1628:     my $items='';
 1629:     foreach my $item (@$storearr) {
 1630:         $items.=&escape($item).'&';
 1631:     }
 1632:     $items=~s/\&$//;
 1633:     if (!$udom) {
 1634:         $udom=$env{'user.domain'};
 1635:         if (defined(&domain($udom,'primary'))) {
 1636:             $uhome=&domain($udom,'primary');
 1637:         } else {
 1638:             undef($uhome);
 1639:         }
 1640:     } else {
 1641:         if (!$uhome) {
 1642:             if (defined(&domain($udom,'primary'))) {
 1643:                 $uhome=&domain($udom,'primary');
 1644:             }
 1645:         }
 1646:     }
 1647:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1648:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
 1649:         my %returnhash;
 1650:         if ($rep eq '' || $rep =~ /^error: 2 /) {
 1651:             return %returnhash;
 1652:         }
 1653:         my @pairs=split(/\&/,$rep);
 1654:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 1655:             return @pairs;
 1656:         }
 1657:         my $i=0;
 1658:         foreach my $item (@$storearr) {
 1659:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
 1660:             $i++;
 1661:         }
 1662:         return %returnhash;
 1663:     } else {
 1664:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
 1665:     }
 1666: }
 1667: 
 1668: # -------------------------------------------- put items in domain db files 
 1669: 
 1670: sub put_dom {
 1671:     my ($namespace,$storehash,$udom,$uhome)=@_;
 1672:     if (!$udom) {
 1673:         $udom=$env{'user.domain'};
 1674:         if (defined(&domain($udom,'primary'))) {
 1675:             $uhome=&domain($udom,'primary');
 1676:         } else {
 1677:             undef($uhome);
 1678:         }
 1679:     } else {
 1680:         if (!$uhome) {
 1681:             if (defined(&domain($udom,'primary'))) {
 1682:                 $uhome=&domain($udom,'primary');
 1683:             }
 1684:         }
 1685:     } 
 1686:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1687:         my $items='';
 1688:         foreach my $item (keys(%$storehash)) {
 1689:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 1690:         }
 1691:         $items=~s/\&$//;
 1692:         return &reply("putdom:$udom:$namespace:$items",$uhome);
 1693:     } else {
 1694:         &logthis("put_dom failed - no homeserver and/or domain");
 1695:     }
 1696: }
 1697: 
 1698: # --------------------- newput for items in db file owned by domainconfig user
 1699: sub newput_dom {
 1700:     my ($namespace,$storehash,$udom) = @_;
 1701:     my $result;
 1702:     if (!$udom) {
 1703:         $udom=$env{'user.domain'};
 1704:     }
 1705:     if ($udom) {
 1706:         my $uname = &get_domainconfiguser($udom);
 1707:         $result = &newput($namespace,$storehash,$udom,$uname);
 1708:     }
 1709:     return $result;
 1710: }
 1711: 
 1712: # --------------------- delete for items in db file owned by domainconfig user
 1713: sub del_dom {
 1714:     my ($namespace,$storearr,$udom)=@_;
 1715:     if (ref($storearr) eq 'ARRAY') {
 1716:         if (!$udom) {
 1717:             $udom=$env{'user.domain'};
 1718:         }
 1719:         if ($udom) {
 1720:             my $uname = &get_domainconfiguser($udom); 
 1721:             return &del($namespace,$storearr,$udom,$uname);
 1722:         }
 1723:     }
 1724: }
 1725: 
 1726: # ----------------------------------construct domainconfig user for a domain 
 1727: sub get_domainconfiguser {
 1728:     my ($udom) = @_;
 1729:     return $udom.'-domainconfig';
 1730: }
 1731: 
 1732: sub retrieve_inst_usertypes {
 1733:     my ($udom) = @_;
 1734:     my (%returnhash,@order);
 1735:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 1736:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
 1737:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
 1738:         %returnhash = %{$domdefs{'inststatustypes'}};
 1739:         @order = @{$domdefs{'inststatusorder'}};
 1740:     } else {
 1741:         if (defined(&domain($udom,'primary'))) {
 1742:             my $uhome=&domain($udom,'primary');
 1743:             my $rep=&reply("inst_usertypes:$udom",$uhome);
 1744:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
 1745:                 &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
 1746:                 return (\%returnhash,\@order);
 1747:             }
 1748:             my ($hashitems,$orderitems) = split(/:/,$rep); 
 1749:             my @pairs=split(/\&/,$hashitems);
 1750:             foreach my $item (@pairs) {
 1751:                 my ($key,$value)=split(/=/,$item,2);
 1752:                 $key = &unescape($key);
 1753:                 next if ($key =~ /^error: 2 /);
 1754:                 $returnhash{$key}=&thaw_unescape($value);
 1755:             }
 1756:             my @esc_order = split(/\&/,$orderitems);
 1757:             foreach my $item (@esc_order) {
 1758:                 push(@order,&unescape($item));
 1759:             }
 1760:         } else {
 1761:             &logthis("get_dom failed - no primary domain server for $udom");
 1762:         }
 1763:     }
 1764:     return (\%returnhash,\@order);
 1765: }
 1766: 
 1767: sub is_domainimage {
 1768:     my ($url) = @_;
 1769:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
 1770:         if (&domain($1) ne '') {
 1771:             return '1';
 1772:         }
 1773:     }
 1774:     return;
 1775: }
 1776: 
 1777: sub inst_directory_query {
 1778:     my ($srch) = @_;
 1779:     my $udom = $srch->{'srchdomain'};
 1780:     my %results;
 1781:     my $homeserver = &domain($udom,'primary');
 1782:     my $outcome;
 1783:     if ($homeserver ne '') {
 1784: 	my $queryid=&reply("querysend:instdirsearch:".
 1785: 			   &escape($srch->{'srchby'}).':'.
 1786: 			   &escape($srch->{'srchterm'}).':'.
 1787: 			   &escape($srch->{'srchtype'}),$homeserver);
 1788: 	my $host=&hostname($homeserver);
 1789: 	if ($queryid !~/^\Q$host\E\_/) {
 1790: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1791: 	    return;
 1792: 	}
 1793: 	my $response = &get_query_reply($queryid);
 1794: 	my $maxtries = 5;
 1795: 	my $tries = 1;
 1796: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1797: 	    $response = &get_query_reply($queryid);
 1798: 	    $tries ++;
 1799: 	}
 1800: 
 1801:         if (!&error($response) && $response ne 'refused') {
 1802:             if ($response eq 'unavailable') {
 1803:                 $outcome = $response;
 1804:             } else {
 1805:                 $outcome = 'ok';
 1806:                 my @matches = split(/\n/,$response);
 1807:                 foreach my $match (@matches) {
 1808:                     my ($key,$value) = split(/=/,$match);
 1809:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 1810:                 }
 1811:             }
 1812:         }
 1813:     }
 1814:     return ($outcome,%results);
 1815: }
 1816: 
 1817: sub usersearch {
 1818:     my ($srch) = @_;
 1819:     my $dom = $srch->{'srchdomain'};
 1820:     my %results;
 1821:     my %libserv = &all_library();
 1822:     my $query = 'usersearch';
 1823:     foreach my $tryserver (keys(%libserv)) {
 1824:         if (&host_domain($tryserver) eq $dom) {
 1825:             my $host=&hostname($tryserver);
 1826:             my $queryid=
 1827:                 &reply("querysend:".&escape($query).':'.
 1828:                        &escape($srch->{'srchby'}).':'.
 1829:                        &escape($srch->{'srchtype'}).':'.
 1830:                        &escape($srch->{'srchterm'}),$tryserver);
 1831:             if ($queryid !~/^\Q$host\E\_/) {
 1832:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 1833:                 next;
 1834:             }
 1835:             my $reply = &get_query_reply($queryid);
 1836:             my $maxtries = 1;
 1837:             my $tries = 1;
 1838:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 1839:                 $reply = &get_query_reply($queryid);
 1840:                 $tries ++;
 1841:             }
 1842:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 1843:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 1844:             } else {
 1845:                 my @matches;
 1846:                 if ($reply =~ /\n/) {
 1847:                     @matches = split(/\n/,$reply);
 1848:                 } else {
 1849:                     @matches = split(/\&/,$reply);
 1850:                 }
 1851:                 foreach my $match (@matches) {
 1852:                     my ($uname,$udom,%userhash);
 1853:                     foreach my $entry (split(/:/,$match)) {
 1854:                         my ($key,$value) =
 1855:                             map {&unescape($_);} split(/=/,$entry);
 1856:                         $userhash{$key} = $value;
 1857:                         if ($key eq 'username') {
 1858:                             $uname = $value;
 1859:                         } elsif ($key eq 'domain') {
 1860:                             $udom = $value;
 1861:                         }
 1862:                     }
 1863:                     $results{$uname.':'.$udom} = \%userhash;
 1864:                 }
 1865:             }
 1866:         }
 1867:     }
 1868:     return %results;
 1869: }
 1870: 
 1871: sub get_instuser {
 1872:     my ($udom,$uname,$id) = @_;
 1873:     my $homeserver = &domain($udom,'primary');
 1874:     my ($outcome,%results);
 1875:     if ($homeserver ne '') {
 1876:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 1877:                            &escape($id).':'.&escape($udom),$homeserver);
 1878:         my $host=&hostname($homeserver);
 1879:         if ($queryid !~/^\Q$host\E\_/) {
 1880:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1881:             return;
 1882:         }
 1883:         my $response = &get_query_reply($queryid);
 1884:         my $maxtries = 5;
 1885:         my $tries = 1;
 1886:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1887:             $response = &get_query_reply($queryid);
 1888:             $tries ++;
 1889:         }
 1890:         if (!&error($response) && $response ne 'refused') {
 1891:             if ($response eq 'unavailable') {
 1892:                 $outcome = $response;
 1893:             } else {
 1894:                 $outcome = 'ok';
 1895:                 my @matches = split(/\n/,$response);
 1896:                 foreach my $match (@matches) {
 1897:                     my ($key,$value) = split(/=/,$match);
 1898:                     $results{&unescape($key)} = &thaw_unescape($value);
 1899:                 }
 1900:             }
 1901:         }
 1902:     }
 1903:     my %userinfo;
 1904:     if (ref($results{$uname}) eq 'HASH') {
 1905:         %userinfo = %{$results{$uname}};
 1906:     } 
 1907:     return ($outcome,%userinfo);
 1908: }
 1909: 
 1910: sub inst_rulecheck {
 1911:     my ($udom,$uname,$id,$item,$rules) = @_;
 1912:     my %returnhash;
 1913:     if ($udom ne '') {
 1914:         if (ref($rules) eq 'ARRAY') {
 1915:             @{$rules} = map {&escape($_);} (@{$rules});
 1916:             my $rulestr = join(':',@{$rules});
 1917:             my $homeserver=&domain($udom,'primary');
 1918:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1919:                 my $response;
 1920:                 if ($item eq 'username') {                
 1921:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 1922:                                               ':'.&escape($uname).':'.$rulestr,
 1923:                                               $homeserver));
 1924:                 } elsif ($item eq 'id') {
 1925:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 1926:                                               ':'.&escape($id).':'.$rulestr,
 1927:                                               $homeserver));
 1928:                 } elsif ($item eq 'selfcreate') {
 1929:                     $response=&unescape(&reply('instselfcreatecheck:'.
 1930:                                                &escape($udom).':'.&escape($uname).
 1931:                                               ':'.$rulestr,$homeserver));
 1932:                 }
 1933:                 if ($response ne 'refused') {
 1934:                     my @pairs=split(/\&/,$response);
 1935:                     foreach my $item (@pairs) {
 1936:                         my ($key,$value)=split(/=/,$item,2);
 1937:                         $key = &unescape($key);
 1938:                         next if ($key =~ /^error: 2 /);
 1939:                         $returnhash{$key}=&thaw_unescape($value);
 1940:                     }
 1941:                 }
 1942:             }
 1943:         }
 1944:     }
 1945:     return %returnhash;
 1946: }
 1947: 
 1948: sub inst_userrules {
 1949:     my ($udom,$check) = @_;
 1950:     my (%ruleshash,@ruleorder);
 1951:     if ($udom ne '') {
 1952:         my $homeserver=&domain($udom,'primary');
 1953:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1954:             my $response;
 1955:             if ($check eq 'id') {
 1956:                 $response=&reply('instidrules:'.&escape($udom),
 1957:                                  $homeserver);
 1958:             } elsif ($check eq 'email') {
 1959:                 $response=&reply('instemailrules:'.&escape($udom),
 1960:                                  $homeserver);
 1961:             } else {
 1962:                 $response=&reply('instuserrules:'.&escape($udom),
 1963:                                  $homeserver);
 1964:             }
 1965:             if (($response ne 'refused') && ($response ne 'error') && 
 1966:                 ($response ne 'unknown_cmd') && 
 1967:                 ($response ne 'no_such_host')) {
 1968:                 my ($hashitems,$orderitems) = split(/:/,$response);
 1969:                 my @pairs=split(/\&/,$hashitems);
 1970:                 foreach my $item (@pairs) {
 1971:                     my ($key,$value)=split(/=/,$item,2);
 1972:                     $key = &unescape($key);
 1973:                     next if ($key =~ /^error: 2 /);
 1974:                     $ruleshash{$key}=&thaw_unescape($value);
 1975:                 }
 1976:                 my @esc_order = split(/\&/,$orderitems);
 1977:                 foreach my $item (@esc_order) {
 1978:                     push(@ruleorder,&unescape($item));
 1979:                 }
 1980:             }
 1981:         }
 1982:     }
 1983:     return (\%ruleshash,\@ruleorder);
 1984: }
 1985: 
 1986: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 1987: 
 1988: sub get_domain_defaults {
 1989:     my ($domain,$ignore_cache) = @_;
 1990:     return if (($domain eq '') || ($domain eq 'public'));
 1991:     my $cachetime = 60*60*24;
 1992:     unless ($ignore_cache) {
 1993:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 1994:         if (defined($cached)) {
 1995:             if (ref($result) eq 'HASH') {
 1996:                 return %{$result};
 1997:             }
 1998:         }
 1999:     }
 2000:     my %domdefaults;
 2001:     my %domconfig =
 2002:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
 2003:                                   'requestcourses','inststatus',
 2004:                                   'coursedefaults','usersessions',
 2005:                                   'requestauthor'],$domain);
 2006:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 2007:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 2008:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 2009:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 2010:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 2011:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
 2012:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
 2013:     } else {
 2014:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 2015:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 2016:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 2017:     }
 2018:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 2019:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 2020:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 2021:         } else {
 2022:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 2023:         }
 2024:         my @usertools = ('aboutme','blog','webdav','portfolio');
 2025:         foreach my $item (@usertools) {
 2026:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 2027:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 2028:             }
 2029:         }
 2030:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
 2031:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
 2032:         }
 2033:     }
 2034:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 2035:         foreach my $item ('official','unofficial','community','textbook') {
 2036:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
 2037:         }
 2038:     }
 2039:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
 2040:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
 2041:     }
 2042:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
 2043:         foreach my $item ('inststatustypes','inststatusorder') {
 2044:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
 2045:         }
 2046:     }
 2047:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
 2048:         $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
 2049:         if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
 2050:             $domdefaults{'officialcredits'} = $domconfig{'coursedefaults'}{'coursecredits'}{'official'};
 2051:             $domdefaults{'unofficialcredits'} = $domconfig{'coursedefaults'}{'coursecredits'}{'unofficial'};
 2052:             $domdefaults{'textbookcredits'} = $domconfig{'coursedefaults'}{'coursecredits'}{'textbook'};
 2053:         }
 2054:         if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
 2055:             $domdefaults{'officialquota'} = $domconfig{'coursedefaults'}{'uploadquota'}{'official'};
 2056:             $domdefaults{'unofficialquota'} = $domconfig{'coursedefaults'}{'uploadquota'}{'unofficial'};
 2057:             $domdefaults{'communityquota'} = $domconfig{'coursedefaults'}{'uploadquota'}{'community'};
 2058:             $domdefaults{'textbookquota'} = $domconfig{'coursedefaults'}{'uploadquota'}{'textbook'};
 2059:         }
 2060:     }
 2061:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
 2062:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
 2063:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
 2064:         }
 2065:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
 2066:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
 2067:         }
 2068:     }
 2069:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
 2070:     return %domdefaults;
 2071: }
 2072: 
 2073: # --------------------------------------------------- Assign a key to a student
 2074: 
 2075: sub assign_access_key {
 2076: #
 2077: # a valid key looks like uname:udom#comments
 2078: # comments are being appended
 2079: #
 2080:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 2081:     $kdom=
 2082:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 2083:     $knum=
 2084:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 2085:     $cdom=
 2086:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2087:     $cnum=
 2088:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2089:     $udom=$env{'user.name'} unless (defined($udom));
 2090:     $uname=$env{'user.domain'} unless (defined($uname));
 2091:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 2092:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 2093:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 2094:                                                   # assigned to this person
 2095:                                                   # - this should not happen,
 2096:                                                   # unless something went wrong
 2097:                                                   # the first time around
 2098: # ready to assign
 2099:         $logentry=$1.'; '.$logentry;
 2100:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 2101:                                                  $kdom,$knum) eq 'ok') {
 2102: # key now belongs to user
 2103: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 2104:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 2105:                 &appenv({'environment.'.$envkey => $ckey});
 2106:                 return 'ok';
 2107:             } else {
 2108:                 return 
 2109:   'error: Count not permanently assign key, will need to be re-entered later.';
 2110: 	    }
 2111:         } else {
 2112:             return 'error: Could not assign key, try again later.';
 2113:         }
 2114:     } elsif (!$existing{$ckey}) {
 2115: # the key does not exist
 2116: 	return 'error: The key does not exist';
 2117:     } else {
 2118: # the key is somebody else's
 2119: 	return 'error: The key is already in use';
 2120:     }
 2121: }
 2122: 
 2123: # ------------------------------------------ put an additional comment on a key
 2124: 
 2125: sub comment_access_key {
 2126: #
 2127: # a valid key looks like uname:udom#comments
 2128: # comments are being appended
 2129: #
 2130:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 2131:     $cdom=
 2132:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2133:     $cnum=
 2134:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2135:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2136:     if ($existing{$ckey}) {
 2137:         $existing{$ckey}.='; '.$logentry;
 2138: # ready to assign
 2139:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 2140:                                                  $cdom,$cnum) eq 'ok') {
 2141: 	    return 'ok';
 2142:         } else {
 2143: 	    return 'error: Count not store comment.';
 2144:         }
 2145:     } else {
 2146: # the key does not exist
 2147: 	return 'error: The key does not exist';
 2148:     }
 2149: }
 2150: 
 2151: # ------------------------------------------------------ Generate a set of keys
 2152: 
 2153: sub generate_access_keys {
 2154:     my ($number,$cdom,$cnum,$logentry)=@_;
 2155:     $cdom=
 2156:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2157:     $cnum=
 2158:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2159:     unless (&allowed('mky',$cdom)) { return 0; }
 2160:     unless (($cdom) && ($cnum)) { return 0; }
 2161:     if ($number>10000) { return 0; }
 2162:     sleep(2); # make sure don't get same seed twice
 2163:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 2164:     my $total=0;
 2165:     for (my $i=1;$i<=$number;$i++) {
 2166:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 2167:                   sprintf("%lx",int(100000*rand)).'-'.
 2168:                   sprintf("%lx",int(100000*rand));
 2169:        $newkey=~s/1/g/g; # folks mix up 1 and l
 2170:        $newkey=~s/0/h/g; # and also 0 and O
 2171:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 2172:        if ($existing{$newkey}) {
 2173:            $i--;
 2174:        } else {
 2175: 	  if (&put('accesskeys',
 2176:               { $newkey => '# generated '.localtime().
 2177:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 2178:                            '; '.$logentry },
 2179: 		   $cdom,$cnum) eq 'ok') {
 2180:               $total++;
 2181: 	  }
 2182:        }
 2183:     }
 2184:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 2185:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 2186:     return $total;
 2187: }
 2188: 
 2189: # ------------------------------------------------------- Validate an accesskey
 2190: 
 2191: sub validate_access_key {
 2192:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 2193:     $cdom=
 2194:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2195:     $cnum=
 2196:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2197:     $udom=$env{'user.domain'} unless (defined($udom));
 2198:     $uname=$env{'user.name'} unless (defined($uname));
 2199:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2200:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 2201: }
 2202: 
 2203: # ------------------------------------- Find the section of student in a course
 2204: sub devalidate_getsection_cache {
 2205:     my ($udom,$unam,$courseid)=@_;
 2206:     my $hashid="$udom:$unam:$courseid";
 2207:     &devalidate_cache_new('getsection',$hashid);
 2208: }
 2209: 
 2210: sub courseid_to_courseurl {
 2211:     my ($courseid) = @_;
 2212:     #already url style courseid
 2213:     return $courseid if ($courseid =~ m{^/});
 2214: 
 2215:     if (exists($env{'course.'.$courseid.'.num'})) {
 2216: 	my $cnum = $env{'course.'.$courseid.'.num'};
 2217: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 2218: 	return "/$cdom/$cnum";
 2219:     }
 2220: 
 2221:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 2222:     if (exists($courseinfo{'num'})) {
 2223: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 2224:     }
 2225: 
 2226:     return undef;
 2227: }
 2228: 
 2229: sub getsection {
 2230:     my ($udom,$unam,$courseid)=@_;
 2231:     my $cachetime=1800;
 2232: 
 2233:     my $hashid="$udom:$unam:$courseid";
 2234:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 2235:     if (defined($cached)) { return $result; }
 2236: 
 2237:     my %Pending; 
 2238:     my %Expired;
 2239:     #
 2240:     # Each role can either have not started yet (pending), be active, 
 2241:     #    or have expired.
 2242:     #
 2243:     # If there is an active role, we are done.
 2244:     #
 2245:     # If there is more than one role which has not started yet, 
 2246:     #     choose the one which will start sooner
 2247:     # If there is one role which has not started yet, return it.
 2248:     #
 2249:     # If there is more than one expired role, choose the one which ended last.
 2250:     # If there is a role which has expired, return it.
 2251:     #
 2252:     $courseid = &courseid_to_courseurl($courseid);
 2253:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 2254:     foreach my $key (keys(%roleshash)) {
 2255:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 2256:         my $section=$1;
 2257:         if ($key eq $courseid.'_st') { $section=''; }
 2258:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 2259:         my $now=time;
 2260:         if (defined($end) && $end && ($now > $end)) {
 2261:             $Expired{$end}=$section;
 2262:             next;
 2263:         }
 2264:         if (defined($start) && $start && ($now < $start)) {
 2265:             $Pending{$start}=$section;
 2266:             next;
 2267:         }
 2268:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 2269:     }
 2270:     #
 2271:     # Presumedly there will be few matching roles from the above
 2272:     # loop and the sorting time will be negligible.
 2273:     if (scalar(keys(%Pending))) {
 2274:         my ($time) = sort {$a <=> $b} keys(%Pending);
 2275:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 2276:     } 
 2277:     if (scalar(keys(%Expired))) {
 2278:         my @sorted = sort {$a <=> $b} keys(%Expired);
 2279:         my $time = pop(@sorted);
 2280:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 2281:     }
 2282:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 2283: }
 2284: 
 2285: sub save_cache {
 2286:     &purge_remembered();
 2287:     #&Apache::loncommon::validate_page();
 2288:     undef(%env);
 2289:     undef($env_loaded);
 2290: }
 2291: 
 2292: my $to_remember=-1;
 2293: my %remembered;
 2294: my %accessed;
 2295: my $kicks=0;
 2296: my $hits=0;
 2297: sub make_key {
 2298:     my ($name,$id) = @_;
 2299:     if (length($id) > 65 
 2300: 	&& length(&escape($id)) > 200) {
 2301: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 2302:     }
 2303:     return &escape($name.':'.$id);
 2304: }
 2305: 
 2306: sub devalidate_cache_new {
 2307:     my ($name,$id,$debug) = @_;
 2308:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 2309:     $id=&make_key($name,$id);
 2310:     $memcache->delete($id);
 2311:     delete($remembered{$id});
 2312:     delete($accessed{$id});
 2313: }
 2314: 
 2315: sub is_cached_new {
 2316:     my ($name,$id,$debug) = @_;
 2317:     $id=&make_key($name,$id);
 2318:     if (exists($remembered{$id})) {
 2319: 	if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
 2320: 	$accessed{$id}=[&gettimeofday()];
 2321: 	$hits++;
 2322: 	return ($remembered{$id},1);
 2323:     }
 2324:     my $value = $memcache->get($id);
 2325:     if (!(defined($value))) {
 2326: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 2327: 	return (undef,undef);
 2328:     }
 2329:     if ($value eq '__undef__') {
 2330: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 2331: 	$value=undef;
 2332:     }
 2333:     &make_room($id,$value,$debug);
 2334:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 2335:     return ($value,1);
 2336: }
 2337: 
 2338: sub do_cache_new {
 2339:     my ($name,$id,$value,$time,$debug) = @_;
 2340:     $id=&make_key($name,$id);
 2341:     my $setvalue=$value;
 2342:     if (!defined($setvalue)) {
 2343: 	$setvalue='__undef__';
 2344:     }
 2345:     if (!defined($time) ) {
 2346: 	$time=600;
 2347:     }
 2348:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 2349:     my $result = $memcache->set($id,$setvalue,$time);
 2350:     if (! $result) {
 2351: 	&logthis("caching of id -> $id  failed");
 2352: 	$memcache->disconnect_all();
 2353:     }
 2354:     # need to make a copy of $value
 2355:     &make_room($id,$value,$debug);
 2356:     return $value;
 2357: }
 2358: 
 2359: sub make_room {
 2360:     my ($id,$value,$debug)=@_;
 2361: 
 2362:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
 2363:                                     : $value;
 2364:     if ($to_remember<0) { return; }
 2365:     $accessed{$id}=[&gettimeofday()];
 2366:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 2367:     my $to_kick;
 2368:     my $max_time=0;
 2369:     foreach my $other (keys(%accessed)) {
 2370: 	if (&tv_interval($accessed{$other}) > $max_time) {
 2371: 	    $to_kick=$other;
 2372: 	    $max_time=&tv_interval($accessed{$other});
 2373: 	}
 2374:     }
 2375:     delete($remembered{$to_kick});
 2376:     delete($accessed{$to_kick});
 2377:     $kicks++;
 2378:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 2379:     return;
 2380: }
 2381: 
 2382: sub purge_remembered {
 2383:     #&logthis("Tossing ".scalar(keys(%remembered)));
 2384:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 2385:     undef(%remembered);
 2386:     undef(%accessed);
 2387: }
 2388: # ------------------------------------- Read an entry from a user's environment
 2389: 
 2390: sub userenvironment {
 2391:     my ($udom,$unam,@what)=@_;
 2392:     my $items;
 2393:     foreach my $item (@what) {
 2394:         $items.=&escape($item).'&';
 2395:     }
 2396:     $items=~s/\&$//;
 2397:     my %returnhash=();
 2398:     my $uhome = &homeserver($unam,$udom);
 2399:     unless ($uhome eq 'no_host') {
 2400:         my @answer=split(/\&/, 
 2401:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
 2402:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
 2403:             return %returnhash;
 2404:         }
 2405:         my $i;
 2406:         for ($i=0;$i<=$#what;$i++) {
 2407: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
 2408:         }
 2409:     }
 2410:     return %returnhash;
 2411: }
 2412: 
 2413: # ---------------------------------------------------------- Get a studentphoto
 2414: sub studentphoto {
 2415:     my ($udom,$unam,$ext) = @_;
 2416:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 2417:     if (defined($env{'request.course.id'})) {
 2418:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 2419:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 2420:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 2421:             } else {
 2422:                 my ($result,$perm_reqd)=
 2423: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 2424:                 if ($result eq 'ok') {
 2425:                     if (!($perm_reqd eq 'yes')) {
 2426:                         return(&retrievestudentphoto($udom,$unam,$ext));
 2427:                     }
 2428:                 }
 2429:             }
 2430:         }
 2431:     } else {
 2432:         my ($result,$perm_reqd) = 
 2433: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 2434:         if ($result eq 'ok') {
 2435:             if (!($perm_reqd eq 'yes')) {
 2436:                 return(&retrievestudentphoto($udom,$unam,$ext));
 2437:             }
 2438:         }
 2439:     }
 2440:     return '/adm/lonKaputt/lonlogo_broken.gif';
 2441: }
 2442: 
 2443: sub retrievestudentphoto {
 2444:     my ($udom,$unam,$ext,$type) = @_;
 2445:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 2446:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 2447:     if ($ret eq 'ok') {
 2448:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 2449:         if ($type eq 'thumbnail') {
 2450:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 2451:         }
 2452:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 2453:         return $tokenurl;
 2454:     } else {
 2455:         if ($type eq 'thumbnail') {
 2456:             return '/adm/lonKaputt/genericstudent_tn.gif';
 2457:         } else { 
 2458:             return '/adm/lonKaputt/lonlogo_broken.gif';
 2459:         }
 2460:     }
 2461: }
 2462: 
 2463: # -------------------------------------------------------------------- New chat
 2464: 
 2465: sub chatsend {
 2466:     my ($newentry,$anon,$group)=@_;
 2467:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 2468:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2469:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 2470:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 2471: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 2472: 		   &escape($newentry)).':'.$group,$chome);
 2473: }
 2474: 
 2475: # ------------------------------------------ Find current version of a resource
 2476: 
 2477: sub getversion {
 2478:     my $fname=&clutter(shift);
 2479:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
 2480:     return &currentversion(&filelocation('',$fname));
 2481: }
 2482: 
 2483: sub currentversion {
 2484:     my $fname=shift;
 2485:     my $author=$fname;
 2486:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2487:     my ($udom,$uname)=split(/\//,$author);
 2488:     my $home=&homeserver($uname,$udom);
 2489:     if ($home eq 'no_host') { 
 2490:         return -1; 
 2491:     }
 2492:     my $answer=&reply("currentversion:$fname",$home);
 2493:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 2494: 	return -1;
 2495:     }
 2496:     return $answer;
 2497: }
 2498: 
 2499: #
 2500: # Return special version number of resource if set by override, empty otherwise
 2501: #
 2502: sub usedversion {
 2503:     my $fname=shift;
 2504:     unless ($fname) { $fname=$env{'request.uri'}; }
 2505:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
 2506:     if ($urlversion) { return $urlversion; }
 2507:     return '';
 2508: }
 2509: 
 2510: # ----------------------------- Subscribe to a resource, return URL if possible
 2511: 
 2512: sub subscribe {
 2513:     my $fname=shift;
 2514:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 2515:     $fname=~s/[\n\r]//g;
 2516:     my $author=$fname;
 2517:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2518:     my ($udom,$uname)=split(/\//,$author);
 2519:     my $home=homeserver($uname,$udom);
 2520:     if ($home eq 'no_host') {
 2521:         return 'not_found';
 2522:     }
 2523:     my $answer=reply("sub:$fname",$home);
 2524:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 2525: 	$answer.=' by '.$home;
 2526:     }
 2527:     return $answer;
 2528: }
 2529:     
 2530: # -------------------------------------------------------------- Replicate file
 2531: 
 2532: sub repcopy {
 2533:     my $filename=shift;
 2534:     $filename=~s/\/+/\//g;
 2535:     my $londocroot = $perlvar{'lonDocRoot'};
 2536:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
 2537:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
 2538:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
 2539: 	$filename=~m{^/*(uploaded|editupload)/}) {
 2540: 	return &repcopy_userfile($filename);
 2541:     }
 2542:     $filename=~s/[\n\r]//g;
 2543:     my $transname="$filename.in.transfer";
 2544: # FIXME: this should flock
 2545:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 2546:     my $remoteurl=subscribe($filename);
 2547:     if ($remoteurl =~ /^con_lost by/) {
 2548: 	   &logthis("Subscribe returned $remoteurl: $filename");
 2549:            return 'unavailable';
 2550:     } elsif ($remoteurl eq 'not_found') {
 2551: 	   #&logthis("Subscribe returned not_found: $filename");
 2552: 	   return 'not_found';
 2553:     } elsif ($remoteurl =~ /^rejected by/) {
 2554: 	   &logthis("Subscribe returned $remoteurl: $filename");
 2555:            return 'forbidden';
 2556:     } elsif ($remoteurl eq 'directory') {
 2557:            return 'ok';
 2558:     } else {
 2559:         my $author=$filename;
 2560:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2561:         my ($udom,$uname)=split(/\//,$author);
 2562:         my $home=homeserver($uname,$udom);
 2563:         unless ($home eq $perlvar{'lonHostID'}) {
 2564:            my @parts=split(/\//,$filename);
 2565:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 2566:            if ($path ne "$londocroot/res") {
 2567:                &logthis("Malconfiguration for replication: $filename");
 2568: 	       return 'bad_request';
 2569:            }
 2570:            my $count;
 2571:            for ($count=5;$count<$#parts;$count++) {
 2572:                $path.="/$parts[$count]";
 2573:                if ((-e $path)!=1) {
 2574: 		   mkdir($path,0777);
 2575:                }
 2576:            }
 2577:            my $ua=new LWP::UserAgent;
 2578:            my $request=new HTTP::Request('GET',"$remoteurl");
 2579:            my $response=$ua->request($request,$transname);
 2580:            if ($response->is_error()) {
 2581: 	       unlink($transname);
 2582:                my $message=$response->status_line;
 2583:                &logthis("<font color=\"blue\">WARNING:"
 2584:                        ." LWP get: $message: $filename</font>");
 2585:                return 'unavailable';
 2586:            } else {
 2587: 	       if ($remoteurl!~/\.meta$/) {
 2588:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 2589:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
 2590:                   if ($mresponse->is_error()) {
 2591: 		      unlink($filename.'.meta');
 2592:                       &logthis(
 2593:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 2594:                   }
 2595: 	       }
 2596:                rename($transname,$filename);
 2597:                return 'ok';
 2598:            }
 2599:        }
 2600:     }
 2601: }
 2602: 
 2603: # ------------------------------------------------ Get server side include body
 2604: sub ssi_body {
 2605:     my ($filelink,%form)=@_;
 2606:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 2607:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 2608:     }
 2609:     my $output='';
 2610:     my $response;
 2611:     if ($filelink=~/^https?\:/) {
 2612:        ($output,$response)=&externalssi($filelink);
 2613:     } else {
 2614:        $filelink .= $filelink=~/\?/ ? '&' : '?';
 2615:        $filelink .= 'inhibitmenu=yes';
 2616:        ($output,$response)=&ssi($filelink,%form);
 2617:     }
 2618:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 2619:     $output=~s/^.*?\<body[^\>]*\>//si;
 2620:     $output=~s/\<\/body\s*\>.*?$//si;
 2621:     if (wantarray) {
 2622:         return ($output, $response);
 2623:     } else {
 2624:         return $output;
 2625:     }
 2626: }
 2627: 
 2628: # --------------------------------------------------------- Server Side Include
 2629: 
 2630: sub absolute_url {
 2631:     my ($host_name) = @_;
 2632:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 2633:     if ($host_name eq '') {
 2634: 	$host_name = $ENV{'SERVER_NAME'};
 2635:     }
 2636:     return $protocol.$host_name;
 2637: }
 2638: 
 2639: #
 2640: #   Server side include.
 2641: # Parameters:
 2642: #  fn     Possibly encrypted resource name/id.
 2643: #  form   Hash that describes how the rendering should be done
 2644: #         and other things.
 2645: # Returns:
 2646: #   Scalar context: The content of the response.
 2647: #   Array context:  2 element list of the content and the full response object.
 2648: #     
 2649: sub ssi {
 2650: 
 2651:     my ($fn,%form)=@_;
 2652:     my $ua=new LWP::UserAgent;
 2653:     my $request;
 2654: 
 2655:     $form{'no_update_last_known'}=1;
 2656:     &Apache::lonenc::check_encrypt(\$fn);
 2657:     if (%form) {
 2658:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 2659:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
 2660:     } else {
 2661:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 2662:     }
 2663: 
 2664:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 2665:     my $response= $ua->request($request);
 2666:     my $content = $response->content;
 2667: 
 2668: 
 2669:     if (wantarray) {
 2670: 	return ($content, $response);
 2671:     } else {
 2672: 	return $content;
 2673:     }
 2674: }
 2675: 
 2676: sub externalssi {
 2677:     my ($url)=@_;
 2678:     my $ua=new LWP::UserAgent;
 2679:     my $request=new HTTP::Request('GET',$url);
 2680:     my $response=$ua->request($request);
 2681:     if (wantarray) {
 2682:         return ($response->content, $response);
 2683:     } else {
 2684:         return $response->content;
 2685:     }
 2686: }
 2687: 
 2688: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 2689: 
 2690: sub allowuploaded {
 2691:     my ($srcurl,$url)=@_;
 2692:     $url=&clutter(&declutter($url));
 2693:     my $dir=$url;
 2694:     $dir=~s/\/[^\/]+$//;
 2695:     my %httpref=();
 2696:     my $httpurl=&hreflocation('',$url);
 2697:     $httpref{'httpref.'.$httpurl}=$srcurl;
 2698:     &Apache::lonnet::appenv(\%httpref);
 2699: }
 2700: 
 2701: #
 2702: # Determine if the current user should be able to edit a particular resource,
 2703: # when viewing in course context.
 2704: # (a) When viewing resource used to determine if "Edit" item is included in 
 2705: #     Functions.
 2706: # (b) When displaying folder contents in course editor, used to determine if
 2707: #     "Edit" link will be displayed alongside resource.
 2708: #
 2709: #  input: six args -- filename (decluttered), course number, course domain,
 2710: #                   url, symb (if registered) and group (if this is a group
 2711: #                   item -- e.g., bulletin board, group page etc.).
 2712: #  output: array of five scalars -- 
 2713: #          $cfile -- url for file editing if editable on current server
 2714: #          $home -- homeserver of resource (i.e., for author if published,
 2715: #                                           or course if uploaded.).
 2716: #          $switchserver --  1 if server switch will be needed.
 2717: #          $forceedit -- 1 if icon/link should be to go to edit mode 
 2718: #          $forceview -- 1 if icon/link should be to go to view mode
 2719: #
 2720: 
 2721: sub can_edit_resource {
 2722:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
 2723:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
 2724: #
 2725: # For aboutme pages user can only edit his/her own.
 2726: #
 2727:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
 2728:         my ($sdom,$sname) = ($1,$2);
 2729:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
 2730:             $home = $env{'user.home'};
 2731:             $cfile = $resurl;
 2732:             if ($env{'form.forceedit'}) {
 2733:                 $forceview = 1;
 2734:             } else {
 2735:                 $forceedit = 1;
 2736:             }
 2737:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
 2738:         } else {
 2739:             return;
 2740:         }
 2741:     }
 2742: 
 2743:     if ($env{'request.course.id'}) {
 2744:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
 2745:         if ($group ne '') {
 2746: # if this is a group homepage or group bulletin board, check group privs
 2747:             my $allowed = 0;
 2748:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
 2749:                 if ((&allowed('mdg',$env{'request.course.id'}.
 2750:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 2751:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 2752:                     $allowed = 1;
 2753:                 }
 2754:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
 2755:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 2756:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 2757:                     $allowed = 1;
 2758:                 }
 2759:             }
 2760:             if ($allowed) {
 2761:                 $home=&homeserver($cnum,$cdom);
 2762:                 if ($env{'form.forceedit'}) {
 2763:                     $forceview = 1;
 2764:                 } else {
 2765:                     $forceedit = 1;
 2766:                 }
 2767:                 $cfile = $resurl;
 2768:             } else {
 2769:                 return;
 2770:             }
 2771:         } else {
 2772:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
 2773:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
 2774:                     return;
 2775:                 }
 2776:             } elsif (!$crsedit) {
 2777: #
 2778: # No edit allowed where CC has switched to student role.
 2779: #
 2780:                 return;
 2781:             }
 2782:         }
 2783:     }
 2784: 
 2785:     if ($file ne '') {
 2786:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
 2787:             if (&is_course_upload($file,$cnum,$cdom)) {
 2788:                 $uploaded = 1;
 2789:                 $incourse = 1;
 2790:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
 2791:                     $cfile = &hreflocation('',$file);
 2792:                     if ($env{'form.forceedit'}) {
 2793:                         $forceview = 1;
 2794:                     } else {
 2795:                         $forceedit = 1;
 2796:                     }
 2797:                 }
 2798:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
 2799:                 $incourse = 1;
 2800:                 if ($env{'form.forceedit'}) {
 2801:                     $forceview = 1;
 2802:                 } else {
 2803:                     $forceedit = 1;
 2804:                 }
 2805:                 $cfile = $resurl;
 2806:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
 2807:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
 2808:                     $incourse = 1;
 2809:                     if ($env{'form.forceedit'}) {
 2810:                         $forceview = 1;
 2811:                     } else {
 2812:                         $forceedit = 1;
 2813:                     }
 2814:                     $cfile = $resurl;
 2815:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
 2816:                     $incourse = 1;
 2817:                     $cfile = $resurl.'/smpedit';
 2818:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
 2819:                     $incourse = 1;
 2820:                     if ($env{'form.forceedit'}) {
 2821:                         $forceview = 1;
 2822:                     } else {
 2823:                         $forceedit = 1;
 2824:                     }
 2825:                     $cfile = $resurl;
 2826:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 2827:                     $incourse = 1;
 2828:                     if ($env{'form.forceedit'}) {
 2829:                         $forceview = 1;
 2830:                     } else {
 2831:                         $forceedit = 1;
 2832:                     }
 2833:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 2834:                 }
 2835:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
 2836:                 my $template = '/res/lib/templates/simpleproblem.problem';
 2837:                 if (&is_on_map($template)) { 
 2838:                     $incourse = 1;
 2839:                     $forceview = 1;
 2840:                     $cfile = $template;
 2841:                 }
 2842:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 2843:                     $incourse = 1;
 2844:                     if ($env{'form.forceedit'}) {
 2845:                         $forceview = 1;
 2846:                     } else {
 2847:                         $forceedit = 1;
 2848:                     }
 2849:                     $cfile = $resurl;
 2850:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
 2851:                 $incourse = 1;
 2852:                 $forceview = 1;
 2853:                 if ($symb) {
 2854:                     my ($map,$id,$res)=&decode_symb($symb);
 2855:                     $env{'request.symb'} = $symb;
 2856:                     $cfile = &clutter($res);
 2857:                 } else {
 2858:                     $cfile = $env{'form.suppurl'};
 2859:                     $cfile =~ s{^http://}{};
 2860:                     $cfile = '/adm/wrapper/ext/'.$cfile;
 2861:                 }
 2862:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 2863:                 if ($env{'form.forceedit'}) {
 2864:                     $forceview = 1;
 2865:                 } else {
 2866:                     $forceedit = 1;
 2867:                 }
 2868:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 2869:             }
 2870:         }
 2871:         if ($uploaded || $incourse) {
 2872:             $home=&homeserver($cnum,$cdom);
 2873:         } elsif ($file !~ m{/$}) {
 2874:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
 2875:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
 2876:             # Check that the user has permission to edit this resource
 2877:             my $setpriv = 1;
 2878:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
 2879:             if (defined($cfudom)) {
 2880:                 $home=&homeserver($cfuname,$cfudom);
 2881:                 $cfile=$file;
 2882:             }
 2883:         }
 2884:         if (($cfile ne '') && (!$incourse || $uploaded) && 
 2885:             (($home ne '') && ($home ne 'no_host'))) {
 2886:             my @ids=&current_machine_ids();
 2887:             unless (grep(/^\Q$home\E$/,@ids)) {
 2888:                 $switchserver=1;
 2889:             }
 2890:         }
 2891:     }
 2892:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
 2893: }
 2894: 
 2895: sub is_course_upload {
 2896:     my ($file,$cnum,$cdom) = @_;
 2897:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
 2898:     $uploadpath =~ s{^\/}{};
 2899:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
 2900:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
 2901:         return 1;
 2902:     }
 2903:     return;
 2904: }
 2905: 
 2906: sub in_course {
 2907:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
 2908:     if ($hideprivileged) {
 2909:         my $skipuser;
 2910:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
 2911:         my @possdoms = ($cdom);  
 2912:         if ($coursehash{'checkforpriv'}) { 
 2913:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
 2914:         }
 2915:         if (&privileged($uname,$udom,\@possdoms)) {
 2916:             $skipuser = 1;
 2917:             if ($coursehash{'nothideprivileged'}) {
 2918:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 2919:                     my $user;
 2920:                     if ($item =~ /:/) {
 2921:                         $user = $item;
 2922:                     } else {
 2923:                         $user = join(':',split(/[\@]/,$item));
 2924:                     }
 2925:                     if ($user eq $uname.':'.$udom) {
 2926:                         undef($skipuser);
 2927:                         last;
 2928:                     }
 2929:                 }
 2930:             }
 2931:             if ($skipuser) {
 2932:                 return 0;
 2933:             }
 2934:         }
 2935:     }
 2936:     $type ||= 'any';
 2937:     if (!defined($cdom) || !defined($cnum)) {
 2938:         my $cid  = $env{'request.course.id'};
 2939:         $cdom = $env{'course.'.$cid.'.domain'};
 2940:         $cnum = $env{'course.'.$cid.'.num'};
 2941:     }
 2942:     my $typesref;
 2943:     if (($type eq 'any') || ($type eq 'all')) {
 2944:         $typesref = ['active','previous','future'];
 2945:     } elsif ($type eq 'previous' || $type eq 'future') {
 2946:         $typesref = [$type];
 2947:     }
 2948:     my %roles = &get_my_roles($uname,$udom,'userroles',
 2949:                               $typesref,undef,[$cdom]);
 2950:     my ($tmp) = keys(%roles);
 2951:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
 2952:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
 2953:     if (@course_roles > 0) {
 2954:         return 1;
 2955:     }
 2956:     return 0;
 2957: }
 2958: 
 2959: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 2960: # input: action, courseID, current domain, intended
 2961: #        path to file, source of file, instruction to parse file for objects,
 2962: #        ref to hash for embedded objects,
 2963: #        ref to hash for codebase of java objects.
 2964: #        reference to scalar to accommodate mime type determined
 2965: #          from File::MMagic if $parser = parse.
 2966: #
 2967: # output: url to file (if action was uploaddoc), 
 2968: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 2969: #
 2970: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 2971: # course.
 2972: #
 2973: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2974: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 2975: #          course's home server.
 2976: #
 2977: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 2978: #          be copied from $source (current location) to 
 2979: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2980: #         and will then be copied to
 2981: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 2982: #         course's home server.
 2983: #
 2984: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2985: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 2986: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2987: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 2988: #         in course's home server.
 2989: #
 2990: 
 2991: sub process_coursefile {
 2992:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
 2993:         $mimetype)=@_;
 2994:     my $fetchresult;
 2995:     my $home=&homeserver($docuname,$docudom);
 2996:     if ($action eq 'propagate') {
 2997:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2998: 			     $home);
 2999:     } else {
 3000:         my $fpath = '';
 3001:         my $fname = $file;
 3002:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3003:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3004:         my $filepath = &build_filepath($fpath);
 3005:         if ($action eq 'copy') {
 3006:             if ($source eq '') {
 3007:                 $fetchresult = 'no source file';
 3008:                 return $fetchresult;
 3009:             } else {
 3010:                 my $destination = $filepath.'/'.$fname;
 3011:                 rename($source,$destination);
 3012:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3013:                                  $home);
 3014:             }
 3015:         } elsif ($action eq 'uploaddoc') {
 3016:             open(my $fh,'>'.$filepath.'/'.$fname);
 3017:             print $fh $env{'form.'.$source};
 3018:             close($fh);
 3019:             if ($parser eq 'parse') {
 3020:                 my $mm = new File::MMagic;
 3021:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
 3022:                 if ($type eq 'text/html') {
 3023:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 3024:                     unless ($parse_result eq 'ok') {
 3025:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 3026:                     }
 3027:                 }
 3028:                 if (ref($mimetype)) {
 3029:                     $$mimetype = $type;
 3030:                 } 
 3031:             }
 3032:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3033:                                  $home);
 3034:             if ($fetchresult eq 'ok') {
 3035:                 return '/uploaded/'.$fpath.'/'.$fname;
 3036:             } else {
 3037:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3038:                         ' to host '.$home.': '.$fetchresult);
 3039:                 return '/adm/notfound.html';
 3040:             }
 3041:         }
 3042:     }
 3043:     unless ( $fetchresult eq 'ok') {
 3044:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3045:              ' to host '.$home.': '.$fetchresult);
 3046:     }
 3047:     return $fetchresult;
 3048: }
 3049: 
 3050: sub build_filepath {
 3051:     my ($fpath) = @_;
 3052:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 3053:     unless ($fpath eq '') {
 3054:         my @parts=split('/',$fpath);
 3055:         foreach my $part (@parts) {
 3056:             $filepath.= '/'.$part;
 3057:             if ((-e $filepath)!=1) {
 3058:                 mkdir($filepath,0777);
 3059:             }
 3060:         }
 3061:     }
 3062:     return $filepath;
 3063: }
 3064: 
 3065: sub store_edited_file {
 3066:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 3067:     my $file = $primary_url;
 3068:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 3069:     my $fpath = '';
 3070:     my $fname = $file;
 3071:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3072:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3073:     my $filepath = &build_filepath($fpath);
 3074:     open(my $fh,'>'.$filepath.'/'.$fname);
 3075:     print $fh $content;
 3076:     close($fh);
 3077:     my $home=&homeserver($docuname,$docudom);
 3078:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3079: 			  $home);
 3080:     if ($$fetchresult eq 'ok') {
 3081:         return '/uploaded/'.$fpath.'/'.$fname;
 3082:     } else {
 3083:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3084: 		 ' to host '.$home.': '.$$fetchresult);
 3085:         return '/adm/notfound.html';
 3086:     }
 3087: }
 3088: 
 3089: sub clean_filename {
 3090:     my ($fname,$args)=@_;
 3091: # Replace Windows backslashes by forward slashes
 3092:     $fname=~s/\\/\//g;
 3093:     if (!$args->{'keep_path'}) {
 3094:         # Get rid of everything but the actual filename
 3095: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 3096:     }
 3097: # Replace spaces by underscores
 3098:     $fname=~s/\s+/\_/g;
 3099: # Replace all other weird characters by nothing
 3100:     $fname=~s{[^/\w\.\-]}{}g;
 3101: # Replace all .\d. sequences with _\d. so they no longer look like version
 3102: # numbers
 3103:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 3104:     return $fname;
 3105: }
 3106: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
 3107: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
 3108: # image with the same aspect ratio as the original, but with dimensions which do 
 3109: # not exceed $resizewidth and $resizeheight.
 3110:  
 3111: sub resizeImage {
 3112:     my ($img_path,$resizewidth,$resizeheight) = @_;
 3113:     my $ima = Image::Magick->new;
 3114:     my $resized;
 3115:     if (-e $img_path) {
 3116:         $ima->Read($img_path);
 3117:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
 3118:             my $width = $ima->Get('width');
 3119:             my $height = $ima->Get('height');
 3120:             if ($width > $resizewidth) {
 3121: 	        my $factor = $width/$resizewidth;
 3122:                 my $newheight = $height/$factor;
 3123:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
 3124:                 $resized = 1;
 3125:             }
 3126:         }
 3127:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
 3128:             my $width = $ima->Get('width');
 3129:             my $height = $ima->Get('height');
 3130:             if ($height > $resizeheight) {
 3131:                 my $factor = $height/$resizeheight;
 3132:                 my $newwidth = $width/$factor;
 3133:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
 3134:                 $resized = 1;
 3135:             }
 3136:         }
 3137:         if ($resized) {
 3138:             $ima->Write($img_path);
 3139:         }
 3140:     }
 3141:     return;
 3142: }
 3143: 
 3144: # --------------- Take an uploaded file and put it into the userfiles directory
 3145: # input: $formname - the contents of the file are in $env{"form.$formname"}
 3146: #                    the desired filename is in $env{"form.$formname.filename"}
 3147: #        $context - possible values: coursedoc, existingfile, overwrite, 
 3148: #                                    canceloverwrite, or ''. 
 3149: #                   if 'coursedoc': upload to the current course
 3150: #                   if 'existingfile': write file to tmp/overwrites directory 
 3151: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
 3152: #                   $context is passed as argument to &finishuserfileupload
 3153: #        $subdir - directory in userfile to store the file into
 3154: #        $parser - instruction to parse file for objects ($parser = parse)    
 3155: #        $allfiles - reference to hash for embedded objects
 3156: #        $codebase - reference to hash for codebase of java objects
 3157: #        $desuname - username for permanent storage of uploaded file
 3158: #        $dsetudom - domain for permanaent storage of uploaded file
 3159: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 3160: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 3161: #        $resizewidth - width (pixels) to which to resize uploaded image
 3162: #        $resizeheight - height (pixels) to which to resize uploaded image
 3163: #        $mimetype - reference to scalar to accommodate mime type determined
 3164: #                    from File::MMagic.
 3165: # 
 3166: # output: url of file in userspace, or error: <message> 
 3167: #             or /adm/notfound.html if failure to upload occurse
 3168: 
 3169: sub userfileupload {
 3170:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
 3171:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
 3172:     if (!defined($subdir)) { $subdir='unknown'; }
 3173:     my $fname=$env{'form.'.$formname.'.filename'};
 3174:     $fname=&clean_filename($fname);
 3175:     # See if there is anything left
 3176:     unless ($fname) { return 'error: no uploaded file'; }
 3177:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
 3178:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
 3179:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
 3180:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3181:         my $now = time;
 3182:         my $filepath;
 3183:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
 3184:              $filepath = 'tmp/helprequests/'.$now;
 3185:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
 3186:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 3187:                          '_'.$env{'user.domain'}.'/pending';
 3188:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3189:             my ($docuname,$docudom);
 3190:             if ($destudom) {
 3191:                 $docudom = $destudom;
 3192:             } else {
 3193:                 $docudom = $env{'user.domain'};
 3194:             }
 3195:             if ($destuname) {
 3196:                 $docuname = $destuname;
 3197:             } else {
 3198:                 $docuname = $env{'user.name'};
 3199:             }
 3200:             if (exists($env{'form.group'})) {
 3201:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3202:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3203:             }
 3204:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
 3205:             if ($context eq 'canceloverwrite') {
 3206:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
 3207:                 if (-e  $tempfile) {
 3208:                     my @info = stat($tempfile);
 3209:                     if ($info[9] eq $env{'form.timestamp'}) {
 3210:                         unlink($tempfile);
 3211:                     }
 3212:                 }
 3213:                 return;
 3214:             }
 3215:         }
 3216:         # Create the directory if not present
 3217:         my @parts=split(/\//,$filepath);
 3218:         my $fullpath = $perlvar{'lonDaemons'};
 3219:         for (my $i=0;$i<@parts;$i++) {
 3220:             $fullpath .= '/'.$parts[$i];
 3221:             if ((-e $fullpath)!=1) {
 3222:                 mkdir($fullpath,0777);
 3223:             }
 3224:         }
 3225:         open(my $fh,'>'.$fullpath.'/'.$fname);
 3226:         print $fh $env{'form.'.$formname};
 3227:         close($fh);
 3228:         if ($context eq 'existingfile') {
 3229:             my @info = stat($fullpath.'/'.$fname);
 3230:             return ($fullpath.'/'.$fname,$info[9]);
 3231:         } else {
 3232:             return $fullpath.'/'.$fname;
 3233:         }
 3234:     }
 3235:     if ($subdir eq 'scantron') {
 3236:         $fname = 'scantron_orig_'.$fname;
 3237:     } else {
 3238:         $fname="$subdir/$fname";
 3239:     }
 3240:     if ($context eq 'coursedoc') {
 3241: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3242: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3243:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 3244:             return &finishuserfileupload($docuname,$docudom,
 3245: 					 $formname,$fname,$parser,$allfiles,
 3246: 					 $codebase,$thumbwidth,$thumbheight,
 3247:                                          $resizewidth,$resizeheight,$context,$mimetype);
 3248:         } else {
 3249:             if ($env{'form.folder'}) {
 3250:                 $fname=$env{'form.folder'}.'/'.$fname;
 3251:             }
 3252:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 3253: 				       $fname,$formname,$parser,
 3254: 				       $allfiles,$codebase,$mimetype);
 3255:         }
 3256:     } elsif (defined($destuname)) {
 3257:         my $docuname=$destuname;
 3258:         my $docudom=$destudom;
 3259: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 3260: 				     $parser,$allfiles,$codebase,
 3261:                                      $thumbwidth,$thumbheight,
 3262:                                      $resizewidth,$resizeheight,$context,$mimetype);
 3263:     } else {
 3264:         my $docuname=$env{'user.name'};
 3265:         my $docudom=$env{'user.domain'};
 3266:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
 3267:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3268:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3269:         }
 3270: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 3271: 				     $parser,$allfiles,$codebase,
 3272:                                      $thumbwidth,$thumbheight,
 3273:                                      $resizewidth,$resizeheight,$context,$mimetype);
 3274:     }
 3275: }
 3276: 
 3277: sub finishuserfileupload {
 3278:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 3279:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
 3280:     my $path=$docudom.'/'.$docuname.'/';
 3281:     my $filepath=$perlvar{'lonDocRoot'};
 3282:   
 3283:     my ($fnamepath,$file,$fetchthumb);
 3284:     $file=$fname;
 3285:     if ($fname=~m|/|) {
 3286:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 3287: 	$path.=$fnamepath.'/';
 3288:     }
 3289:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 3290:     my $count;
 3291:     for ($count=4;$count<=$#parts;$count++) {
 3292:         $filepath.="/$parts[$count]";
 3293:         if ((-e $filepath)!=1) {
 3294: 	    mkdir($filepath,0777);
 3295:         }
 3296:     }
 3297: 
 3298: # Save the file
 3299:     {
 3300: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
 3301: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 3302: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 3303: 	    return '/adm/notfound.html';
 3304: 	}
 3305:         if ($context eq 'overwrite') {
 3306:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
 3307:             my $target = $filepath.'/'.$file;
 3308:             if (-e $source) {
 3309:                 my @info = stat($source);
 3310:                 if ($info[9] eq $env{'form.timestamp'}) {   
 3311:                     unless (&File::Copy::move($source,$target)) {
 3312:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
 3313:                         return "Moving from $source failed";
 3314:                     }
 3315:                 } else {
 3316:                     return "Temporary file: $source had unexpected date/time for last modification";
 3317:                 }
 3318:             } else {
 3319:                 return "Temporary file: $source missing";
 3320:             }
 3321:         } elsif (!print FH ($env{'form.'.$formname})) {
 3322: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 3323: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 3324: 	    return '/adm/notfound.html';
 3325: 	}
 3326: 	close(FH);
 3327:         if ($resizewidth && $resizeheight) {
 3328:             my $mm = new File::MMagic;
 3329:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
 3330:             if ($mime_type =~ m{^image/}) {
 3331: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
 3332:             }  
 3333: 	}
 3334:     }
 3335:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
 3336:         if (ref($mimetype)) {
 3337:             if ($$mimetype eq '') {
 3338:                 my $mm = new File::MMagic;
 3339:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
 3340:                 $$mimetype = $type;
 3341:             }
 3342:         }
 3343:     }
 3344:     if ($parser eq 'parse') {
 3345:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
 3346:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
 3347:                                                        $allfiles,$codebase);
 3348:             unless ($parse_result eq 'ok') {
 3349:                 &logthis('Failed to parse '.$filepath.$file.
 3350: 	   	         ' for embedded media: '.$parse_result); 
 3351:             }
 3352:         }
 3353:     }
 3354:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 3355:         my $input = $filepath.'/'.$file;
 3356:         my $output = $filepath.'/'.'tn-'.$file;
 3357:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 3358:         system("convert -sample $thumbsize $input $output");
 3359:         if (-e $filepath.'/'.'tn-'.$file) {
 3360:             $fetchthumb  = 1; 
 3361:         }
 3362:     }
 3363:  
 3364: # Notify homeserver to grep it
 3365: #
 3366:     my $docuhome=&homeserver($docuname,$docudom);	
 3367:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 3368:     if ($fetchresult eq 'ok') {
 3369:         if ($fetchthumb) {
 3370:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 3371:             if ($thumbresult ne 'ok') {
 3372:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 3373:                          $docuhome.': '.$thumbresult);
 3374:             }
 3375:         }
 3376: #
 3377: # Return the URL to it
 3378:         return '/uploaded/'.$path.$file;
 3379:     } else {
 3380:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 3381: 		 ': '.$fetchresult);
 3382:         return '/adm/notfound.html';
 3383:     }
 3384: }
 3385: 
 3386: sub extract_embedded_items {
 3387:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 3388:     my @state = ();
 3389:     my (%lastids,%related,%shockwave,%flashvars);
 3390:     my %javafiles = (
 3391:                       codebase => '',
 3392:                       code => '',
 3393:                       archive => ''
 3394:                     );
 3395:     my %mediafiles = (
 3396:                       src => '',
 3397:                       movie => '',
 3398:                      );
 3399:     my $p;
 3400:     if ($content) {
 3401:         $p = HTML::LCParser->new($content);
 3402:     } else {
 3403:         $p = HTML::LCParser->new($fullpath);
 3404:     }
 3405:     while (my $t=$p->get_token()) {
 3406: 	if ($t->[0] eq 'S') {
 3407: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 3408: 	    push(@state, $tagname);
 3409:             if (lc($tagname) eq 'allow') {
 3410:                 &add_filetype($allfiles,$attr->{'src'},'src');
 3411:             }
 3412: 	    if (lc($tagname) eq 'img') {
 3413: 		&add_filetype($allfiles,$attr->{'src'},'src');
 3414: 	    }
 3415: 	    if (lc($tagname) eq 'a') {
 3416:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
 3417:                     &add_filetype($allfiles,$attr->{'href'},'href');
 3418:                 }
 3419: 	    }
 3420:             if (lc($tagname) eq 'script') {
 3421:                 my $src;
 3422:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 3423:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 3424:                 } else {
 3425:                     if ($attr->{'src'} ne '') {
 3426:                         $src = $attr->{'src'};
 3427:                         &add_filetype($allfiles,$src,'src');
 3428:                     }
 3429:                 }
 3430:                 my $text = $p->get_trimmed_text();
 3431:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
 3432:                     my @swfargs = split(/,/,$1);
 3433:                     foreach my $item (@swfargs) {
 3434:                         $item =~ s/["']//g;
 3435:                         $item =~ s/^\s+//;
 3436:                         $item =~ s/\s+$//;
 3437:                     }
 3438:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
 3439:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
 3440:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
 3441:                         } else {
 3442:                             $related{$swfargs[0]} = [$swfargs[2]];
 3443:                         }
 3444:                     }
 3445:                 }
 3446:             }
 3447:             if (lc($tagname) eq 'link') {
 3448:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 3449:                     &add_filetype($allfiles,$attr->{'href'},'href');
 3450:                 }
 3451:             }
 3452: 	    if (lc($tagname) eq 'object' ||
 3453: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 3454: 		foreach my $item (keys(%javafiles)) {
 3455: 		    $javafiles{$item} = '';
 3456: 		}
 3457:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
 3458:                     $lastids{lc($tagname)} = $attr->{'id'};
 3459:                 }
 3460: 	    }
 3461: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 3462: 		my $name = lc($attr->{'name'});
 3463: 		foreach my $item (keys(%javafiles)) {
 3464: 		    if ($name eq $item) {
 3465: 			$javafiles{$item} = $attr->{'value'};
 3466: 			last;
 3467: 		    }
 3468: 		}
 3469:                 my $pathfrom;
 3470: 		foreach my $item (keys(%mediafiles)) {
 3471: 		    if ($name eq $item) {
 3472:                         $pathfrom = $attr->{'value'};
 3473:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
 3474: 			&add_filetype($allfiles,$pathfrom,$name);
 3475: 			last;
 3476: 		    }
 3477: 		}
 3478:                 if ($name eq 'flashvars') {
 3479:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
 3480:                 }
 3481:                 if ($pathfrom ne '') {
 3482:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
 3483:                                          $pathfrom);
 3484:                 }
 3485: 	    }
 3486: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 3487: 		foreach my $item (keys(%javafiles)) {
 3488: 		    if ($attr->{$item}) {
 3489: 			$javafiles{$item} = $attr->{$item};
 3490: 			last;
 3491: 		    }
 3492: 		}
 3493: 		foreach my $item (keys(%mediafiles)) {
 3494: 		    if ($attr->{$item}) {
 3495: 			&add_filetype($allfiles,$attr->{$item},$item);
 3496: 			last;
 3497: 		    }
 3498: 		}
 3499:                 if (lc($tagname) eq 'embed') {
 3500:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
 3501:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
 3502:                                              $attr->{'src'});
 3503:                     }
 3504:                 }
 3505: 	    }
 3506:             if (lc($tagname) eq 'iframe') {
 3507:                 my $src = $attr->{'src'} ;
 3508:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
 3509:                     &add_filetype($allfiles,$src,'src');
 3510:                 } elsif ($src =~ m{^/}) {
 3511:                     if ($env{'request.course.id'}) {
 3512:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3513:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3514:                         my $url = &hreflocation('',$fullpath);
 3515:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
 3516:                             my $relpath = $1;
 3517:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
 3518:                                 &add_filetype($allfiles,$1,'src');
 3519:                             }
 3520:                         }
 3521:                     }
 3522:                 }
 3523:             }
 3524:             if ($t->[4] =~ m{/>$}) {
 3525:                 pop(@state);
 3526:             }
 3527: 	} elsif ($t->[0] eq 'E') {
 3528: 	    my ($tagname) = ($t->[1]);
 3529: 	    if ($javafiles{'codebase'} ne '') {
 3530: 		$javafiles{'codebase'} .= '/';
 3531: 	    }  
 3532: 	    if (lc($tagname) eq 'applet' ||
 3533: 		lc($tagname) eq 'object' ||
 3534: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 3535: 		) {
 3536: 		foreach my $item (keys(%javafiles)) {
 3537: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 3538: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 3539: 			&add_filetype($allfiles,$file,$item);
 3540: 		    }
 3541: 		}
 3542: 	    } 
 3543: 	    pop @state;
 3544: 	}
 3545:     }
 3546:     foreach my $id (sort(keys(%flashvars))) {
 3547:         if ($shockwave{$id} ne '') {
 3548:             my @pairs = split(/\&/,$flashvars{$id});
 3549:             foreach my $pair (@pairs) {
 3550:                 my ($key,$value) = split(/\=/,$pair);
 3551:                 if ($key eq 'thumb') {
 3552:                     &add_filetype($allfiles,$value,$key);
 3553:                 } elsif ($key eq 'content') {
 3554:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
 3555:                     my ($ext) = ($value =~ /\.([^.]+)$/);
 3556:                     if ($ext ne '') {
 3557:                         &add_filetype($allfiles,$path.$value,$ext);
 3558:                     }
 3559:                 }
 3560:             }
 3561:         }
 3562:     }
 3563:     return 'ok';
 3564: }
 3565: 
 3566: sub add_filetype {
 3567:     my ($allfiles,$file,$type)=@_;
 3568:     if (exists($allfiles->{$file})) {
 3569: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 3570: 	    push(@{$allfiles->{$file}}, &escape($type));
 3571: 	}
 3572:     } else {
 3573: 	@{$allfiles->{$file}} = (&escape($type));
 3574:     }
 3575: }
 3576: 
 3577: sub embedded_dependency {
 3578:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
 3579:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
 3580:         if (($identifier ne '') &&
 3581:             (ref($related->{$identifier}) eq 'ARRAY') &&
 3582:             ($pathfrom ne '')) {
 3583:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
 3584:             foreach my $dep (@{$related->{$identifier}}) {
 3585:                 &add_filetype($allfiles,$path.$dep,'object');
 3586:             }
 3587:         }
 3588:     }
 3589:     return;
 3590: }
 3591: 
 3592: sub removeuploadedurl {
 3593:     my ($url)=@_;	
 3594:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 3595:     return &removeuserfile($uname,$udom,$fname);
 3596: }
 3597: 
 3598: sub removeuserfile {
 3599:     my ($docuname,$docudom,$fname)=@_;
 3600:     my $home=&homeserver($docuname,$docudom);    
 3601:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 3602:     if ($result eq 'ok') {	
 3603:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 3604:             my $metafile = $fname.'.meta';
 3605:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 3606: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 3607:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 3608:             my $sqlresult = 
 3609:                 &update_portfolio_table($docuname,$docudom,$file,
 3610:                                         'portfolio_metadata',$group,
 3611:                                         'delete');
 3612:         }
 3613:     }
 3614:     return $result;
 3615: }
 3616: 
 3617: sub mkdiruserfile {
 3618:     my ($docuname,$docudom,$dir)=@_;
 3619:     my $home=&homeserver($docuname,$docudom);
 3620:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 3621: }
 3622: 
 3623: sub renameuserfile {
 3624:     my ($docuname,$docudom,$old,$new)=@_;
 3625:     my $home=&homeserver($docuname,$docudom);
 3626:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 3627:                         &escape("$old").':'.&escape("$new"),$home);
 3628:     if ($result eq 'ok') {
 3629:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 3630:             my $oldmeta = $old.'.meta';
 3631:             my $newmeta = $new.'.meta';
 3632:             my $metaresult = 
 3633:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 3634: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 3635:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 3636:             my $sqlresult = 
 3637:                 &update_portfolio_table($docuname,$docudom,$file,
 3638:                                         'portfolio_metadata',$group,
 3639:                                         'delete');
 3640:         }
 3641:     }
 3642:     return $result;
 3643: }
 3644: 
 3645: # ------------------------------------------------------------------------- Log
 3646: 
 3647: sub log {
 3648:     my ($dom,$nam,$hom,$what)=@_;
 3649:     return critical("log:$dom:$nam:$what",$hom);
 3650: }
 3651: 
 3652: # ------------------------------------------------------------------ Course Log
 3653: #
 3654: # This routine flushes several buffers of non-mission-critical nature
 3655: #
 3656: 
 3657: sub flushcourselogs {
 3658:     &logthis('Flushing log buffers');
 3659: #
 3660: # course logs
 3661: # This is a log of all transactions in a course, which can be used
 3662: # for data mining purposes
 3663: #
 3664: # It also collects the courseid database, which lists last transaction
 3665: # times and course titles for all courseids
 3666: #
 3667:     my %courseidbuffer=();
 3668:     foreach my $crsid (keys(%courselogs)) {
 3669:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 3670: 		          &escape($courselogs{$crsid}),
 3671: 		          $coursehombuf{$crsid}) eq 'ok') {
 3672: 	    delete $courselogs{$crsid};
 3673:         } else {
 3674:             &logthis('Failed to flush log buffer for '.$crsid);
 3675:             if (length($courselogs{$crsid})>40000) {
 3676:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 3677:                         " exceeded maximum size, deleting.</font>");
 3678:                delete $courselogs{$crsid};
 3679:             }
 3680:         }
 3681:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 3682:             'description' => $coursedescrbuf{$crsid},
 3683:             'inst_code'    => $courseinstcodebuf{$crsid},
 3684:             'type'        => $coursetypebuf{$crsid},
 3685:             'owner'       => $courseownerbuf{$crsid},
 3686:         };
 3687:     }
 3688: #
 3689: # Write course id database (reverse lookup) to homeserver of courses 
 3690: # Is used in pickcourse
 3691: #
 3692:     foreach my $crs_home (keys(%courseidbuffer)) {
 3693:         my $response = &courseidput(&host_domain($crs_home),
 3694:                                     $courseidbuffer{$crs_home},
 3695:                                     $crs_home,'timeonly');
 3696:     }
 3697: #
 3698: # File accesses
 3699: # Writes to the dynamic metadata of resources to get hit counts, etc.
 3700: #
 3701:     foreach my $entry (keys(%accesshash)) {
 3702:         if ($entry =~ /___count$/) {
 3703:             my ($dom,$name);
 3704:             ($dom,$name,undef)=
 3705: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 3706:             if (! defined($dom) || $dom eq '' || 
 3707:                 ! defined($name) || $name eq '') {
 3708:                 my $cid = $env{'request.course.id'};
 3709:                 $dom  = $env{'request.'.$cid.'.domain'};
 3710:                 $name = $env{'request.'.$cid.'.num'};
 3711:             }
 3712:             my $value = $accesshash{$entry};
 3713:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 3714:             my %temphash=($url => $value);
 3715:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 3716:             if ($result eq 'ok') {
 3717:                 delete $accesshash{$entry};
 3718:             }
 3719:         } else {
 3720:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 3721:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
 3722:             my %temphash=($entry => $accesshash{$entry});
 3723:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 3724:                 delete $accesshash{$entry};
 3725:             }
 3726:         }
 3727:     }
 3728: #
 3729: # Roles
 3730: # Reverse lookup of user roles for course faculty/staff and co-authorship
 3731: #
 3732:     foreach my $entry (keys(%userrolehash)) {
 3733:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 3734: 	    split(/\:/,$entry);
 3735:         if (&Apache::lonnet::put('nohist_userroles',
 3736:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 3737:                 $rudom,$runame) eq 'ok') {
 3738: 	    delete $userrolehash{$entry};
 3739:         }
 3740:     }
 3741: #
 3742: # Reverse lookup of domain roles (dc, ad, li, sc, au)
 3743: #
 3744:     my %domrolebuffer = ();
 3745:     foreach my $entry (keys(%domainrolehash)) {
 3746:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 3747:         if ($domrolebuffer{$rudom}) {
 3748:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 3749:                       '='.&escape($domainrolehash{$entry});
 3750:         } else {
 3751:             $domrolebuffer{$rudom}.=&escape($entry).
 3752:                       '='.&escape($domainrolehash{$entry});
 3753:         }
 3754:         delete $domainrolehash{$entry};
 3755:     }
 3756:     foreach my $dom (keys(%domrolebuffer)) {
 3757: 	my %servers = &get_servers($dom,'library');
 3758: 	foreach my $tryserver (keys(%servers)) {
 3759: 	    unless (&reply('domroleput:'.$dom.':'.
 3760: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
 3761: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 3762: 	    }
 3763:         }
 3764:     }
 3765:     $dumpcount++;
 3766: }
 3767: 
 3768: sub courselog {
 3769:     my $what=shift;
 3770:     $what=time.':'.$what;
 3771:     unless ($env{'request.course.id'}) { return ''; }
 3772:     $coursedombuf{$env{'request.course.id'}}=
 3773:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 3774:     $coursenumbuf{$env{'request.course.id'}}=
 3775:        $env{'course.'.$env{'request.course.id'}.'.num'};
 3776:     $coursehombuf{$env{'request.course.id'}}=
 3777:        $env{'course.'.$env{'request.course.id'}.'.home'};
 3778:     $coursedescrbuf{$env{'request.course.id'}}=
 3779:        $env{'course.'.$env{'request.course.id'}.'.description'};
 3780:     $courseinstcodebuf{$env{'request.course.id'}}=
 3781:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 3782:     $courseownerbuf{$env{'request.course.id'}}=
 3783:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 3784:     $coursetypebuf{$env{'request.course.id'}}=
 3785:        $env{'course.'.$env{'request.course.id'}.'.type'};
 3786:     if (defined $courselogs{$env{'request.course.id'}}) {
 3787: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 3788:     } else {
 3789: 	$courselogs{$env{'request.course.id'}}.=$what;
 3790:     }
 3791:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 3792: 	&flushcourselogs();
 3793:     }
 3794: }
 3795: 
 3796: sub courseacclog {
 3797:     my $fnsymb=shift;
 3798:     unless ($env{'request.course.id'}) { return ''; }
 3799:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 3800:     if ($fnsymb=~/$LONCAPA::assess_re/) {
 3801:         $what.=':POST';
 3802:         # FIXME: Probably ought to escape things....
 3803: 	foreach my $key (keys(%env)) {
 3804:             if ($key=~/^form\.(.*)/) {
 3805:                 my $formitem = $1;
 3806:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 3807:                     $what.=':'.$formitem.'='.$env{$key};
 3808:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 3809:                     $what.=':'.$formitem.'='.$env{$key};
 3810:                 }
 3811:             }
 3812:         }
 3813:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 3814:         # FIXME: We should not be depending on a form parameter that someone
 3815:         # editing lonsearchcat.pm might change in the future.
 3816:         if ($env{'form.phase'} eq 'course_search') {
 3817:             $what.= ':POST';
 3818:             # FIXME: Probably ought to escape things....
 3819:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 3820:                                  'crsdiscuss') {
 3821:                 $what.=':'.$element.'='.$env{'form.'.$element};
 3822:             }
 3823:         }
 3824:     }
 3825:     &courselog($what);
 3826: }
 3827: 
 3828: sub countacc {
 3829:     my $url=&declutter(shift);
 3830:     return if (! defined($url) || $url eq '');
 3831:     unless ($env{'request.course.id'}) { return ''; }
 3832: #
 3833: # Mark that this url was used in this course
 3834: #
 3835:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 3836: #
 3837: # Increase the access count for this resource in this child process
 3838: #
 3839:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 3840:     $accesshash{$key}++;
 3841: }
 3842: 
 3843: sub linklog {
 3844:     my ($from,$to)=@_;
 3845:     $from=&declutter($from);
 3846:     $to=&declutter($to);
 3847:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 3848:     $accesshash{$to.'___'.$from.'___goto'}=1;
 3849: }
 3850: 
 3851: sub statslog {
 3852:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
 3853:     if ($users<2) { return; }
 3854:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
 3855:             'course'       => $env{'request.course.id'},
 3856:             'sections'     => '"all"',
 3857:             'num_students' => $users,
 3858:             'part'         => $part,
 3859:             'symb'         => $symb,
 3860:             'mean_tries'   => $av_attempts,
 3861:             'deg_of_diff'  => $degdiff});
 3862:     foreach my $key (keys(%dynstore)) {
 3863:         $accesshash{$key}=$dynstore{$key};
 3864:     }
 3865: }
 3866:   
 3867: sub userrolelog {
 3868:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 3869:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
 3870:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 3871:        $userrolehash
 3872:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 3873:                     =$tend.':'.$tstart;
 3874:     }
 3875:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
 3876:        $userrolehash
 3877:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 3878:                     =$tend.':'.$tstart;
 3879:     }
 3880:     if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
 3881:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 3882:        $domainrolehash
 3883:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 3884:                     = $tend.':'.$tstart;
 3885:     }
 3886: }
 3887: 
 3888: sub courserolelog {
 3889:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 3890:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 3891:         my $cdom = $1;
 3892:         my $cnum = $2;
 3893:         my $sec = $3;
 3894:         my $namespace = 'rolelog';
 3895:         my %storehash = (
 3896:                            role    => $trole,
 3897:                            start   => $tstart,
 3898:                            end     => $tend,
 3899:                            selfenroll => $selfenroll,
 3900:                            context    => $context,
 3901:                         );
 3902:         if ($trole eq 'gr') {
 3903:             $namespace = 'groupslog';
 3904:             $storehash{'group'} = $sec;
 3905:         } else {
 3906:             $storehash{'section'} = $sec;
 3907:         }
 3908:         &write_log('course',$namespace,\%storehash,$delflag,$username,
 3909:                    $domain,$cnum,$cdom);
 3910:         if (($trole ne 'st') || ($sec ne '')) {
 3911:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 3912:         }
 3913:     }
 3914:     return;
 3915: }
 3916: 
 3917: sub domainrolelog {
 3918:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 3919:     if ($area =~ m{^/($match_domain)/$}) {
 3920:         my $cdom = $1;
 3921:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
 3922:         my $namespace = 'rolelog';
 3923:         my %storehash = (
 3924:                            role    => $trole,
 3925:                            start   => $tstart,
 3926:                            end     => $tend,
 3927:                            context => $context,
 3928:                         );
 3929:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
 3930:                    $domain,$domconfiguser,$cdom);
 3931:     }
 3932:     return;
 3933: 
 3934: }
 3935: 
 3936: sub coauthorrolelog {
 3937:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 3938:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
 3939:         my $audom = $1;
 3940:         my $auname = $2;
 3941:         my $namespace = 'rolelog';
 3942:         my %storehash = (
 3943:                            role    => $trole,
 3944:                            start   => $tstart,
 3945:                            end     => $tend,
 3946:                            context => $context,
 3947:                         );
 3948:         &write_log('author',$namespace,\%storehash,$delflag,$username,
 3949:                    $domain,$auname,$audom);
 3950:     }
 3951:     return;
 3952: }
 3953: 
 3954: sub get_course_adv_roles {
 3955:     my ($cid,$codes) = @_;
 3956:     $cid=$env{'request.course.id'} unless (defined($cid));
 3957:     my %coursehash=&coursedescription($cid);
 3958:     my $crstype = &Apache::loncommon::course_type($cid);
 3959:     my %nothide=();
 3960:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3961:         if ($user !~ /:/) {
 3962: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 3963:         } else {
 3964:             $nothide{$user}=1;
 3965:         }
 3966:     }
 3967:     my @possdoms = ($coursehash{'domain'});
 3968:     if ($coursehash{'checkforpriv'}) {
 3969:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
 3970:     }
 3971:     my %returnhash=();
 3972:     my %dumphash=
 3973:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 3974:     my $now=time;
 3975:     my %privileged;
 3976:     foreach my $entry (keys(%dumphash)) {
 3977: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 3978:         if (($tstart) && ($tstart<0)) { next; }
 3979:         if (($tend) && ($tend<$now)) { next; }
 3980:         if (($tstart) && ($now<$tstart)) { next; }
 3981:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 3982: 	if ($username eq '' || $domain eq '') { next; }
 3983:         if ((&privileged($username,$domain,\@possdoms)) &&
 3984:             (!$nothide{$username.':'.$domain})) { next; }
 3985: 	if ($role eq 'cr') { next; }
 3986:         if ($codes) {
 3987:             if ($section) { $role .= ':'.$section; }
 3988:             if ($returnhash{$role}) {
 3989:                 $returnhash{$role}.=','.$username.':'.$domain;
 3990:             } else {
 3991:                 $returnhash{$role}=$username.':'.$domain;
 3992:             }
 3993:         } else {
 3994:             my $key=&plaintext($role,$crstype);
 3995:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 3996:             if ($returnhash{$key}) {
 3997: 	        $returnhash{$key}.=','.$username.':'.$domain;
 3998:             } else {
 3999:                 $returnhash{$key}=$username.':'.$domain;
 4000:             }
 4001:         }
 4002:     }
 4003:     return %returnhash;
 4004: }
 4005: 
 4006: sub get_my_roles {
 4007:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 4008:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 4009:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 4010:     my (%dumphash,%nothide);
 4011:     if ($context eq 'userroles') {
 4012:         %dumphash = &dump('roles',$udom,$uname);
 4013:     } else {
 4014:         %dumphash = &dump('nohist_userroles',$udom,$uname);
 4015:         if ($hidepriv) {
 4016:             my %coursehash=&coursedescription($udom.'_'.$uname);
 4017:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 4018:                 if ($user !~ /:/) {
 4019:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 4020:                 } else {
 4021:                     $nothide{$user} = 1;
 4022:                 }
 4023:             }
 4024:         }
 4025:     }
 4026:     my %returnhash=();
 4027:     my $now=time;
 4028:     my %privileged;
 4029:     foreach my $entry (keys(%dumphash)) {
 4030:         my ($role,$tend,$tstart);
 4031:         if ($context eq 'userroles') {
 4032:             next if ($entry =~ /^rolesdef/);
 4033: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 4034:         } else {
 4035:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 4036:         }
 4037:         if (($tstart) && ($tstart<0)) { next; }
 4038:         my $status = 'active';
 4039:         if (($tend) && ($tend<=$now)) {
 4040:             $status = 'previous';
 4041:         } 
 4042:         if (($tstart) && ($now<$tstart)) {
 4043:             $status = 'future';
 4044:         }
 4045:         if (ref($types) eq 'ARRAY') {
 4046:             if (!grep(/^\Q$status\E$/,@{$types})) {
 4047:                 next;
 4048:             } 
 4049:         } else {
 4050:             if ($status ne 'active') {
 4051:                 next;
 4052:             }
 4053:         }
 4054:         my ($rolecode,$username,$domain,$section,$area);
 4055:         if ($context eq 'userroles') {
 4056:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
 4057:             (undef,$domain,$username,$section) = split(/\//,$area);
 4058:         } else {
 4059:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 4060:         }
 4061:         if (ref($roledoms) eq 'ARRAY') {
 4062:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 4063:                 next;
 4064:             }
 4065:         }
 4066:         if (ref($roles) eq 'ARRAY') {
 4067:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 4068:                 if ($role =~ /^cr\//) {
 4069:                     if (!grep(/^cr$/,@{$roles})) {
 4070:                         next;
 4071:                     }
 4072:                 } elsif ($role =~ /^gr\//) {
 4073:                     if (!grep(/^gr$/,@{$roles})) {
 4074:                         next;
 4075:                     }
 4076:                 } else {
 4077:                     next;
 4078:                 }
 4079:             }
 4080:         }
 4081:         if ($hidepriv) {
 4082:             my @privroles = ('dc','su');
 4083:             if ($context eq 'userroles') {
 4084:                 next if (grep(/^\Q$role\E$/,@privroles));
 4085:             } else {
 4086:                 my $possdoms = [$domain];
 4087:                 if (ref($roledoms) eq 'ARRAY') {
 4088:                    push(@{$possdoms},@{$roledoms}); 
 4089:                 }
 4090:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
 4091:                     if (!$nothide{$username.':'.$domain}) {
 4092:                         next;
 4093:                     }
 4094:                 }
 4095:             }
 4096:         }
 4097:         if ($withsec) {
 4098:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 4099:                 $tstart.':'.$tend;
 4100:         } else {
 4101:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 4102:         }
 4103:     }
 4104:     return %returnhash;
 4105: }
 4106: 
 4107: # ----------------------------------------------------- Frontpage Announcements
 4108: #
 4109: #
 4110: 
 4111: sub postannounce {
 4112:     my ($server,$text)=@_;
 4113:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 4114:     unless ($text=~/\w/) { $text=''; }
 4115:     return &reply('setannounce:'.&escape($text),$server);
 4116: }
 4117: 
 4118: sub getannounce {
 4119: 
 4120:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 4121: 	my $announcement='';
 4122: 	while (my $line = <$fh>) { $announcement .= $line; }
 4123: 	close($fh);
 4124: 	if ($announcement=~/\w/) { 
 4125: 	    return 
 4126:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 4127:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 4128: 	} else {
 4129: 	    return '';
 4130: 	}
 4131:     } else {
 4132: 	return '';
 4133:     }
 4134: }
 4135: 
 4136: # ---------------------------------------------------------- Course ID routines
 4137: # Deal with domain's nohist_courseid.db files
 4138: #
 4139: 
 4140: sub courseidput {
 4141:     my ($domain,$storehash,$coursehome,$caller) = @_;
 4142:     return unless (ref($storehash) eq 'HASH');
 4143:     my $outcome;
 4144:     if ($caller eq 'timeonly') {
 4145:         my $cids = '';
 4146:         foreach my $item (keys(%$storehash)) {
 4147:             $cids.=&escape($item).'&';
 4148:         }
 4149:         $cids=~s/\&$//;
 4150:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 4151:                           $coursehome);       
 4152:     } else {
 4153:         my $items = '';
 4154:         foreach my $item (keys(%$storehash)) {
 4155:             $items.= &escape($item).'='.
 4156:                      &freeze_escape($$storehash{$item}).'&';
 4157:         }
 4158:         $items=~s/\&$//;
 4159:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 4160:                           $coursehome);
 4161:     }
 4162:     if ($outcome eq 'unknown_cmd') {
 4163:         my $what;
 4164:         foreach my $cid (keys(%$storehash)) {
 4165:             $what .= &escape($cid).'=';
 4166:             foreach my $item ('description','inst_code','owner','type') {
 4167:                 $what .= &escape($storehash->{$cid}{$item}).':';
 4168:             }
 4169:             $what =~ s/\:$/&/;
 4170:         }
 4171:         $what =~ s/\&$//;  
 4172:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 4173:     } else {
 4174:         return $outcome;
 4175:     }
 4176: }
 4177: 
 4178: sub courseiddump {
 4179:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 4180:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 4181:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
 4182:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
 4183:     my $as_hash = 1;
 4184:     my %returnhash;
 4185:     if (!$domfilter) { $domfilter=''; }
 4186:     my %libserv = &all_library();
 4187:     foreach my $tryserver (keys(%libserv)) {
 4188:         if ( (  $hostidflag == 1 
 4189: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 4190: 	     || (!defined($hostidflag)) ) {
 4191: 
 4192: 	    if (($domfilter eq '') ||
 4193: 		(&host_domain($tryserver) eq $domfilter)) {
 4194:                 my $rep;
 4195:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
 4196:                     $rep = LONCAPA::Lond::dump_course_id_handler(
 4197:                         join(":", (&host_domain($tryserver), $sincefilter, 
 4198:                                 &escape($descfilter), &escape($instcodefilter), 
 4199:                                 &escape($ownerfilter), &escape($coursefilter),
 4200:                                 &escape($typefilter), &escape($regexp_ok), 
 4201:                                 $as_hash, &escape($selfenrollonly), 
 4202:                                 &escape($catfilter), $showhidden, $caller, 
 4203:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
 4204:                                 &escape($createdbefore), &escape($createdafter), 
 4205:                                 &escape($creationcontext), $domcloner)));
 4206:                 } else {
 4207:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
 4208:                              $sincefilter.':'.&escape($descfilter).':'.
 4209:                              &escape($instcodefilter).':'.&escape($ownerfilter).
 4210:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
 4211:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
 4212:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
 4213:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
 4214:                              &escape($cc_clone).':'.$cloneonly.':'.
 4215:                              &escape($createdbefore).':'.&escape($createdafter).':'.
 4216:                              &escape($creationcontext).':'.$domcloner,
 4217:                              $tryserver);
 4218:                 }
 4219:                      
 4220:                 my @pairs=split(/\&/,$rep);
 4221:                 foreach my $item (@pairs) {
 4222:                     my ($key,$value)=split(/\=/,$item,2);
 4223:                     $key = &unescape($key);
 4224:                     next if ($key =~ /^error: 2 /);
 4225:                     my $result = &thaw_unescape($value);
 4226:                     if (ref($result) eq 'HASH') {
 4227:                         $returnhash{$key}=$result;
 4228:                     } else {
 4229:                         my @responses = split(/:/,$value);
 4230:                         my @items = ('description','inst_code','owner','type');
 4231:                         for (my $i=0; $i<@responses; $i++) {
 4232:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 4233:                         }
 4234:                     }
 4235:                 }
 4236:             }
 4237:         }
 4238:     }
 4239:     return %returnhash;
 4240: }
 4241: 
 4242: sub courselastaccess {
 4243:     my ($cdom,$cnum,$hostidref) = @_;
 4244:     my %returnhash;
 4245:     if ($cdom && $cnum) {
 4246:         my $chome = &homeserver($cnum,$cdom);
 4247:         if ($chome ne 'no_host') {
 4248:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
 4249:             &extract_lastaccess(\%returnhash,$rep);
 4250:         }
 4251:     } else {
 4252:         if (!$cdom) { $cdom=''; }
 4253:         my %libserv = &all_library();
 4254:         foreach my $tryserver (keys(%libserv)) {
 4255:             if (ref($hostidref) eq 'ARRAY') {
 4256:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
 4257:             } 
 4258:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
 4259:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
 4260:                 &extract_lastaccess(\%returnhash,$rep);
 4261:             }
 4262:         }
 4263:     }
 4264:     return %returnhash;
 4265: }
 4266: 
 4267: sub extract_lastaccess {
 4268:     my ($returnhash,$rep) = @_;
 4269:     if (ref($returnhash) eq 'HASH') {
 4270:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
 4271:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
 4272:                  $rep eq '') {
 4273:             my @pairs=split(/\&/,$rep);
 4274:             foreach my $item (@pairs) {
 4275:                 my ($key,$value)=split(/\=/,$item,2);
 4276:                 $key = &unescape($key);
 4277:                 next if ($key =~ /^error: 2 /);
 4278:                 $returnhash->{$key} = &thaw_unescape($value);
 4279:             }
 4280:         }
 4281:     }
 4282:     return;
 4283: }
 4284: 
 4285: # ---------------------------------------------------------- DC e-mail
 4286: 
 4287: sub dcmailput {
 4288:     my ($domain,$msgid,$message,$server)=@_;
 4289:     my $status = &Apache::lonnet::critical(
 4290:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 4291:        &escape($message),$server);
 4292:     return $status;
 4293: }
 4294: 
 4295: sub dcmaildump {
 4296:     my ($dom,$startdate,$enddate,$senders) = @_;
 4297:     my %returnhash=();
 4298: 
 4299:     if (defined(&domain($dom,'primary'))) {
 4300:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 4301:                                                          &escape($enddate).':';
 4302: 	my @esc_senders=map { &escape($_)} @$senders;
 4303: 	$cmd.=&escape(join('&',@esc_senders));
 4304: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 4305:             my ($key,$value) = split(/\=/,$line,2);
 4306:             if (($key) && ($value)) {
 4307:                 $returnhash{&unescape($key)} = &unescape($value);
 4308:             }
 4309:         }
 4310:     }
 4311:     return %returnhash;
 4312: }
 4313: # ---------------------------------------------------------- Domain roles
 4314: 
 4315: sub get_domain_roles {
 4316:     my ($dom,$roles,$startdate,$enddate)=@_;
 4317:     if ((!defined($startdate)) || ($startdate eq '')) {
 4318:         $startdate = '.';
 4319:     }
 4320:     if ((!defined($enddate)) || ($enddate eq '')) {
 4321:         $enddate = '.';
 4322:     }
 4323:     my $rolelist;
 4324:     if (ref($roles) eq 'ARRAY') {
 4325:         $rolelist = join('&',@{$roles});
 4326:     }
 4327:     my %personnel = ();
 4328: 
 4329:     my %servers = &get_servers($dom,'library');
 4330:     foreach my $tryserver (keys(%servers)) {
 4331: 	%{$personnel{$tryserver}}=();
 4332: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 4333: 					    &escape($startdate).':'.
 4334: 					    &escape($enddate).':'.
 4335: 					    &escape($rolelist), $tryserver))) {
 4336: 	    my ($key,$value) = split(/\=/,$line,2);
 4337: 	    if (($key) && ($value)) {
 4338: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 4339: 	    }
 4340: 	}
 4341:     }
 4342:     return %personnel;
 4343: }
 4344: 
 4345: # ----------------------------------------------------------- Interval timing 
 4346: 
 4347: {
 4348: # Caches needed for speedup of navmaps
 4349: # We don't want to cache this for very long at all (5 seconds at most)
 4350: # 
 4351: # The user for whom we cache
 4352: my $cachedkey='';
 4353: # The cached times for this user
 4354: my %cachedtimes=();
 4355: # When this was last done
 4356: my $cachedtime=();
 4357: 
 4358: sub load_all_first_access {
 4359:     my ($uname,$udom)=@_;
 4360:     if (($cachedkey eq $uname.':'.$udom) &&
 4361:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
 4362:         return;
 4363:     }
 4364:     $cachedtime=time;
 4365:     $cachedkey=$uname.':'.$udom;
 4366:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
 4367: }
 4368: 
 4369: sub get_first_access {
 4370:     my ($type,$argsymb,$argmap)=@_;
 4371:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 4372:     if ($argsymb) { $symb=$argsymb; }
 4373:     my ($map,$id,$res)=&decode_symb($symb);
 4374:     if ($argmap) { $map = $argmap; }
 4375:     if ($type eq 'course') {
 4376: 	$res='course';
 4377:     } elsif ($type eq 'map') {
 4378: 	$res=&symbread($map);
 4379:     } else {
 4380: 	$res=$symb;
 4381:     }
 4382:     &load_all_first_access($uname,$udom);
 4383:     return $cachedtimes{"$courseid\0$res"};
 4384: }
 4385: 
 4386: sub set_first_access {
 4387:     my ($type,$interval)=@_;
 4388:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 4389:     my ($map,$id,$res)=&decode_symb($symb);
 4390:     if ($type eq 'course') {
 4391: 	$res='course';
 4392:     } elsif ($type eq 'map') {
 4393: 	$res=&symbread($map);
 4394:     } else {
 4395: 	$res=$symb;
 4396:     }
 4397:     $cachedkey='';
 4398:     my $firstaccess=&get_first_access($type,$symb,$map);
 4399:     if (!$firstaccess) {
 4400:         my $start = time;
 4401: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
 4402:                           $udom,$uname);
 4403:         if ($putres eq 'ok') {
 4404:             &put('timerinterval',{"$courseid\0$res"=>$interval},
 4405:                  $udom,$uname); 
 4406:             &appenv(
 4407:                      {
 4408:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
 4409:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
 4410:                      }
 4411:                   );
 4412:         }
 4413:         return $putres;
 4414:     }
 4415:     return 'already_set';
 4416: }
 4417: }
 4418: # --------------------------------------------- Set Expire Date for Spreadsheet
 4419: 
 4420: sub expirespread {
 4421:     my ($uname,$udom,$stype,$usymb)=@_;
 4422:     my $cid=$env{'request.course.id'}; 
 4423:     if ($cid) {
 4424:        my $now=time;
 4425:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 4426:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 4427:                             $env{'course.'.$cid.'.num'}.
 4428: 	        	    ':nohist_expirationdates:'.
 4429:                             &escape($key).'='.$now,
 4430:                             $env{'course.'.$cid.'.home'})
 4431:     }
 4432:     return 'ok';
 4433: }
 4434: 
 4435: # ----------------------------------------------------- Devalidate Spreadsheets
 4436: 
 4437: sub devalidate {
 4438:     my ($symb,$uname,$udom)=@_;
 4439:     my $cid=$env{'request.course.id'}; 
 4440:     if ($cid) {
 4441:         # delete the stored spreadsheets for
 4442:         # - the student level sheet of this user in course's homespace
 4443:         # - the assessment level sheet for this resource 
 4444:         #   for this user in user's homespace
 4445: 	# - current conditional state info
 4446: 	my $key=$uname.':'.$udom.':';
 4447:         my $status=
 4448: 	    &del('nohist_calculatedsheets',
 4449: 		 [$key.'studentcalc:'],
 4450: 		 $env{'course.'.$cid.'.domain'},
 4451: 		 $env{'course.'.$cid.'.num'})
 4452: 		.' '.
 4453: 	    &del('nohist_calculatedsheets_'.$cid,
 4454: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 4455:         unless ($status eq 'ok ok') {
 4456:            &logthis('Could not devalidate spreadsheet '.
 4457:                     $uname.' at '.$udom.' for '.
 4458: 		    $symb.': '.$status);
 4459:         }
 4460: 	&delenv('user.state.'.$cid);
 4461:     }
 4462: }
 4463: 
 4464: sub get_scalar {
 4465:     my ($string,$end) = @_;
 4466:     my $value;
 4467:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 4468: 	$value = $1;
 4469:     } elsif ($$string =~ s/^([^&]*?)&//) {
 4470: 	$value = $1;
 4471:     }
 4472:     return &unescape($value);
 4473: }
 4474: 
 4475: sub array2str {
 4476:   my (@array) = @_;
 4477:   my $result=&arrayref2str(\@array);
 4478:   $result=~s/^__ARRAY_REF__//;
 4479:   $result=~s/__END_ARRAY_REF__$//;
 4480:   return $result;
 4481: }
 4482: 
 4483: sub arrayref2str {
 4484:   my ($arrayref) = @_;
 4485:   my $result='__ARRAY_REF__';
 4486:   foreach my $elem (@$arrayref) {
 4487:     if(ref($elem) eq 'ARRAY') {
 4488:       $result.=&arrayref2str($elem).'&';
 4489:     } elsif(ref($elem) eq 'HASH') {
 4490:       $result.=&hashref2str($elem).'&';
 4491:     } elsif(ref($elem)) {
 4492:       #print("Got a ref of ".(ref($elem))." skipping.");
 4493:     } else {
 4494:       $result.=&escape($elem).'&';
 4495:     }
 4496:   }
 4497:   $result=~s/\&$//;
 4498:   $result .= '__END_ARRAY_REF__';
 4499:   return $result;
 4500: }
 4501: 
 4502: sub hash2str {
 4503:   my (%hash) = @_;
 4504:   my $result=&hashref2str(\%hash);
 4505:   $result=~s/^__HASH_REF__//;
 4506:   $result=~s/__END_HASH_REF__$//;
 4507:   return $result;
 4508: }
 4509: 
 4510: sub hashref2str {
 4511:   my ($hashref)=@_;
 4512:   my $result='__HASH_REF__';
 4513:   foreach my $key (sort(keys(%$hashref))) {
 4514:     if (ref($key) eq 'ARRAY') {
 4515:       $result.=&arrayref2str($key).'=';
 4516:     } elsif (ref($key) eq 'HASH') {
 4517:       $result.=&hashref2str($key).'=';
 4518:     } elsif (ref($key)) {
 4519:       $result.='=';
 4520:       #print("Got a ref of ".(ref($key))." skipping.");
 4521:     } else {
 4522: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
 4523:     }
 4524: 
 4525:     if(ref($hashref->{$key}) eq 'ARRAY') {
 4526:       $result.=&arrayref2str($hashref->{$key}).'&';
 4527:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 4528:       $result.=&hashref2str($hashref->{$key}).'&';
 4529:     } elsif(ref($hashref->{$key})) {
 4530:        $result.='&';
 4531:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 4532:     } else {
 4533:       $result.=&escape($hashref->{$key}).'&';
 4534:     }
 4535:   }
 4536:   $result=~s/\&$//;
 4537:   $result .= '__END_HASH_REF__';
 4538:   return $result;
 4539: }
 4540: 
 4541: sub str2hash {
 4542:     my ($string)=@_;
 4543:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 4544:     return %$hash;
 4545: }
 4546: 
 4547: sub str2hashref {
 4548:   my ($string) = @_;
 4549: 
 4550:   my %hash;
 4551: 
 4552:   if($string !~ /^__HASH_REF__/) {
 4553:       if (! ($string eq '' || !defined($string))) {
 4554: 	  $hash{'error'}='Not hash reference';
 4555:       }
 4556:       return (\%hash, $string);
 4557:   }
 4558: 
 4559:   $string =~ s/^__HASH_REF__//;
 4560: 
 4561:   while($string !~ /^__END_HASH_REF__/) {
 4562:       #key
 4563:       my $key='';
 4564:       if($string =~ /^__HASH_REF__/) {
 4565:           ($key, $string)=&str2hashref($string);
 4566:           if(defined($key->{'error'})) {
 4567:               $hash{'error'}='Bad data';
 4568:               return (\%hash, $string);
 4569:           }
 4570:       } elsif($string =~ /^__ARRAY_REF__/) {
 4571:           ($key, $string)=&str2arrayref($string);
 4572:           if($key->[0] eq 'Array reference error') {
 4573:               $hash{'error'}='Bad data';
 4574:               return (\%hash, $string);
 4575:           }
 4576:       } else {
 4577:           $string =~ s/^(.*?)=//;
 4578: 	  $key=&unescape($1);
 4579:       }
 4580:       $string =~ s/^=//;
 4581: 
 4582:       #value
 4583:       my $value='';
 4584:       if($string =~ /^__HASH_REF__/) {
 4585:           ($value, $string)=&str2hashref($string);
 4586:           if(defined($value->{'error'})) {
 4587:               $hash{'error'}='Bad data';
 4588:               return (\%hash, $string);
 4589:           }
 4590:       } elsif($string =~ /^__ARRAY_REF__/) {
 4591:           ($value, $string)=&str2arrayref($string);
 4592:           if($value->[0] eq 'Array reference error') {
 4593:               $hash{'error'}='Bad data';
 4594:               return (\%hash, $string);
 4595:           }
 4596:       } else {
 4597: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 4598:       }
 4599:       $string =~ s/^&//;
 4600: 
 4601:       $hash{$key}=$value;
 4602:   }
 4603: 
 4604:   $string =~ s/^__END_HASH_REF__//;
 4605: 
 4606:   return (\%hash, $string);
 4607: }
 4608: 
 4609: sub str2array {
 4610:     my ($string)=@_;
 4611:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 4612:     return @$array;
 4613: }
 4614: 
 4615: sub str2arrayref {
 4616:   my ($string) = @_;
 4617:   my @array;
 4618: 
 4619:   if($string !~ /^__ARRAY_REF__/) {
 4620:       if (! ($string eq '' || !defined($string))) {
 4621: 	  $array[0]='Array reference error';
 4622:       }
 4623:       return (\@array, $string);
 4624:   }
 4625: 
 4626:   $string =~ s/^__ARRAY_REF__//;
 4627: 
 4628:   while($string !~ /^__END_ARRAY_REF__/) {
 4629:       my $value='';
 4630:       if($string =~ /^__HASH_REF__/) {
 4631:           ($value, $string)=&str2hashref($string);
 4632:           if(defined($value->{'error'})) {
 4633:               $array[0] ='Array reference error';
 4634:               return (\@array, $string);
 4635:           }
 4636:       } elsif($string =~ /^__ARRAY_REF__/) {
 4637:           ($value, $string)=&str2arrayref($string);
 4638:           if($value->[0] eq 'Array reference error') {
 4639:               $array[0] ='Array reference error';
 4640:               return (\@array, $string);
 4641:           }
 4642:       } else {
 4643: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 4644:       }
 4645:       $string =~ s/^&//;
 4646: 
 4647:       push(@array, $value);
 4648:   }
 4649: 
 4650:   $string =~ s/^__END_ARRAY_REF__//;
 4651: 
 4652:   return (\@array, $string);
 4653: }
 4654: 
 4655: # -------------------------------------------------------------------Temp Store
 4656: 
 4657: sub tmpreset {
 4658:   my ($symb,$namespace,$domain,$stuname) = @_;
 4659:   if (!$symb) {
 4660:     $symb=&symbread();
 4661:     if (!$symb) { $symb= $env{'request.url'}; }
 4662:   }
 4663:   $symb=escape($symb);
 4664: 
 4665:   if (!$namespace) { $namespace=$env{'request.state'}; }
 4666:   $namespace=~s/\//\_/g;
 4667:   $namespace=~s/\W//g;
 4668: 
 4669:   if (!$domain) { $domain=$env{'user.domain'}; }
 4670:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4671:   if ($domain eq 'public' && $stuname eq 'public') {
 4672:       $stuname=$ENV{'REMOTE_ADDR'};
 4673:   }
 4674:   my $path=LONCAPA::tempdir();
 4675:   my %hash;
 4676:   if (tie(%hash,'GDBM_File',
 4677: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4678: 	  &GDBM_WRCREAT(),0640)) {
 4679:     foreach my $key (keys(%hash)) {
 4680:       if ($key=~ /:$symb/) {
 4681: 	delete($hash{$key});
 4682:       }
 4683:     }
 4684:   }
 4685: }
 4686: 
 4687: sub tmpstore {
 4688:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4689: 
 4690:   if (!$symb) {
 4691:     $symb=&symbread();
 4692:     if (!$symb) { $symb= $env{'request.url'}; }
 4693:   }
 4694:   $symb=escape($symb);
 4695: 
 4696:   if (!$namespace) {
 4697:     # I don't think we would ever want to store this for a course.
 4698:     # it seems this will only be used if we don't have a course.
 4699:     #$namespace=$env{'request.course.id'};
 4700:     #if (!$namespace) {
 4701:       $namespace=$env{'request.state'};
 4702:     #}
 4703:   }
 4704:   $namespace=~s/\//\_/g;
 4705:   $namespace=~s/\W//g;
 4706:   if (!$domain) { $domain=$env{'user.domain'}; }
 4707:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4708:   if ($domain eq 'public' && $stuname eq 'public') {
 4709:       $stuname=$ENV{'REMOTE_ADDR'};
 4710:   }
 4711:   my $now=time;
 4712:   my %hash;
 4713:   my $path=LONCAPA::tempdir();
 4714:   if (tie(%hash,'GDBM_File',
 4715: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4716: 	  &GDBM_WRCREAT(),0640)) {
 4717:     $hash{"version:$symb"}++;
 4718:     my $version=$hash{"version:$symb"};
 4719:     my $allkeys=''; 
 4720:     foreach my $key (keys(%$storehash)) {
 4721:       $allkeys.=$key.':';
 4722:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 4723:     }
 4724:     $hash{"$version:$symb:timestamp"}=$now;
 4725:     $allkeys.='timestamp';
 4726:     $hash{"$version:keys:$symb"}=$allkeys;
 4727:     if (untie(%hash)) {
 4728:       return 'ok';
 4729:     } else {
 4730:       return "error:$!";
 4731:     }
 4732:   } else {
 4733:     return "error:$!";
 4734:   }
 4735: }
 4736: 
 4737: # -----------------------------------------------------------------Temp Restore
 4738: 
 4739: sub tmprestore {
 4740:   my ($symb,$namespace,$domain,$stuname) = @_;
 4741: 
 4742:   if (!$symb) {
 4743:     $symb=&symbread();
 4744:     if (!$symb) { $symb= $env{'request.url'}; }
 4745:   }
 4746:   $symb=escape($symb);
 4747: 
 4748:   if (!$namespace) { $namespace=$env{'request.state'}; }
 4749: 
 4750:   if (!$domain) { $domain=$env{'user.domain'}; }
 4751:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4752:   if ($domain eq 'public' && $stuname eq 'public') {
 4753:       $stuname=$ENV{'REMOTE_ADDR'};
 4754:   }
 4755:   my %returnhash;
 4756:   $namespace=~s/\//\_/g;
 4757:   $namespace=~s/\W//g;
 4758:   my %hash;
 4759:   my $path=LONCAPA::tempdir();
 4760:   if (tie(%hash,'GDBM_File',
 4761: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4762: 	  &GDBM_READER(),0640)) {
 4763:     my $version=$hash{"version:$symb"};
 4764:     $returnhash{'version'}=$version;
 4765:     my $scope;
 4766:     for ($scope=1;$scope<=$version;$scope++) {
 4767:       my $vkeys=$hash{"$scope:keys:$symb"};
 4768:       my @keys=split(/:/,$vkeys);
 4769:       my $key;
 4770:       $returnhash{"$scope:keys"}=$vkeys;
 4771:       foreach $key (@keys) {
 4772: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 4773: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 4774:       }
 4775:     }
 4776:     if (!(untie(%hash))) {
 4777:       return "error:$!";
 4778:     }
 4779:   } else {
 4780:     return "error:$!";
 4781:   }
 4782:   return %returnhash;
 4783: }
 4784: 
 4785: # ----------------------------------------------------------------------- Store
 4786: 
 4787: sub store {
 4788:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4789:     my $home='';
 4790: 
 4791:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4792: 
 4793:     $symb=&symbclean($symb);
 4794:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 4795: 
 4796:     if (!$domain) { $domain=$env{'user.domain'}; }
 4797:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4798: 
 4799:     &devalidate($symb,$stuname,$domain);
 4800: 
 4801:     $symb=escape($symb);
 4802:     if (!$namespace) { 
 4803:        unless ($namespace=$env{'request.course.id'}) { 
 4804:           return ''; 
 4805:        } 
 4806:     }
 4807:     if (!$home) { $home=$env{'user.home'}; }
 4808: 
 4809:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 4810:     $$storehash{'host'}=$perlvar{'lonHostID'};
 4811: 
 4812:     my $namevalue='';
 4813:     foreach my $key (keys(%$storehash)) {
 4814:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4815:     }
 4816:     $namevalue=~s/\&$//;
 4817:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 4818:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 4819: }
 4820: 
 4821: # -------------------------------------------------------------- Critical Store
 4822: 
 4823: sub cstore {
 4824:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4825:     my $home='';
 4826: 
 4827:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4828: 
 4829:     $symb=&symbclean($symb);
 4830:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 4831: 
 4832:     if (!$domain) { $domain=$env{'user.domain'}; }
 4833:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4834: 
 4835:     &devalidate($symb,$stuname,$domain);
 4836: 
 4837:     $symb=escape($symb);
 4838:     if (!$namespace) { 
 4839:        unless ($namespace=$env{'request.course.id'}) { 
 4840:           return ''; 
 4841:        } 
 4842:     }
 4843:     if (!$home) { $home=$env{'user.home'}; }
 4844: 
 4845:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 4846:     $$storehash{'host'}=$perlvar{'lonHostID'};
 4847: 
 4848:     my $namevalue='';
 4849:     foreach my $key (keys(%$storehash)) {
 4850:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4851:     }
 4852:     $namevalue=~s/\&$//;
 4853:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 4854:     return critical
 4855:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 4856: }
 4857: 
 4858: # --------------------------------------------------------------------- Restore
 4859: 
 4860: sub restore {
 4861:     my ($symb,$namespace,$domain,$stuname) = @_;
 4862:     my $home='';
 4863: 
 4864:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4865: 
 4866:     if (!$symb) {
 4867:         return if ($namespace eq 'courserequests');
 4868:         unless ($symb=escape(&symbread())) { return ''; }
 4869:     } else {
 4870:         unless ($namespace eq 'courserequests') {
 4871:             $symb=&escape(&symbclean($symb));
 4872:         }
 4873:     }
 4874:     if (!$namespace) { 
 4875:        unless ($namespace=$env{'request.course.id'}) { 
 4876:           return ''; 
 4877:        } 
 4878:     }
 4879:     if (!$domain) { $domain=$env{'user.domain'}; }
 4880:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4881:     if (!$home) { $home=$env{'user.home'}; }
 4882:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 4883: 
 4884:     my %returnhash=();
 4885:     foreach my $line (split(/\&/,$answer)) {
 4886: 	my ($name,$value)=split(/\=/,$line);
 4887:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 4888:     }
 4889:     my $version;
 4890:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 4891:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 4892:           $returnhash{$item}=$returnhash{$version.':'.$item};
 4893:        }
 4894:     }
 4895:     return %returnhash;
 4896: }
 4897: 
 4898: # ---------------------------------------------------------- Course Description
 4899: #
 4900: #  
 4901: 
 4902: sub coursedescription {
 4903:     my ($courseid,$args)=@_;
 4904:     $courseid=~s/^\///;
 4905:     $courseid=~s/\_/\//g;
 4906:     my ($cdomain,$cnum)=split(/\//,$courseid);
 4907:     my $chome=&homeserver($cnum,$cdomain);
 4908:     my $normalid=$cdomain.'_'.$cnum;
 4909:     # need to always cache even if we get errors otherwise we keep 
 4910:     # trying and trying and trying to get the course description.
 4911:     my %envhash=();
 4912:     my %returnhash=();
 4913:     
 4914:     my $expiretime=600;
 4915:     if ($env{'request.course.id'} eq $normalid) {
 4916: 	$expiretime=120;
 4917:     }
 4918: 
 4919:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 4920:     if (!$args->{'freshen_cache'}
 4921: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 4922: 	foreach my $key (keys(%env)) {
 4923: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 4924: 	    my ($setting) = $1;
 4925: 	    $returnhash{$setting} = $env{$key};
 4926: 	}
 4927: 	return %returnhash;
 4928:     }
 4929: 
 4930:     # get the data again
 4931: 
 4932:     if (!$args->{'one_time'}) {
 4933: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 4934:     }
 4935: 
 4936:     if ($chome ne 'no_host') {
 4937:        %returnhash=&dump('environment',$cdomain,$cnum);
 4938:        if (!exists($returnhash{'con_lost'})) {
 4939: 	   my $username = $env{'user.name'}; # Defult username
 4940: 	   if(defined $args->{'user'}) {
 4941: 	       $username = $args->{'user'};
 4942: 	   }
 4943:            $returnhash{'home'}= $chome;
 4944: 	   $returnhash{'domain'} = $cdomain;
 4945: 	   $returnhash{'num'} = $cnum;
 4946:            if (!defined($returnhash{'type'})) {
 4947:                $returnhash{'type'} = 'Course';
 4948:            }
 4949:            while (my ($name,$value) = each %returnhash) {
 4950:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 4951:            }
 4952:            $returnhash{'url'}=&clutter($returnhash{'url'});
 4953:            $returnhash{'fn'}=LONCAPA::tempdir() .
 4954: 	       $username.'_'.$cdomain.'_'.$cnum;
 4955:            $envhash{'course.'.$normalid.'.home'}=$chome;
 4956:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 4957:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 4958:        }
 4959:     }
 4960:     if (!$args->{'one_time'}) {
 4961: 	&appenv(\%envhash);
 4962:     }
 4963:     return %returnhash;
 4964: }
 4965: 
 4966: sub update_released_required {
 4967:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
 4968:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
 4969:         $cid = $env{'request.course.id'};
 4970:         $cdom = $env{'course.'.$cid.'.domain'};
 4971:         $cnum = $env{'course.'.$cid.'.num'};
 4972:         $chome = $env{'course.'.$cid.'.home'};
 4973:     }
 4974:     if ($needsrelease) {
 4975:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
 4976:         my $needsupdate;
 4977:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
 4978:             $needsupdate = 1;
 4979:         } else {
 4980:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
 4981:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
 4982:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
 4983:                 $needsupdate = 1;
 4984:             }
 4985:         }
 4986:         if ($needsupdate) {
 4987:             my %needshash = (
 4988:                              'internal.releaserequired' => $needsrelease,
 4989:                             );
 4990:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
 4991:             if ($putresult eq 'ok') {
 4992:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
 4993:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 4994:                 if (ref($crsinfo{$cid}) eq 'HASH') {
 4995:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
 4996:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
 4997:                 }
 4998:             }
 4999:         }
 5000:     }
 5001:     return;
 5002: }
 5003: 
 5004: # -------------------------------------------------See if a user is privileged
 5005: 
 5006: sub privileged {
 5007:     my ($username,$domain,$possdomains,$possroles)=@_;
 5008:     my $now = time;
 5009:     my $roles;
 5010:     if (ref($possroles) eq 'ARRAY') {
 5011:         $roles = $possroles; 
 5012:     } else {
 5013:         $roles = ['dc','su'];
 5014:     }
 5015:     if (ref($possdomains) eq 'ARRAY') {
 5016:         my %privileged = &privileged_by_domain($possdomains,$roles);
 5017:         foreach my $dom (@{$possdomains}) {
 5018:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
 5019:                 (ref($privileged{$dom}) eq 'HASH')) {
 5020:                 foreach my $role (@{$roles}) {
 5021:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 5022:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
 5023:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
 5024:                             return 1 unless (($end && $end < $now) ||
 5025:                                              ($start && $start > $now));
 5026:                         }
 5027:                     }
 5028:                 }
 5029:             }
 5030:         }
 5031:     } else {
 5032:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
 5033:         my $now = time;
 5034: 
 5035:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys %rolesdump}) {
 5036:             my ($trole, $tend, $tstart) = split(/_/, $role);
 5037:             if (grep(/^\Q$trole\E$/,@{$roles})) {
 5038:                 return 1 unless ($tend && $tend < $now) 
 5039:                         or ($tstart && $tstart > $now);
 5040:             }
 5041:         }
 5042:     }
 5043:     return 0;
 5044: }
 5045: 
 5046: sub privileged_by_domain {
 5047:     my ($domains,$roles) = @_;
 5048:     my %privileged = ();
 5049:     my $cachetime = 60*60*24;
 5050:     my $now = time;
 5051:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
 5052:         return %privileged;
 5053:     }
 5054:     foreach my $dom (@{$domains}) {
 5055:         next if (ref($privileged{$dom}) eq 'HASH');
 5056:         my $needroles;
 5057:         foreach my $role (@{$roles}) {
 5058:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
 5059:             if (defined($cached)) {
 5060:                 if (ref($result) eq 'HASH') {
 5061:                     $privileged{$dom}{$role} = $result;
 5062:                 }
 5063:             } else {
 5064:                 $needroles = 1;
 5065:             }
 5066:         }
 5067:         if ($needroles) {
 5068:             my %dompersonnel = &get_domain_roles($dom,$roles);
 5069:             $privileged{$dom} = {};
 5070:             foreach my $server (keys(%dompersonnel)) {
 5071:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 5072:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
 5073:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
 5074:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
 5075:                         next if ($end && $end < $now);
 5076:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
 5077:                             $dompersonnel{$server}{$item};
 5078:                     }
 5079:                 }
 5080:             }
 5081:             if (ref($privileged{$dom}) eq 'HASH') {
 5082:                 foreach my $role (@{$roles}) {
 5083:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 5084:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
 5085:                     } else {
 5086:                         my %hash = ();
 5087:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
 5088:                     }
 5089:                 }
 5090:             }
 5091:         }
 5092:     }
 5093:     return %privileged;
 5094: }
 5095: 
 5096: # -------------------------------------------------------- Get user privileges
 5097: 
 5098: sub rolesinit {
 5099:     my ($domain, $username) = @_;
 5100:     my %userroles = ('user.login.time' => time);
 5101:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
 5102: 
 5103:     # firstaccess and timerinterval are related to timed maps/resources. 
 5104:     # also, blocking can be triggered by an activating timer
 5105:     # it's saved in the user's %env.
 5106:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
 5107:     my %timerinterval = &dump('timerinterval', $domain, $username);
 5108:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
 5109:         %timerintchk, %timerintenv);
 5110: 
 5111:     foreach my $key (keys(%firstaccess)) {
 5112:         my ($cid, $rest) = split(/\0/, $key);
 5113:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
 5114:     }
 5115: 
 5116:     foreach my $key (keys(%timerinterval)) {
 5117:         my ($cid,$rest) = split(/\0/,$key);
 5118:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
 5119:     }
 5120: 
 5121:     my %allroles=();
 5122:     my %allgroups=();
 5123: 
 5124:     for my $area (grep { ! /^rolesdef_/ } keys %rolesdump) {
 5125:         my $role = $rolesdump{$area};
 5126:         $area =~ s/\_\w\w$//;
 5127: 
 5128:         my ($trole, $tend, $tstart, $group_privs);
 5129: 
 5130:         if ($role =~ /^cr/) {
 5131:         # Custom role, defined by a user 
 5132:         # e.g., user.role.cr/msu/smith/mynewrole
 5133:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 5134:                 $trole = $1;
 5135:                 ($tend, $tstart) = split('_', $2);
 5136:             } else {
 5137:                 $trole = $role;
 5138:             }
 5139:         } elsif ($role =~ m|^gr/|) {
 5140:         # Role of member in a group, defined within a course/community
 5141:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
 5142:             ($trole, $tend, $tstart) = split(/_/, $role);
 5143:             next if $tstart eq '-1';
 5144:             ($trole, $group_privs) = split(/\//, $trole);
 5145:             $group_privs = &unescape($group_privs);
 5146:         } else {
 5147:         # Just a normal role, defined in roles.tab
 5148:             ($trole, $tend, $tstart) = split(/_/,$role);
 5149:         }
 5150: 
 5151:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 5152:                  $username);
 5153:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 5154: 
 5155:         # role expired or not available yet?
 5156:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
 5157:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
 5158: 
 5159:         next if $area eq '' or $trole eq '';
 5160: 
 5161:         my $spec = "$trole.$area";
 5162:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
 5163: 
 5164:         if ($trole =~ /^cr\//) {
 5165:         # Custom role, defined by a user
 5166:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 5167:         } elsif ($trole eq 'gr') {
 5168:         # Role of a member in a group, defined within a course/community
 5169:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 5170:             next;
 5171:         } else {
 5172:         # Normal role, defined in roles.tab
 5173:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 5174:         }
 5175: 
 5176:         my $cid = $tdomain.'_'.$trest;
 5177:         unless ($firstaccchk{$cid}) {
 5178:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
 5179:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
 5180:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
 5181:                         $coursetimerstarts{$cid}{$item}; 
 5182:                 }
 5183:             }
 5184:             $firstaccchk{$cid} = 1;
 5185:         }
 5186:         unless ($timerintchk{$cid}) {
 5187:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
 5188:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
 5189:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
 5190:                        $coursetimerintervals{$cid}{$item};
 5191:                 }
 5192:             }
 5193:             $timerintchk{$cid} = 1;
 5194:         }
 5195:     }
 5196: 
 5197:     @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
 5198:         \%allroles, \%allgroups);
 5199:     $env{'user.adv'} = $userroles{'user.adv'};
 5200: 
 5201:     return (\%userroles,\%firstaccenv,\%timerintenv);
 5202: }
 5203: 
 5204: sub set_arearole {
 5205:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
 5206:     unless ($nolog) {
 5207: # log the associated role with the area
 5208:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 5209:     }
 5210:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 5211: }
 5212: 
 5213: sub custom_roleprivs {
 5214:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 5215:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 5216:     my $homsvr=homeserver($rauthor,$rdomain);
 5217:     if (&hostname($homsvr) ne '') {
 5218:         my ($rdummy,$roledef)=
 5219:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 5220:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 5221:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 5222:             if (defined($syspriv)) {
 5223:                 if ($trest =~ /^$match_community$/) {
 5224:                     $syspriv =~ s/bre\&S//; 
 5225:                 }
 5226:                 $$allroles{'cm./'}.=':'.$syspriv;
 5227:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 5228:             }
 5229:             if ($tdomain ne '') {
 5230:                 if (defined($dompriv)) {
 5231:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 5232:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 5233:                 }
 5234:                 if (($trest ne '') && (defined($coursepriv))) {
 5235:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 5236:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 5237:                 }
 5238:             }
 5239:         }
 5240:     }
 5241: }
 5242: 
 5243: sub group_roleprivs {
 5244:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 5245:     my $access = 1;
 5246:     my $now = time;
 5247:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 5248:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 5249:     if ($access) {
 5250:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 5251:         $$allgroups{$course}{$group} .=':'.$group_privs;
 5252:     }
 5253: }
 5254: 
 5255: sub standard_roleprivs {
 5256:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 5257:     if (defined($pr{$trole.':s'})) {
 5258:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 5259:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 5260:     }
 5261:     if ($tdomain ne '') {
 5262:         if (defined($pr{$trole.':d'})) {
 5263:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 5264:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 5265:         }
 5266:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 5267:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 5268:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 5269:         }
 5270:     }
 5271: }
 5272: 
 5273: sub set_userprivs {
 5274:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
 5275:     my $author=0;
 5276:     my $adv=0;
 5277:     my %grouproles = ();
 5278:     if (keys(%{$allgroups}) > 0) {
 5279:         my @groupkeys; 
 5280:         foreach my $role (keys(%{$allroles})) {
 5281:             push(@groupkeys,$role);
 5282:         }
 5283:         if (ref($groups_roles) eq 'HASH') {
 5284:             foreach my $key (keys(%{$groups_roles})) {
 5285:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
 5286:                     push(@groupkeys,$key);
 5287:                 }
 5288:             }
 5289:         }
 5290:         if (@groupkeys > 0) {
 5291:             foreach my $role (@groupkeys) {
 5292:                 my ($trole,$area,$sec,$extendedarea);
 5293:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 5294:                     $trole = $1;
 5295:                     $area = $2;
 5296:                     $sec = $3;
 5297:                     $extendedarea = $area.$sec;
 5298:                     if (exists($$allgroups{$area})) {
 5299:                         foreach my $group (keys(%{$$allgroups{$area}})) {
 5300:                             my $spec = $trole.'.'.$extendedarea;
 5301:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
 5302:                                                 $$allgroups{$area}{$group};
 5303:                         }
 5304:                     }
 5305:                 }
 5306:             }
 5307:         }
 5308:     }
 5309:     foreach my $group (keys(%grouproles)) {
 5310:         $$allroles{$group} = $grouproles{$group};
 5311:     }
 5312:     foreach my $role (keys(%{$allroles})) {
 5313:         my %thesepriv;
 5314:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 5315:         foreach my $item (split(/:/,$$allroles{$role})) {
 5316:             if ($item ne '') {
 5317:                 my ($privilege,$restrictions)=split(/&/,$item);
 5318:                 if ($restrictions eq '') {
 5319:                     $thesepriv{$privilege}='F';
 5320:                 } elsif ($thesepriv{$privilege} ne 'F') {
 5321:                     $thesepriv{$privilege}.=$restrictions;
 5322:                 }
 5323:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 5324:             }
 5325:         }
 5326:         my $thesestr='';
 5327:         foreach my $priv (sort(keys(%thesepriv))) {
 5328: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 5329: 	}
 5330:         $userroles->{'user.priv.'.$role} = $thesestr;
 5331:     }
 5332:     return ($author,$adv);
 5333: }
 5334: 
 5335: sub role_status {
 5336:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 5337:     my @pwhere = ();
 5338:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 5339:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
 5340:         unless (!defined($$role) || $$role eq '') {
 5341:             $$where=join('.',@pwhere);
 5342:             $$trolecode=$$role.'.'.$$where;
 5343:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 5344:             $$tstatus='is';
 5345:             if ($$tstart && $$tstart>$update) {
 5346:                 $$tstatus='future';
 5347:                 if ($$tstart<$now) {
 5348:                     if ($$tstart && $$tstart>$refresh) {
 5349:                         if (($$where ne '') && ($$role ne '')) {
 5350:                             my (%allroles,%allgroups,$group_privs,
 5351:                                 %groups_roles,@rolecodes);
 5352:                             my %userroles = (
 5353:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 5354:                             );
 5355:                             @rolecodes = ('cm'); 
 5356:                             my $spec=$$role.'.'.$$where;
 5357:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 5358:                             if ($$role =~ /^cr\//) {
 5359:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 5360:                                 push(@rolecodes,'cr');
 5361:                             } elsif ($$role eq 'gr') {
 5362:                                 push(@rolecodes,$$role);
 5363:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 5364:                                                     $env{'user.name'});
 5365:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
 5366:                                 (undef,my $group_privs) = split(/\//,$trole);
 5367:                                 $group_privs = &unescape($group_privs);
 5368:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 5369:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
 5370:                                 &get_groups_roles($tdomain,$trest,
 5371:                                                   \%course_roles,\@rolecodes,
 5372:                                                   \%groups_roles);
 5373:                             } else {
 5374:                                 push(@rolecodes,$$role);
 5375:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 5376:                             }
 5377:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
 5378:                             &appenv(\%userroles,\@rolecodes);
 5379:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 5380:                         }
 5381:                     }
 5382:                     $$tstatus = 'is';
 5383:                 }
 5384:             }
 5385:             if ($$tend) {
 5386:                 if ($$tend<$update) {
 5387:                     $$tstatus='expired';
 5388:                 } elsif ($$tend<$now) {
 5389:                     $$tstatus='will_not';
 5390:                 }
 5391:             }
 5392:         }
 5393:     }
 5394: }
 5395: 
 5396: sub get_groups_roles {
 5397:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
 5398:     return unless((ref($cdom_courseroles) eq 'HASH') && 
 5399:                   (ref($rolecodes) eq 'ARRAY') && 
 5400:                   (ref($groups_roles) eq 'HASH')); 
 5401:     if (keys(%{$cdom_courseroles}) > 0) {
 5402:         my ($cnum) = ($rest =~ /^($match_courseid)/);
 5403:         if ($cdom ne '' && $cnum ne '') {
 5404:             foreach my $key (keys(%{$cdom_courseroles})) {
 5405:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
 5406:                     my $crsrole = $1;
 5407:                     my $crssec = $2;
 5408:                     if ($crsrole =~ /^cr/) {
 5409:                         unless (grep(/^cr$/,@{$rolecodes})) {
 5410:                             push(@{$rolecodes},'cr');
 5411:                         }
 5412:                     } else {
 5413:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
 5414:                             push(@{$rolecodes},$crsrole);
 5415:                         }
 5416:                     }
 5417:                     my $rolekey = "$crsrole./$cdom/$cnum";
 5418:                     if ($crssec ne '') {
 5419:                         $rolekey .= "/$crssec";
 5420:                     }
 5421:                     $rolekey .= './';
 5422:                     $groups_roles->{$rolekey} = $rolecodes;
 5423:                 }
 5424:             }
 5425:         }
 5426:     }
 5427:     return;
 5428: }
 5429: 
 5430: sub delete_env_groupprivs {
 5431:     my ($where,$courseroles,$possroles) = @_;
 5432:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
 5433:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
 5434:     unless (ref($courseroles->{$udom}) eq 'HASH') {
 5435:         %{$courseroles->{$udom}} =
 5436:             &get_my_roles('','','userroles',['active'],
 5437:                           $possroles,[$udom],1);
 5438:     }
 5439:     if (ref($courseroles->{$udom}) eq 'HASH') {
 5440:         foreach my $item (keys(%{$courseroles->{$udom}})) {
 5441:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
 5442:             my $area = '/'.$cdom.'/'.$cnum;
 5443:             my $privkey = "user.priv.$crsrole.$area";
 5444:             if ($crssec ne '') {
 5445:                 $privkey .= '/'.$crssec;
 5446:             }
 5447:             $privkey .= ".$area/$group";
 5448:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
 5449:         }
 5450:     }
 5451:     return;
 5452: }
 5453: 
 5454: sub check_adhoc_privs {
 5455:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
 5456:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 5457:     my $setprivs;
 5458:     if ($env{$cckey}) {
 5459:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 5460:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 5461:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 5462:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
 5463:             $setprivs = 1;
 5464:         }
 5465:     } else {
 5466:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
 5467:         $setprivs = 1;
 5468:     }
 5469:     return $setprivs;
 5470: }
 5471: 
 5472: sub set_adhoc_privileges {
 5473: # role can be cc or ca
 5474:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
 5475:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 5476:     my $spec = $role.'.'.$area;
 5477:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 5478:                                   $env{'user.name'},1);
 5479:     my %ccrole = ();
 5480:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
 5481:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
 5482:     &appenv(\%userroles,[$role,'cm']);
 5483:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 5484:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
 5485:         &appenv( {'request.role'        => $spec,
 5486:                   'request.role.domain' => $dcdom,
 5487:                   'request.course.sec'  => ''
 5488:                  }
 5489:                );
 5490:         my $tadv=0;
 5491:         if (&allowed('adv') eq 'F') { $tadv=1; }
 5492:         &appenv({'request.role.adv'    => $tadv});
 5493:     }
 5494: }
 5495: 
 5496: # --------------------------------------------------------------- get interface
 5497: 
 5498: sub get {
 5499:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5500:    my $items='';
 5501:    foreach my $item (@$storearr) {
 5502:        $items.=&escape($item).'&';
 5503:    }
 5504:    $items=~s/\&$//;
 5505:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5506:    if (!$uname) { $uname=$env{'user.name'}; }
 5507:    my $uhome=&homeserver($uname,$udomain);
 5508: 
 5509:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 5510:    my @pairs=split(/\&/,$rep);
 5511:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 5512:      return @pairs;
 5513:    }
 5514:    my %returnhash=();
 5515:    my $i=0;
 5516:    foreach my $item (@$storearr) {
 5517:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 5518:       $i++;
 5519:    }
 5520:    return %returnhash;
 5521: }
 5522: 
 5523: # --------------------------------------------------------------- del interface
 5524: 
 5525: sub del {
 5526:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5527:    my $items='';
 5528:    foreach my $item (@$storearr) {
 5529:        $items.=&escape($item).'&';
 5530:    }
 5531: 
 5532:    $items=~s/\&$//;
 5533:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5534:    if (!$uname) { $uname=$env{'user.name'}; }
 5535:    my $uhome=&homeserver($uname,$udomain);
 5536:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 5537: }
 5538: 
 5539: # -------------------------------------------------------------- dump interface
 5540: 
 5541: sub unserialize {
 5542:     my ($rep, $escapedkeys) = @_;
 5543: 
 5544:     return {} if $rep =~ /^error/;
 5545: 
 5546:     my %returnhash=();
 5547: 	foreach my $item (split /\&/, $rep) {
 5548: 	    my ($key, $value) = split(/=/, $item, 2);
 5549: 	    $key = unescape($key) unless $escapedkeys;
 5550: 	    next if $key =~ /^error: 2 /;
 5551: 	    $returnhash{$key} = Apache::lonnet::thaw_unescape($value);
 5552: 	}
 5553:     #return %returnhash;
 5554:     return \%returnhash;
 5555: }        
 5556: 
 5557: # see Lond::dump_with_regexp
 5558: # if $escapedkeys hash keys won't get unescaped.
 5559: sub dump {
 5560:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
 5561:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5562:     if (!$uname) { $uname=$env{'user.name'}; }
 5563:     my $uhome=&homeserver($uname,$udomain);
 5564: 
 5565:     my $reply;
 5566:     if (grep { $_ eq $uhome } current_machine_ids()) {
 5567:         # user is hosted on this machine
 5568:         $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
 5569:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
 5570:         return %{unserialize($reply, $escapedkeys)};
 5571:     }
 5572:     if ($regexp) {
 5573: 	$regexp=&escape($regexp);
 5574:     } else {
 5575: 	$regexp='.';
 5576:     }
 5577:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 5578:     my @pairs=split(/\&/,$rep);
 5579:     my %returnhash=();
 5580:     if (!($rep =~ /^error/ )) {
 5581: 	foreach my $item (@pairs) {
 5582: 	    my ($key,$value)=split(/=/,$item,2);
 5583:         $key = unescape($key) unless $escapedkeys;
 5584:         #$key = &unescape($key);
 5585: 	    next if ($key =~ /^error: 2 /);
 5586: 	    $returnhash{$key}=&thaw_unescape($value);
 5587: 	}
 5588:     }
 5589:     return %returnhash;
 5590: }
 5591: 
 5592: 
 5593: # --------------------------------------------------------- dumpstore interface
 5594: 
 5595: sub dumpstore {
 5596:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 5597:    # same as dump but keys must be escaped. They may contain colon separated
 5598:    # lists of values that may themself contain colons (e.g. symbs).
 5599:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
 5600: }
 5601: 
 5602: # -------------------------------------------------------------- keys interface
 5603: 
 5604: sub getkeys {
 5605:    my ($namespace,$udomain,$uname)=@_;
 5606:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5607:    if (!$uname) { $uname=$env{'user.name'}; }
 5608:    my $uhome=&homeserver($uname,$udomain);
 5609:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 5610:    my @keyarray=();
 5611:    foreach my $key (split(/\&/,$rep)) {
 5612:       next if ($key =~ /^error: 2 /);
 5613:       push(@keyarray,&unescape($key));
 5614:    }
 5615:    return @keyarray;
 5616: }
 5617: 
 5618: # --------------------------------------------------------------- currentdump
 5619: sub currentdump {
 5620:    my ($courseid,$sdom,$sname)=@_;
 5621:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 5622:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 5623:    $sname    = $env{'user.name'}         if (! defined($sname));
 5624:    my $uhome = &homeserver($sname,$sdom);
 5625:    my $rep;
 5626: 
 5627:    if (grep { $_ eq $uhome } current_machine_ids()) {
 5628:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
 5629:                    $courseid)));
 5630:    } else {
 5631:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 5632:    }
 5633: 
 5634:    return if ($rep =~ /^(error:|no_such_host)/);
 5635:    #
 5636:    my %returnhash=();
 5637:    #
 5638:    if ($rep eq "unknown_cmd") { 
 5639:        # an old lond will not know currentdump
 5640:        # Do a dump and make it look like a currentdump
 5641:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 5642:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 5643:        my %hash = @tmp;
 5644:        @tmp=();
 5645:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 5646:    } else {
 5647:        my @pairs=split(/\&/,$rep);
 5648:        foreach my $pair (@pairs) {
 5649:            my ($key,$value)=split(/=/,$pair,2);
 5650:            my ($symb,$param) = split(/:/,$key);
 5651:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 5652:                                                         &thaw_unescape($value);
 5653:        }
 5654:    }
 5655:    return %returnhash;
 5656: }
 5657: 
 5658: sub convert_dump_to_currentdump{
 5659:     my %hash = %{shift()};
 5660:     my %returnhash;
 5661:     # Code ripped from lond, essentially.  The only difference
 5662:     # here is the unescaping done by lonnet::dump().  Conceivably
 5663:     # we might run in to problems with parameter names =~ /^v\./
 5664:     while (my ($key,$value) = each(%hash)) {
 5665:         my ($v,$symb,$param) = split(/:/,$key);
 5666: 	$symb  = &unescape($symb);
 5667: 	$param = &unescape($param);
 5668:         next if ($v eq 'version' || $symb eq 'keys');
 5669:         next if (exists($returnhash{$symb}) &&
 5670:                  exists($returnhash{$symb}->{$param}) &&
 5671:                  $returnhash{$symb}->{'v.'.$param} > $v);
 5672:         $returnhash{$symb}->{$param}=$value;
 5673:         $returnhash{$symb}->{'v.'.$param}=$v;
 5674:     }
 5675:     #
 5676:     # Remove all of the keys in the hashes which keep track of
 5677:     # the version of the parameter.
 5678:     while (my ($symb,$param_hash) = each(%returnhash)) {
 5679:         # use a foreach because we are going to delete from the hash.
 5680:         foreach my $key (keys(%$param_hash)) {
 5681:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 5682:         }
 5683:     }
 5684:     return \%returnhash;
 5685: }
 5686: 
 5687: # ------------------------------------------------------ critical inc interface
 5688: 
 5689: sub cinc {
 5690:     return &inc(@_,'critical');
 5691: }
 5692: 
 5693: # --------------------------------------------------------------- inc interface
 5694: 
 5695: sub inc {
 5696:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 5697:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5698:     if (!$uname) { $uname=$env{'user.name'}; }
 5699:     my $uhome=&homeserver($uname,$udomain);
 5700:     my $items='';
 5701:     if (! ref($store)) {
 5702:         # got a single value, so use that instead
 5703:         $items = &escape($store).'=&';
 5704:     } elsif (ref($store) eq 'SCALAR') {
 5705:         $items = &escape($$store).'=&';        
 5706:     } elsif (ref($store) eq 'ARRAY') {
 5707:         $items = join('=&',map {&escape($_);} @{$store});
 5708:     } elsif (ref($store) eq 'HASH') {
 5709:         while (my($key,$value) = each(%{$store})) {
 5710:             $items.= &escape($key).'='.&escape($value).'&';
 5711:         }
 5712:     }
 5713:     $items=~s/\&$//;
 5714:     if ($critical) {
 5715: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 5716:     } else {
 5717: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 5718:     }
 5719: }
 5720: 
 5721: # --------------------------------------------------------------- put interface
 5722: 
 5723: sub put {
 5724:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5725:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5726:    if (!$uname) { $uname=$env{'user.name'}; }
 5727:    my $uhome=&homeserver($uname,$udomain);
 5728:    my $items='';
 5729:    foreach my $item (keys(%$storehash)) {
 5730:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5731:    }
 5732:    $items=~s/\&$//;
 5733:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 5734: }
 5735: 
 5736: # ------------------------------------------------------------ newput interface
 5737: 
 5738: sub newput {
 5739:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5740:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5741:    if (!$uname) { $uname=$env{'user.name'}; }
 5742:    my $uhome=&homeserver($uname,$udomain);
 5743:    my $items='';
 5744:    foreach my $key (keys(%$storehash)) {
 5745:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 5746:    }
 5747:    $items=~s/\&$//;
 5748:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 5749: }
 5750: 
 5751: # ---------------------------------------------------------  putstore interface
 5752: 
 5753: sub putstore {
 5754:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 5755:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5756:    if (!$uname) { $uname=$env{'user.name'}; }
 5757:    my $uhome=&homeserver($uname,$udomain);
 5758:    my $items='';
 5759:    foreach my $key (keys(%$storehash)) {
 5760:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 5761:    }
 5762:    $items=~s/\&$//;
 5763:    my $esc_symb=&escape($symb);
 5764:    my $esc_v=&escape($version);
 5765:    my $reply =
 5766:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 5767: 	      $uhome);
 5768:    if ($reply eq 'unknown_cmd') {
 5769:        # gfall back to way things use to be done
 5770:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 5771: 			    $uname);
 5772:    }
 5773:    return $reply;
 5774: }
 5775: 
 5776: sub old_putstore {
 5777:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 5778:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5779:     if (!$uname) { $uname=$env{'user.name'}; }
 5780:     my $uhome=&homeserver($uname,$udomain);
 5781:     my %newstorehash;
 5782:     foreach my $item (keys(%$storehash)) {
 5783: 	my $key = $version.':'.&escape($symb).':'.$item;
 5784: 	$newstorehash{$key} = $storehash->{$item};
 5785:     }
 5786:     my $items='';
 5787:     my %allitems = ();
 5788:     foreach my $item (keys(%newstorehash)) {
 5789: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 5790: 	    my $key = $1.':keys:'.$2;
 5791: 	    $allitems{$key} .= $3.':';
 5792: 	}
 5793: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 5794:     }
 5795:     foreach my $item (keys(%allitems)) {
 5796: 	$allitems{$item} =~ s/\:$//;
 5797: 	$items.= $item.'='.$allitems{$item}.'&';
 5798:     }
 5799:     $items=~s/\&$//;
 5800:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 5801: }
 5802: 
 5803: # ------------------------------------------------------ critical put interface
 5804: 
 5805: sub cput {
 5806:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5807:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5808:    if (!$uname) { $uname=$env{'user.name'}; }
 5809:    my $uhome=&homeserver($uname,$udomain);
 5810:    my $items='';
 5811:    foreach my $item (keys(%$storehash)) {
 5812:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5813:    }
 5814:    $items=~s/\&$//;
 5815:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 5816: }
 5817: 
 5818: # -------------------------------------------------------------- eget interface
 5819: 
 5820: sub eget {
 5821:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5822:    my $items='';
 5823:    foreach my $item (@$storearr) {
 5824:        $items.=&escape($item).'&';
 5825:    }
 5826:    $items=~s/\&$//;
 5827:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5828:    if (!$uname) { $uname=$env{'user.name'}; }
 5829:    my $uhome=&homeserver($uname,$udomain);
 5830:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 5831:    my @pairs=split(/\&/,$rep);
 5832:    my %returnhash=();
 5833:    my $i=0;
 5834:    foreach my $item (@$storearr) {
 5835:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 5836:       $i++;
 5837:    }
 5838:    return %returnhash;
 5839: }
 5840: 
 5841: # ------------------------------------------------------------ tmpput interface
 5842: sub tmpput {
 5843:     my ($storehash,$server,$context)=@_;
 5844:     my $items='';
 5845:     foreach my $item (keys(%$storehash)) {
 5846: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5847:     }
 5848:     $items=~s/\&$//;
 5849:     if (defined($context)) {
 5850:         $items .= ':'.&escape($context);
 5851:     }
 5852:     return &reply("tmpput:$items",$server);
 5853: }
 5854: 
 5855: # ------------------------------------------------------------ tmpget interface
 5856: sub tmpget {
 5857:     my ($token,$server)=@_;
 5858:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 5859:     my $rep=&reply("tmpget:$token",$server);
 5860:     my %returnhash;
 5861:     foreach my $item (split(/\&/,$rep)) {
 5862: 	my ($key,$value)=split(/=/,$item);
 5863:         next if ($key =~ /^error: 2 /);
 5864: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 5865:     }
 5866:     return %returnhash;
 5867: }
 5868: 
 5869: # ------------------------------------------------------------ tmpdel interface
 5870: sub tmpdel {
 5871:     my ($token,$server)=@_;
 5872:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 5873:     return &reply("tmpdel:$token",$server);
 5874: }
 5875: 
 5876: # ------------------------------------------------------------ get_timebased_id 
 5877: 
 5878: sub get_timebased_id {
 5879:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
 5880:         $maxtries) = @_;
 5881:     my ($newid,$error,$dellock);
 5882:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
 5883:         return ('','ok','invalid call to get suffix');
 5884:     }
 5885: 
 5886: # set defaults for any optional args for which values were not supplied
 5887:     if ($who eq '') {
 5888:         $who = $env{'user.name'}.':'.$env{'user.domain'};
 5889:     }
 5890:     if (!$locktries) {
 5891:         $locktries = 3;
 5892:     }
 5893:     if (!$maxtries) {
 5894:         $maxtries = 10;
 5895:     }
 5896:     
 5897:     if (($cdom eq '') || ($cnum eq '')) {
 5898:         if ($env{'request.course.id'}) {
 5899:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5900:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5901:         }
 5902:         if (($cdom eq '') || ($cnum eq '')) {
 5903:             return ('','ok','call to get suffix not in course context');
 5904:         }
 5905:     }
 5906: 
 5907: # construct locking item
 5908:     my $lockhash = {
 5909:                       $prefix."\0".'locked_'.$keyid => $who,
 5910:                    };
 5911:     my $tries = 0;
 5912: 
 5913: # attempt to get lock on nohist_$namespace file
 5914:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 5915:     while (($gotlock ne 'ok') && $tries <$locktries) {
 5916:         $tries ++;
 5917:         sleep 1;
 5918:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 5919:     }
 5920: 
 5921: # attempt to get unique identifier, based on current timestamp
 5922:     if ($gotlock eq 'ok') {
 5923:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
 5924:         my $id = time;
 5925:         $newid = $id;
 5926:         my $idtries = 0;
 5927:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
 5928:             if ($idtype eq 'concat') {
 5929:                 $newid = $id.$idtries;
 5930:             } else {
 5931:                 $newid ++;
 5932:             }
 5933:             $idtries ++;
 5934:         }
 5935:         if (!exists($inuse{$prefix."\0".$newid})) {
 5936:             my %new_item =  (
 5937:                               $prefix."\0".$newid => $who,
 5938:                             );
 5939:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
 5940:                                                  $cdom,$cnum);
 5941:             if ($putresult ne 'ok') {
 5942:                 undef($newid);
 5943:                 $error = 'error saving new item: '.$putresult;
 5944:             }
 5945:         } else {
 5946:              $error = ('error: no unique suffix available for the new item ');
 5947:         }
 5948: #  remove lock
 5949:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
 5950:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
 5951:     } else {
 5952:         $error = "error: could not obtain lockfile\n";
 5953:         $dellock = 'ok';
 5954:     }
 5955:     return ($newid,$dellock,$error);
 5956: }
 5957: 
 5958: # -------------------------------------------------- portfolio access checking
 5959: 
 5960: sub portfolio_access {
 5961:     my ($requrl) = @_;
 5962:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 5963:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
 5964:     if ($result) {
 5965:         my %setters;
 5966:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 5967:             my ($startblock,$endblock) =
 5968:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 5969:             if ($startblock && $endblock) {
 5970:                 return 'B';
 5971:             }
 5972:         } else {
 5973:             my ($startblock,$endblock) =
 5974:                 &Apache::loncommon::blockcheck(\%setters,'port');
 5975:             if ($startblock && $endblock) {
 5976:                 return 'B';
 5977:             }
 5978:         }
 5979:     }
 5980:     if ($result eq 'ok') {
 5981:        return 'F';
 5982:     } elsif ($result =~ /^[^:]+:guest_/) {
 5983:        return 'A';
 5984:     }
 5985:     return '';
 5986: }
 5987: 
 5988: sub get_portfolio_access {
 5989:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
 5990: 
 5991:     if (!ref($access_hash)) {
 5992: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 5993: 	my %access_controls = &get_access_controls($current_perms,$group,
 5994: 						   $file_name);
 5995: 	$access_hash = $access_controls{$file_name};
 5996:     }
 5997: 
 5998:     my ($public,$guest,@domains,@users,@courses,@groups);
 5999:     my $now = time;
 6000:     if (ref($access_hash) eq 'HASH') {
 6001:         foreach my $key (keys(%{$access_hash})) {
 6002:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 6003:             if ($start > $now) {
 6004:                 next;
 6005:             }
 6006:             if ($end && $end<$now) {
 6007:                 next;
 6008:             }
 6009:             if ($scope eq 'public') {
 6010:                 $public = $key;
 6011:                 last;
 6012:             } elsif ($scope eq 'guest') {
 6013:                 $guest = $key;
 6014:             } elsif ($scope eq 'domains') {
 6015:                 push(@domains,$key);
 6016:             } elsif ($scope eq 'users') {
 6017:                 push(@users,$key);
 6018:             } elsif ($scope eq 'course') {
 6019:                 push(@courses,$key);
 6020:             } elsif ($scope eq 'group') {
 6021:                 push(@groups,$key);
 6022:             }
 6023:         }
 6024:         if ($public) {
 6025:             return 'ok';
 6026:         }
 6027:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 6028:             if ($guest) {
 6029:                 return $guest;
 6030:             }
 6031:         } else {
 6032:             if (@domains > 0) {
 6033:                 foreach my $domkey (@domains) {
 6034:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 6035:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 6036:                             return 'ok';
 6037:                         }
 6038:                     }
 6039:                 }
 6040:             }
 6041:             if (@users > 0) {
 6042:                 foreach my $userkey (@users) {
 6043:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 6044:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 6045:                             if (ref($item) eq 'HASH') {
 6046:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 6047:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 6048:                                     return 'ok';
 6049:                                 }
 6050:                             }
 6051:                         }
 6052:                     } 
 6053:                 }
 6054:             }
 6055:             my %roleshash;
 6056:             my @courses_and_groups = @courses;
 6057:             push(@courses_and_groups,@groups); 
 6058:             if (@courses_and_groups > 0) {
 6059:                 my (%allgroups,%allroles); 
 6060:                 my ($start,$end,$role,$sec,$group);
 6061:                 foreach my $envkey (%env) {
 6062:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 6063:                         my $cid = $2.'_'.$3; 
 6064:                         if ($1 eq 'gr') {
 6065:                             $group = $4;
 6066:                             $allgroups{$cid}{$group} = $env{$envkey};
 6067:                         } else {
 6068:                             if ($4 eq '') {
 6069:                                 $sec = 'none';
 6070:                             } else {
 6071:                                 $sec = $4;
 6072:                             }
 6073:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 6074:                         }
 6075:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 6076:                         my $cid = $2.'_'.$3;
 6077:                         if ($4 eq '') {
 6078:                             $sec = 'none';
 6079:                         } else {
 6080:                             $sec = $4;
 6081:                         }
 6082:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 6083:                     }
 6084:                 }
 6085:                 if (keys(%allroles) == 0) {
 6086:                     return;
 6087:                 }
 6088:                 foreach my $key (@courses_and_groups) {
 6089:                     my %content = %{$$access_hash{$key}};
 6090:                     my $cnum = $content{'number'};
 6091:                     my $cdom = $content{'domain'};
 6092:                     my $cid = $cdom.'_'.$cnum;
 6093:                     if (!exists($allroles{$cid})) {
 6094:                         next;
 6095:                     }    
 6096:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 6097:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 6098:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 6099:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 6100:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 6101:                         foreach my $role (keys(%{$allroles{$cid}})) {
 6102:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 6103:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 6104:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 6105:                                         if (grep/^all$/,@sections) {
 6106:                                             return 'ok';
 6107:                                         } else {
 6108:                                             if (grep/^$sec$/,@sections) {
 6109:                                                 return 'ok';
 6110:                                             }
 6111:                                         }
 6112:                                     }
 6113:                                 }
 6114:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 6115:                                     if (grep/^none$/,@groups) {
 6116:                                         return 'ok';
 6117:                                     }
 6118:                                 } else {
 6119:                                     if (grep/^all$/,@groups) {
 6120:                                         return 'ok';
 6121:                                     } 
 6122:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 6123:                                         if (grep/^$group$/,@groups) {
 6124:                                             return 'ok';
 6125:                                         }
 6126:                                     }
 6127:                                 } 
 6128:                             }
 6129:                         }
 6130:                     }
 6131:                 }
 6132:             }
 6133:             if ($guest) {
 6134:                 return $guest;
 6135:             }
 6136:         }
 6137:     }
 6138:     return;
 6139: }
 6140: 
 6141: sub course_group_datechecker {
 6142:     my ($dates,$now,$status) = @_;
 6143:     my ($start,$end) = split(/\./,$dates);
 6144:     if (!$start && !$end) {
 6145:         return 'ok';
 6146:     }
 6147:     if (grep/^active$/,@{$status}) {
 6148:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 6149:             return 'ok';
 6150:         }
 6151:     }
 6152:     if (grep/^previous$/,@{$status}) {
 6153:         if ($end > $now ) {
 6154:             return 'ok';
 6155:         }
 6156:     }
 6157:     if (grep/^future$/,@{$status}) {
 6158:         if ($start > $now) {
 6159:             return 'ok';
 6160:         }
 6161:     }
 6162:     return; 
 6163: }
 6164: 
 6165: sub parse_portfolio_url {
 6166:     my ($url) = @_;
 6167: 
 6168:     my ($type,$udom,$unum,$group,$file_name);
 6169:     
 6170:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 6171: 	$type = 1;
 6172:         $udom = $1;
 6173:         $unum = $2;
 6174:         $file_name = $3;
 6175:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 6176: 	$type = 2;
 6177:         $udom = $1;
 6178:         $unum = $2;
 6179:         $group = $3;
 6180:         $file_name = $3.'/'.$4;
 6181:     }
 6182:     if (wantarray) {
 6183: 	return ($type,$udom,$unum,$file_name,$group);
 6184:     }
 6185:     return $type;
 6186: }
 6187: 
 6188: sub is_portfolio_url {
 6189:     my ($url) = @_;
 6190:     return scalar(&parse_portfolio_url($url));
 6191: }
 6192: 
 6193: sub is_portfolio_file {
 6194:     my ($file) = @_;
 6195:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 6196:         return 1;
 6197:     }
 6198:     return;
 6199: }
 6200: 
 6201: sub usertools_access {
 6202:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
 6203:     my ($access,%tools);
 6204:     if ($context eq '') {
 6205:         $context = 'tools';
 6206:     }
 6207:     if ($context eq 'requestcourses') {
 6208:         %tools = (
 6209:                       official   => 1,
 6210:                       unofficial => 1,
 6211:                       community  => 1,
 6212:                       textbook   => 1,
 6213:                  );
 6214:     } elsif ($context eq 'requestauthor') {
 6215:         %tools = (
 6216:                       requestauthor => 1,
 6217:                  );
 6218:     } else {
 6219:         %tools = (
 6220:                       aboutme   => 1,
 6221:                       blog      => 1,
 6222:                       webdav    => 1,
 6223:                       portfolio => 1,
 6224:                  );
 6225:     }
 6226:     return if (!defined($tools{$tool}));
 6227: 
 6228:     if (($udom eq '') || ($uname eq '')) {
 6229:         $udom = $env{'user.domain'};
 6230:         $uname = $env{'user.name'};
 6231:     }
 6232: 
 6233:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 6234:         if ($action ne 'reload') {
 6235:             if ($context eq 'requestcourses') {
 6236:                 return $env{'environment.canrequest.'.$tool};
 6237:             } elsif ($context eq 'requestauthor') {
 6238:                 return $env{'environment.canrequest.author'};
 6239:             } else {
 6240:                 return $env{'environment.availabletools.'.$tool};
 6241:             }
 6242:         }
 6243:     }
 6244: 
 6245:     my ($toolstatus,$inststatus,$envkey);
 6246:     if ($context eq 'requestauthor') {
 6247:         $envkey = $context; 
 6248:     } else {
 6249:         $envkey = $context.'.'.$tool;
 6250:     }
 6251: 
 6252:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 6253:          ($action ne 'reload')) {
 6254:         $toolstatus = $env{'environment.'.$envkey};
 6255:         $inststatus = $env{'environment.inststatus'};
 6256:     } else {
 6257:         if (ref($userenvref) eq 'HASH') {
 6258:             $toolstatus = $userenvref->{$envkey};
 6259:             $inststatus = $userenvref->{'inststatus'};
 6260:         } else {
 6261:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
 6262:             $toolstatus = $userenv{$envkey};
 6263:             $inststatus = $userenv{'inststatus'};
 6264:         }
 6265:     }
 6266: 
 6267:     if ($toolstatus ne '') {
 6268:         if ($toolstatus) {
 6269:             $access = 1;
 6270:         } else {
 6271:             $access = 0;
 6272:         }
 6273:         return $access;
 6274:     }
 6275: 
 6276:     my ($is_adv,%domdef);
 6277:     if (ref($is_advref) eq 'HASH') {
 6278:         $is_adv = $is_advref->{'is_adv'};
 6279:     } else {
 6280:         $is_adv = &is_advanced_user($udom,$uname);
 6281:     }
 6282:     if (ref($domdefref) eq 'HASH') {
 6283:         %domdef = %{$domdefref};
 6284:     } else {
 6285:         %domdef = &get_domain_defaults($udom);
 6286:     }
 6287:     if (ref($domdef{$tool}) eq 'HASH') {
 6288:         if ($is_adv) {
 6289:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 6290:                 if ($domdef{$tool}{'_LC_adv'}) { 
 6291:                     $access = 1;
 6292:                 } else {
 6293:                     $access = 0;
 6294:                 }
 6295:                 return $access;
 6296:             }
 6297:         }
 6298:         if ($inststatus ne '') {
 6299:             my ($hasaccess,$hasnoaccess);
 6300:             foreach my $affiliation (split(/:/,$inststatus)) {
 6301:                 if ($domdef{$tool}{$affiliation} ne '') { 
 6302:                     if ($domdef{$tool}{$affiliation}) {
 6303:                         $hasaccess = 1;
 6304:                     } else {
 6305:                         $hasnoaccess = 1;
 6306:                     }
 6307:                 }
 6308:             }
 6309:             if ($hasaccess || $hasnoaccess) {
 6310:                 if ($hasaccess) {
 6311:                     $access = 1;
 6312:                 } elsif ($hasnoaccess) {
 6313:                     $access = 0; 
 6314:                 }
 6315:                 return $access;
 6316:             }
 6317:         } else {
 6318:             if ($domdef{$tool}{'default'} ne '') {
 6319:                 if ($domdef{$tool}{'default'}) {
 6320:                     $access = 1;
 6321:                 } elsif ($domdef{$tool}{'default'} == 0) {
 6322:                     $access = 0;
 6323:                 }
 6324:                 return $access;
 6325:             }
 6326:         }
 6327:     } else {
 6328:         if (($context eq 'tools') && ($tool ne 'webdav')) {
 6329:             $access = 1;
 6330:         } else {
 6331:             $access = 0;
 6332:         }
 6333:         return $access;
 6334:     }
 6335: }
 6336: 
 6337: sub is_course_owner {
 6338:     my ($cdom,$cnum,$udom,$uname) = @_;
 6339:     if (($udom eq '') || ($uname eq '')) {
 6340:         $udom = $env{'user.domain'};
 6341:         $uname = $env{'user.name'};
 6342:     }
 6343:     unless (($udom eq '') || ($uname eq '')) {
 6344:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
 6345:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
 6346:                 return 1;
 6347:             } else {
 6348:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
 6349:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
 6350:                     return 1;
 6351:                 }
 6352:             }
 6353:         }
 6354:     }
 6355:     return;
 6356: }
 6357: 
 6358: sub is_advanced_user {
 6359:     my ($udom,$uname) = @_;
 6360:     if ($udom ne '' && $uname ne '') {
 6361:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 6362:             if (wantarray) {
 6363:                 return ($env{'user.adv'},$env{'user.author'});
 6364:             } else {
 6365:                 return $env{'user.adv'};
 6366:             }
 6367:         }
 6368:     }
 6369:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 6370:     my %allroles;
 6371:     my ($is_adv,$is_author);
 6372:     foreach my $role (keys(%roleshash)) {
 6373:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 6374:         my $area = '/'.$tdomain.'/'.$trest;
 6375:         if ($sec ne '') {
 6376:             $area .= '/'.$sec;
 6377:         }
 6378:         if (($area ne '') && ($trole ne '')) {
 6379:             my $spec=$trole.'.'.$area;
 6380:             if ($trole =~ /^cr\//) {
 6381:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 6382:             } elsif ($trole ne 'gr') {
 6383:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 6384:             }
 6385:             if ($trole eq 'au') {
 6386:                 $is_author = 1;
 6387:             }
 6388:         }
 6389:     }
 6390:     foreach my $role (keys(%allroles)) {
 6391:         last if ($is_adv);
 6392:         foreach my $item (split(/:/,$allroles{$role})) {
 6393:             if ($item ne '') {
 6394:                 my ($privilege,$restrictions)=split(/&/,$item);
 6395:                 if ($privilege eq 'adv') {
 6396:                     $is_adv = 1;
 6397:                     last;
 6398:                 }
 6399:             }
 6400:         }
 6401:     }
 6402:     if (wantarray) {
 6403:         return ($is_adv,$is_author);
 6404:     }
 6405:     return $is_adv;
 6406: }
 6407: 
 6408: sub check_can_request {
 6409:     my ($dom,$can_request,$request_domains) = @_;
 6410:     my $canreq = 0;
 6411:     my ($types,$typename) = &Apache::loncommon::course_types();
 6412:     my @options = ('approval','validate','autolimit');
 6413:     my $optregex = join('|',@options);
 6414:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
 6415:         foreach my $type (@{$types}) {
 6416:             if (&usertools_access($env{'user.name'},
 6417:                                   $env{'user.domain'},
 6418:                                   $type,undef,'requestcourses')) {
 6419:                 $canreq ++;
 6420:                 if (ref($request_domains) eq 'HASH') {
 6421:                     push(@{$request_domains->{$type}},$env{'user.domain'});
 6422:                 }
 6423:                 if ($dom eq $env{'user.domain'}) {
 6424:                     $can_request->{$type} = 1;
 6425:                 }
 6426:             }
 6427:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
 6428:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
 6429:                 if (@curr > 0) {
 6430:                     foreach my $item (@curr) {
 6431:                         if (ref($request_domains) eq 'HASH') {
 6432:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
 6433:                             if ($otherdom ne '') {
 6434:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
 6435:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
 6436:                                         push(@{$request_domains->{$type}},$otherdom);
 6437:                                     }
 6438:                                 } else {
 6439:                                     push(@{$request_domains->{$type}},$otherdom);
 6440:                                 }
 6441:                             }
 6442:                         }
 6443:                     }
 6444:                     unless($dom eq $env{'user.domain'}) {
 6445:                         $canreq ++;
 6446:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
 6447:                             $can_request->{$type} = 1;
 6448:                         }
 6449:                     }
 6450:                 }
 6451:             }
 6452:         }
 6453:     }
 6454:     return $canreq;
 6455: }
 6456: 
 6457: # ---------------------------------------------- Custom access rule evaluation
 6458: 
 6459: sub customaccess {
 6460:     my ($priv,$uri)=@_;
 6461:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 6462:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 6463:     $udom = &LONCAPA::clean_domain($udom);
 6464:     $ucrs = &LONCAPA::clean_username($ucrs);
 6465:     my $access=0;
 6466:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 6467: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 6468: 	if ($type eq 'user') {
 6469: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 6470: 		my ($tdom,$tuname)=split(m{/},$scope);
 6471: 		if ($tdom) {
 6472: 		    if ($tdom ne $env{'user.domain'}) { next; }
 6473: 		}
 6474: 		if ($tuname) {
 6475: 		    if ($tuname ne $env{'user.name'}) { next; }
 6476: 		}
 6477: 		$access=($effect eq 'allow');
 6478: 		last;
 6479: 	    }
 6480: 	} else {
 6481: 	    if ($role) {
 6482: 		if ($role ne $urole) { next; }
 6483: 	    }
 6484: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 6485: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 6486: 		if ($tdom) {
 6487: 		    if ($tdom ne $udom) { next; }
 6488: 		}
 6489: 		if ($tcrs) {
 6490: 		    if ($tcrs ne $ucrs) { next; }
 6491: 		}
 6492: 		if ($tsec) {
 6493: 		    if ($tsec ne $usec) { next; }
 6494: 		}
 6495: 		$access=($effect eq 'allow');
 6496: 		last;
 6497: 	    }
 6498: 	    if ($realm eq '' && $role eq '') {
 6499: 		$access=($effect eq 'allow');
 6500: 	    }
 6501: 	}
 6502:     }
 6503:     return $access;
 6504: }
 6505: 
 6506: # ------------------------------------------------- Check for a user privilege
 6507: 
 6508: sub allowed {
 6509:     my ($priv,$uri,$symb,$role)=@_;
 6510:     my $ver_orguri=$uri;
 6511:     $uri=&deversion($uri);
 6512:     my $orguri=$uri;
 6513:     $uri=&declutter($uri);
 6514: 
 6515:     if ($priv eq 'evb') {
 6516: # Evade communication block restrictions for specified role in a course
 6517:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 6518:             return $1;
 6519:         } else {
 6520:             return;
 6521:         }
 6522:     }
 6523: 
 6524:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 6525: # Free bre access to adm and meta resources
 6526:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
 6527: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 6528: 	&& ($priv eq 'bre')) {
 6529: 	return 'F';
 6530:     }
 6531: 
 6532: # Free bre access to user's own portfolio contents
 6533:     my ($space,$domain,$name,@dir)=split('/',$uri);
 6534:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 6535: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 6536:         my %setters;
 6537:         my ($startblock,$endblock) = 
 6538:             &Apache::loncommon::blockcheck(\%setters,'port');
 6539:         if ($startblock && $endblock) {
 6540:             return 'B';
 6541:         } else {
 6542:             return 'F';
 6543:         }
 6544:     }
 6545: 
 6546: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 6547:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 6548:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 6549:         if (exists($env{'request.course.id'})) {
 6550:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6551:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 6552:             if (($domain eq $cdom) && ($name eq $cnum)) {
 6553:                 my $courseprivid=$env{'request.course.id'};
 6554:                 $courseprivid=~s/\_/\//;
 6555:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 6556:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 6557:                     return $1; 
 6558:                 } else {
 6559:                     if ($env{'request.course.sec'}) {
 6560:                         $courseprivid.='/'.$env{'request.course.sec'};
 6561:                     }
 6562:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 6563:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 6564:                         return $2;
 6565:                     }
 6566:                 }
 6567:             }
 6568:         }
 6569:     }
 6570: 
 6571: # Free bre to public access
 6572: 
 6573:     if ($priv eq 'bre') {
 6574:         my $copyright=&metadata($uri,'copyright');
 6575: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 6576:            return 'F'; 
 6577:         }
 6578:         if ($copyright eq 'priv') {
 6579:             $uri=~/([^\/]+)\/([^\/]+)\//;
 6580: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 6581: 		return '';
 6582:             }
 6583:         }
 6584:         if ($copyright eq 'domain') {
 6585:             $uri=~/([^\/]+)\/([^\/]+)\//;
 6586: 	    unless (($env{'user.domain'} eq $1) ||
 6587:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 6588: 		return '';
 6589:             }
 6590:         }
 6591:         if ($env{'request.role'}=~ /li\.\//) {
 6592:             # Library role, so allow browsing of resources in this domain.
 6593:             return 'F';
 6594:         }
 6595:         if ($copyright eq 'custom') {
 6596: 	    unless (&customaccess($priv,$uri)) { return ''; }
 6597:         }
 6598:     }
 6599:     # Domain coordinator is trying to create a course
 6600:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 6601:         # uri is the requested domain in this case.
 6602:         # comparison to 'request.role.domain' shows if the user has selected
 6603:         # a role of dc for the domain in question.
 6604:         return 'F' if ($uri eq $env{'request.role.domain'});
 6605:     }
 6606: 
 6607:     my $thisallowed='';
 6608:     my $statecond=0;
 6609:     my $courseprivid='';
 6610: 
 6611:     my $ownaccess;
 6612:     # Community Coordinator or Assistant Co-author browsing resource space.
 6613:     if (($priv eq 'bro') && ($env{'user.author'})) {
 6614:         if ($uri eq '') {
 6615:             $ownaccess = 1;
 6616:         } else {
 6617:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
 6618:                 my $udom = $env{'user.domain'};
 6619:                 my $uname = $env{'user.name'};
 6620:                 if ($uri =~ m{^\Q$udom\E/?$}) {
 6621:                     $ownaccess = 1;
 6622:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
 6623:                     unless ($uri =~ m{\.\./}) {
 6624:                         $ownaccess = 1;
 6625:                     }
 6626:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
 6627:                     my $now = time;
 6628:                     if ($uri =~ m{^([^/]+)/?$}) {
 6629:                         my $adom = $1;
 6630:                         foreach my $key (keys(%env)) {
 6631:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
 6632:                                 my ($start,$end) = split('.',$env{$key});
 6633:                                 if (($now >= $start) && (!$end || $end < $now)) {
 6634:                                     $ownaccess = 1;
 6635:                                     last;
 6636:                                 }
 6637:                             }
 6638:                         }
 6639:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
 6640:                         my $adom = $1;
 6641:                         my $aname = $2;
 6642:                         foreach my $role ('ca','aa') { 
 6643:                             if ($env{"user.role.$role./$adom/$aname"}) {
 6644:                                 my ($start,$end) =
 6645:                                     split('.',$env{"user.role.$role./$adom/$aname"});
 6646:                                 if (($now >= $start) && (!$end || $end < $now)) {
 6647:                                     $ownaccess = 1;
 6648:                                     last;
 6649:                                 }
 6650:                             }
 6651:                         }
 6652:                     }
 6653:                 }
 6654:             }
 6655:         }
 6656:     }
 6657: 
 6658: # Course
 6659: 
 6660:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 6661:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6662:             $thisallowed.=$1;
 6663:         }
 6664:     }
 6665: 
 6666: # Domain
 6667: 
 6668:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 6669:        =~/\Q$priv\E\&([^\:]*)/) {
 6670:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6671:             $thisallowed.=$1;
 6672:         }
 6673:     }
 6674: 
 6675: # User who is not author or co-author might still be able to edit
 6676: # resource of an author in the domain (e.g., if Domain Coordinator).
 6677:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
 6678:         (&allowed('mdc',$env{'request.course.id'}))) {
 6679:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
 6680:             $thisallowed.=$1;
 6681:         }
 6682:     }
 6683: 
 6684: # Course: uri itself is a course
 6685:     my $courseuri=$uri;
 6686:     $courseuri=~s/\_(\d)/\/$1/;
 6687:     $courseuri=~s/^([^\/])/\/$1/;
 6688: 
 6689:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 6690:        =~/\Q$priv\E\&([^\:]*)/) {
 6691:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6692:             $thisallowed.=$1;
 6693:         }
 6694:     }
 6695: 
 6696: # URI is an uploaded document for this course, default permissions don't matter
 6697: # not allowing 'edit' access (editupload) to uploaded course docs
 6698:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 6699: 	$thisallowed='';
 6700:         my ($match)=&is_on_map($uri);
 6701:         if ($match) {
 6702:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 6703:                   =~/\Q$priv\E\&([^\:]*)/) {
 6704:                 my @blockers = &has_comm_blocking($priv,$symb,$uri);
 6705:                 if (@blockers > 0) {
 6706:                     $thisallowed = 'B';
 6707:                 } else {
 6708:                     $thisallowed.=$1;
 6709:                 }
 6710:             }
 6711:         } else {
 6712:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 6713:             if ($refuri) {
 6714:                 if ($refuri =~ m|^/adm/|) {
 6715:                     $thisallowed='F';
 6716:                 } else {
 6717:                     $refuri=&declutter($refuri);
 6718:                     my ($match) = &is_on_map($refuri);
 6719:                     if ($match) {
 6720:                         my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 6721:                         if (@blockers > 0) {
 6722:                             $thisallowed = 'B';
 6723:                         } else {
 6724:                             $thisallowed='F';
 6725:                         }
 6726:                     }
 6727:                 }
 6728:             }
 6729:         }
 6730:     }
 6731: 
 6732:     if ($priv eq 'bre'
 6733: 	&& $thisallowed ne 'F' 
 6734: 	&& $thisallowed ne '2'
 6735: 	&& &is_portfolio_url($uri)) {
 6736: 	$thisallowed = &portfolio_access($uri);
 6737:     }
 6738:     
 6739: # Full access at system, domain or course-wide level? Exit.
 6740:     if ($thisallowed=~/F/) {
 6741: 	return 'F';
 6742:     }
 6743: 
 6744: # If this is generating or modifying users, exit with special codes
 6745: 
 6746:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 6747: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 6748: 	    my ($audom,$auname)=split('/',$uri);
 6749: # no author name given, so this just checks on the general right to make a co-author in this domain
 6750: 	    unless ($auname) { return $thisallowed; }
 6751: # an author name is given, so we are about to actually make a co-author for a certain account
 6752: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 6753: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 6754: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 6755: 	}
 6756: 	return $thisallowed;
 6757:     }
 6758: #
 6759: # Gathered so far: system, domain and course wide privileges
 6760: #
 6761: # Course: See if uri or referer is an individual resource that is part of 
 6762: # the course
 6763: 
 6764:     if ($env{'request.course.id'}) {
 6765: 
 6766:        $courseprivid=$env{'request.course.id'};
 6767:        if ($env{'request.course.sec'}) {
 6768:           $courseprivid.='/'.$env{'request.course.sec'};
 6769:        }
 6770:        $courseprivid=~s/\_/\//;
 6771:        my $checkreferer=1;
 6772:        my ($match,$cond)=&is_on_map($uri);
 6773:        if ($match) {
 6774:            $statecond=$cond;
 6775:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 6776:                =~/\Q$priv\E\&([^\:]*)/) {
 6777:                my $value = $1;
 6778:                if ($priv eq 'bre') {
 6779:                    my @blockers = &has_comm_blocking($priv,$symb,$uri);
 6780:                    if (@blockers > 0) {
 6781:                        $thisallowed = 'B';
 6782:                    } else {
 6783:                        $thisallowed.=$value;
 6784:                    }
 6785:                } else {
 6786:                    $thisallowed.=$value;
 6787:                }
 6788:                $checkreferer=0;
 6789:            }
 6790:        }
 6791:        
 6792:        if ($checkreferer) {
 6793: 	  my $refuri=$env{'httpref.'.$orguri};
 6794:             unless ($refuri) {
 6795:                 foreach my $key (keys(%env)) {
 6796: 		    if ($key=~/^httpref\..*\*/) {
 6797: 			my $pattern=$key;
 6798:                         $pattern=~s/^httpref\.\/res\///;
 6799:                         $pattern=~s/\*/\[\^\/\]\+/g;
 6800:                         $pattern=~s/\//\\\//g;
 6801:                         if ($orguri=~/$pattern/) {
 6802: 			    $refuri=$env{$key};
 6803:                         }
 6804:                     }
 6805:                 }
 6806:             }
 6807: 
 6808:          if ($refuri) { 
 6809: 	  $refuri=&declutter($refuri);
 6810:           my ($match,$cond)=&is_on_map($refuri);
 6811:             if ($match) {
 6812:               my $refstatecond=$cond;
 6813:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 6814:                   =~/\Q$priv\E\&([^\:]*)/) {
 6815:                   my $value = $1;
 6816:                   if ($priv eq 'bre') {
 6817:                       my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 6818:                       if (@blockers > 0) {
 6819:                           $thisallowed = 'B';
 6820:                       } else {
 6821:                           $thisallowed.=$value;
 6822:                       }
 6823:                   } else {
 6824:                       $thisallowed.=$value;
 6825:                   }
 6826:                   $uri=$refuri;
 6827:                   $statecond=$refstatecond;
 6828:               }
 6829:           }
 6830:         }
 6831:        }
 6832:    }
 6833: 
 6834: #
 6835: # Gathered now: all privileges that could apply, and condition number
 6836: # 
 6837: #
 6838: # Full or no access?
 6839: #
 6840: 
 6841:     if ($thisallowed=~/F/) {
 6842: 	return 'F';
 6843:     }
 6844: 
 6845:     unless ($thisallowed) {
 6846:         return '';
 6847:     }
 6848: 
 6849: # Restrictions exist, deal with them
 6850: #
 6851: #   C:according to course preferences
 6852: #   R:according to resource settings
 6853: #   L:unless locked
 6854: #   X:according to user session state
 6855: #
 6856: 
 6857: # Possibly locked functionality, check all courses
 6858: # Locks might take effect only after 10 minutes cache expiration for other
 6859: # courses, and 2 minutes for current course
 6860: 
 6861:     my $envkey;
 6862:     if ($thisallowed=~/L/) {
 6863:         foreach $envkey (keys(%env)) {
 6864:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 6865:                my $courseid=$2;
 6866:                my $roleid=$1.'.'.$2;
 6867:                $courseid=~s/^\///;
 6868:                my $expiretime=600;
 6869:                if ($env{'request.role'} eq $roleid) {
 6870: 		  $expiretime=120;
 6871:                }
 6872: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 6873:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 6874:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 6875: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 6876:                }
 6877:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 6878:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 6879: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 6880:                        &log($env{'user.domain'},$env{'user.name'},
 6881:                             $env{'user.home'},
 6882:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 6883:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 6884:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 6885: 		       return '';
 6886:                    }
 6887:                }
 6888:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 6889:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 6890: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 6891:                        &log($env{'user.domain'},$env{'user.name'},
 6892:                             $env{'user.home'},
 6893:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 6894:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 6895:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 6896: 		       return '';
 6897:                    }
 6898:                }
 6899: 	   }
 6900:        }
 6901:     }
 6902:    
 6903: #
 6904: # Rest of the restrictions depend on selected course
 6905: #
 6906: 
 6907:     unless ($env{'request.course.id'}) {
 6908: 	if ($thisallowed eq 'A') {
 6909: 	    return 'A';
 6910:         } elsif ($thisallowed eq 'B') {
 6911:             return 'B';
 6912: 	} else {
 6913: 	    return '1';
 6914: 	}
 6915:     }
 6916: 
 6917: #
 6918: # Now user is definitely in a course
 6919: #
 6920: 
 6921: 
 6922: # Course preferences
 6923: 
 6924:    if ($thisallowed=~/C/) {
 6925:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 6926:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 6927:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 6928: 	   =~/\Q$rolecode\E/) {
 6929: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 6930: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 6931: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 6932: 			$env{'request.course.id'});
 6933: 	   }
 6934:            return '';
 6935:        }
 6936: 
 6937:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 6938: 	   =~/\Q$unamedom\E/) {
 6939: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 6940: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 6941: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 6942: 			$env{'request.course.id'});
 6943: 	   }
 6944:            return '';
 6945:        }
 6946:    }
 6947: 
 6948: # Resource preferences
 6949: 
 6950:    if ($thisallowed=~/R/) {
 6951:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 6952:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 6953: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 6954: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 6955: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 6956: 	   }
 6957: 	   return '';
 6958:        }
 6959:    }
 6960: 
 6961: # Restricted by state or randomout?
 6962: 
 6963:    if ($thisallowed=~/X/) {
 6964:       if ($env{'acc.randomout'}) {
 6965: 	 if (!$symb) { $symb=&symbread($uri,1); }
 6966:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 6967:             return ''; 
 6968:          }
 6969:       }
 6970:       if (&condval($statecond)) {
 6971: 	 return '2';
 6972:       } else {
 6973:          return '';
 6974:       }
 6975:    }
 6976: 
 6977:     if ($thisallowed eq 'A') {
 6978: 	return 'A';
 6979:     } elsif ($thisallowed eq 'B') {
 6980:         return 'B';
 6981:     }
 6982:    return 'F';
 6983: }
 6984: 
 6985: # ------------------------------------------- Check construction space access
 6986: 
 6987: sub constructaccess {
 6988:     my ($url,$setpriv)=@_;
 6989: 
 6990: # We do not allow editing of previous versions of files
 6991:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
 6992: 
 6993: # Get username and domain from URL
 6994:     my ($ownername,$ownerdomain,$ownerhome);
 6995: 
 6996:     ($ownerdomain,$ownername) =
 6997:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)/});
 6998: 
 6999: # The URL does not really point to any authorspace, forget it
 7000:     unless (($ownername) && ($ownerdomain)) { return ''; }
 7001: 
 7002: # Now we need to see if the user has access to the authorspace of
 7003: # $ownername at $ownerdomain
 7004: 
 7005:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
 7006: # Real author for this?
 7007:        $ownerhome = $env{'user.home'};
 7008:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
 7009:           return ($ownername,$ownerdomain,$ownerhome);
 7010:        }
 7011:     } else {
 7012: # Co-author for this?
 7013:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
 7014:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
 7015:             $ownerhome = &homeserver($ownername,$ownerdomain);
 7016:             return ($ownername,$ownerdomain,$ownerhome);
 7017:         }
 7018:     }
 7019: 
 7020: # We don't have any access right now. If we are not possibly going to do anything about this,
 7021: # we might as well leave
 7022:    unless ($setpriv) { return ''; }
 7023: 
 7024: # Backdoor access?
 7025:     my $allowed=&allowed('eco',$ownerdomain);
 7026: # Nope
 7027:     unless ($allowed) { return ''; }
 7028: # Looks like we may have access, but could be locked by the owner of the construction space
 7029:     if ($allowed eq 'U') {
 7030:         my %blocked=&get('environment',['domcoord.author'],
 7031:                          $ownerdomain,$ownername);
 7032: # Is blocked by owner
 7033:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
 7034:     }
 7035:     if (($allowed eq 'F') || ($allowed eq 'U')) {
 7036: # Grant temporary access
 7037:         my $then=$env{'user.login.time'};
 7038:         my $update=$env{'user.update.time'};
 7039:         if (!$update) { $update = $then; }
 7040:         my $refresh=$env{'user.refresh.time'};
 7041:         if (!$refresh) { $refresh = $update; }
 7042:         my $now = time;
 7043:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
 7044:                            $now,'ca','constructaccess');
 7045:         $ownerhome = &homeserver($ownername,$ownerdomain);
 7046:         return($ownername,$ownerdomain,$ownerhome);
 7047:     }
 7048: # No business here
 7049:     return '';
 7050: }
 7051: 
 7052: sub get_comm_blocks {
 7053:     my ($cdom,$cnum) = @_;
 7054:     if ($cdom eq '' || $cnum eq '') {
 7055:         return unless ($env{'request.course.id'});
 7056:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7057:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7058:     }
 7059:     my %commblocks;
 7060:     my $hashid=$cdom.'_'.$cnum;
 7061:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
 7062:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
 7063:         %commblocks = %{$blocksref};
 7064:     } else {
 7065:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
 7066:         my $cachetime = 600;
 7067:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
 7068:     }
 7069:     return %commblocks;
 7070: }
 7071: 
 7072: sub has_comm_blocking {
 7073:     my ($priv,$symb,$uri,$blocks) = @_;
 7074:     return unless ($env{'request.course.id'});
 7075:     return unless ($priv eq 'bre');
 7076:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 7077:     my %commblocks;
 7078:     if (ref($blocks) eq 'HASH') {
 7079:         %commblocks = %{$blocks};
 7080:     } else {
 7081:         %commblocks = &get_comm_blocks();
 7082:     }
 7083:     return unless (keys(%commblocks) > 0);
 7084:     if (!$symb) { $symb=&symbread($uri,1); }
 7085:     my ($map,$resid,undef)=&decode_symb($symb);
 7086:     my %tocheck = (
 7087:                     maps      => $map,
 7088:                     resources => $symb,
 7089:                   );
 7090:     my @blockers;
 7091:     my $now = time;
 7092:     my $navmap = Apache::lonnavmaps::navmap->new();
 7093:     foreach my $block (keys(%commblocks)) {
 7094:         if ($block =~ /^(\d+)____(\d+)$/) {
 7095:             my ($start,$end) = ($1,$2);
 7096:             if ($start <= $now && $end >= $now) {
 7097:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 7098:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 7099:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 7100:                             if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
 7101:                                 unless (grep(/^\Q$block\E$/,@blockers)) {
 7102:                                     push(@blockers,$block);
 7103:                                 }
 7104:                             }
 7105:                         }
 7106:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 7107:                             if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
 7108:                                 unless (grep(/^\Q$block\E$/,@blockers)) {  
 7109:                                     push(@blockers,$block);
 7110:                                 }
 7111:                             }
 7112:                         }
 7113:                     }
 7114:                 }
 7115:             }
 7116:         } elsif ($block =~ /^firstaccess____(.+)$/) {
 7117:             my $item = $1;
 7118:             my @to_test;
 7119:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 7120:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 7121:                     my $check_interval;
 7122:                     if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
 7123:                         my @interval;
 7124:                         my $type = 'map';
 7125:                         if ($item eq 'course') {
 7126:                             $type = 'course';
 7127:                             @interval=&EXT("resource.0.interval");
 7128:                         } else {
 7129:                             if ($item =~ /___\d+___/) {
 7130:                                 $type = 'resource';
 7131:                                 @interval=&EXT("resource.0.interval",$item);
 7132:                                 if (ref($navmap)) {                        
 7133:                                     my $res = $navmap->getBySymb($item); 
 7134:                                     push(@to_test,$res);
 7135:                                 }
 7136:                             } else {
 7137:                                 my $mapsymb = &symbread($item,1);
 7138:                                 if ($mapsymb) {
 7139:                                     if (ref($navmap)) {
 7140:                                         my $mapres = $navmap->getBySymb($mapsymb);
 7141:                                         @to_test = $mapres->retrieveResources($mapres,undef,0,1);
 7142:                                         foreach my $res (@to_test) {
 7143:                                             my $symb = $res->symb();
 7144:                                             next if ($symb eq $mapsymb);
 7145:                                             if ($symb ne '') {
 7146:                                                 @interval=&EXT("resource.0.interval",$symb);
 7147:                                                 last;
 7148:                                             }
 7149:                                         }
 7150:                                     }
 7151:                                 }
 7152:                             }
 7153:                         }
 7154:                         if ($interval[0] =~ /\d+/) {
 7155:                             my $first_access;
 7156:                             if ($type eq 'resource') {
 7157:                                 $first_access=&get_first_access($interval[1],$item);
 7158:                             } elsif ($type eq 'map') {
 7159:                                 $first_access=&get_first_access($interval[1],undef,$item);
 7160:                             } else {
 7161:                                 $first_access=&get_first_access($interval[1]);
 7162:                             }
 7163:                             if ($first_access) {
 7164:                                 my $timesup = $first_access+$interval[0];
 7165:                                 if ($timesup > $now) {
 7166:                                     foreach my $res (@to_test) {
 7167:                                         if ($res->is_problem()) {
 7168:                                             if ($res->completable()) {
 7169:                                                 unless (grep(/^\Q$block\E$/,@blockers)) {
 7170:                                                     push(@blockers,$block);
 7171:                                                 }
 7172:                                                 last;
 7173:                                             }
 7174:                                         }
 7175:                                     }
 7176:                                 }
 7177:                             }
 7178:                         }
 7179:                     }
 7180:                 }
 7181:             }
 7182:         }
 7183:     }
 7184:     return @blockers;
 7185: }
 7186: 
 7187: sub check_docs_block {
 7188:     my ($docsblock,$tocheck) =@_;
 7189:     if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
 7190:         return;
 7191:     }
 7192:     if (ref($docsblock->{'maps'}) eq 'HASH') {
 7193:         if ($tocheck->{'maps'}) {
 7194:             if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
 7195:                 return 1;
 7196:             }
 7197:         }
 7198:     }
 7199:     if (ref($docsblock->{'resources'}) eq 'HASH') {
 7200:         if ($tocheck->{'resources'}) {
 7201:             if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
 7202:                 return 1;
 7203:             }
 7204:         }
 7205:     }
 7206:     return;
 7207: }
 7208: 
 7209: #
 7210: #   Removes the versino from a URI and
 7211: #   splits it in to its filename and path to the filename.
 7212: #   Seems like File::Basename could have done this more clearly.
 7213: #   Parameters:
 7214: #      $uri   - input URI
 7215: #   Returns:
 7216: #     Two element list consisting of 
 7217: #     $pathname  - the URI up to and excluding the trailing /
 7218: #     $filename  - The part of the URI following the last /
 7219: #  NOTE:
 7220: #    Another realization of this is simply:
 7221: #    use File::Basename;
 7222: #    ...
 7223: #    $uri = shift;
 7224: #    $filename = basename($uri);
 7225: #    $path     = dirname($uri);
 7226: #    return ($filename, $path);
 7227: #
 7228: #     The implementation below is probably faster however.
 7229: #
 7230: sub split_uri_for_cond {
 7231:     my $uri=&deversion(&declutter(shift));
 7232:     my @uriparts=split(/\//,$uri);
 7233:     my $filename=pop(@uriparts);
 7234:     my $pathname=join('/',@uriparts);
 7235:     return ($pathname,$filename);
 7236: }
 7237: # --------------------------------------------------- Is a resource on the map?
 7238: 
 7239: sub is_on_map {
 7240:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 7241:     #Trying to find the conditional for the file
 7242:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 7243: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 7244:     if ($match) {
 7245: 	return (1,$1);
 7246:     } else {
 7247: 	return (0,0);
 7248:     }
 7249: }
 7250: 
 7251: # --------------------------------------------------------- Get symb from alias
 7252: 
 7253: sub get_symb_from_alias {
 7254:     my $symb=shift;
 7255:     my ($map,$resid,$url)=&decode_symb($symb);
 7256: # Already is a symb
 7257:     if ($url) { return $symb; }
 7258: # Must be an alias
 7259:     my $aliassymb='';
 7260:     my %bighash;
 7261:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7262:                             &GDBM_READER(),0640)) {
 7263:         my $rid=$bighash{'mapalias_'.$symb};
 7264: 	if ($rid) {
 7265: 	    my ($mapid,$resid)=split(/\./,$rid);
 7266: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 7267: 				    $resid,$bighash{'src_'.$rid});
 7268: 	}
 7269:         untie %bighash;
 7270:     }
 7271:     return $aliassymb;
 7272: }
 7273: 
 7274: # ----------------------------------------------------------------- Define Role
 7275: 
 7276: sub definerole {
 7277:   if (allowed('mcr','/')) {
 7278:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 7279:     foreach my $role (split(':',$sysrole)) {
 7280: 	my ($crole,$cqual)=split(/\&/,$role);
 7281:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 7282:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 7283: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 7284:                return "refused:s:$crole&$cqual"; 
 7285:             }
 7286:         }
 7287:     }
 7288:     foreach my $role (split(':',$domrole)) {
 7289: 	my ($crole,$cqual)=split(/\&/,$role);
 7290:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 7291:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 7292: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 7293:                return "refused:d:$crole&$cqual"; 
 7294:             }
 7295:         }
 7296:     }
 7297:     foreach my $role (split(':',$courole)) {
 7298: 	my ($crole,$cqual)=split(/\&/,$role);
 7299:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 7300:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 7301: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 7302:                return "refused:c:$crole&$cqual"; 
 7303:             }
 7304:         }
 7305:     }
 7306:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 7307:                 "$env{'user.domain'}:$env{'user.name'}:".
 7308: 	        "rolesdef_$rolename=".
 7309:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 7310:     return reply($command,$env{'user.home'});
 7311:   } else {
 7312:     return 'refused';
 7313:   }
 7314: }
 7315: 
 7316: # ---------------- Make a metadata query against the network of library servers
 7317: 
 7318: sub metadata_query {
 7319:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
 7320:     my %rhash;
 7321:     my %libserv = &all_library();
 7322:     my @server_list = (defined($server_array) ? @$server_array
 7323:                                               : keys(%libserv) );
 7324:     for my $server (@server_list) {
 7325:         my $domains = ''; 
 7326:         if (ref($domains_hash) eq 'HASH') {
 7327:             $domains = $domains_hash->{$server}; 
 7328:         }
 7329: 	unless ($custom or $customshow) {
 7330: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
 7331: 	    $rhash{$server}=$reply;
 7332: 	}
 7333: 	else {
 7334: 	    my $reply=&reply("querysend:".&escape($query).':'.
 7335: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
 7336: 			     $server);
 7337: 	    $rhash{$server}=$reply;
 7338: 	}
 7339:     }
 7340:     return \%rhash;
 7341: }
 7342: 
 7343: # ----------------------------------------- Send log queries and wait for reply
 7344: 
 7345: sub log_query {
 7346:     my ($uname,$udom,$query,%filters)=@_;
 7347:     my $uhome=&homeserver($uname,$udom);
 7348:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 7349:     my $uhost=&hostname($uhome);
 7350:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 7351:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 7352:                        $uhome);
 7353:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 7354:     return get_query_reply($queryid);
 7355: }
 7356: 
 7357: # -------------------------- Update MySQL table for portfolio file
 7358: 
 7359: sub update_portfolio_table {
 7360:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 7361:     if ($group ne '') {
 7362:         $file_name =~s /^\Q$group\E//;
 7363:     }
 7364:     my $homeserver = &homeserver($uname,$udom);
 7365:     my $queryid=
 7366:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 7367:                ':'.&escape($file_name).':'.$action,$homeserver);
 7368:     my $reply = &get_query_reply($queryid);
 7369:     return $reply;
 7370: }
 7371: 
 7372: # -------------------------- Update MySQL allusers table
 7373: 
 7374: sub update_allusers_table {
 7375:     my ($uname,$udom,$names) = @_;
 7376:     my $homeserver = &homeserver($uname,$udom);
 7377:     my $queryid=
 7378:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 7379:                'lastname='.&escape($names->{'lastname'}).'%%'.
 7380:                'firstname='.&escape($names->{'firstname'}).'%%'.
 7381:                'middlename='.&escape($names->{'middlename'}).'%%'.
 7382:                'generation='.&escape($names->{'generation'}).'%%'.
 7383:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 7384:                'id='.&escape($names->{'id'}),$homeserver);
 7385:     return;
 7386: }
 7387: 
 7388: # ------- Request retrieval of institutional classlists for course(s)
 7389: 
 7390: sub fetch_enrollment_query {
 7391:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 7392:     my $homeserver;
 7393:     my $maxtries = 1;
 7394:     if ($context eq 'automated') {
 7395:         $homeserver = $perlvar{'lonHostID'};
 7396:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 7397:     } else {
 7398:         $homeserver = &homeserver($cnum,$dom);
 7399:     }
 7400:     my $host=&hostname($homeserver);
 7401:     my $cmd = '';
 7402:     foreach my $affiliate (keys(%{$affiliatesref})) {
 7403:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 7404:     }
 7405:     $cmd =~ s/%%$//;
 7406:     $cmd = &escape($cmd);
 7407:     my $query = 'fetchenrollment';
 7408:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 7409:     unless ($queryid=~/^\Q$host\E\_/) { 
 7410:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 7411:         return 'error: '.$queryid;
 7412:     }
 7413:     my $reply = &get_query_reply($queryid);
 7414:     my $tries = 1;
 7415:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 7416:         $reply = &get_query_reply($queryid);
 7417:         $tries ++;
 7418:     }
 7419:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 7420:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 7421:     } else {
 7422:         my @responses = split(/:/,$reply);
 7423:         if ($homeserver eq $perlvar{'lonHostID'}) {
 7424:             foreach my $line (@responses) {
 7425:                 my ($key,$value) = split(/=/,$line,2);
 7426:                 $$replyref{$key} = $value;
 7427:             }
 7428:         } else {
 7429:             my $pathname = LONCAPA::tempdir();
 7430:             foreach my $line (@responses) {
 7431:                 my ($key,$value) = split(/=/,$line);
 7432:                 $$replyref{$key} = $value;
 7433:                 if ($value > 0) {
 7434:                     foreach my $item (@{$$affiliatesref{$key}}) {
 7435:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 7436:                         my $destname = $pathname.'/'.$filename;
 7437:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 7438:                         if ($xml_classlist =~ /^error/) {
 7439:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 7440:                         } else {
 7441:                             if ( open(FILE,">$destname") ) {
 7442:                                 print FILE &unescape($xml_classlist);
 7443:                                 close(FILE);
 7444:                             } else {
 7445:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 7446:                             }
 7447:                         }
 7448:                     }
 7449:                 }
 7450:             }
 7451:         }
 7452:         return 'ok';
 7453:     }
 7454:     return 'error';
 7455: }
 7456: 
 7457: sub get_query_reply {
 7458:     my $queryid=shift;
 7459:     my $replyfile=LONCAPA::tempdir().$queryid;
 7460:     my $reply='';
 7461:     for (1..100) {
 7462: 	sleep 2;
 7463:         if (-e $replyfile.'.end') {
 7464: 	    if (open(my $fh,$replyfile)) {
 7465: 		$reply = join('',<$fh>);
 7466: 		close($fh);
 7467: 	   } else { return 'error: reply_file_error'; }
 7468:            return &unescape($reply);
 7469: 	}
 7470:     }
 7471:     return 'timeout:'.$queryid;
 7472: }
 7473: 
 7474: sub courselog_query {
 7475: #
 7476: # possible filters:
 7477: # url: url or symb
 7478: # username
 7479: # domain
 7480: # action: view, submit, grade
 7481: # start: timestamp
 7482: # end: timestamp
 7483: #
 7484:     my (%filters)=@_;
 7485:     unless ($env{'request.course.id'}) { return 'no_course'; }
 7486:     if ($filters{'url'}) {
 7487: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 7488:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 7489:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 7490:     }
 7491:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7492:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7493:     return &log_query($cname,$cdom,'courselog',%filters);
 7494: }
 7495: 
 7496: sub userlog_query {
 7497: #
 7498: # possible filters:
 7499: # action: log check role
 7500: # start: timestamp
 7501: # end: timestamp
 7502: #
 7503:     my ($uname,$udom,%filters)=@_;
 7504:     return &log_query($uname,$udom,'userlog',%filters);
 7505: }
 7506: 
 7507: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 7508: 
 7509: sub auto_run {
 7510:     my ($cnum,$cdom) = @_;
 7511:     my $response = 0;
 7512:     my $settings;
 7513:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 7514:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 7515:         $settings = $domconfig{'autoenroll'};
 7516:         if ($settings->{'run'} eq '1') {
 7517:             $response = 1;
 7518:         }
 7519:     } else {
 7520:         my $homeserver;
 7521:         if (&is_course($cdom,$cnum)) {
 7522:             $homeserver = &homeserver($cnum,$cdom);
 7523:         } else {
 7524:             $homeserver = &domain($cdom,'primary');
 7525:         }
 7526:         if ($homeserver ne 'no_host') {
 7527:             $response = &reply('autorun:'.$cdom,$homeserver);
 7528:         }
 7529:     }
 7530:     return $response;
 7531: }
 7532: 
 7533: sub auto_get_sections {
 7534:     my ($cnum,$cdom,$inst_coursecode) = @_;
 7535:     my $homeserver;
 7536:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
 7537:         $homeserver = &homeserver($cnum,$cdom);
 7538:     }
 7539:     if (!defined($homeserver)) { 
 7540:         if ($cdom =~ /^$match_domain$/) {
 7541:             $homeserver = &domain($cdom,'primary');
 7542:         }
 7543:     }
 7544:     my @secs;
 7545:     if (defined($homeserver)) {
 7546:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 7547:         unless ($response eq 'refused') {
 7548:             @secs = split(/:/,$response);
 7549:         }
 7550:     }
 7551:     return @secs;
 7552: }
 7553: 
 7554: sub auto_new_course {
 7555:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
 7556:     my $homeserver = &homeserver($cnum,$cdom);
 7557:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
 7558:     return $response;
 7559: }
 7560: 
 7561: sub auto_validate_courseID {
 7562:     my ($cnum,$cdom,$inst_course_id) = @_;
 7563:     my $homeserver = &homeserver($cnum,$cdom);
 7564:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 7565:     return $response;
 7566: }
 7567: 
 7568: sub auto_validate_instcode {
 7569:     my ($cnum,$cdom,$instcode,$owner) = @_;
 7570:     my ($homeserver,$response);
 7571:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 7572:         $homeserver = &homeserver($cnum,$cdom);
 7573:     }
 7574:     if (!defined($homeserver)) {
 7575:         if ($cdom =~ /^$match_domain$/) {
 7576:             $homeserver = &domain($cdom,'primary');
 7577:         }
 7578:     }
 7579:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
 7580:                         &escape($instcode).':'.&escape($owner),$homeserver));
 7581:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
 7582:     return ($outcome,$description,$defaultcredits);
 7583: }
 7584: 
 7585: sub auto_create_password {
 7586:     my ($cnum,$cdom,$authparam,$udom) = @_;
 7587:     my ($homeserver,$response);
 7588:     my $create_passwd = 0;
 7589:     my $authchk = '';
 7590:     if ($udom =~ /^$match_domain$/) {
 7591:         $homeserver = &domain($udom,'primary');
 7592:     }
 7593:     if ($homeserver eq '') {
 7594:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 7595:             $homeserver = &homeserver($cnum,$cdom);
 7596:         }
 7597:     }
 7598:     if ($homeserver eq '') {
 7599:         $authchk = 'nodomain';
 7600:     } else {
 7601:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 7602:         if ($response eq 'refused') {
 7603:             $authchk = 'refused';
 7604:         } else {
 7605:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 7606:         }
 7607:     }
 7608:     return ($authparam,$create_passwd,$authchk);
 7609: }
 7610: 
 7611: sub auto_photo_permission {
 7612:     my ($cnum,$cdom,$students) = @_;
 7613:     my $homeserver = &homeserver($cnum,$cdom);
 7614:     my ($outcome,$perm_reqd,$conditions) = 
 7615: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 7616:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 7617: 	return (undef,undef);
 7618:     }
 7619:     return ($outcome,$perm_reqd,$conditions);
 7620: }
 7621: 
 7622: sub auto_checkphotos {
 7623:     my ($uname,$udom,$pid) = @_;
 7624:     my $homeserver = &homeserver($uname,$udom);
 7625:     my ($result,$resulttype);
 7626:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 7627: 				   &escape($uname).':'.&escape($pid),
 7628: 				   $homeserver));
 7629:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 7630: 	return (undef,undef);
 7631:     }
 7632:     if ($outcome) {
 7633:         ($result,$resulttype) = split(/:/,$outcome);
 7634:     } 
 7635:     return ($result,$resulttype);
 7636: }
 7637: 
 7638: sub auto_photochoice {
 7639:     my ($cnum,$cdom) = @_;
 7640:     my $homeserver = &homeserver($cnum,$cdom);
 7641:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 7642: 						       &escape($cdom),
 7643: 						       $homeserver)));
 7644:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 7645: 	return (undef,undef);
 7646:     }
 7647:     return ($update,$comment);
 7648: }
 7649: 
 7650: sub auto_photoupdate {
 7651:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 7652:     my $homeserver = &homeserver($cnum,$dom);
 7653:     my $host=&hostname($homeserver);
 7654:     my $cmd = '';
 7655:     my $maxtries = 1;
 7656:     foreach my $affiliate (keys(%{$affiliatesref})) {
 7657:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 7658:     }
 7659:     $cmd =~ s/%%$//;
 7660:     $cmd = &escape($cmd);
 7661:     my $query = 'institutionalphotos';
 7662:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 7663:     unless ($queryid=~/^\Q$host\E\_/) {
 7664:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 7665:         return 'error: '.$queryid;
 7666:     }
 7667:     my $reply = &get_query_reply($queryid);
 7668:     my $tries = 1;
 7669:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 7670:         $reply = &get_query_reply($queryid);
 7671:         $tries ++;
 7672:     }
 7673:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 7674:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 7675:     } else {
 7676:         my @responses = split(/:/,$reply);
 7677:         my $outcome = shift(@responses); 
 7678:         foreach my $item (@responses) {
 7679:             my ($key,$value) = split(/=/,$item);
 7680:             $$photo{$key} = $value;
 7681:         }
 7682:         return $outcome;
 7683:     }
 7684:     return 'error';
 7685: }
 7686: 
 7687: sub auto_instcode_format {
 7688:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 7689: 	$cat_order) = @_;
 7690:     my $courses = '';
 7691:     my @homeservers;
 7692:     if ($caller eq 'global') {
 7693: 	my %servers = &get_servers($codedom,'library');
 7694: 	foreach my $tryserver (keys(%servers)) {
 7695: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7696: 		push(@homeservers,$tryserver);
 7697: 	    }
 7698:         }
 7699:     } elsif ($caller eq 'requests') {
 7700:         if ($codedom =~ /^$match_domain$/) {
 7701:             my $chome = &domain($codedom,'primary');
 7702:             unless ($chome eq 'no_host') {
 7703:                 push(@homeservers,$chome);
 7704:             }
 7705:         }
 7706:     } else {
 7707:         push(@homeservers,&homeserver($caller,$codedom));
 7708:     }
 7709:     foreach my $code (keys(%{$instcodes})) {
 7710:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 7711:     }
 7712:     chop($courses);
 7713:     my $ok_response = 0;
 7714:     my $response;
 7715:     while (@homeservers > 0 && $ok_response == 0) {
 7716:         my $server = shift(@homeservers); 
 7717:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 7718:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 7719:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 7720: 		split(/:/,$response);
 7721:             %{$codes} = (%{$codes},&str2hash($codes_str));
 7722:             push(@{$codetitles},&str2array($codetitles_str));
 7723:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 7724:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 7725:             $ok_response = 1;
 7726:         }
 7727:     }
 7728:     if ($ok_response) {
 7729:         return 'ok';
 7730:     } else {
 7731:         return $response;
 7732:     }
 7733: }
 7734: 
 7735: sub auto_instcode_defaults {
 7736:     my ($domain,$returnhash,$code_order) = @_;
 7737:     my @homeservers;
 7738: 
 7739:     my %servers = &get_servers($domain,'library');
 7740:     foreach my $tryserver (keys(%servers)) {
 7741: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7742: 	    push(@homeservers,$tryserver);
 7743: 	}
 7744:     }
 7745: 
 7746:     my $response;
 7747:     foreach my $server (@homeservers) {
 7748:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 7749:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 7750: 	
 7751: 	foreach my $pair (split(/\&/,$response)) {
 7752: 	    my ($name,$value)=split(/\=/,$pair);
 7753: 	    if ($name eq 'code_order') {
 7754: 		@{$code_order} = split(/\&/,&unescape($value));
 7755: 	    } else {
 7756: 		$returnhash->{&unescape($name)}=&unescape($value);
 7757: 	    }
 7758: 	}
 7759: 	return 'ok';
 7760:     }
 7761: 
 7762:     return $response;
 7763: }
 7764: 
 7765: sub auto_possible_instcodes {
 7766:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
 7767:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
 7768:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 7769:         return;
 7770:     }
 7771:     my (@homeservers,$uhome);
 7772:     if (defined(&domain($domain,'primary'))) {
 7773:         $uhome=&domain($domain,'primary');
 7774:         push(@homeservers,&domain($domain,'primary'));
 7775:     } else {
 7776:         my %servers = &get_servers($domain,'library');
 7777:         foreach my $tryserver (keys(%servers)) {
 7778:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7779:                 push(@homeservers,$tryserver);
 7780:             }
 7781:         }
 7782:     }
 7783:     my $response;
 7784:     foreach my $server (@homeservers) {
 7785:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
 7786:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 7787:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
 7788:             split(':',$response);
 7789:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
 7790:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
 7791:         foreach my $item (split('&',$cat_title)) {   
 7792:             my ($name,$value)=split('=',$item);
 7793:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
 7794:         }
 7795:         foreach my $item (split('&',$cat_order)) {
 7796:             my ($name,$value)=split('=',$item);
 7797:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
 7798:         }
 7799:         return 'ok';
 7800:     }
 7801:     return $response;
 7802: }
 7803: 
 7804: sub auto_courserequest_checks {
 7805:     my ($dom) = @_;
 7806:     my ($homeserver,%validations);
 7807:     if ($dom =~ /^$match_domain$/) {
 7808:         $homeserver = &domain($dom,'primary');
 7809:     }
 7810:     unless ($homeserver eq 'no_host') {
 7811:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
 7812:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 7813:             my @items = split(/&/,$response);
 7814:             foreach my $item (@items) {
 7815:                 my ($key,$value) = split('=',$item);
 7816:                 $validations{&unescape($key)} = &thaw_unescape($value);
 7817:             }
 7818:         }
 7819:     }
 7820:     return %validations; 
 7821: }
 7822: 
 7823: sub auto_courserequest_validation {
 7824:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
 7825:     my ($homeserver,$response);
 7826:     if ($dom =~ /^$match_domain$/) {
 7827:         $homeserver = &domain($dom,'primary');
 7828:     }
 7829:     unless ($homeserver eq 'no_host') {  
 7830:           
 7831:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
 7832:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
 7833:                                     ':'.&escape($instcode).':'.&escape($instseclist),
 7834:                                     $homeserver));
 7835:     }
 7836:     return $response;
 7837: }
 7838: 
 7839: sub auto_validate_class_sec {
 7840:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 7841:     my $homeserver = &homeserver($cnum,$cdom);
 7842:     my $ownerlist;
 7843:     if (ref($owners) eq 'ARRAY') {
 7844:         $ownerlist = join(',',@{$owners});
 7845:     } else {
 7846:         $ownerlist = $owners;
 7847:     }
 7848:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 7849:                         &escape($ownerlist).':'.$cdom,$homeserver);
 7850:     return $response;
 7851: }
 7852: 
 7853: # ------------------------------------------------------- Course Group routines
 7854: 
 7855: sub get_coursegroups {
 7856:     my ($cdom,$cnum,$group,$namespace) = @_;
 7857:     return(&dump($namespace,$cdom,$cnum,$group));
 7858: }
 7859: 
 7860: sub modify_coursegroup {
 7861:     my ($cdom,$cnum,$groupsettings) = @_;
 7862:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 7863: }
 7864: 
 7865: sub toggle_coursegroup_status {
 7866:     my ($cdom,$cnum,$group,$action) = @_;
 7867:     my ($from_namespace,$to_namespace);
 7868:     if ($action eq 'delete') {
 7869:         $from_namespace = 'coursegroups';
 7870:         $to_namespace = 'deleted_groups';
 7871:     } else {
 7872:         $from_namespace = 'deleted_groups';
 7873:         $to_namespace = 'coursegroups';
 7874:     }
 7875:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 7876:     if (my $tmp = &error(%curr_group)) {
 7877:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 7878:         return ('read error',$tmp);
 7879:     } else {
 7880:         my %savedsettings = %curr_group; 
 7881:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 7882:         my $deloutcome;
 7883:         if ($result eq 'ok') {
 7884:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 7885:         } else {
 7886:             return ('write error',$result);
 7887:         }
 7888:         if ($deloutcome eq 'ok') {
 7889:             return 'ok';
 7890:         } else {
 7891:             return ('delete error',$deloutcome);
 7892:         }
 7893:     }
 7894: }
 7895: 
 7896: sub modify_group_roles {
 7897:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 7898:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 7899:     my $role = 'gr/'.&escape($userprivs);
 7900:     my ($uname,$udom) = split(/:/,$user);
 7901:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 7902:     if ($result eq 'ok') {
 7903:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 7904:     }
 7905:     return $result;
 7906: }
 7907: 
 7908: sub modify_coursegroup_membership {
 7909:     my ($cdom,$cnum,$membership) = @_;
 7910:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 7911:     return $result;
 7912: }
 7913: 
 7914: sub get_active_groups {
 7915:     my ($udom,$uname,$cdom,$cnum) = @_;
 7916:     my $now = time;
 7917:     my %groups = ();
 7918:     foreach my $key (keys(%env)) {
 7919:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 7920:             my ($start,$end) = split(/\./,$env{$key});
 7921:             if (($end!=0) && ($end<$now)) { next; }
 7922:             if (($start!=0) && ($start>$now)) { next; }
 7923:             if ($1 eq $cdom && $2 eq $cnum) {
 7924:                 $groups{$3} = $env{$key} ;
 7925:             }
 7926:         }
 7927:     }
 7928:     return %groups;
 7929: }
 7930: 
 7931: sub get_group_membership {
 7932:     my ($cdom,$cnum,$group) = @_;
 7933:     return(&dump('groupmembership',$cdom,$cnum,$group));
 7934: }
 7935: 
 7936: sub get_users_groups {
 7937:     my ($udom,$uname,$courseid) = @_;
 7938:     my @usersgroups;
 7939:     my $cachetime=1800;
 7940: 
 7941:     my $hashid="$udom:$uname:$courseid";
 7942:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 7943:     if (defined($cached)) {
 7944:         @usersgroups = split(/:/,$grouplist);
 7945:     } else {  
 7946:         $grouplist = '';
 7947:         my $courseurl = &courseid_to_courseurl($courseid);
 7948:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 7949:         my $access_end = $env{'course.'.$courseid.
 7950:                               '.default_enrollment_end_date'};
 7951:         my $now = time;
 7952:         foreach my $key (keys(%roleshash)) {
 7953:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 7954:                 my $group = $1;
 7955:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 7956:                     my $start = $2;
 7957:                     my $end = $1;
 7958:                     if ($start == -1) { next; } # deleted from group
 7959:                     if (($start!=0) && ($start>$now)) { next; }
 7960:                     if (($end!=0) && ($end<$now)) {
 7961:                         if ($access_end && $access_end < $now) {
 7962:                             if ($access_end - $end < 86400) {
 7963:                                 push(@usersgroups,$group);
 7964:                             }
 7965:                         }
 7966:                         next;
 7967:                     }
 7968:                     push(@usersgroups,$group);
 7969:                 }
 7970:             }
 7971:         }
 7972:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 7973:         $grouplist = join(':',@usersgroups);
 7974:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 7975:     }
 7976:     return @usersgroups;
 7977: }
 7978: 
 7979: sub devalidate_getgroups_cache {
 7980:     my ($udom,$uname,$cdom,$cnum)=@_;
 7981:     my $courseid = $cdom.'_'.$cnum;
 7982: 
 7983:     my $hashid="$udom:$uname:$courseid";
 7984:     &devalidate_cache_new('getgroups',$hashid);
 7985: }
 7986: 
 7987: # ------------------------------------------------------------------ Plain Text
 7988: 
 7989: sub plaintext {
 7990:     my ($short,$type,$cid,$forcedefault) = @_;
 7991:     if ($short =~ m{^cr/}) {
 7992: 	return (split('/',$short))[-1];
 7993:     }
 7994:     if (!defined($cid)) {
 7995:         $cid = $env{'request.course.id'};
 7996:     }
 7997:     my %rolenames = (
 7998:                       Course    => 'std',
 7999:                       Community => 'alt1',
 8000:                     );
 8001:     if ($cid ne '') {
 8002:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
 8003:             unless ($forcedefault) {
 8004:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
 8005:                 &Apache::lonlocal::mt_escape(\$roletext);
 8006:                 return &Apache::lonlocal::mt($roletext);
 8007:             }
 8008:         }
 8009:     }
 8010:     if ((defined($type)) && (defined($rolenames{$type})) &&
 8011:         (defined($rolenames{$type})) && 
 8012:         (defined($prp{$short}{$rolenames{$type}}))) {
 8013:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 8014:     } elsif ($cid ne '') {
 8015:         my $crstype = $env{'course.'.$cid.'.type'};
 8016:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
 8017:             (defined($prp{$short}{$rolenames{$crstype}}))) {
 8018:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
 8019:         }
 8020:     }
 8021:     return &Apache::lonlocal::mt($prp{$short}{'std'});
 8022: }
 8023: 
 8024: # ----------------------------------------------------------------- Assign Role
 8025: 
 8026: sub assignrole {
 8027:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
 8028:         $context)=@_;
 8029:     my $mrole;
 8030:     if ($role =~ /^cr\//) {
 8031:         my $cwosec=$url;
 8032:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 8033: 	unless (&allowed('ccr',$cwosec)) {
 8034:            my $refused = 1;
 8035:            if ($context eq 'requestcourses') {
 8036:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 8037:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
 8038:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
 8039:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 8040:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 8041:                            if ($crsenv{'internal.courseowner'} eq
 8042:                                $env{'user.name'}.':'.$env{'user.domain'}) {
 8043:                                $refused = '';
 8044:                            }
 8045:                        }
 8046:                    }
 8047:                }
 8048:            }
 8049:            if ($refused) {
 8050:                &logthis('Refused custom assignrole: '.
 8051:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
 8052:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
 8053:                return 'refused';
 8054:            }
 8055:         }
 8056:         $mrole='cr';
 8057:     } elsif ($role =~ /^gr\//) {
 8058:         my $cwogrp=$url;
 8059:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 8060:         unless (&allowed('mdg',$cwogrp)) {
 8061:             &logthis('Refused group assignrole: '.
 8062:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 8063:                     $env{'user.name'}.' at '.$env{'user.domain'});
 8064:             return 'refused';
 8065:         }
 8066:         $mrole='gr';
 8067:     } else {
 8068:         my $cwosec=$url;
 8069:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 8070:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 8071:             my $refused;
 8072:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 8073:                 if (!(&allowed('c'.$role,$url))) {
 8074:                     $refused = 1;
 8075:                 }
 8076:             } else {
 8077:                 $refused = 1;
 8078:             }
 8079:             if ($refused) {
 8080:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 8081:                 if (!$selfenroll && $context eq 'course') {
 8082:                     my %crsenv;
 8083:                     if ($role eq 'cc' || $role eq 'co') {
 8084:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 8085:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
 8086:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
 8087:                                 if ($crsenv{'internal.courseowner'} eq 
 8088:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 8089:                                     $refused = '';
 8090:                                 }
 8091:                             }
 8092:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
 8093:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
 8094:                                 if ($crsenv{'internal.courseowner'} eq 
 8095:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 8096:                                     $refused = '';
 8097:                                 }
 8098:                             }
 8099:                         }
 8100:                     }
 8101:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 8102:                     $refused = '';
 8103:                 } elsif ($context eq 'requestcourses') {
 8104:                     my @possroles = ('st','ta','ep','in','cc','co');
 8105:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
 8106:                         my $wrongcc;
 8107:                         if ($cnum =~ /^$match_community$/) {
 8108:                             $wrongcc = 1 if ($role eq 'cc');
 8109:                         } else {
 8110:                             $wrongcc = 1 if ($role eq 'co');
 8111:                         }
 8112:                         unless ($wrongcc) {
 8113:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 8114:                             if ($crsenv{'internal.courseowner'} eq 
 8115:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
 8116:                                 $refused = '';
 8117:                             }
 8118:                         }
 8119:                     }
 8120:                 } elsif ($context eq 'requestauthor') {
 8121:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
 8122:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
 8123:                         if ($env{'environment.requestauthor'} eq 'automatic') {
 8124:                             $refused = '';
 8125:                         } else {
 8126:                             my %domdefaults = &get_domain_defaults($udom);
 8127:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
 8128:                                 my $checkbystatus;
 8129:                                 if ($env{'user.adv'}) { 
 8130:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
 8131:                                     if ($disposition eq 'automatic') {
 8132:                                         $refused = '';
 8133:                                     } elsif ($disposition eq '') {
 8134:                                         $checkbystatus = 1;
 8135:                                     } 
 8136:                                 } else {
 8137:                                     $checkbystatus = 1;
 8138:                                 }
 8139:                                 if ($checkbystatus) {
 8140:                                     if ($env{'environment.inststatus'}) {
 8141:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
 8142:                                         foreach my $type (@inststatuses) {
 8143:                                             if (($type ne '') &&
 8144:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
 8145:                                                 $refused = '';
 8146:                                             }
 8147:                                         }
 8148:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
 8149:                                         $refused = '';
 8150:                                     }
 8151:                                 }
 8152:                             }
 8153:                         }
 8154:                     }
 8155:                 }
 8156:                 if ($refused) {
 8157:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 8158:                              ' '.$role.' '.$end.' '.$start.' by '.
 8159: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
 8160:                     return 'refused';
 8161:                 }
 8162:             }
 8163:         } elsif ($role eq 'au') {
 8164:             if ($url ne '/'.$udom.'/') {
 8165:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
 8166:                          ' to assign author role for '.$uname.':'.$udom.
 8167:                          ' in domain: '.$url.' refused (wrong domain).');
 8168:                 return 'refused';
 8169:             }
 8170:         }
 8171:         $mrole=$role;
 8172:     }
 8173:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 8174:                 "$udom:$uname:$url".'_'."$mrole=$role";
 8175:     if ($end) { $command.='_'.$end; }
 8176:     if ($start) {
 8177: 	if ($end) { 
 8178:            $command.='_'.$start; 
 8179:         } else {
 8180:            $command.='_0_'.$start;
 8181:         }
 8182:     }
 8183:     my $origstart = $start;
 8184:     my $origend = $end;
 8185:     my $delflag;
 8186: # actually delete
 8187:     if ($deleteflag) {
 8188: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 8189: # modify command to delete the role
 8190:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 8191:                 "$udom:$uname:$url".'_'."$mrole";
 8192: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 8193: # set start and finish to negative values for userrolelog
 8194:            $start=-1;
 8195:            $end=-1;
 8196:            $delflag = 1;
 8197:         }
 8198:     }
 8199: # send command
 8200:     my $answer=&reply($command,&homeserver($uname,$udom));
 8201: # log new user role if status is ok
 8202:     if ($answer eq 'ok') {
 8203: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 8204:         if (($role eq 'cc') || ($role eq 'in') ||
 8205:             ($role eq 'ep') || ($role eq 'ad') ||
 8206:             ($role eq 'ta') || ($role eq 'st') ||
 8207:             ($role=~/^cr/) || ($role eq 'gr') ||
 8208:             ($role eq 'co')) {
 8209: # for course roles, perform group memberships changes triggered by role change.
 8210:             unless ($role =~ /^gr/) {
 8211:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 8212:                                                  $origstart,$selfenroll,$context);
 8213:             }
 8214:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 8215:                            $selfenroll,$context);
 8216:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
 8217:                  ($role eq 'au') || ($role eq 'dc')) {
 8218:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 8219:                            $context);
 8220:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
 8221:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 8222:                              $context); 
 8223:         }
 8224:         if ($role eq 'cc') {
 8225:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
 8226:         }
 8227:     }
 8228:     return $answer;
 8229: }
 8230: 
 8231: sub autoupdate_coowners {
 8232:     my ($url,$end,$start,$uname,$udom) = @_;
 8233:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
 8234:     if (($cdom ne '') && ($cnum ne '')) {
 8235:         my $now = time;
 8236:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
 8237:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
 8238:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
 8239:             my $instcode = $coursehash{'internal.coursecode'};
 8240:             if ($instcode ne '') {
 8241:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
 8242:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
 8243:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
 8244:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
 8245:                         if ($result eq 'valid') {
 8246:                             if ($coursehash{'internal.co-owners'}) {
 8247:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 8248:                                     push(@newcoowners,$coowner);
 8249:                                 }
 8250:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
 8251:                                     push(@newcoowners,$uname.':'.$udom);
 8252:                                 }
 8253:                                 @newcoowners = sort(@newcoowners);
 8254:                             } else {
 8255:                                 push(@newcoowners,$uname.':'.$udom);
 8256:                             }
 8257:                         } else {
 8258:                             if ($coursehash{'internal.co-owners'}) {
 8259:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 8260:                                     unless ($coowner eq $uname.':'.$udom) {
 8261:                                         push(@newcoowners,$coowner);
 8262:                                     }
 8263:                                 }
 8264:                                 unless (@newcoowners > 0) {
 8265:                                     $delcoowners = 1;
 8266:                                     $coowners = '';
 8267:                                 }
 8268:                             }
 8269:                         }
 8270:                         if (@newcoowners || $delcoowners) {
 8271:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
 8272:                                             $delcoowners,@newcoowners);
 8273:                         }
 8274:                     }
 8275:                 }
 8276:             }
 8277:         }
 8278:     }
 8279: }
 8280: 
 8281: sub store_coowners {
 8282:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
 8283:     my $cid = $cdom.'_'.$cnum;
 8284:     my ($coowners,$delresult,$putresult);
 8285:     if (@newcoowners) {
 8286:         $coowners = join(',',@newcoowners);
 8287:         my %coownershash = (
 8288:                             'internal.co-owners' => $coowners,
 8289:                            );
 8290:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
 8291:         if ($putresult eq 'ok') {
 8292:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
 8293:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
 8294:             }
 8295:         }
 8296:     }
 8297:     if ($delcoowners) {
 8298:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
 8299:         if ($delresult eq 'ok') {
 8300:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
 8301:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
 8302:             }
 8303:         }
 8304:     }
 8305:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
 8306:         my %crsinfo =
 8307:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 8308:         if (ref($crsinfo{$cid}) eq 'HASH') {
 8309:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
 8310:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
 8311:         }
 8312:     }
 8313: }
 8314: 
 8315: # -------------------------------------------------- Modify user authentication
 8316: # Overrides without validation
 8317: 
 8318: sub modifyuserauth {
 8319:     my ($udom,$uname,$umode,$upass)=@_;
 8320:     my $uhome=&homeserver($uname,$udom);
 8321:     unless (&allowed('mau',$udom)) { return 'refused'; }
 8322:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 8323:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 8324:              ' in domain '.$env{'request.role.domain'});  
 8325:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 8326: 		     &escape($upass),$uhome);
 8327:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 8328:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 8329:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 8330:     &log($udom,,$uname,$uhome,
 8331:         'Authentication changed by '.$env{'user.domain'}.', '.
 8332:                                      $env{'user.name'}.', '.$umode.
 8333:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 8334:     unless ($reply eq 'ok') {
 8335:         &logthis('Authentication mode error: '.$reply);
 8336: 	return 'error: '.$reply;
 8337:     }   
 8338:     return 'ok';
 8339: }
 8340: 
 8341: # --------------------------------------------------------------- Modify a user
 8342: 
 8343: sub modifyuser {
 8344:     my ($udom,    $uname, $uid,
 8345:         $umode,   $upass, $first,
 8346:         $middle,  $last,  $gene,
 8347:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
 8348:     $udom= &LONCAPA::clean_domain($udom);
 8349:     $uname=&LONCAPA::clean_username($uname);
 8350:     my $showcandelete = 'none';
 8351:     if (ref($candelete) eq 'ARRAY') {
 8352:         if (@{$candelete} > 0) {
 8353:             $showcandelete = join(', ',@{$candelete});
 8354:         }
 8355:     }
 8356:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 8357:              $umode.', '.$first.', '.$middle.', '.
 8358: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
 8359:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 8360:                                      ' desiredhome not specified'). 
 8361:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 8362:              ' in domain '.$env{'request.role.domain'});
 8363:     my $uhome=&homeserver($uname,$udom,'true');
 8364:     my $newuser;
 8365:     if ($uhome eq 'no_host') {
 8366:         $newuser = 1;
 8367:     }
 8368: # ----------------------------------------------------------------- Create User
 8369:     if (($uhome eq 'no_host') && 
 8370: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 8371:         my $unhome='';
 8372:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 8373:             $unhome = $desiredhome;
 8374: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 8375: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 8376:         } else { # load balancing routine for determining $unhome
 8377:             my $loadm=10000000;
 8378: 	    my %servers = &get_servers($udom,'library');
 8379: 	    foreach my $tryserver (keys(%servers)) {
 8380: 		my $answer=reply('load',$tryserver);
 8381: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 8382: 		    $loadm=$answer;
 8383: 		    $unhome=$tryserver;
 8384: 		}
 8385: 	    }
 8386:         }
 8387:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 8388: 	    return 'error: unable to find a home server for '.$uname.
 8389:                    ' in domain '.$udom;
 8390:         }
 8391:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 8392:                          &escape($upass),$unhome);
 8393: 	unless ($reply eq 'ok') {
 8394:             return 'error: '.$reply;
 8395:         }   
 8396:         $uhome=&homeserver($uname,$udom,'true');
 8397:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 8398: 	    return 'error: unable verify users home machine.';
 8399:         }
 8400:     }   # End of creation of new user
 8401: # ---------------------------------------------------------------------- Add ID
 8402:     if ($uid) {
 8403:        $uid=~tr/A-Z/a-z/;
 8404:        my %uidhash=&idrget($udom,$uname);
 8405:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 8406:          && (!$forceid)) {
 8407: 	  unless ($uid eq $uidhash{$uname}) {
 8408: 	      return 'error: user id "'.$uid.'" does not match '.
 8409:                   'current user id "'.$uidhash{$uname}.'".';
 8410:           }
 8411:        } else {
 8412: 	  &idput($udom,($uname => $uid));
 8413:        }
 8414:     }
 8415: # -------------------------------------------------------------- Add names, etc
 8416:     my @tmp=&get('environment',
 8417: 		   ['firstname','middlename','lastname','generation','id',
 8418:                     'permanentemail','inststatus'],
 8419: 		   $udom,$uname);
 8420:     my (%names,%oldnames);
 8421:     if ($tmp[0] =~ m/^error:.*/) { 
 8422:         %names=(); 
 8423:     } else {
 8424:         %names = @tmp;
 8425:         %oldnames = %names;
 8426:     }
 8427: #
 8428: # If name, email and/or uid are blank (e.g., because an uploaded file
 8429: # of users did not contain them), do not overwrite existing values
 8430: # unless field is in $candelete array ref.  
 8431: #
 8432: 
 8433:     my @fields = ('firstname','middlename','lastname','generation',
 8434:                   'permanentemail','id');
 8435:     my %newvalues;
 8436:     if (ref($candelete) eq 'ARRAY') {
 8437:         foreach my $field (@fields) {
 8438:             if (grep(/^\Q$field\E$/,@{$candelete})) {
 8439:                 if ($field eq 'firstname') {
 8440:                     $names{$field} = $first;
 8441:                 } elsif ($field eq 'middlename') {
 8442:                     $names{$field} = $middle;
 8443:                 } elsif ($field eq 'lastname') {
 8444:                     $names{$field} = $last;
 8445:                 } elsif ($field eq 'generation') { 
 8446:                     $names{$field} = $gene;
 8447:                 } elsif ($field eq 'permanentemail') {
 8448:                     $names{$field} = $email;
 8449:                 } elsif ($field eq 'id') {
 8450:                     $names{$field}  = $uid;
 8451:                 }
 8452:             }
 8453:         }
 8454:     }
 8455:     if ($first)  { $names{'firstname'}  = $first; }
 8456:     if (defined($middle)) { $names{'middlename'} = $middle; }
 8457:     if ($last)   { $names{'lastname'}   = $last; }
 8458:     if (defined($gene))   { $names{'generation'} = $gene; }
 8459:     if ($email) {
 8460:        $email=~s/[^\w\@\.\-\,]//gs;
 8461:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
 8462:     }
 8463:     if ($uid) { $names{'id'}  = $uid; }
 8464:     if (defined($inststatus)) {
 8465:         $names{'inststatus'} = '';
 8466:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
 8467:         if (ref($usertypes) eq 'HASH') {
 8468:             my @okstatuses; 
 8469:             foreach my $item (split(/:/,$inststatus)) {
 8470:                 if (defined($usertypes->{$item})) {
 8471:                     push(@okstatuses,$item);  
 8472:                 }
 8473:             }
 8474:             if (@okstatuses) {
 8475:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
 8476:             }
 8477:         }
 8478:     }
 8479:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
 8480:                  $umode.', '.$first.', '.$middle.', '.
 8481:                  $last.', '.$gene.', '.$email.', '.$inststatus;
 8482:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
 8483:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
 8484:     } else {
 8485:         $logmsg .= ' during self creation';
 8486:     }
 8487:     my $changed;
 8488:     if ($newuser) {
 8489:         $changed = 1;
 8490:     } else {
 8491:         foreach my $field (@fields) {
 8492:             if ($names{$field} ne $oldnames{$field}) {
 8493:                 $changed = 1;
 8494:                 last;
 8495:             }
 8496:         }
 8497:     }
 8498:     unless ($changed) {
 8499:         $logmsg = 'No changes in user information needed for: '.$logmsg;
 8500:         &logthis($logmsg);
 8501:         return 'ok';
 8502:     }
 8503:     my $reply = &put('environment', \%names, $udom,$uname);
 8504:     if ($reply ne 'ok') { 
 8505:         return 'error: '.$reply;
 8506:     }
 8507:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
 8508:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
 8509:     }
 8510:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
 8511:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 8512:     $logmsg = 'Success modifying user '.$logmsg;
 8513:     &logthis($logmsg);
 8514:     return 'ok';
 8515: }
 8516: 
 8517: # -------------------------------------------------------------- Modify student
 8518: 
 8519: sub modifystudent {
 8520:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 8521:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
 8522:         $selfenroll,$context,$inststatus,$credits)=@_;
 8523:     if (!$cid) {
 8524: 	unless ($cid=$env{'request.course.id'}) {
 8525: 	    return 'not_in_class';
 8526: 	}
 8527:     }
 8528: # --------------------------------------------------------------- Make the user
 8529:     my $reply=&modifyuser
 8530: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 8531:          $desiredhome,$email,$inststatus);
 8532:     unless ($reply eq 'ok') { return $reply; }
 8533:     # This will cause &modify_student_enrollment to get the uid from the
 8534:     # student's environment
 8535:     $uid = undef if (!$forceid);
 8536:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 8537:                                         $gene,$usec,$end,$start,$type,$locktype,
 8538:                                         $cid,$selfenroll,$context,$credits);
 8539:     return $reply;
 8540: }
 8541: 
 8542: sub modify_student_enrollment {
 8543:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
 8544:         $locktype,$cid,$selfenroll,$context,$credits) = @_;
 8545:     my ($cdom,$cnum,$chome);
 8546:     if (!$cid) {
 8547: 	unless ($cid=$env{'request.course.id'}) {
 8548: 	    return 'not_in_class';
 8549: 	}
 8550: 	$cdom=$env{'course.'.$cid.'.domain'};
 8551: 	$cnum=$env{'course.'.$cid.'.num'};
 8552:     } else {
 8553: 	($cdom,$cnum)=split(/_/,$cid);
 8554:     }
 8555:     $chome=$env{'course.'.$cid.'.home'};
 8556:     if (!$chome) {
 8557: 	$chome=&homeserver($cnum,$cdom);
 8558:     }
 8559:     if (!$chome) { return 'unknown_course'; }
 8560:     # Make sure the user exists
 8561:     my $uhome=&homeserver($uname,$udom);
 8562:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 8563: 	return 'error: no such user';
 8564:     }
 8565:     # Get student data if we were not given enough information
 8566:     if (!defined($first)  || $first  eq '' || 
 8567:         !defined($last)   || $last   eq '' || 
 8568:         !defined($uid)    || $uid    eq '' || 
 8569:         !defined($middle) || $middle eq '' || 
 8570:         !defined($gene)   || $gene   eq '') {
 8571:         # They did not supply us with enough data to enroll the student, so
 8572:         # we need to pick up more information.
 8573:         my %tmp = &get('environment',
 8574:                        ['firstname','middlename','lastname', 'generation','id']
 8575:                        ,$udom,$uname);
 8576: 
 8577:         #foreach my $key (keys(%tmp)) {
 8578:         #    &logthis("key $key = ".$tmp{$key});
 8579:         #}
 8580:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 8581:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 8582:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 8583:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 8584:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 8585:     }
 8586:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 8587:     my $user = "$uname:$udom";
 8588:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
 8589:     my $reply=cput('classlist',
 8590: 		   {$user => 
 8591: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits) },
 8592: 		   $cdom,$cnum);
 8593:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
 8594:         &devalidate_getsection_cache($udom,$uname,$cid);
 8595:     } else { 
 8596: 	return 'error: '.$reply;
 8597:     }
 8598:     # Add student role to user
 8599:     my $uurl='/'.$cid;
 8600:     $uurl=~s/\_/\//g;
 8601:     if ($usec) {
 8602: 	$uurl.='/'.$usec;
 8603:     }
 8604:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
 8605:                              $selfenroll,$context);
 8606:     if ($result ne 'ok') {
 8607:         if ($old_entry{$user} ne '') {
 8608:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
 8609:         } else {
 8610:             $reply = &del('classlist',[$user],$cdom,$cnum);
 8611:         }
 8612:     }
 8613:     return $result; 
 8614: }
 8615: 
 8616: sub format_name {
 8617:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 8618:     my $name;
 8619:     if ($first ne 'lastname') {
 8620: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 8621:     } else {
 8622: 	if ($lastname=~/\S/) {
 8623: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 8624: 	    $name=~s/\s+,/,/;
 8625: 	} else {
 8626: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 8627: 	}
 8628:     }
 8629:     $name=~s/^\s+//;
 8630:     $name=~s/\s+$//;
 8631:     $name=~s/\s+/ /g;
 8632:     return $name;
 8633: }
 8634: 
 8635: # ------------------------------------------------- Write to course preferences
 8636: 
 8637: sub writecoursepref {
 8638:     my ($courseid,%prefs)=@_;
 8639:     $courseid=~s/^\///;
 8640:     $courseid=~s/\_/\//g;
 8641:     my ($cdomain,$cnum)=split(/\//,$courseid);
 8642:     my $chome=homeserver($cnum,$cdomain);
 8643:     if (($chome eq '') || ($chome eq 'no_host')) { 
 8644: 	return 'error: no such course';
 8645:     }
 8646:     my $cstring='';
 8647:     foreach my $pref (keys(%prefs)) {
 8648: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 8649:     }
 8650:     $cstring=~s/\&$//;
 8651:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 8652: }
 8653: 
 8654: # ---------------------------------------------------------- Make/modify course
 8655: 
 8656: sub createcourse {
 8657:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 8658:         $course_owner,$crstype,$cnum,$context,$category)=@_;
 8659:     $url=&declutter($url);
 8660:     my $cid='';
 8661:     if ($context eq 'requestcourses') {
 8662:         my $can_create = 0;
 8663:         my ($ownername,$ownerdom) = split(':',$course_owner);
 8664:         if ($udom eq $ownerdom) {
 8665:             if (&usertools_access($ownername,$ownerdom,$category,undef,
 8666:                                   $context)) {
 8667:                 $can_create = 1;
 8668:             }
 8669:         } else {
 8670:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
 8671:                                            $category);
 8672:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
 8673:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
 8674:                 if (@curr > 0) {
 8675:                     my @options = qw(approval validate autolimit);
 8676:                     my $optregex = join('|',@options);
 8677:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
 8678:                         $can_create = 1;
 8679:                     }
 8680:                 }
 8681:             }
 8682:         }
 8683:         if ($can_create) {
 8684:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
 8685:                 unless (&allowed('ccc',$udom)) {
 8686:                     return 'refused'; 
 8687:                 }
 8688:             }
 8689:         } else {
 8690:             return 'refused';
 8691:         }
 8692:     } elsif (!&allowed('ccc',$udom)) {
 8693:         return 'refused';
 8694:     }
 8695: # --------------------------------------------------------------- Get Unique ID
 8696:     my $uname;
 8697:     if ($cnum =~ /^$match_courseid$/) {
 8698:         my $chome=&homeserver($cnum,$udom,'true');
 8699:         if (($chome eq '') || ($chome eq 'no_host')) {
 8700:             $uname = $cnum;
 8701:         } else {
 8702:             $uname = &generate_coursenum($udom,$crstype);
 8703:         }
 8704:     } else {
 8705:         $uname = &generate_coursenum($udom,$crstype);
 8706:     }
 8707:     return $uname if ($uname =~ /^error/);
 8708: # -------------------------------------------------- Check supplied server name
 8709:     if (!defined($course_server)) {
 8710:         if (defined(&domain($udom,'primary'))) {
 8711:             $course_server = &domain($udom,'primary');
 8712:         } else {
 8713:             $course_server = $env{'user.home'}; 
 8714:         }
 8715:     }
 8716:     my %host_servers =
 8717:         &Apache::lonnet::get_servers($udom,'library');
 8718:     unless ($host_servers{$course_server}) {
 8719:         return 'error: invalid home server for course: '.$course_server;
 8720:     }
 8721: # ------------------------------------------------------------- Make the course
 8722:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 8723:                       $course_server);
 8724:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 8725:     my $uhome=&homeserver($uname,$udom,'true');
 8726:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 8727: 	return 'error: no such course';
 8728:     }
 8729: # ----------------------------------------------------------------- Course made
 8730: # log existence
 8731:     my $now = time;
 8732:     my $newcourse = {
 8733:                     $udom.'_'.$uname => {
 8734:                                      description => $description,
 8735:                                      inst_code   => $inst_code,
 8736:                                      owner       => $course_owner,
 8737:                                      type        => $crstype,
 8738:                                      creator     => $env{'user.name'}.':'.
 8739:                                                     $env{'user.domain'},
 8740:                                      created     => $now,
 8741:                                      context     => $context,
 8742:                                                 },
 8743:                     };
 8744:     &courseidput($udom,$newcourse,$uhome,'notime');
 8745: # set toplevel url
 8746:     my $topurl=$url;
 8747:     unless ($nonstandard) {
 8748: # ------------------------------------------ For standard courses, make top url
 8749:         my $mapurl=&clutter($url);
 8750:         if ($mapurl eq '/res/') { $mapurl=''; }
 8751:         $env{'form.initmap'}=(<<ENDINITMAP);
 8752: <map>
 8753: <resource id="1" type="start"></resource>
 8754: <resource id="2" src="$mapurl"></resource>
 8755: <resource id="3" type="finish"></resource>
 8756: <link index="1" from="1" to="2"></link>
 8757: <link index="2" from="2" to="3"></link>
 8758: </map>
 8759: ENDINITMAP
 8760:         $topurl=&declutter(
 8761:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 8762:                           );
 8763:     }
 8764: # ----------------------------------------------------------- Write preferences
 8765:     &writecoursepref($udom.'_'.$uname,
 8766:                      ('description'              => $description,
 8767:                       'url'                      => $topurl,
 8768:                       'internal.creator'         => $env{'user.name'}.':'.
 8769:                                                     $env{'user.domain'},
 8770:                       'internal.created'         => $now,
 8771:                       'internal.creationcontext' => $context)
 8772:                     );
 8773:     return '/'.$udom.'/'.$uname;
 8774: }
 8775: 
 8776: # ------------------------------------------------------------------- Create ID
 8777: sub generate_coursenum {
 8778:     my ($udom,$crstype) = @_;
 8779:     my $domdesc = &domain($udom);
 8780:     return 'error: invalid domain' if ($domdesc eq '');
 8781:     my $first;
 8782:     if ($crstype eq 'Community') {
 8783:         $first = '0';
 8784:     } else {
 8785:         $first = int(1+rand(9)); 
 8786:     } 
 8787:     my $uname=$first.
 8788:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 8789:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
 8790:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 8791: # ----------------------------------------------- Make sure that does not exist
 8792:     my $uhome=&homeserver($uname,$udom,'true');
 8793:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
 8794:         if ($crstype eq 'Community') {
 8795:             $first = '0';
 8796:         } else {
 8797:             $first = int(1+rand(9));
 8798:         }
 8799:         $uname=$first.
 8800:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 8801:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
 8802:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 8803:         $uhome=&homeserver($uname,$udom,'true');
 8804:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
 8805:             return 'error: unable to generate unique course-ID';
 8806:         }
 8807:     }
 8808:     return $uname;
 8809: }
 8810: 
 8811: sub is_course {
 8812:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
 8813:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
 8814: 
 8815:     return unless $cdom and $cnum;
 8816: 
 8817:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
 8818:         '.');
 8819: 
 8820:     return unless(exists($courses{$cdom.'_'.$cnum}));
 8821:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
 8822: }
 8823: 
 8824: sub store_userdata {
 8825:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
 8826:     my $result;
 8827:     if ($datakey ne '') {
 8828:         if (ref($storehash) eq 'HASH') {
 8829:             if ($udom eq '' || $uname eq '') {
 8830:                 $udom = $env{'user.domain'};
 8831:                 $uname = $env{'user.name'};
 8832:             }
 8833:             my $uhome=&homeserver($uname,$udom);
 8834:             if (($uhome eq '') || ($uhome eq 'no_host')) {
 8835:                 $result = 'error: no_host';
 8836:             } else {
 8837:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
 8838:                 $storehash->{'host'} = $perlvar{'lonHostID'};
 8839: 
 8840:                 my $namevalue='';
 8841:                 foreach my $key (keys(%{$storehash})) {
 8842:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 8843:                 }
 8844:                 $namevalue=~s/\&$//;
 8845:                 unless ($namespace eq 'courserequests') {
 8846:                     $datakey = &escape($datakey);
 8847:                 }
 8848:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
 8849:                                   $namevalue,$uhome);
 8850:             }
 8851:         } else {
 8852:             $result = 'error: data to store was not a hash reference'; 
 8853:         }
 8854:     } else {
 8855:         $result= 'error: invalid requestkey'; 
 8856:     }
 8857:     return $result;
 8858: }
 8859: 
 8860: # ---------------------------------------------------------- Assign Custom Role
 8861: 
 8862: sub assigncustomrole {
 8863:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
 8864:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 8865:                        $end,$start,$deleteflag,$selfenroll,$context);
 8866: }
 8867: 
 8868: # ----------------------------------------------------------------- Revoke Role
 8869: 
 8870: sub revokerole {
 8871:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
 8872:     my $now=time;
 8873:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
 8874: }
 8875: 
 8876: # ---------------------------------------------------------- Revoke Custom Role
 8877: 
 8878: sub revokecustomrole {
 8879:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
 8880:     my $now=time;
 8881:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 8882:            $deleteflag,$selfenroll,$context);
 8883: }
 8884: 
 8885: # ------------------------------------------------------------ Disk usage
 8886: sub diskusage {
 8887:     my ($udom,$uname,$directorypath,$getpropath)=@_;
 8888:     $directorypath =~ s/\/$//;
 8889:     my $listing=&reply('du2:'.&escape($directorypath).':'
 8890:                        .&escape($getpropath).':'.&escape($uname).':'
 8891:                        .&escape($udom),homeserver($uname,$udom));
 8892:     if ($listing eq 'unknown_cmd') {
 8893:         if ($getpropath) {
 8894:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
 8895:         }
 8896:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
 8897:     }
 8898:     return $listing;
 8899: }
 8900: 
 8901: sub is_locked {
 8902:     my ($file_name, $domain, $user, $which) = @_;
 8903:     my @check;
 8904:     my $is_locked;
 8905:     push (@check,$file_name);
 8906:     my %locked = &get('file_permissions',\@check,
 8907: 		      $env{'user.domain'},$env{'user.name'});
 8908:     my ($tmp)=keys(%locked);
 8909:     if ($tmp=~/^error:/) { undef(%locked); }
 8910:     
 8911:     if (ref($locked{$file_name}) eq 'ARRAY') {
 8912:         $is_locked = 'false';
 8913:         foreach my $entry (@{$locked{$file_name}}) {
 8914:            if (ref($entry) eq 'ARRAY') {
 8915:                $is_locked = 'true';
 8916:                if (ref($which) eq 'ARRAY') {
 8917:                    push(@{$which},$entry);
 8918:                } else {
 8919:                    last;
 8920:                }
 8921:            }
 8922:        }
 8923:     } else {
 8924:         $is_locked = 'false';
 8925:     }
 8926:     return $is_locked;
 8927: }
 8928: 
 8929: sub declutter_portfile {
 8930:     my ($file) = @_;
 8931:     $file =~ s{^(/portfolio/|portfolio/)}{/};
 8932:     return $file;
 8933: }
 8934: 
 8935: # ------------------------------------------------------------- Mark as Read Only
 8936: 
 8937: sub mark_as_readonly {
 8938:     my ($domain,$user,$files,$what) = @_;
 8939:     my %current_permissions = &dump('file_permissions',$domain,$user);
 8940:     my ($tmp)=keys(%current_permissions);
 8941:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 8942:     foreach my $file (@{$files}) {
 8943: 	$file = &declutter_portfile($file);
 8944:         push(@{$current_permissions{$file}},$what);
 8945:     }
 8946:     &put('file_permissions',\%current_permissions,$domain,$user);
 8947:     return;
 8948: }
 8949: 
 8950: # ------------------------------------------------------------Save Selected Files
 8951: 
 8952: sub save_selected_files {
 8953:     my ($user, $path, @files) = @_;
 8954:     my $filename = $user."savedfiles";
 8955:     my @other_files = &files_not_in_path($user, $path);
 8956:     open (OUT, '>'.$tmpdir.$filename);
 8957:     foreach my $file (@files) {
 8958:         print (OUT $env{'form.currentpath'}.$file."\n");
 8959:     }
 8960:     foreach my $file (@other_files) {
 8961:         print (OUT $file."\n");
 8962:     }
 8963:     close (OUT);
 8964:     return 'ok';
 8965: }
 8966: 
 8967: sub clear_selected_files {
 8968:     my ($user) = @_;
 8969:     my $filename = $user."savedfiles";
 8970:     open (OUT, '>'.LONCAPA::tempdir().$filename);
 8971:     print (OUT undef);
 8972:     close (OUT);
 8973:     return ("ok");    
 8974: }
 8975: 
 8976: sub files_in_path {
 8977:     my ($user, $path) = @_;
 8978:     my $filename = $user."savedfiles";
 8979:     my %return_files;
 8980:     open (IN, '<'.LONCAPA::tempdir().$filename);
 8981:     while (my $line_in = <IN>) {
 8982:         chomp ($line_in);
 8983:         my @paths_and_file = split (m!/!, $line_in);
 8984:         my $file_part = pop (@paths_and_file);
 8985:         my $path_part = join ('/', @paths_and_file);
 8986:         $path_part.='/';
 8987:         my $path_and_file = $path_part.$file_part;
 8988:         if ($path_part eq $path) {
 8989:             $return_files{$file_part}= 'selected';
 8990:         }
 8991:     }
 8992:     close (IN);
 8993:     return (\%return_files);
 8994: }
 8995: 
 8996: # called in portfolio select mode, to show files selected NOT in current directory
 8997: sub files_not_in_path {
 8998:     my ($user, $path) = @_;
 8999:     my $filename = $user."savedfiles";
 9000:     my @return_files;
 9001:     my $path_part;
 9002:     open(IN, '<'.LONCAPA::.$filename);
 9003:     while (my $line = <IN>) {
 9004:         #ok, I know it's clunky, but I want it to work
 9005:         my @paths_and_file = split(m|/|, $line);
 9006:         my $file_part = pop(@paths_and_file);
 9007:         chomp($file_part);
 9008:         my $path_part = join('/', @paths_and_file);
 9009:         $path_part .= '/';
 9010:         my $path_and_file = $path_part.$file_part;
 9011:         if ($path_part ne $path) {
 9012:             push(@return_files, ($path_and_file));
 9013:         }
 9014:     }
 9015:     close(OUT);
 9016:     return (@return_files);
 9017: }
 9018: 
 9019: #----------------------------------------------Get portfolio file permissions
 9020: 
 9021: sub get_portfile_permissions {
 9022:     my ($domain,$user) = @_;
 9023:     my %current_permissions = &dump('file_permissions',$domain,$user);
 9024:     my ($tmp)=keys(%current_permissions);
 9025:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 9026:     return \%current_permissions;
 9027: }
 9028: 
 9029: #---------------------------------------------Get portfolio file access controls
 9030: 
 9031: sub get_access_controls {
 9032:     my ($current_permissions,$group,$file) = @_;
 9033:     my %access;
 9034:     my $real_file = $file;
 9035:     $file =~ s/\.meta$//;
 9036:     if (defined($file)) {
 9037:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
 9038:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
 9039:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
 9040:             }
 9041:         }
 9042:     } else {
 9043:         foreach my $key (keys(%{$current_permissions})) {
 9044:             if ($key =~ /\0accesscontrol$/) {
 9045:                 if (defined($group)) {
 9046:                     if ($key !~ m-^\Q$group\E/-) {
 9047:                         next;
 9048:                     }
 9049:                 }
 9050:                 my ($fullpath) = split(/\0/,$key);
 9051:                 if (ref($$current_permissions{$key}) eq 'HASH') {
 9052:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
 9053:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
 9054:                     }
 9055:                 }
 9056:             }
 9057:         }
 9058:     }
 9059:     return %access;
 9060: }
 9061: 
 9062: sub modify_access_controls {
 9063:     my ($file_name,$changes,$domain,$user)=@_;
 9064:     my ($outcome,$deloutcome);
 9065:     my %store_permissions;
 9066:     my %new_values;
 9067:     my %new_control;
 9068:     my %translation;
 9069:     my @deletions = ();
 9070:     my $now = time;
 9071:     if (exists($$changes{'activate'})) {
 9072:         if (ref($$changes{'activate'}) eq 'HASH') {
 9073:             my @newitems = sort(keys(%{$$changes{'activate'}}));
 9074:             my $numnew = scalar(@newitems);
 9075:             for (my $i=0; $i<$numnew; $i++) {
 9076:                 my $newkey = $newitems[$i];
 9077:                 my $newid = &Apache::loncommon::get_cgi_id();
 9078:                 if ($newkey =~ /^\d+:/) { 
 9079:                     $newkey =~ s/^(\d+)/$newid/;
 9080:                     $translation{$1} = $newid;
 9081:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
 9082:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
 9083:                     $translation{$1} = $newid;
 9084:                 }
 9085:                 $new_values{$file_name."\0".$newkey} = 
 9086:                                           $$changes{'activate'}{$newitems[$i]};
 9087:                 $new_control{$newkey} = $now;
 9088:             }
 9089:         }
 9090:     }
 9091:     my %todelete;
 9092:     my %changed_items;
 9093:     foreach my $action ('delete','update') {
 9094:         if (exists($$changes{$action})) {
 9095:             if (ref($$changes{$action}) eq 'HASH') {
 9096:                 foreach my $key (keys(%{$$changes{$action}})) {
 9097:                     my ($itemnum) = ($key =~ /^([^:]+):/);
 9098:                     if ($action eq 'delete') { 
 9099:                         $todelete{$itemnum} = 1;
 9100:                     } else {
 9101:                         $changed_items{$itemnum} = $key;
 9102:                     }
 9103:                 }
 9104:             }
 9105:         }
 9106:     }
 9107:     # get lock on access controls for file.
 9108:     my $lockhash = {
 9109:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
 9110:                                                        ':'.$env{'user.domain'},
 9111:                    }; 
 9112:     my $tries = 0;
 9113:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 9114:    
 9115:     while (($gotlock ne 'ok') && $tries <3) {
 9116:         $tries ++;
 9117:         sleep 1;
 9118:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 9119:     }
 9120:     if ($gotlock eq 'ok') {
 9121:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
 9122:         my ($tmp)=keys(%curr_permissions);
 9123:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
 9124:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
 9125:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
 9126:             if (ref($curr_controls) eq 'HASH') {
 9127:                 foreach my $control_item (keys(%{$curr_controls})) {
 9128:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
 9129:                     if (defined($todelete{$itemnum})) {
 9130:                         push(@deletions,$file_name."\0".$control_item);
 9131:                     } else {
 9132:                         if (defined($changed_items{$itemnum})) {
 9133:                             $new_control{$changed_items{$itemnum}} = $now;
 9134:                             push(@deletions,$file_name."\0".$control_item);
 9135:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
 9136:                         } else {
 9137:                             $new_control{$control_item} = $$curr_controls{$control_item};
 9138:                         }
 9139:                     }
 9140:                 }
 9141:             }
 9142:         }
 9143:         my ($group);
 9144:         if (&is_course($domain,$user)) {
 9145:             ($group,my $file) = split(/\//,$file_name,2);
 9146:         }
 9147:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
 9148:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
 9149:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
 9150:         #  remove lock
 9151:         my @del_lock = ($file_name."\0".'locked_access_records');
 9152:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
 9153:         my $sqlresult =
 9154:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
 9155:                                     $group);
 9156:     } else {
 9157:         $outcome = "error: could not obtain lockfile\n";  
 9158:     }
 9159:     return ($outcome,$deloutcome,\%new_values,\%translation);
 9160: }
 9161: 
 9162: sub make_public_indefinitely {
 9163:     my ($requrl) = @_;
 9164:     my $now = time;
 9165:     my $action = 'activate';
 9166:     my $aclnum = 0;
 9167:     if (&is_portfolio_url($requrl)) {
 9168:         my (undef,$udom,$unum,$file_name,$group) =
 9169:             &parse_portfolio_url($requrl);
 9170:         my $current_perms = &get_portfile_permissions($udom,$unum);
 9171:         my %access_controls = &get_access_controls($current_perms,
 9172:                                                    $group,$file_name);
 9173:         foreach my $key (keys(%{$access_controls{$file_name}})) {
 9174:             my ($num,$scope,$end,$start) = 
 9175:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 9176:             if ($scope eq 'public') {
 9177:                 if ($start <= $now && $end == 0) {
 9178:                     $action = 'none';
 9179:                 } else {
 9180:                     $action = 'update';
 9181:                     $aclnum = $num;
 9182:                 }
 9183:                 last;
 9184:             }
 9185:         }
 9186:         if ($action eq 'none') {
 9187:              return 'ok';
 9188:         } else {
 9189:             my %changes;
 9190:             my $newend = 0;
 9191:             my $newstart = $now;
 9192:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
 9193:             $changes{$action}{$newkey} = {
 9194:                 type => 'public',
 9195:                 time => {
 9196:                     start => $newstart,
 9197:                     end   => $newend,
 9198:                 },
 9199:             };
 9200:             my ($outcome,$deloutcome,$new_values,$translation) =
 9201:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
 9202:             return $outcome;
 9203:         }
 9204:     } else {
 9205:         return 'invalid';
 9206:     }
 9207: }
 9208: 
 9209: #------------------------------------------------------Get Marked as Read Only
 9210: 
 9211: sub get_marked_as_readonly {
 9212:     my ($domain,$user,$what,$group) = @_;
 9213:     my $current_permissions = &get_portfile_permissions($domain,$user);
 9214:     my @readonly_files;
 9215:     my $cmp1=$what;
 9216:     if (ref($what)) { $cmp1=join('',@{$what}) };
 9217:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 9218:         if (defined($group)) {
 9219:             if ($file_name !~ m-^\Q$group\E/-) {
 9220:                 next;
 9221:             }
 9222:         }
 9223:         if (ref($value) eq "ARRAY"){
 9224:             foreach my $stored_what (@{$value}) {
 9225:                 my $cmp2=$stored_what;
 9226:                 if (ref($stored_what) eq 'ARRAY') {
 9227:                     $cmp2=join('',@{$stored_what});
 9228:                 }
 9229:                 if ($cmp1 eq $cmp2) {
 9230:                     push(@readonly_files, $file_name);
 9231:                     last;
 9232:                 } elsif (!defined($what)) {
 9233:                     push(@readonly_files, $file_name);
 9234:                     last;
 9235:                 }
 9236:             }
 9237:         }
 9238:     }
 9239:     return @readonly_files;
 9240: }
 9241: #-----------------------------------------------------------Get Marked as Read Only Hash
 9242: 
 9243: sub get_marked_as_readonly_hash {
 9244:     my ($current_permissions,$group,$what) = @_;
 9245:     my %readonly_files;
 9246:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 9247:         if (defined($group)) {
 9248:             if ($file_name !~ m-^\Q$group\E/-) {
 9249:                 next;
 9250:             }
 9251:         }
 9252:         if (ref($value) eq "ARRAY"){
 9253:             foreach my $stored_what (@{$value}) {
 9254:                 if (ref($stored_what) eq 'ARRAY') {
 9255:                     foreach my $lock_descriptor(@{$stored_what}) {
 9256:                         if ($lock_descriptor eq 'graded') {
 9257:                             $readonly_files{$file_name} = 'graded';
 9258:                         } elsif ($lock_descriptor eq 'handback') {
 9259:                             $readonly_files{$file_name} = 'handback';
 9260:                         } else {
 9261:                             if (!exists($readonly_files{$file_name})) {
 9262:                                 $readonly_files{$file_name} = 'locked';
 9263:                             }
 9264:                         }
 9265:                     }
 9266:                 } 
 9267:             }
 9268:         } 
 9269:     }
 9270:     return %readonly_files;
 9271: }
 9272: # ------------------------------------------------------------ Unmark as Read Only
 9273: 
 9274: sub unmark_as_readonly {
 9275:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
 9276:     # for portfolio submissions, $what contains [$symb,$crsid] 
 9277:     my ($domain,$user,$what,$file_name,$group) = @_;
 9278:     $file_name = &declutter_portfile($file_name);
 9279:     my $symb_crs = $what;
 9280:     if (ref($what)) { $symb_crs=join('',@$what); }
 9281:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
 9282:     my ($tmp)=keys(%current_permissions);
 9283:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 9284:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
 9285:     foreach my $file (@readonly_files) {
 9286: 	my $clean_file = &declutter_portfile($file);
 9287: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
 9288: 	my $current_locks = $current_permissions{$file};
 9289:         my @new_locks;
 9290:         my @del_keys;
 9291:         if (ref($current_locks) eq "ARRAY"){
 9292:             foreach my $locker (@{$current_locks}) {
 9293:                 my $compare=$locker;
 9294:                 if (ref($locker) eq 'ARRAY') {
 9295:                     $compare=join('',@{$locker});
 9296:                     if ($compare ne $symb_crs) {
 9297:                         push(@new_locks, $locker);
 9298:                     }
 9299:                 }
 9300:             }
 9301:             if (scalar(@new_locks) > 0) {
 9302:                 $current_permissions{$file} = \@new_locks;
 9303:             } else {
 9304:                 push(@del_keys, $file);
 9305:                 &del('file_permissions',\@del_keys, $domain, $user);
 9306:                 delete($current_permissions{$file});
 9307:             }
 9308:         }
 9309:     }
 9310:     &put('file_permissions',\%current_permissions,$domain,$user);
 9311:     return;
 9312: }
 9313: 
 9314: # ------------------------------------------------------------ Directory lister
 9315: 
 9316: sub dirlist {
 9317:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
 9318:     $uri=~s/^\///;
 9319:     $uri=~s/\/$//;
 9320:     my ($udom, $uname);
 9321:     if ($getuserdir) {
 9322:         $udom = $userdomain;
 9323:         $uname = $username;
 9324:     } else {
 9325:         (undef,$udom,$uname)=split(/\//,$uri);
 9326:         if(defined($userdomain)) {
 9327:             $udom = $userdomain;
 9328:         }
 9329:         if(defined($username)) {
 9330:             $uname = $username;
 9331:         }
 9332:     }
 9333:     my ($dirRoot,$listing,@listing_results);
 9334: 
 9335:     $dirRoot = $perlvar{'lonDocRoot'};
 9336:     if (defined($getpropath)) {
 9337:         $dirRoot = &propath($udom,$uname);
 9338:         $dirRoot =~ s/\/$//;
 9339:     } elsif (defined($getuserdir)) {
 9340:         my $subdir=$uname.'__';
 9341:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 9342:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
 9343:                    ."/$udom/$subdir/$uname";
 9344:     } elsif (defined($alternateRoot)) {
 9345:         $dirRoot = $alternateRoot;
 9346:     }
 9347: 
 9348:     if($udom) {
 9349:         if($uname) {
 9350:             my $uhome = &homeserver($uname,$udom);
 9351:             if ($uhome eq 'no_host') {
 9352:                 return ([],'no_host');
 9353:             }
 9354:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
 9355:                               .$getuserdir.':'.&escape($dirRoot)
 9356:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
 9357:             if ($listing eq 'unknown_cmd') {
 9358:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
 9359:             } else {
 9360:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 9361:             }
 9362:             if ($listing eq 'unknown_cmd') {
 9363:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
 9364:                 @listing_results = split(/:/,$listing);
 9365:             } else {
 9366:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 9367:             }
 9368:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
 9369:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
 9370:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
 9371:                 return ([],$listing);
 9372:             } else {
 9373:                 return (\@listing_results);
 9374:             }
 9375:         } elsif(!$alternateRoot) {
 9376:             my (%allusers,%listerror);
 9377: 	    my %servers = &get_servers($udom,'library');
 9378:  	    foreach my $tryserver (keys(%servers)) {
 9379:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
 9380:                                   &escape($udom),$tryserver);
 9381:                 if ($listing eq 'unknown_cmd') {
 9382: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
 9383: 				      $udom, $tryserver);
 9384:                 } else {
 9385:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
 9386:                 }
 9387: 		if ($listing eq 'unknown_cmd') {
 9388: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 9389: 				      $udom, $tryserver);
 9390: 		    @listing_results = split(/:/,$listing);
 9391: 		} else {
 9392: 		    @listing_results =
 9393: 			map { &unescape($_); } split(/:/,$listing);
 9394: 		}
 9395:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
 9396:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
 9397:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
 9398:                     $listerror{$tryserver} = $listing;
 9399:                 } else {
 9400: 		    foreach my $line (@listing_results) {
 9401: 			my ($entry) = split(/&/,$line,2);
 9402: 			$allusers{$entry} = 1;
 9403: 		    }
 9404: 		}
 9405:             }
 9406:             my @alluserslist=();
 9407:             foreach my $user (sort(keys(%allusers))) {
 9408:                 push(@alluserslist,$user.'&user');
 9409:             }
 9410:             return (\@alluserslist);
 9411:         } else {
 9412:             return ([],'missing username');
 9413:         }
 9414:     } elsif(!defined($getpropath)) {
 9415:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
 9416:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
 9417:         return (\@all_domains);
 9418:     } else {
 9419:         return ([],'missing domain');
 9420:     }
 9421: }
 9422: 
 9423: # --------------------------------------------- GetFileTimestamp
 9424: # This function utilizes dirlist and returns the date stamp for
 9425: # when it was last modified.  It will also return an error of -1
 9426: # if an error occurs
 9427: 
 9428: sub GetFileTimestamp {
 9429:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
 9430:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
 9431:     $studentName   = &LONCAPA::clean_username($studentName);
 9432:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
 9433:                                     undef,$getuserdir);
 9434:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
 9435:         return -1;
 9436:     }
 9437:     if (ref($fileref) eq 'ARRAY') {
 9438:         my @stats = split('&',$fileref->[0]);
 9439:         # @stats contains first the filename, then the stat output
 9440:         return $stats[10]; # so this is 10 instead of 9.
 9441:     } else {
 9442:         return -1;
 9443:     }
 9444: }
 9445: 
 9446: sub stat_file {
 9447:     my ($uri) = @_;
 9448:     $uri = &clutter_with_no_wrapper($uri);
 9449: 
 9450:     my ($udom,$uname,$file);
 9451:     if ($uri =~ m-^/(uploaded|editupload)/-) {
 9452: 	($udom,$uname,$file) =
 9453: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
 9454: 	$file = 'userfiles/'.$file;
 9455:     }
 9456:     if ($uri =~ m-^/res/-) {
 9457: 	($udom,$uname) = 
 9458: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
 9459: 	$file = $uri;
 9460:     }
 9461: 
 9462:     if (!$udom || !$uname || !$file) {
 9463: 	# unable to handle the uri
 9464: 	return ();
 9465:     }
 9466:     my $getpropath;
 9467:     if ($file =~ /^userfiles\//) {
 9468:         $getpropath = 1;
 9469:     }
 9470:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
 9471:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
 9472:         return ();
 9473:     } else {
 9474:         if (ref($listref) eq 'ARRAY') {
 9475:             my @stats = split('&',$listref->[0]);
 9476: 	    shift(@stats); #filename is first
 9477: 	    return @stats;
 9478:         }
 9479:     }
 9480:     return ();
 9481: }
 9482: 
 9483: # -------------------------------------------------------- Value of a Condition
 9484: 
 9485: # gets the value of a specific preevaluated condition
 9486: #    stored in the string  $env{user.state.<cid>}
 9487: # or looks up a condition reference in the bighash and if if hasn't
 9488: # already been evaluated recurses into docondval to get the value of
 9489: # the condition, then memoizing it to 
 9490: #   $env{user.state.<cid>.<condition>}
 9491: sub directcondval {
 9492:     my $number=shift;
 9493:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
 9494: 	&Apache::lonuserstate::evalstate();
 9495:     }
 9496:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
 9497: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
 9498:     } elsif ($number =~ /^_/) {
 9499: 	my $sub_condition;
 9500: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 9501: 		&GDBM_READER(),0640)) {
 9502: 	    $sub_condition=$bighash{'conditions'.$number};
 9503: 	    untie(%bighash);
 9504: 	}
 9505: 	my $value = &docondval($sub_condition);
 9506: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
 9507: 	return $value;
 9508:     }
 9509:     if ($env{'user.state.'.$env{'request.course.id'}}) {
 9510:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
 9511:     } else {
 9512:        return 2;
 9513:     }
 9514: }
 9515: 
 9516: # get the collection of conditions for this resource
 9517: sub condval {
 9518:     my $condidx=shift;
 9519:     my $allpathcond='';
 9520:     foreach my $cond (split(/\|/,$condidx)) {
 9521: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
 9522: 	    $allpathcond.=
 9523: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
 9524: 	}
 9525:     }
 9526:     $allpathcond=~s/\|$//;
 9527:     return &docondval($allpathcond);
 9528: }
 9529: 
 9530: #evaluates an expression of conditions
 9531: sub docondval {
 9532:     my ($allpathcond) = @_;
 9533:     my $result=0;
 9534:     if ($env{'request.course.id'}
 9535: 	&& defined($allpathcond)) {
 9536: 	my $operand='|';
 9537: 	my @stack;
 9538: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
 9539: 	    if ($chunk eq '(') {
 9540: 		push @stack,($operand,$result);
 9541: 	    } elsif ($chunk eq ')') {
 9542: 		my $before=pop @stack;
 9543: 		if (pop @stack eq '&') {
 9544: 		    $result=$result>$before?$before:$result;
 9545: 		} else {
 9546: 		    $result=$result>$before?$result:$before;
 9547: 		}
 9548: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
 9549: 		$operand=$chunk;
 9550: 	    } else {
 9551: 		my $new=directcondval($chunk);
 9552: 		if ($operand eq '&') {
 9553: 		    $result=$result>$new?$new:$result;
 9554: 		} else {
 9555: 		    $result=$result>$new?$result:$new;
 9556: 		}
 9557: 	    }
 9558: 	}
 9559:     }
 9560:     return $result;
 9561: }
 9562: 
 9563: # ---------------------------------------------------- Devalidate courseresdata
 9564: 
 9565: sub devalidatecourseresdata {
 9566:     my ($coursenum,$coursedomain)=@_;
 9567:     my $hashid=$coursenum.':'.$coursedomain;
 9568:     &devalidate_cache_new('courseres',$hashid);
 9569: }
 9570: 
 9571: 
 9572: # --------------------------------------------------- Course Resourcedata Query
 9573: #
 9574: #  Parameters:
 9575: #      $coursenum    - Number of the course.
 9576: #      $coursedomain - Domain at which the course was created.
 9577: #  Returns:
 9578: #     A hash of the course parameters along (I think) with timestamps
 9579: #     and version info.
 9580: 
 9581: sub get_courseresdata {
 9582:     my ($coursenum,$coursedomain)=@_;
 9583:     my $coursehom=&homeserver($coursenum,$coursedomain);
 9584:     my $hashid=$coursenum.':'.$coursedomain;
 9585:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
 9586:     my %dumpreply;
 9587:     unless (defined($cached)) {
 9588: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 9589: 	$result=\%dumpreply;
 9590: 	my ($tmp) = keys(%dumpreply);
 9591: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 9592: 	    &do_cache_new('courseres',$hashid,$result,600);
 9593: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 9594: 	    return $tmp;
 9595: 	} elsif ($tmp =~ /^(error)/) {
 9596: 	    $result=undef;
 9597: 	    &do_cache_new('courseres',$hashid,$result,600);
 9598: 	}
 9599:     }
 9600:     return $result;
 9601: }
 9602: 
 9603: sub devalidateuserresdata {
 9604:     my ($uname,$udom)=@_;
 9605:     my $hashid="$udom:$uname";
 9606:     &devalidate_cache_new('userres',$hashid);
 9607: }
 9608: 
 9609: sub get_userresdata {
 9610:     my ($uname,$udom)=@_;
 9611:     #most student don\'t have any data set, check if there is some data
 9612:     if (&EXT_cache_status($udom,$uname)) { return undef; }
 9613: 
 9614:     my $hashid="$udom:$uname";
 9615:     my ($result,$cached)=&is_cached_new('userres',$hashid);
 9616:     if (!defined($cached)) {
 9617: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
 9618: 	$result=\%resourcedata;
 9619: 	&do_cache_new('userres',$hashid,$result,600);
 9620:     }
 9621:     my ($tmp)=keys(%$result);
 9622:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
 9623: 	return $result;
 9624:     }
 9625:     #error 2 occurs when the .db doesn't exist
 9626:     if ($tmp!~/error: 2 /) {
 9627: 	&logthis("<font color=\"blue\">WARNING:".
 9628: 		 " Trying to get resource data for ".
 9629: 		 $uname." at ".$udom.": ".
 9630: 		 $tmp."</font>");
 9631:     } elsif ($tmp=~/error: 2 /) {
 9632: 	#&EXT_cache_set($udom,$uname);
 9633: 	&do_cache_new('userres',$hashid,undef,600);
 9634: 	undef($tmp); # not really an error so don't send it back
 9635:     }
 9636:     return $tmp;
 9637: }
 9638: #----------------------------------------------- resdata - return resource data
 9639: #  Purpose:
 9640: #    Return resource data for either users or for a course.
 9641: #  Parameters:
 9642: #     $name      - Course/user name.
 9643: #     $domain    - Name of the domain the user/course is registered on.
 9644: #     $type      - Type of thing $name is (must be 'course' or 'user'
 9645: #     @which     - Array of names of resources desired.
 9646: #  Returns:
 9647: #     The value of the first reasource in @which that is found in the
 9648: #     resource hash.
 9649: #  Exceptional Conditions:
 9650: #     If the $type passed in is not valid (not the string 'course' or 
 9651: #     'user', an undefined  reference is returned.
 9652: #     If none of the resources are found, an undef is returned
 9653: sub resdata {
 9654:     my ($name,$domain,$type,@which)=@_;
 9655:     my $result;
 9656:     if ($type eq 'course') {
 9657: 	$result=&get_courseresdata($name,$domain);
 9658:     } elsif ($type eq 'user') {
 9659: 	$result=&get_userresdata($name,$domain);
 9660:     }
 9661:     if (!ref($result)) { return $result; }    
 9662:     foreach my $item (@which) {
 9663: 	if (defined($result->{$item->[0]})) {
 9664: 	    return [$result->{$item->[0]},$item->[1]];
 9665: 	}
 9666:     }
 9667:     return undef;
 9668: }
 9669: 
 9670: sub get_numsuppfiles {
 9671:     my ($cnum,$cdom,$ignorecache)=@_;
 9672:     my $hashid=$cnum.':'.$cdom;
 9673:     my ($suppcount,$cached);
 9674:     unless ($ignorecache) {
 9675:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
 9676:     }
 9677:     unless (defined($cached)) {
 9678:         my $chome=&homeserver($cnum,$cdom);
 9679:         unless ($chome eq 'no_host') {
 9680:             ($suppcount,my $errors) = (0,0);
 9681:             my $suppmap = 'supplemental.sequence';
 9682:             ($suppcount,$errors) = 
 9683:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
 9684:         }
 9685:         &do_cache_new('suppcount',$hashid,$suppcount,600);
 9686:     }
 9687:     return $suppcount;
 9688: }
 9689: 
 9690: #
 9691: # EXT resource caching routines
 9692: #
 9693: 
 9694: sub clear_EXT_cache_status {
 9695:     &delenv('cache.EXT.');
 9696: }
 9697: 
 9698: sub EXT_cache_status {
 9699:     my ($target_domain,$target_user) = @_;
 9700:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 9701:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
 9702:         # We know already the user has no data
 9703:         return 1;
 9704:     } else {
 9705:         return 0;
 9706:     }
 9707: }
 9708: 
 9709: sub EXT_cache_set {
 9710:     my ($target_domain,$target_user) = @_;
 9711:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 9712:     #&appenv({$cachename => time});
 9713: }
 9714: 
 9715: # --------------------------------------------------------- Value of a Variable
 9716: sub EXT {
 9717: 
 9718:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
 9719:     unless ($varname) { return ''; }
 9720:     #get real user name/domain, courseid and symb
 9721:     my $courseid;
 9722:     my $publicuser;
 9723:     if ($symbparm) {
 9724: 	$symbparm=&get_symb_from_alias($symbparm);
 9725:     }
 9726:     if (!($uname && $udom)) {
 9727:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
 9728:       if (!$symbparm) {	$symbparm=$cursymb; }
 9729:     } else {
 9730: 	$courseid=$env{'request.course.id'};
 9731:     }
 9732:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 9733:     my $rest;
 9734:     if (defined($therest[0])) {
 9735:        $rest=join('.',@therest);
 9736:     } else {
 9737:        $rest='';
 9738:     }
 9739: 
 9740:     my $qualifierrest=$qualifier;
 9741:     if ($rest) { $qualifierrest.='.'.$rest; }
 9742:     my $spacequalifierrest=$space;
 9743:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 9744:     if ($realm eq 'user') {
 9745: # --------------------------------------------------------------- user.resource
 9746: 	if ($space eq 'resource') {
 9747: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
 9748: 		  || defined($Apache::lonhomework::parsing_a_task))
 9749: 		 &&
 9750: 		 ($symbparm eq &symbread()) ) {	
 9751: 		# if we are in the middle of processing the resource the
 9752: 		# get the value we are planning on committing
 9753:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
 9754:                     return $Apache::lonhomework::results{$qualifierrest};
 9755:                 } else {
 9756:                     return $Apache::lonhomework::history{$qualifierrest};
 9757:                 }
 9758: 	    } else {
 9759: 		my %restored;
 9760: 		if ($publicuser || $env{'request.state'} eq 'construct') {
 9761: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
 9762: 		} else {
 9763: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
 9764: 		}
 9765: 		return $restored{$qualifierrest};
 9766: 	    }
 9767: # ----------------------------------------------------------------- user.access
 9768:         } elsif ($space eq 'access') {
 9769: 	    # FIXME - not supporting calls for a specific user
 9770:             return &allowed($qualifier,$rest);
 9771: # ------------------------------------------ user.preferences, user.environment
 9772:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 9773: 	    if (($uname eq $env{'user.name'}) &&
 9774: 		($udom eq $env{'user.domain'})) {
 9775: 		return $env{join('.',('environment',$qualifierrest))};
 9776: 	    } else {
 9777: 		my %returnhash;
 9778: 		if (!$publicuser) {
 9779: 		    %returnhash=&userenvironment($udom,$uname,
 9780: 						 $qualifierrest);
 9781: 		}
 9782: 		return $returnhash{$qualifierrest};
 9783: 	    }
 9784: # ----------------------------------------------------------------- user.course
 9785:         } elsif ($space eq 'course') {
 9786: 	    # FIXME - not supporting calls for a specific user
 9787:             return $env{join('.',('request.course',$qualifier))};
 9788: # ------------------------------------------------------------------- user.role
 9789:         } elsif ($space eq 'role') {
 9790: 	    # FIXME - not supporting calls for a specific user
 9791:             my ($role,$where)=split(/\./,$env{'request.role'});
 9792:             if ($qualifier eq 'value') {
 9793: 		return $role;
 9794:             } elsif ($qualifier eq 'extent') {
 9795:                 return $where;
 9796:             }
 9797: # ----------------------------------------------------------------- user.domain
 9798:         } elsif ($space eq 'domain') {
 9799:             return $udom;
 9800: # ------------------------------------------------------------------- user.name
 9801:         } elsif ($space eq 'name') {
 9802:             return $uname;
 9803: # ---------------------------------------------------- Any other user namespace
 9804:         } else {
 9805: 	    my %reply;
 9806: 	    if (!$publicuser) {
 9807: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
 9808: 	    }
 9809: 	    return $reply{$qualifierrest};
 9810:         }
 9811:     } elsif ($realm eq 'query') {
 9812: # ---------------------------------------------- pull stuff out of query string
 9813:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 9814: 						[$spacequalifierrest]);
 9815: 	return $env{'form.'.$spacequalifierrest}; 
 9816:    } elsif ($realm eq 'request') {
 9817: # ------------------------------------------------------------- request.browser
 9818:         if ($space eq 'browser') {
 9819:             return $env{'browser.'.$qualifier};
 9820: # ------------------------------------------------------------ request.filename
 9821:         } else {
 9822:             return $env{'request.'.$spacequalifierrest};
 9823:         }
 9824:     } elsif ($realm eq 'course') {
 9825: # ---------------------------------------------------------- course.description
 9826:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
 9827:     } elsif ($realm eq 'resource') {
 9828: 
 9829: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
 9830: 	    if (!$symbparm) { $symbparm=&symbread(); }
 9831: 	}
 9832: 
 9833:         if ($qualifier eq '') {
 9834: 	    if ($space eq 'title') {
 9835: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
 9836: 	        return &gettitle($symbparm);
 9837: 	    }
 9838: 	
 9839: 	    if ($space eq 'map') {
 9840: 	        my ($map) = &decode_symb($symbparm);
 9841: 	        return &symbread($map);
 9842: 	    }
 9843:             if ($space eq 'maptitle') {
 9844:                 my ($map) = &decode_symb($symbparm);
 9845:                 return &gettitle($map);
 9846:             }
 9847: 	    if ($space eq 'filename') {
 9848: 	        if ($symbparm) {
 9849: 		    return &clutter((&decode_symb($symbparm))[2]);
 9850: 	        }
 9851: 	        return &hreflocation('',$env{'request.filename'});
 9852: 	    }
 9853: 
 9854:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
 9855:                 if ($space eq 'visibleparts') {
 9856:                     my $navmap = Apache::lonnavmaps::navmap->new();
 9857:                     my $item;
 9858:                     if (ref($navmap)) {
 9859:                         my $res = $navmap->getBySymb($symbparm);
 9860:                         my $parts = $res->parts();
 9861:                         if (ref($parts) eq 'ARRAY') {
 9862:                             $item = join(',',@{$parts});
 9863:                         }
 9864:                         undef($navmap);
 9865:                     }
 9866:                     return $item;
 9867:                 }
 9868:             }
 9869:         }
 9870: 
 9871: 	my ($section, $group, @groups);
 9872: 	my ($courselevelm,$courselevel);
 9873:         if (($courseid eq '') && ($cid)) {
 9874:             $courseid = $cid;
 9875:         }
 9876: 	if (($symbparm && $courseid) && 
 9877: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
 9878: 
 9879: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
 9880: 
 9881: # ----------------------------------------------------- Cascading lookup scheme
 9882: 	    my $symbp=$symbparm;
 9883: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
 9884: 
 9885: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
 9886: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
 9887: 
 9888: 	    if (($env{'user.name'} eq $uname) &&
 9889: 		($env{'user.domain'} eq $udom)) {
 9890: 		$section=$env{'request.course.sec'};
 9891:                 @groups = split(/:/,$env{'request.course.groups'});  
 9892:                 @groups=&sort_course_groups($courseid,@groups); 
 9893: 	    } else {
 9894: 		if (! defined($usection)) {
 9895: 		    $section=&getsection($udom,$uname,$courseid);
 9896: 		} else {
 9897: 		    $section = $usection;
 9898: 		}
 9899:                 @groups = &get_users_groups($udom,$uname,$courseid);
 9900: 	    }
 9901: 
 9902: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
 9903: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
 9904: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
 9905: 
 9906: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
 9907: 	    my $courselevelr=$courseid.'.'.$symbparm;
 9908: 	    $courselevelm=$courseid.'.'.$mapparm;
 9909: 
 9910: # ----------------------------------------------------------- first, check user
 9911: 
 9912: 	    my $userreply=&resdata($uname,$udom,'user',
 9913: 				       ([$courselevelr,'resource'],
 9914: 					[$courselevelm,'map'     ],
 9915: 					[$courselevel, 'course'  ]));
 9916: 	    if (defined($userreply)) { return &get_reply($userreply); }
 9917: 
 9918: # ------------------------------------------------ second, check some of course
 9919:             my $coursereply;
 9920:             if (@groups > 0) {
 9921:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
 9922:                                        $mapparm,$spacequalifierrest);
 9923:                 if (defined($coursereply)) { return &get_reply($coursereply); }
 9924:             }
 9925: 
 9926: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 9927: 				  $env{'course.'.$courseid.'.domain'},
 9928: 				  'course',
 9929: 				  ([$seclevelr,   'resource'],
 9930: 				   [$seclevelm,   'map'     ],
 9931: 				   [$seclevel,    'course'  ],
 9932: 				   [$courselevelr,'resource']));
 9933: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 9934: 
 9935: # ------------------------------------------------------ third, check map parms
 9936: 	    my %parmhash=();
 9937: 	    my $thisparm='';
 9938: 	    if (tie(%parmhash,'GDBM_File',
 9939: 		    $env{'request.course.fn'}.'_parms.db',
 9940: 		    &GDBM_READER(),0640)) {
 9941: 		$thisparm=$parmhash{$symbparm};
 9942: 		untie(%parmhash);
 9943: 	    }
 9944: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
 9945: 	}
 9946: # ------------------------------------------ fourth, look in resource metadata
 9947: 
 9948: 	$spacequalifierrest=~s/\./\_/;
 9949: 	my $filename;
 9950: 	if (!$symbparm) { $symbparm=&symbread(); }
 9951: 	if ($symbparm) {
 9952: 	    $filename=(&decode_symb($symbparm))[2];
 9953: 	} else {
 9954: 	    $filename=$env{'request.filename'};
 9955: 	}
 9956: 	my $metadata=&metadata($filename,$spacequalifierrest);
 9957: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 9958: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
 9959: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 9960: 
 9961: # ---------------------------------------------- fourth, look in rest of course
 9962: 	if ($symbparm && defined($courseid) && 
 9963: 	    $courseid eq $env{'request.course.id'}) {
 9964: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 9965: 				     $env{'course.'.$courseid.'.domain'},
 9966: 				     'course',
 9967: 				     ([$courselevelm,'map'   ],
 9968: 				      [$courselevel, 'course']));
 9969: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 9970: 	}
 9971: # ------------------------------------------------------------------ Cascade up
 9972: 	unless ($space eq '0') {
 9973: 	    my @parts=split(/_/,$space);
 9974: 	    my $id=pop(@parts);
 9975: 	    my $part=join('_',@parts);
 9976: 	    if ($part eq '') { $part='0'; }
 9977: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
 9978: 				 $symbparm,$udom,$uname,$section,1);
 9979: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
 9980: 	}
 9981: 	if ($recurse) { return undef; }
 9982: 	my $pack_def=&packages_tab_default($filename,$varname);
 9983: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
 9984: # ---------------------------------------------------- Any other user namespace
 9985:     } elsif ($realm eq 'environment') {
 9986: # ----------------------------------------------------------------- environment
 9987: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
 9988: 	    return $env{'environment.'.$spacequalifierrest};
 9989: 	} else {
 9990: 	    if ($uname eq 'anonymous' && $udom eq '') {
 9991: 		return '';
 9992: 	    }
 9993: 	    my %returnhash=&userenvironment($udom,$uname,
 9994: 					    $spacequalifierrest);
 9995: 	    return $returnhash{$spacequalifierrest};
 9996: 	}
 9997:     } elsif ($realm eq 'system') {
 9998: # ----------------------------------------------------------------- system.time
 9999: 	if ($space eq 'time') {
10000: 	    return time;
10001:         }
10002:     } elsif ($realm eq 'server') {
10003: # ----------------------------------------------------------------- system.time
10004: 	if ($space eq 'name') {
10005: 	    return $ENV{'SERVER_NAME'};
10006:         }
10007:     }
10008:     return '';
10009: }
10010: 
10011: sub get_reply {
10012:     my ($reply_value) = @_;
10013:     if (ref($reply_value) eq 'ARRAY') {
10014:         if (wantarray) {
10015: 	    return @$reply_value;
10016:         }
10017:         return $reply_value->[0];
10018:     } else {
10019:         return $reply_value;
10020:     }
10021: }
10022: 
10023: sub check_group_parms {
10024:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
10025:     my @groupitems = ();
10026:     my $resultitem;
10027:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
10028:     foreach my $group (@{$groups}) {
10029:         foreach my $level (@levels) {
10030:              my $item = $courseid.'.['.$group.'].'.$level->[0];
10031:              push(@groupitems,[$item,$level->[1]]);
10032:         }
10033:     }
10034:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
10035:                             $env{'course.'.$courseid.'.domain'},
10036:                                      'course',@groupitems);
10037:     return $coursereply;
10038: }
10039: 
10040: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
10041:     my ($courseid,@groups) = @_;
10042:     @groups = sort(@groups);
10043:     return @groups;
10044: }
10045: 
10046: sub packages_tab_default {
10047:     my ($uri,$varname)=@_;
10048:     my (undef,$part,$name)=split(/\./,$varname);
10049: 
10050:     my (@extension,@specifics,$do_default);
10051:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
10052: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
10053: 	if ($pack_type eq 'default') {
10054: 	    $do_default=1;
10055: 	} elsif ($pack_type eq 'extension') {
10056: 	    push(@extension,[$package,$pack_type,$pack_part]);
10057: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
10058: 	    # only look at packages defaults for packages that this id is
10059: 	    push(@specifics,[$package,$pack_type,$pack_part]);
10060: 	}
10061:     }
10062:     # first look for a package that matches the requested part id
10063:     foreach my $package (@specifics) {
10064: 	my (undef,$pack_type,$pack_part)=@{$package};
10065: 	next if ($pack_part ne $part);
10066: 	if (defined($packagetab{"$pack_type&$name&default"})) {
10067: 	    return $packagetab{"$pack_type&$name&default"};
10068: 	}
10069:     }
10070:     # look for any possible matching non extension_ package
10071:     foreach my $package (@specifics) {
10072: 	my (undef,$pack_type,$pack_part)=@{$package};
10073: 	if (defined($packagetab{"$pack_type&$name&default"})) {
10074: 	    return $packagetab{"$pack_type&$name&default"};
10075: 	}
10076: 	if ($pack_type eq 'part') { $pack_part='0'; }
10077: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
10078: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
10079: 	}
10080:     }
10081:     # look for any posible extension_ match
10082:     foreach my $package (@extension) {
10083: 	my ($package,$pack_type)=@{$package};
10084: 	if (defined($packagetab{"$pack_type&$name&default"})) {
10085: 	    return $packagetab{"$pack_type&$name&default"};
10086: 	}
10087: 	if (defined($packagetab{$package."&$name&default"})) {
10088: 	    return $packagetab{$package."&$name&default"};
10089: 	}
10090:     }
10091:     # look for a global default setting
10092:     if ($do_default && defined($packagetab{"default&$name&default"})) {
10093: 	return $packagetab{"default&$name&default"};
10094:     }
10095:     return undef;
10096: }
10097: 
10098: sub add_prefix_and_part {
10099:     my ($prefix,$part)=@_;
10100:     my $keyroot;
10101:     if (defined($prefix) && $prefix !~ /^__/) {
10102: 	# prefix that has a part already
10103: 	$keyroot=$prefix;
10104:     } elsif (defined($prefix)) {
10105: 	# prefix that is missing a part
10106: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
10107:     } else {
10108: 	# no prefix at all
10109: 	if (defined($part)) { $keyroot='_'.$part; }
10110:     }
10111:     return $keyroot;
10112: }
10113: 
10114: # ---------------------------------------------------------------- Get metadata
10115: 
10116: my %metaentry;
10117: my %importedpartids;
10118: sub metadata {
10119:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
10120:     $uri=&declutter($uri);
10121:     # if it is a non metadata possible uri return quickly
10122:     if (($uri eq '') || 
10123: 	(($uri =~ m|^/*adm/|) && 
10124: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
10125:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
10126: 	return undef;
10127:     }
10128:     if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) 
10129: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
10130: 	return undef;
10131:     }
10132:     my $filename=$uri;
10133:     $uri=~s/\.meta$//;
10134: #
10135: # Is the metadata already cached?
10136: # Look at timestamp of caching
10137: # Everything is cached by the main uri, libraries are never directly cached
10138: #
10139:     if (!defined($liburi)) {
10140: 	my ($result,$cached)=&is_cached_new('meta',$uri);
10141: 	if (defined($cached)) { return $result->{':'.$what}; }
10142:     }
10143:     {
10144: # Imported parts would go here
10145:         my %importedids=();
10146:         my @origfileimportpartids=();
10147:         my $importedparts=0;
10148: #
10149: # Is this a recursive call for a library?
10150: #
10151: #	if (! exists($metacache{$uri})) {
10152: #	    $metacache{$uri}={};
10153: #	}
10154: 	my $cachetime = 60*60;
10155:         if ($liburi) {
10156: 	    $liburi=&declutter($liburi);
10157:             $filename=$liburi;
10158:         } else {
10159: 	    &devalidate_cache_new('meta',$uri);
10160: 	    undef(%metaentry);
10161: 	}
10162:         my %metathesekeys=();
10163:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
10164: 	my $metastring;
10165: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
10166: 	    my $which = &hreflocation('','/'.($liburi || $uri));
10167: 	    $metastring = 
10168: 		&Apache::lonnet::ssi_body($which,
10169: 					  ('grade_target' => 'meta'));
10170: 	    $cachetime = 1; # only want this cached in the child not long term
10171: 	} elsif (($uri !~ m -^(editupload)/-) && 
10172:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
10173: 	    my $file=&filelocation('',&clutter($filename));
10174: 	    #push(@{$metaentry{$uri.'.file'}},$file);
10175: 	    $metastring=&getfile($file);
10176: 	}
10177:         my $parser=HTML::LCParser->new(\$metastring);
10178:         my $token;
10179:         undef %metathesekeys;
10180:         while ($token=$parser->get_token) {
10181: 	    if ($token->[0] eq 'S') {
10182: 		if (defined($token->[2]->{'package'})) {
10183: #
10184: # This is a package - get package info
10185: #
10186: 		    my $package=$token->[2]->{'package'};
10187: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10188: 		    if (defined($token->[2]->{'id'})) { 
10189: 			$keyroot.='_'.$token->[2]->{'id'}; 
10190: 		    }
10191: 		    if ($metaentry{':packages'}) {
10192: 			$metaentry{':packages'}.=','.$package.$keyroot;
10193: 		    } else {
10194: 			$metaentry{':packages'}=$package.$keyroot;
10195: 		    }
10196: 		    foreach my $pack_entry (keys(%packagetab)) {
10197: 			my $part=$keyroot;
10198: 			$part=~s/^\_//;
10199: 			if ($pack_entry=~/^\Q$package\E\&/ || 
10200: 			    $pack_entry=~/^\Q$package\E_0\&/) {
10201: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
10202: 			    # ignore package.tab specified default values
10203:                             # here &package_tab_default() will fetch those
10204: 			    if ($subp eq 'default') { next; }
10205: 			    my $value=$packagetab{$pack_entry};
10206: 			    my $unikey;
10207: 			    if ($pack =~ /_0$/) {
10208: 				$unikey='parameter_0_'.$name;
10209: 				$part=0;
10210: 			    } else {
10211: 				$unikey='parameter'.$keyroot.'_'.$name;
10212: 			    }
10213: 			    if ($subp eq 'display') {
10214: 				$value.=' [Part: '.$part.']';
10215: 			    }
10216: 			    $metaentry{':'.$unikey.'.part'}=$part;
10217: 			    $metathesekeys{$unikey}=1;
10218: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10219: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
10220: 			    }
10221: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
10222: 				$metaentry{':'.$unikey}=
10223: 				    $metaentry{':'.$unikey.'.default'};
10224: 			    }
10225: 			}
10226: 		    }
10227: 		} else {
10228: #
10229: # This is not a package - some other kind of start tag
10230: #
10231: 		    my $entry=$token->[1];
10232: 		    my $unikey='';
10233: 
10234: 		    if ($entry eq 'import') {
10235: #
10236: # Importing a library here
10237: #
10238:                         my $location=$parser->get_text('/import');
10239:                         my $dir=$filename;
10240:                         $dir=~s|[^/]*$||;
10241:                         $location=&filelocation($dir,$location);
10242:                        
10243:                         my $importmode=$token->[2]->{'importmode'};
10244:                         if ($importmode eq 'problem') {
10245: # Import as problem/response
10246:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10247:                         } elsif ($importmode eq 'part') {
10248: # Import as part(s)
10249:                            $importedparts=1;
10250: # We need to get the original file and the imported file to get the part order correct
10251: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
10252: # Load and inspect original file
10253:                            if ($#origfileimportpartids<0) {
10254:                               undef(%importedpartids);
10255:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
10256:                               my $origfile=&getfile($origfilelocation);
10257:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10258:                            }
10259: 
10260: # Load and inspect imported file
10261:                            my $impfile=&getfile($location);
10262:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10263:                            if ($#impfilepartids>=0) {
10264: # This problem had parts
10265:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
10266:                            } else {
10267: # Importing by turning a single problem into a problem part
10268: # It gets the import-tags ID as part-ID
10269:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
10270:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
10271:                            }
10272:                         } else {
10273: # Normal import
10274:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10275:                            if (defined($token->[2]->{'id'})) {
10276:                               $unikey.='_'.$token->[2]->{'id'};
10277:                            }
10278:                         }
10279: 
10280: 			if ($depthcount<20) {
10281: 			    my $metadata = 
10282: 				&metadata($uri,'keys', $location,$unikey,
10283: 					  $depthcount+1);
10284: 			    foreach my $meta (split(',',$metadata)) {
10285: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
10286: 				$metathesekeys{$meta}=1;
10287: 			    }
10288: 			
10289:                         }
10290: 		    } else {
10291: #
10292: # Not importing, some other kind of non-package, non-library start tag
10293: # 
10294:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
10295:                         if (defined($token->[2]->{'id'})) {
10296:                             $unikey.='_'.$token->[2]->{'id'};
10297:                         }
10298: 			if (defined($token->[2]->{'name'})) { 
10299: 			    $unikey.='_'.$token->[2]->{'name'}; 
10300: 			}
10301: 			$metathesekeys{$unikey}=1;
10302: 			foreach my $param (@{$token->[3]}) {
10303: 			    $metaentry{':'.$unikey.'.'.$param} =
10304: 				$token->[2]->{$param};
10305: 			}
10306: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
10307: 			my $default=$metaentry{':'.$unikey.'.default'};
10308: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
10309: 		 # only ws inside the tag, and not in default, so use default
10310: 		 # as value
10311: 			    $metaentry{':'.$unikey}=$default;
10312: 			} elsif ( $internaltext =~ /\S/ ) {
10313: 		  # something interesting inside the tag
10314: 			    $metaentry{':'.$unikey}=$internaltext;
10315: 			} else {
10316: 		  # no interesting values, don't set a default
10317: 			}
10318: # end of not-a-package not-a-library import
10319: 		    }
10320: # end of not-a-package start tag
10321: 		}
10322: # the next is the end of "start tag"
10323: 	    }
10324: 	}
10325: 	my ($extension) = ($uri =~ /\.(\w+)$/);
10326: 	$extension = lc($extension);
10327: 	if ($extension eq 'htm') { $extension='html'; }
10328: 
10329: 	foreach my $key (keys(%packagetab)) {
10330: 	    #no specific packages #how's our extension
10331: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
10332: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
10333: 					 \%metathesekeys);
10334: 	}
10335: 
10336: 	if (!exists($metaentry{':packages'})
10337: 	    || $packagetab{"import_defaults&extension_$extension"}) {
10338: 	    foreach my $key (keys(%packagetab)) {
10339: 		#no specific packages well let's get default then
10340: 		if ($key!~/^default&/) { next; }
10341: 		&metadata_create_package_def($uri,$key,'default',
10342: 					     \%metathesekeys);
10343: 	    }
10344: 	}
10345: # are there custom rights to evaluate
10346: 	if ($metaentry{':copyright'} eq 'custom') {
10347: 
10348:     #
10349:     # Importing a rights file here
10350:     #
10351: 	    unless ($depthcount) {
10352: 		my $location=$metaentry{':customdistributionfile'};
10353: 		my $dir=$filename;
10354: 		$dir=~s|[^/]*$||;
10355: 		$location=&filelocation($dir,$location);
10356: 		my $rights_metadata =
10357: 		    &metadata($uri,'keys',$location,'_rights',
10358: 			      $depthcount+1);
10359: 		foreach my $rights (split(',',$rights_metadata)) {
10360: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
10361: 		    $metathesekeys{$rights}=1;
10362: 		}
10363: 	    }
10364: 	}
10365: 	# uniqifiy package listing
10366: 	my %seen;
10367: 	my @uniq_packages =
10368: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
10369: 	$metaentry{':packages'} = join(',',@uniq_packages);
10370: 
10371:         if ($importedparts) {
10372: # We had imported parts and need to rebuild partorder
10373:            $metaentry{':partorder'}='';
10374:            $metathesekeys{'partorder'}=1;
10375:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
10376:                if ($origfileimportpartids[$index] eq 'part') {
10377: # original part, part of the problem
10378:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
10379:                } else {
10380: # we have imported parts at this position
10381:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
10382:                }
10383:            }
10384:            $metaentry{':partorder'}=~s/^\,//;
10385:         }
10386: 
10387: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
10388: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
10389: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
10390: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
10391: # this is the end of "was not already recently cached
10392:     }
10393:     return $metaentry{':'.$what};
10394: }
10395: 
10396: sub metadata_create_package_def {
10397:     my ($uri,$key,$package,$metathesekeys)=@_;
10398:     my ($pack,$name,$subp)=split(/\&/,$key);
10399:     if ($subp eq 'default') { next; }
10400:     
10401:     if (defined($metaentry{':packages'})) {
10402: 	$metaentry{':packages'}.=','.$package;
10403:     } else {
10404: 	$metaentry{':packages'}=$package;
10405:     }
10406:     my $value=$packagetab{$key};
10407:     my $unikey;
10408:     $unikey='parameter_0_'.$name;
10409:     $metaentry{':'.$unikey.'.part'}=0;
10410:     $$metathesekeys{$unikey}=1;
10411:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10412: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
10413:     }
10414:     if (defined($metaentry{':'.$unikey.'.default'})) {
10415: 	$metaentry{':'.$unikey}=
10416: 	    $metaentry{':'.$unikey.'.default'};
10417:     }
10418: }
10419: 
10420: sub metadata_generate_part0 {
10421:     my ($metadata,$metacache,$uri) = @_;
10422:     my %allnames;
10423:     foreach my $metakey (keys(%$metadata)) {
10424: 	if ($metakey=~/^parameter\_(.*)/) {
10425: 	  my $part=$$metacache{':'.$metakey.'.part'};
10426: 	  my $name=$$metacache{':'.$metakey.'.name'};
10427: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
10428: 	    $allnames{$name}=$part;
10429: 	  }
10430: 	}
10431:     }
10432:     foreach my $name (keys(%allnames)) {
10433:       $$metadata{"parameter_0_$name"}=1;
10434:       my $key=":parameter_0_$name";
10435:       $$metacache{"$key.part"}='0';
10436:       $$metacache{"$key.name"}=$name;
10437:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
10438: 					   $allnames{$name}.'_'.$name.
10439: 					   '.type'};
10440:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
10441: 			     '.display'};
10442:       my $expr='[Part: '.$allnames{$name}.']';
10443:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
10444:       $$metacache{"$key.display"}=$olddis;
10445:     }
10446: }
10447: 
10448: # ------------------------------------------------------ Devalidate title cache
10449: 
10450: sub devalidate_title_cache {
10451:     my ($url)=@_;
10452:     if (!$env{'request.course.id'}) { return; }
10453:     my $symb=&symbread($url);
10454:     if (!$symb) { return; }
10455:     my $key=$env{'request.course.id'}."\0".$symb;
10456:     &devalidate_cache_new('title',$key);
10457: }
10458: 
10459: # ------------------------------------------------- Get the title of a course
10460: 
10461: sub current_course_title {
10462:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
10463: }
10464: # ------------------------------------------------- Get the title of a resource
10465: 
10466: sub gettitle {
10467:     my $urlsymb=shift;
10468:     my $symb=&symbread($urlsymb);
10469:     if ($symb) {
10470: 	my $key=$env{'request.course.id'}."\0".$symb;
10471: 	my ($result,$cached)=&is_cached_new('title',$key);
10472: 	if (defined($cached)) { 
10473: 	    return $result;
10474: 	}
10475: 	my ($map,$resid,$url)=&decode_symb($symb);
10476: 	my $title='';
10477: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
10478: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
10479: 	} else {
10480: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10481: 		    &GDBM_READER(),0640)) {
10482: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
10483: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
10484: 		untie(%bighash);
10485: 	    }
10486: 	}
10487: 	$title=~s/\&colon\;/\:/gs;
10488: 	if ($title) {
10489: # Remember both $symb and $title for dynamic metadata
10490:             $accesshash{$symb.'___crstitle'}=$title;
10491:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
10492: # Cache this title and then return it
10493: 	    return &do_cache_new('title',$key,$title,600);
10494: 	}
10495: 	$urlsymb=$url;
10496:     }
10497:     my $title=&metadata($urlsymb,'title');
10498:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
10499:     return $title;
10500: }
10501: 
10502: sub get_slot {
10503:     my ($which,$cnum,$cdom)=@_;
10504:     if (!$cnum || !$cdom) {
10505: 	(undef,my $courseid)=&whichuser();
10506: 	$cdom=$env{'course.'.$courseid.'.domain'};
10507: 	$cnum=$env{'course.'.$courseid.'.num'};
10508:     }
10509:     my $key=join("\0",'slots',$cdom,$cnum,$which);
10510:     my %slotinfo;
10511:     if (exists($remembered{$key})) {
10512: 	$slotinfo{$which} = $remembered{$key};
10513:     } else {
10514: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
10515: 	&Apache::lonhomework::showhash(%slotinfo);
10516: 	my ($tmp)=keys(%slotinfo);
10517: 	if ($tmp=~/^error:/) { return (); }
10518: 	$remembered{$key} = $slotinfo{$which};
10519:     }
10520:     if (ref($slotinfo{$which}) eq 'HASH') {
10521: 	return %{$slotinfo{$which}};
10522:     }
10523:     return $slotinfo{$which};
10524: }
10525: 
10526: sub get_reservable_slots {
10527:     my ($cnum,$cdom,$uname,$udom) = @_;
10528:     my $now = time;
10529:     my $reservable_info;
10530:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
10531:     if (exists($remembered{$key})) {
10532:         $reservable_info = $remembered{$key};
10533:     } else {
10534:         my %resv;
10535:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
10536:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
10537:         $reservable_info = \%resv;
10538:         $remembered{$key} = $reservable_info;
10539:     }
10540:     return $reservable_info;
10541: }
10542: 
10543: sub get_course_slots {
10544:     my ($cnum,$cdom) = @_;
10545:     my $hashid=$cnum.':'.$cdom;
10546:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
10547:     if (defined($cached)) {
10548:         if (ref($result) eq 'HASH') {
10549:             return %{$result};
10550:         }
10551:     } else {
10552:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
10553:         my ($tmp) = keys(%slots);
10554:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
10555:             &do_cache_new('allslots',$hashid,\%slots,600);
10556:             return %slots;
10557:         }
10558:     }
10559:     return;
10560: }
10561: 
10562: sub devalidate_slots_cache {
10563:     my ($cnum,$cdom)=@_;
10564:     my $hashid=$cnum.':'.$cdom;
10565:     &devalidate_cache_new('allslots',$hashid);
10566: }
10567: 
10568: sub get_coursechange {
10569:     my ($cdom,$cnum) = @_;
10570:     if ($cdom eq '' || $cnum eq '') {
10571:         return unless ($env{'request.course.id'});
10572:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10573:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10574:     }
10575:     my $hashid=$cdom.'_'.$cnum;
10576:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
10577:     if ((defined($cached)) && ($change ne '')) {
10578:         return $change;
10579:     } else {
10580:         my %crshash;
10581:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
10582:         if ($crshash{'internal.contentchange'} eq '') {
10583:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
10584:             if ($change eq '') {
10585:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
10586:                 $change = $crshash{'internal.created'};
10587:             }
10588:         } else {
10589:             $change = $crshash{'internal.contentchange'};
10590:         }
10591:         my $cachetime = 600;
10592:         &do_cache_new('crschange',$hashid,$change,$cachetime);
10593:     }
10594:     return $change;
10595: }
10596: 
10597: sub devalidate_coursechange_cache {
10598:     my ($cnum,$cdom)=@_;
10599:     my $hashid=$cnum.':'.$cdom;
10600:     &devalidate_cache_new('crschange',$hashid);
10601: }
10602: 
10603: # ------------------------------------------------- Update symbolic store links
10604: 
10605: sub symblist {
10606:     my ($mapname,%newhash)=@_;
10607:     $mapname=&deversion(&declutter($mapname));
10608:     my %hash;
10609:     if (($env{'request.course.fn'}) && (%newhash)) {
10610:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
10611:                       &GDBM_WRCREAT(),0640)) {
10612: 	    foreach my $url (keys(%newhash)) {
10613: 		next if ($url eq 'last_known'
10614: 			 && $env{'form.no_update_last_known'});
10615: 		$hash{declutter($url)}=&encode_symb($mapname,
10616: 						    $newhash{$url}->[1],
10617: 						    $newhash{$url}->[0]);
10618:             }
10619:             if (untie(%hash)) {
10620: 		return 'ok';
10621:             }
10622:         }
10623:     }
10624:     return 'error';
10625: }
10626: 
10627: # --------------------------------------------------------------- Verify a symb
10628: 
10629: sub symbverify {
10630:     my ($symb,$thisurl,$encstate)=@_;
10631:     my $thisfn=$thisurl;
10632:     $thisfn=&declutter($thisfn);
10633: # direct jump to resource in page or to a sequence - will construct own symbs
10634:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
10635: # check URL part
10636:     my ($map,$resid,$url)=&decode_symb($symb);
10637: 
10638:     unless ($url eq $thisfn) { return 0; }
10639: 
10640:     $symb=&symbclean($symb);
10641:     $thisurl=&deversion($thisurl);
10642:     $thisfn=&deversion($thisfn);
10643: 
10644:     my %bighash;
10645:     my $okay=0;
10646: 
10647:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10648:                             &GDBM_READER(),0640)) {
10649:         my $noclutter;
10650:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
10651:             $thisurl =~ s/\?.+$//;
10652:             if ($map =~ m{^uploaded/.+\.page$}) {
10653:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
10654:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
10655:                 $noclutter = 1;
10656:             }
10657:         }
10658:         my $ids;
10659:         if ($noclutter) {
10660:             $ids=$bighash{'ids_'.$thisurl};
10661:         } else {
10662:             $ids=$bighash{'ids_'.&clutter($thisurl)};
10663:         }
10664:         unless ($ids) {
10665:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
10666:             $ids=$bighash{$idkey};
10667:         }
10668:         if ($ids) {
10669: # ------------------------------------------------------------------- Has ID(s)
10670:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
10671:                 $symb =~ s/\?.+$//;
10672:             }
10673: 	    foreach my $id (split(/\,/,$ids)) {
10674: 	       my ($mapid,$resid)=split(/\./,$id);
10675:                if (
10676:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
10677:    eq $symb) {
10678:                    if (ref($encstate)) {
10679:                        $$encstate = $bighash{'encrypted_'.$id};
10680:                    }
10681: 		   if (($env{'request.role.adv'}) ||
10682: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
10683:                        ($thisurl eq '/adm/navmaps')) {
10684: 		       $okay=1;
10685:                        last;
10686: 		   }
10687: 	       }
10688: 	   }
10689:         }
10690: 	untie(%bighash);
10691:     }
10692:     return $okay;
10693: }
10694: 
10695: # --------------------------------------------------------------- Clean-up symb
10696: 
10697: sub symbclean {
10698:     my $symb=shift;
10699:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
10700: # remove version from map
10701:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
10702: 
10703: # remove version from URL
10704:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
10705: 
10706: # remove wrapper
10707: 
10708:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
10709:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
10710:     return $symb;
10711: }
10712: 
10713: # ---------------------------------------------- Split symb to find map and url
10714: 
10715: sub encode_symb {
10716:     my ($map,$resid,$url)=@_;
10717:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
10718: }
10719: 
10720: sub decode_symb {
10721:     my $symb=shift;
10722:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
10723:     my ($map,$resid,$url)=split(/___/,$symb);
10724:     return (&fixversion($map),$resid,&fixversion($url));
10725: }
10726: 
10727: sub fixversion {
10728:     my $fn=shift;
10729:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
10730:     my %bighash;
10731:     my $uri=&clutter($fn);
10732:     my $key=$env{'request.course.id'}.'_'.$uri;
10733: # is this cached?
10734:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
10735:     if (defined($cached)) { return $result; }
10736: # unfortunately not cached, or expired
10737:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10738: 	    &GDBM_READER(),0640)) {
10739:  	if ($bighash{'version_'.$uri}) {
10740:  	    my $version=$bighash{'version_'.$uri};
10741:  	    unless (($version eq 'mostrecent') || 
10742: 		    ($version==&getversion($uri))) {
10743:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
10744:  	    }
10745:  	}
10746:  	untie %bighash;
10747:     }
10748:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
10749: }
10750: 
10751: sub deversion {
10752:     my $url=shift;
10753:     $url=~s/\.\d+\.(\w+)$/\.$1/;
10754:     return $url;
10755: }
10756: 
10757: # ------------------------------------------------------ Return symb list entry
10758: 
10759: sub symbread {
10760:     my ($thisfn,$donotrecurse)=@_;
10761:     my $cache_str;
10762:     if ($thisfn ne '') {
10763:         $cache_str='request.symbread.cached.'.$thisfn;
10764:         if ($env{$cache_str} ne '') {
10765:             return $env{$cache_str};
10766:         }
10767:     } else {
10768: # no filename provided? try from environment
10769:         if ($env{'request.symb'}) {
10770: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
10771: 	}
10772: 	$thisfn=$env{'request.filename'};
10773:     }
10774:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
10775: # is that filename actually a symb? Verify, clean, and return
10776:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
10777: 	if (&symbverify($thisfn,$1)) {
10778: 	    return $env{$cache_str}=&symbclean($thisfn);
10779: 	}
10780:     }
10781:     $thisfn=declutter($thisfn);
10782:     my %hash;
10783:     my %bighash;
10784:     my $syval='';
10785:     if (($env{'request.course.fn'}) && ($thisfn)) {
10786:         my $targetfn = $thisfn;
10787:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
10788:             $targetfn = 'adm/wrapper/'.$thisfn;
10789:         }
10790: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
10791: 	    $targetfn=$1;
10792: 	}
10793:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
10794:                       &GDBM_READER(),0640)) {
10795: 	    $syval=$hash{$targetfn};
10796:             untie(%hash);
10797:         }
10798: # ---------------------------------------------------------- There was an entry
10799:         if ($syval) {
10800: 	    #unless ($syval=~/\_\d+$/) {
10801: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
10802: 		    #&appenv({'request.ambiguous' => $thisfn});
10803: 		    #return $env{$cache_str}='';
10804: 		#}    
10805: 		#$syval.=$1;
10806: 	    #}
10807:         } else {
10808: # ------------------------------------------------------- Was not in symb table
10809:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10810:                             &GDBM_READER(),0640)) {
10811: # ---------------------------------------------- Get ID(s) for current resource
10812:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
10813:               unless ($ids) { 
10814:                  $ids=$bighash{'ids_/'.$thisfn};
10815:               }
10816:               unless ($ids) {
10817: # alias?
10818: 		  $ids=$bighash{'mapalias_'.$thisfn};
10819:               }
10820:               if ($ids) {
10821: # ------------------------------------------------------------------- Has ID(s)
10822:                  my @possibilities=split(/\,/,$ids);
10823:                  if ($#possibilities==0) {
10824: # ----------------------------------------------- There is only one possibility
10825: 		     my ($mapid,$resid)=split(/\./,$ids);
10826: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
10827: 						    $resid,$thisfn);
10828:                  } elsif (!$donotrecurse) {
10829: # ------------------------------------------ There is more than one possibility
10830:                      my $realpossible=0;
10831:                      foreach my $id (@possibilities) {
10832: 			 my $file=$bighash{'src_'.$id};
10833:                          if (&allowed('bre',$file)) {
10834:          		    my ($mapid,$resid)=split(/\./,$id);
10835:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
10836: 				$realpossible++;
10837:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
10838: 						    $resid,$thisfn);
10839:                             }
10840: 			 }
10841:                      }
10842: 		     if ($realpossible!=1) { $syval=''; }
10843:                  } else {
10844:                      $syval='';
10845:                  }
10846: 	      }
10847:               untie(%bighash)
10848:            }
10849:         }
10850:         if ($syval) {
10851: 	    return $env{$cache_str}=$syval;
10852:         }
10853:     }
10854:     &appenv({'request.ambiguous' => $thisfn});
10855:     return $env{$cache_str}='';
10856: }
10857: 
10858: # ---------------------------------------------------------- Return random seed
10859: 
10860: sub numval {
10861:     my $txt=shift;
10862:     $txt=~tr/A-J/0-9/;
10863:     $txt=~tr/a-j/0-9/;
10864:     $txt=~tr/K-T/0-9/;
10865:     $txt=~tr/k-t/0-9/;
10866:     $txt=~tr/U-Z/0-5/;
10867:     $txt=~tr/u-z/0-5/;
10868:     $txt=~s/\D//g;
10869:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
10870:     return int($txt);
10871: }
10872: 
10873: sub numval2 {
10874:     my $txt=shift;
10875:     $txt=~tr/A-J/0-9/;
10876:     $txt=~tr/a-j/0-9/;
10877:     $txt=~tr/K-T/0-9/;
10878:     $txt=~tr/k-t/0-9/;
10879:     $txt=~tr/U-Z/0-5/;
10880:     $txt=~tr/u-z/0-5/;
10881:     $txt=~s/\D//g;
10882:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10883:     my $total;
10884:     foreach my $val (@txts) { $total+=$val; }
10885:     if ($_64bit) { if ($total > 2**32) { return -1; } }
10886:     return int($total);
10887: }
10888: 
10889: sub numval3 {
10890:     use integer;
10891:     my $txt=shift;
10892:     $txt=~tr/A-J/0-9/;
10893:     $txt=~tr/a-j/0-9/;
10894:     $txt=~tr/K-T/0-9/;
10895:     $txt=~tr/k-t/0-9/;
10896:     $txt=~tr/U-Z/0-5/;
10897:     $txt=~tr/u-z/0-5/;
10898:     $txt=~s/\D//g;
10899:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10900:     my $total;
10901:     foreach my $val (@txts) { $total+=$val; }
10902:     if ($_64bit) { $total=(($total<<32)>>32); }
10903:     return $total;
10904: }
10905: 
10906: sub digest {
10907:     my ($data)=@_;
10908:     my $digest=&Digest::MD5::md5($data);
10909:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
10910:     my ($e,$f);
10911:     {
10912:         use integer;
10913:         $e=($a+$b);
10914:         $f=($c+$d);
10915:         if ($_64bit) {
10916:             $e=(($e<<32)>>32);
10917:             $f=(($f<<32)>>32);
10918:         }
10919:     }
10920:     if (wantarray) {
10921: 	return ($e,$f);
10922:     } else {
10923: 	my $g;
10924: 	{
10925: 	    use integer;
10926: 	    $g=($e+$f);
10927: 	    if ($_64bit) {
10928: 		$g=(($g<<32)>>32);
10929: 	    }
10930: 	}
10931: 	return $g;
10932:     }
10933: }
10934: 
10935: sub latest_rnd_algorithm_id {
10936:     return '64bit5';
10937: }
10938: 
10939: sub get_rand_alg {
10940:     my ($courseid)=@_;
10941:     if (!$courseid) { $courseid=(&whichuser())[1]; }
10942:     if ($courseid) {
10943: 	return $env{"course.$courseid.rndseed"};
10944:     }
10945:     return &latest_rnd_algorithm_id();
10946: }
10947: 
10948: sub validCODE {
10949:     my ($CODE)=@_;
10950:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
10951:     return 0;
10952: }
10953: 
10954: sub getCODE {
10955:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
10956:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
10957: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
10958: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
10959: 	return $Apache::lonhomework::history{'resource.CODE'};
10960:     }
10961:     return undef;
10962: }
10963: #
10964: #  Determines the random seed for a specific context:
10965: #
10966: # parameters:
10967: #   symb      - in course context the symb for the seed.
10968: #   course_id - The course id of the form domain_coursenum.
10969: #   domain    - Domain for the user.
10970: #   course    - Course for the user.
10971: #   cenv      - environment of the course.
10972: #
10973: # NOTE:
10974: #   All parameters are picked out of the environment if missing
10975: #   or not defined.
10976: #   If a symb cannot be determined the current time is used instead.
10977: #
10978: #  For a given well defined symb, courside, domain, username,
10979: #  and course environment, the seed is reproducible.
10980: #
10981: sub rndseed {
10982:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
10983:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
10984:     if (!defined($symb)) {
10985: 	unless ($symb=$wsymb) { return time; }
10986:     }
10987:     if (!defined $courseid) { 
10988: 	$courseid=$wcourseid; 
10989:     }
10990:     if (!defined $domain) { $domain=$wdomain; }
10991:     if (!defined $username) { $username=$wusername }
10992: 
10993:     my $which;
10994:     if (defined($cenv->{'rndseed'})) {
10995: 	$which = $cenv->{'rndseed'};
10996:     } else {
10997: 	$which =&get_rand_alg($courseid);
10998:     }
10999:     if (defined(&getCODE())) {
11000: 
11001: 	if ($which eq '64bit5') {
11002: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
11003: 	} elsif ($which eq '64bit4') {
11004: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
11005: 	} else {
11006: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
11007: 	}
11008:     } elsif ($which eq '64bit5') {
11009: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
11010:     } elsif ($which eq '64bit4') {
11011: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
11012:     } elsif ($which eq '64bit3') {
11013: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
11014:     } elsif ($which eq '64bit2') {
11015: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
11016:     } elsif ($which eq '64bit') {
11017: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
11018:     }
11019:     return &rndseed_32bit($symb,$courseid,$domain,$username);
11020: }
11021: 
11022: sub rndseed_32bit {
11023:     my ($symb,$courseid,$domain,$username)=@_;
11024:     {
11025: 	use integer;
11026: 	my $symbchck=unpack("%32C*",$symb) << 27;
11027: 	my $symbseed=numval($symb) << 22;
11028: 	my $namechck=unpack("%32C*",$username) << 17;
11029: 	my $nameseed=numval($username) << 12;
11030: 	my $domainseed=unpack("%32C*",$domain) << 7;
11031: 	my $courseseed=unpack("%32C*",$courseid);
11032: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
11033: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11034: 	#&logthis("rndseed :$num:$symb");
11035: 	if ($_64bit) { $num=(($num<<32)>>32); }
11036: 	return $num;
11037:     }
11038: }
11039: 
11040: sub rndseed_64bit {
11041:     my ($symb,$courseid,$domain,$username)=@_;
11042:     {
11043: 	use integer;
11044: 	my $symbchck=unpack("%32S*",$symb) << 21;
11045: 	my $symbseed=numval($symb) << 10;
11046: 	my $namechck=unpack("%32S*",$username);
11047: 	
11048: 	my $nameseed=numval($username) << 21;
11049: 	my $domainseed=unpack("%32S*",$domain) << 10;
11050: 	my $courseseed=unpack("%32S*",$courseid);
11051: 	
11052: 	my $num1=$symbchck+$symbseed+$namechck;
11053: 	my $num2=$nameseed+$domainseed+$courseseed;
11054: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11055: 	#&logthis("rndseed :$num:$symb");
11056: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11057: 	return "$num1,$num2";
11058:     }
11059: }
11060: 
11061: sub rndseed_64bit2 {
11062:     my ($symb,$courseid,$domain,$username)=@_;
11063:     {
11064: 	use integer;
11065: 	# strings need to be an even # of cahracters long, it it is odd the
11066:         # last characters gets thrown away
11067: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
11068: 	my $symbseed=numval($symb) << 10;
11069: 	my $namechck=unpack("%32S*",$username.' ');
11070: 	
11071: 	my $nameseed=numval($username) << 21;
11072: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
11073: 	my $courseseed=unpack("%32S*",$courseid.' ');
11074: 	
11075: 	my $num1=$symbchck+$symbseed+$namechck;
11076: 	my $num2=$nameseed+$domainseed+$courseseed;
11077: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11078: 	#&logthis("rndseed :$num:$symb");
11079: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11080: 	return "$num1,$num2";
11081:     }
11082: }
11083: 
11084: sub rndseed_64bit3 {
11085:     my ($symb,$courseid,$domain,$username)=@_;
11086:     {
11087: 	use integer;
11088: 	# strings need to be an even # of cahracters long, it it is odd the
11089:         # last characters gets thrown away
11090: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
11091: 	my $symbseed=numval2($symb) << 10;
11092: 	my $namechck=unpack("%32S*",$username.' ');
11093: 	
11094: 	my $nameseed=numval2($username) << 21;
11095: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
11096: 	my $courseseed=unpack("%32S*",$courseid.' ');
11097: 	
11098: 	my $num1=$symbchck+$symbseed+$namechck;
11099: 	my $num2=$nameseed+$domainseed+$courseseed;
11100: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11101: 	#&logthis("rndseed :$num1:$num2:$_64bit");
11102: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11103: 	
11104: 	return "$num1:$num2";
11105:     }
11106: }
11107: 
11108: sub rndseed_64bit4 {
11109:     my ($symb,$courseid,$domain,$username)=@_;
11110:     {
11111: 	use integer;
11112: 	# strings need to be an even # of cahracters long, it it is odd the
11113:         # last characters gets thrown away
11114: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
11115: 	my $symbseed=numval3($symb) << 10;
11116: 	my $namechck=unpack("%32S*",$username.' ');
11117: 	
11118: 	my $nameseed=numval3($username) << 21;
11119: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
11120: 	my $courseseed=unpack("%32S*",$courseid.' ');
11121: 	
11122: 	my $num1=$symbchck+$symbseed+$namechck;
11123: 	my $num2=$nameseed+$domainseed+$courseseed;
11124: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11125: 	#&logthis("rndseed :$num1:$num2:$_64bit");
11126: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11127: 	
11128: 	return "$num1:$num2";
11129:     }
11130: }
11131: 
11132: sub rndseed_64bit5 {
11133:     my ($symb,$courseid,$domain,$username)=@_;
11134:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
11135:     return "$num1:$num2";
11136: }
11137: 
11138: sub rndseed_CODE_64bit {
11139:     my ($symb,$courseid,$domain,$username)=@_;
11140:     {
11141: 	use integer;
11142: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
11143: 	my $symbseed=numval2($symb);
11144: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11145: 	my $CODEseed=numval(&getCODE());
11146: 	my $courseseed=unpack("%32S*",$courseid.' ');
11147: 	my $num1=$symbseed+$CODEchck;
11148: 	my $num2=$CODEseed+$courseseed+$symbchck;
11149: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11150: 	#&logthis("rndseed :$num1:$num2:$symb");
11151: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
11152: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
11153: 	return "$num1:$num2";
11154:     }
11155: }
11156: 
11157: sub rndseed_CODE_64bit4 {
11158:     my ($symb,$courseid,$domain,$username)=@_;
11159:     {
11160: 	use integer;
11161: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
11162: 	my $symbseed=numval3($symb);
11163: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11164: 	my $CODEseed=numval3(&getCODE());
11165: 	my $courseseed=unpack("%32S*",$courseid.' ');
11166: 	my $num1=$symbseed+$CODEchck;
11167: 	my $num2=$CODEseed+$courseseed+$symbchck;
11168: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11169: 	#&logthis("rndseed :$num1:$num2:$symb");
11170: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
11171: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
11172: 	return "$num1:$num2";
11173:     }
11174: }
11175: 
11176: sub rndseed_CODE_64bit5 {
11177:     my ($symb,$courseid,$domain,$username)=@_;
11178:     my $code = &getCODE();
11179:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
11180:     return "$num1:$num2";
11181: }
11182: 
11183: sub setup_random_from_rndseed {
11184:     my ($rndseed)=@_;
11185:     if ($rndseed =~/([,:])/) {
11186: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
11187: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
11188:     } else {
11189: 	&Math::Random::random_set_seed_from_phrase($rndseed);
11190:     }
11191: }
11192: 
11193: sub latest_receipt_algorithm_id {
11194:     return 'receipt3';
11195: }
11196: 
11197: sub recunique {
11198:     my $fucourseid=shift;
11199:     my $unique;
11200:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
11201: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
11202: 	$unique=$env{"course.$fucourseid.internal.encseed"};
11203:     } else {
11204: 	$unique=$perlvar{'lonReceipt'};
11205:     }
11206:     return unpack("%32C*",$unique);
11207: }
11208: 
11209: sub recprefix {
11210:     my $fucourseid=shift;
11211:     my $prefix;
11212:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
11213: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
11214: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
11215:     } else {
11216: 	$prefix=$perlvar{'lonHostID'};
11217:     }
11218:     return unpack("%32C*",$prefix);
11219: }
11220: 
11221: sub ireceipt {
11222:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
11223: 
11224:     my $return =&recprefix($fucourseid).'-';
11225: 
11226:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
11227: 	$env{'request.state'} eq 'construct') {
11228: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
11229: 	return $return;
11230:     }
11231: 
11232:     my $cuname=unpack("%32C*",$funame);
11233:     my $cudom=unpack("%32C*",$fudom);
11234:     my $cucourseid=unpack("%32C*",$fucourseid);
11235:     my $cusymb=unpack("%32C*",$fusymb);
11236:     my $cunique=&recunique($fucourseid);
11237:     my $cpart=unpack("%32S*",$part);
11238:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
11239: 
11240: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
11241: 			       
11242: 	$return.= ($cunique%$cuname+
11243: 		   $cunique%$cudom+
11244: 		   $cusymb%$cuname+
11245: 		   $cusymb%$cudom+
11246: 		   $cucourseid%$cuname+
11247: 		   $cucourseid%$cudom+
11248: 		   $cpart%$cuname+
11249: 		   $cpart%$cudom);
11250:     } else {
11251: 	$return.= ($cunique%$cuname+
11252: 		   $cunique%$cudom+
11253: 		   $cusymb%$cuname+
11254: 		   $cusymb%$cudom+
11255: 		   $cucourseid%$cuname+
11256: 		   $cucourseid%$cudom);
11257:     }
11258:     return $return;
11259: }
11260: 
11261: sub receipt {
11262:     my ($part)=@_;
11263:     my ($symb,$courseid,$domain,$name) = &whichuser();
11264:     return &ireceipt($name,$domain,$courseid,$symb,$part);
11265: }
11266: 
11267: sub whichuser {
11268:     my ($passedsymb)=@_;
11269:     my ($symb,$courseid,$domain,$name,$publicuser);
11270:     if (defined($env{'form.grade_symb'})) {
11271: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
11272: 	my $allowed=&allowed('vgr',$tmp_courseid);
11273: 	if (!$allowed &&
11274: 	    exists($env{'request.course.sec'}) &&
11275: 	    $env{'request.course.sec'} !~ /^\s*$/) {
11276: 	    $allowed=&allowed('vgr',$tmp_courseid.
11277: 			      '/'.$env{'request.course.sec'});
11278: 	}
11279: 	if ($allowed) {
11280: 	    ($symb)=&get_env_multiple('form.grade_symb');
11281: 	    $courseid=$tmp_courseid;
11282: 	    ($domain)=&get_env_multiple('form.grade_domain');
11283: 	    ($name)=&get_env_multiple('form.grade_username');
11284: 	    return ($symb,$courseid,$domain,$name,$publicuser);
11285: 	}
11286:     }
11287:     if (!$passedsymb) {
11288: 	$symb=&symbread();
11289:     } else {
11290: 	$symb=$passedsymb;
11291:     }
11292:     $courseid=$env{'request.course.id'};
11293:     $domain=$env{'user.domain'};
11294:     $name=$env{'user.name'};
11295:     if ($name eq 'public' && $domain eq 'public') {
11296: 	if (!defined($env{'form.username'})) {
11297: 	    $env{'form.username'}.=time.rand(10000000);
11298: 	}
11299: 	$name.=$env{'form.username'};
11300:     }
11301:     return ($symb,$courseid,$domain,$name,$publicuser);
11302: 
11303: }
11304: 
11305: # ------------------------------------------------------------ Serves up a file
11306: # returns either the contents of the file or 
11307: # -1 if the file doesn't exist
11308: #
11309: # if the target is a file that was uploaded via DOCS, 
11310: # a check will be made to see if a current copy exists on the local server,
11311: # if it does this will be served, otherwise a copy will be retrieved from
11312: # the home server for the course and stored in /home/httpd/html/userfiles on
11313: # the local server.   
11314: 
11315: sub getfile {
11316:     my ($file) = @_;
11317:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
11318:     &repcopy($file);
11319:     return &readfile($file);
11320: }
11321: 
11322: sub repcopy_userfile {
11323:     my ($file)=@_;
11324:     my $londocroot = $perlvar{'lonDocRoot'};
11325:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
11326:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
11327:     my ($cdom,$cnum,$filename) = 
11328: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
11329:     my $uri="/uploaded/$cdom/$cnum/$filename";
11330:     if (-e "$file") {
11331: # we already have a local copy, check it out
11332: 	my @fileinfo = stat($file);
11333: 	my $rtncode;
11334: 	my $info;
11335: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
11336: 	if ($lwpresp ne 'ok') {
11337: # there is no such file anymore, even though we had a local copy
11338: 	    if ($rtncode eq '404') {
11339: 		unlink($file);
11340: 	    }
11341: 	    return -1;
11342: 	}
11343: 	if ($info < $fileinfo[9]) {
11344: # nice, the file we have is up-to-date, just say okay
11345: 	    return 'ok';
11346: 	} else {
11347: # the file is outdated, get rid of it
11348: 	    unlink($file);
11349: 	}
11350:     }
11351: # one way or the other, at this point, we don't have the file
11352: # construct the correct path for the file
11353:     my @parts = ($cdom,$cnum); 
11354:     if ($filename =~ m|^(.+)/[^/]+$|) {
11355: 	push @parts, split(/\//,$1);
11356:     }
11357:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
11358:     foreach my $part (@parts) {
11359: 	$path .= '/'.$part;
11360: 	if (!-e $path) {
11361: 	    mkdir($path,0770);
11362: 	}
11363:     }
11364: # now the path exists for sure
11365: # get a user agent
11366:     my $ua=new LWP::UserAgent;
11367:     my $transferfile=$file.'.in.transfer';
11368: # FIXME: this should flock
11369:     if (-e $transferfile) { return 'ok'; }
11370:     my $request;
11371:     $uri=~s/^\///;
11372:     my $homeserver = &homeserver($cnum,$cdom);
11373:     my $protocol = $protocol{$homeserver};
11374:     $protocol = 'http' if ($protocol ne 'https');
11375:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
11376:     my $response=$ua->request($request,$transferfile);
11377: # did it work?
11378:     if ($response->is_error()) {
11379: 	unlink($transferfile);
11380: 	&logthis("Userfile repcopy failed for $uri");
11381: 	return -1;
11382:     }
11383: # worked, rename the transfer file
11384:     rename($transferfile,$file);
11385:     return 'ok';
11386: }
11387: 
11388: sub tokenwrapper {
11389:     my $uri=shift;
11390:     $uri=~s|^https?\://([^/]+)||;
11391:     $uri=~s|^/||;
11392:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
11393:     my $token=$1;
11394:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
11395:     if ($udom && $uname && $file) {
11396: 	$file=~s|(\?\.*)*$||;
11397:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
11398:         my $homeserver = &homeserver($uname,$udom);
11399:         my $protocol = $protocol{$homeserver};
11400:         $protocol = 'http' if ($protocol ne 'https');
11401:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
11402:                (($uri=~/\?/)?'&':'?').'token='.$token.
11403:                                '&tokenissued='.$perlvar{'lonHostID'};
11404:     } else {
11405:         return '/adm/notfound.html';
11406:     }
11407: }
11408: 
11409: # call with reqtype HEAD: get last modification time
11410: # call with reqtype GET: get the file contents
11411: # Do not call this with reqtype GET for large files! It loads everything into memory
11412: #
11413: sub getuploaded {
11414:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
11415:     $uri=~s/^\///;
11416:     my $homeserver = &homeserver($cnum,$cdom);
11417:     my $protocol = $protocol{$homeserver};
11418:     $protocol = 'http' if ($protocol ne 'https');
11419:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
11420:     my $ua=new LWP::UserAgent;
11421:     my $request=new HTTP::Request($reqtype,$uri);
11422:     my $response=$ua->request($request);
11423:     $$rtncode = $response->code;
11424:     if (! $response->is_success()) {
11425: 	return 'failed';
11426:     }      
11427:     if ($reqtype eq 'HEAD') {
11428: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
11429:     } elsif ($reqtype eq 'GET') {
11430: 	$$info = $response->content;
11431:     }
11432:     return 'ok';
11433: }
11434: 
11435: sub readfile {
11436:     my $file = shift;
11437:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
11438:     my $fh;
11439:     open($fh,"<$file");
11440:     my $a='';
11441:     while (my $line = <$fh>) { $a .= $line; }
11442:     return $a;
11443: }
11444: 
11445: sub filelocation {
11446:     my ($dir,$file) = @_;
11447:     my $location;
11448:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
11449: 
11450:     if ($file =~ m-^/adm/-) {
11451: 	$file=~s-^/adm/wrapper/-/-;
11452: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
11453:     }
11454: 
11455:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
11456:         $location = $file;
11457:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
11458:         my ($udom,$uname,$filename)=
11459:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
11460:         my $home=&homeserver($uname,$udom);
11461:         my $is_me=0;
11462:         my @ids=&current_machine_ids();
11463:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
11464:         if ($is_me) {
11465:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
11466:         } else {
11467:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
11468:   	      $udom.'/'.$uname.'/'.$filename;
11469:         }
11470:     } elsif ($file =~ m-^/adm/-) {
11471: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
11472:     } else {
11473:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
11474:         $file=~s:^/(res|priv)/:/:;
11475:         my $space=$1;
11476:         if ( !( $file =~ m:^/:) ) {
11477:             $location = $dir. '/'.$file;
11478:         } else {
11479:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
11480:         }
11481:     }
11482:     $location=~s://+:/:g; # remove duplicate /
11483:     while ($location=~m{/\.\./}) {
11484: 	if ($location =~ m{/[^/]+/\.\./}) {
11485: 	    $location=~ s{/[^/]+/\.\./}{/}g;
11486: 	} else {
11487: 	    $location=~ s{/\.\./}{/}g;
11488: 	}
11489:     } #remove dir/..
11490:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
11491:     return $location;
11492: }
11493: 
11494: sub hreflocation {
11495:     my ($dir,$file)=@_;
11496:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
11497: 	$file=filelocation($dir,$file);
11498:     } elsif ($file=~m-^/adm/-) {
11499: 	$file=~s-^/adm/wrapper/-/-;
11500: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
11501:     }
11502:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
11503: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
11504:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
11505: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
11506: 	        {/uploaded/$1/$2/}x;
11507:     }
11508:     if ($file=~ m{^/userfiles/}) {
11509: 	$file =~ s{^/userfiles/}{/uploaded/};
11510:     }
11511:     return $file;
11512: }
11513: 
11514: 
11515: 
11516: 
11517: 
11518: sub current_machine_domains {
11519:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
11520: }
11521: 
11522: sub machine_domains {
11523:     my ($hostname) = @_;
11524:     my @domains;
11525:     my %hostname = &all_hostnames();
11526:     while( my($id, $name) = each(%hostname)) {
11527: #	&logthis("-$id-$name-$hostname-");
11528: 	if ($hostname eq $name) {
11529: 	    push(@domains,&host_domain($id));
11530: 	}
11531:     }
11532:     return @domains;
11533: }
11534: 
11535: sub current_machine_ids {
11536:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
11537: }
11538: 
11539: sub machine_ids {
11540:     my ($hostname) = @_;
11541:     $hostname ||= &hostname($perlvar{'lonHostID'});
11542:     my @ids;
11543:     my %name_to_host = &all_names();
11544:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
11545: 	return @{ $name_to_host{$hostname} };
11546:     }
11547:     return;
11548: }
11549: 
11550: sub additional_machine_domains {
11551:     my @domains;
11552:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
11553:     while( my $line = <$fh>) {
11554:         $line =~ s/\s//g;
11555:         push(@domains,$line);
11556:     }
11557:     return @domains;
11558: }
11559: 
11560: sub default_login_domain {
11561:     my $domain = $perlvar{'lonDefDomain'};
11562:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
11563:     foreach my $posdom (&current_machine_domains(),
11564:                         &additional_machine_domains()) {
11565:         if (lc($posdom) eq lc($testdomain)) {
11566:             $domain=$posdom;
11567:             last;
11568:         }
11569:     }
11570:     return $domain;
11571: }
11572: 
11573: # ------------------------------------------------------------- Declutters URLs
11574: 
11575: sub declutter {
11576:     my $thisfn=shift;
11577:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
11578:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
11579:     $thisfn=~s/^\///;
11580:     $thisfn=~s|^adm/wrapper/||;
11581:     $thisfn=~s|^adm/coursedocs/showdoc/||;
11582:     $thisfn=~s/^res\///;
11583:     $thisfn=~s/^priv\///;
11584:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
11585:         $thisfn=~s/\?.+$//;
11586:     }
11587:     return $thisfn;
11588: }
11589: 
11590: # ------------------------------------------------------------- Clutter up URLs
11591: 
11592: sub clutter {
11593:     my $thisfn='/'.&declutter(shift);
11594:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
11595: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
11596:        $thisfn='/res'.$thisfn; 
11597:     }
11598:     if ($thisfn !~m|^/adm|) {
11599: 	if ($thisfn =~ m|^/ext/|) {
11600: 	    $thisfn='/adm/wrapper'.$thisfn;
11601: 	} else {
11602: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
11603: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
11604: 	    if ($embstyle eq 'ssi'
11605: 		|| ($embstyle eq 'hdn')
11606: 		|| ($embstyle eq 'rat')
11607: 		|| ($embstyle eq 'prv')
11608: 		|| ($embstyle eq 'ign')) {
11609: 		#do nothing with these
11610: 	    } elsif (($embstyle eq 'img') 
11611: 		|| ($embstyle eq 'emb')
11612: 		|| ($embstyle eq 'wrp')) {
11613: 		$thisfn='/adm/wrapper'.$thisfn;
11614: 	    } elsif ($embstyle eq 'unk'
11615: 		     && $thisfn!~/\.(sequence|page)$/) {
11616: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
11617: 	    } else {
11618: #		&logthis("Got a blank emb style");
11619: 	    }
11620: 	}
11621:     }
11622:     return $thisfn;
11623: }
11624: 
11625: sub clutter_with_no_wrapper {
11626:     my $uri = &clutter(shift);
11627:     if ($uri =~ m-^/adm/-) {
11628: 	$uri =~ s-^/adm/wrapper/-/-;
11629: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
11630:     }
11631:     return $uri;
11632: }
11633: 
11634: sub freeze_escape {
11635:     my ($value)=@_;
11636:     if (ref($value)) {
11637: 	$value=&nfreeze($value);
11638: 	return '__FROZEN__'.&escape($value);
11639:     }
11640:     return &escape($value);
11641: }
11642: 
11643: 
11644: sub thaw_unescape {
11645:     my ($value)=@_;
11646:     if ($value =~ /^__FROZEN__/) {
11647: 	substr($value,0,10,undef);
11648: 	$value=&unescape($value);
11649: 	return &thaw($value);
11650:     }
11651:     return &unescape($value);
11652: }
11653: 
11654: sub correct_line_ends {
11655:     my ($result)=@_;
11656:     $$result =~s/\r\n/\n/mg;
11657:     $$result =~s/\r/\n/mg;
11658: }
11659: # ================================================================ Main Program
11660: 
11661: sub goodbye {
11662:    &logthis("Starting Shut down");
11663: #not converted to using infrastruture and probably shouldn't be
11664:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
11665: #converted
11666: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
11667:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
11668: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
11669: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
11670: #1.1 only
11671: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
11672: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
11673: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
11674: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
11675:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
11676:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
11677:    &logthis(sprintf("%-20s is %s",'hits',$hits));
11678:    &flushcourselogs();
11679:    &logthis("Shutting down");
11680: }
11681: 
11682: sub get_dns {
11683:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
11684:     if (!$ignore_cache) {
11685: 	my ($content,$cached)=
11686: 	    &Apache::lonnet::is_cached_new('dns',$url);
11687: 	if ($cached) {
11688: 	    &$func($content,$hashref);
11689: 	    return;
11690: 	}
11691:     }
11692: 
11693:     my %alldns;
11694:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11695:     foreach my $dns (<$config>) {
11696: 	next if ($dns !~ /^\^(\S*)/x);
11697:         my $line = $1;
11698:         my ($host,$protocol) = split(/:/,$line);
11699:         if ($protocol ne 'https') {
11700:             $protocol = 'http';
11701:         }
11702: 	$alldns{$host} = $protocol;
11703:     }
11704:     while (%alldns) {
11705: 	my ($dns) = keys(%alldns);
11706: 	my $ua=new LWP::UserAgent;
11707:         $ua->timeout(30);
11708: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
11709: 	my $response=$ua->request($request);
11710:         delete($alldns{$dns});
11711: 	next if ($response->is_error());
11712: 	my @content = split("\n",$response->content);
11713: 	unless ($nocache) {
11714: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
11715: 	}
11716: 	&$func(\@content,$hashref);
11717: 	return;
11718:     }
11719:     close($config);
11720:     my $which = (split('/',$url))[3];
11721:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
11722:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
11723:     my @content = <$config>;
11724:     &$func(\@content,$hashref);
11725:     return;
11726: }
11727: 
11728: # ------------------------------------------------------Get DNS checksums file
11729: sub parse_dns_checksums_tab {
11730:     my ($lines,$hashref) = @_;
11731:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
11732:     my $loncaparev = &get_server_loncaparev($machine_dom);
11733:     my ($release,$timestamp) = split(/\-/,$loncaparev);
11734:     my (%chksum,%revnum);
11735:     if (ref($lines) eq 'ARRAY') {
11736:         chomp(@{$lines});
11737:         my $version = shift(@{$lines});
11738:         if ($version eq $release) {  
11739:             foreach my $line (@{$lines}) {
11740:                 my ($file,$version,$shasum) = split(/,/,$line);
11741:                 $chksum{$file} = $shasum;
11742:                 $revnum{$file} = $version;
11743:             }
11744:             if (ref($hashref) eq 'HASH') {
11745:                 %{$hashref} = (
11746:                                 sums     => \%chksum,
11747:                                 versions => \%revnum,
11748:                               );
11749:             }
11750:         }
11751:     }
11752:     return;
11753: }
11754: 
11755: sub fetch_dns_checksums {
11756:     my %checksums;
11757:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
11758:     my $loncaparev = &get_server_loncaparev($machine_dom);
11759:     my ($release,$timestamp) = split(/\-/,$loncaparev);
11760:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
11761:              \%checksums);
11762:     return \%checksums;
11763: }
11764: 
11765: # ------------------------------------------------------------ Read domain file
11766: {
11767:     my $loaded;
11768:     my %domain;
11769: 
11770:     sub parse_domain_tab {
11771: 	my ($lines) = @_;
11772: 	foreach my $line (@$lines) {
11773: 	    next if ($line =~ /^(\#|\s*$ )/x);
11774: 
11775: 	    chomp($line);
11776: 	    my ($name,@elements) = split(/:/,$line,9);
11777: 	    my %this_domain;
11778: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
11779: 			       'lang_def', 'city', 'longi', 'lati',
11780: 			       'primary') {
11781: 		$this_domain{$field} = shift(@elements);
11782: 	    }
11783: 	    $domain{$name} = \%this_domain;
11784: 	}
11785:     }
11786: 
11787:     sub reset_domain_info {
11788: 	undef($loaded);
11789: 	undef(%domain);
11790:     }
11791: 
11792:     sub load_domain_tab {
11793: 	my ($ignore_cache) = @_;
11794: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
11795: 	my $fh;
11796: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
11797: 	    my @lines = <$fh>;
11798: 	    &parse_domain_tab(\@lines);
11799: 	}
11800: 	close($fh);
11801: 	$loaded = 1;
11802:     }
11803: 
11804:     sub domain {
11805: 	&load_domain_tab() if (!$loaded);
11806: 
11807: 	my ($name,$what) = @_;
11808: 	return if ( !exists($domain{$name}) );
11809: 
11810: 	if (!$what) {
11811: 	    return $domain{$name}{'description'};
11812: 	}
11813: 	return $domain{$name}{$what};
11814:     }
11815: 
11816:     sub domain_info {
11817:         &load_domain_tab() if (!$loaded);
11818:         return %domain;
11819:     }
11820: 
11821: }
11822: 
11823: 
11824: # ------------------------------------------------------------- Read hosts file
11825: {
11826:     my %hostname;
11827:     my %hostdom;
11828:     my %libserv;
11829:     my $loaded;
11830:     my %name_to_host;
11831:     my %internetdom;
11832:     my %LC_dns_serv;
11833: 
11834:     sub parse_hosts_tab {
11835: 	my ($file) = @_;
11836: 	foreach my $configline (@$file) {
11837: 	    next if ($configline =~ /^(\#|\s*$ )/x);
11838:             chomp($configline);
11839: 	    if ($configline =~ /^\^/) {
11840:                 if ($configline =~ /^\^([\w.\-]+)/) {
11841:                     $LC_dns_serv{$1} = 1;
11842:                 }
11843:                 next;
11844:             }
11845: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
11846: 	    $name=~s/\s//g;
11847: 	    if ($id && $domain && $role && $name) {
11848: 		$hostname{$id}=$name;
11849: 		push(@{$name_to_host{$name}}, $id);
11850: 		$hostdom{$id}=$domain;
11851: 		if ($role eq 'library') { $libserv{$id}=$name; }
11852:                 if (defined($protocol)) {
11853:                     if ($protocol eq 'https') {
11854:                         $protocol{$id} = $protocol;
11855:                     } else {
11856:                         $protocol{$id} = 'http'; 
11857:                     }
11858:                 } else {
11859:                     $protocol{$id} = 'http';
11860:                 }
11861:                 if (defined($intdom)) {
11862:                     $internetdom{$id} = $intdom;
11863:                 }
11864: 	    }
11865: 	}
11866:     }
11867:     
11868:     sub reset_hosts_info {
11869: 	&purge_remembered();
11870: 	&reset_domain_info();
11871: 	&reset_hosts_ip_info();
11872: 	undef(%name_to_host);
11873: 	undef(%hostname);
11874: 	undef(%hostdom);
11875: 	undef(%libserv);
11876: 	undef($loaded);
11877:     }
11878: 
11879:     sub load_hosts_tab {
11880: 	my ($ignore_cache) = @_;
11881: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
11882: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11883: 	my @config = <$config>;
11884: 	&parse_hosts_tab(\@config);
11885: 	close($config);
11886: 	$loaded=1;
11887:     }
11888: 
11889:     sub hostname {
11890: 	&load_hosts_tab() if (!$loaded);
11891: 
11892: 	my ($lonid) = @_;
11893: 	return $hostname{$lonid};
11894:     }
11895: 
11896:     sub all_hostnames {
11897: 	&load_hosts_tab() if (!$loaded);
11898: 
11899: 	return %hostname;
11900:     }
11901: 
11902:     sub all_names {
11903: 	&load_hosts_tab() if (!$loaded);
11904: 
11905: 	return %name_to_host;
11906:     }
11907: 
11908:     sub all_host_domain {
11909:         &load_hosts_tab() if (!$loaded);
11910:         return %hostdom;
11911:     }
11912: 
11913:     sub is_library {
11914: 	&load_hosts_tab() if (!$loaded);
11915: 
11916: 	return exists($libserv{$_[0]});
11917:     }
11918: 
11919:     sub all_library {
11920: 	&load_hosts_tab() if (!$loaded);
11921: 
11922: 	return %libserv;
11923:     }
11924: 
11925:     sub unique_library {
11926: 	#2x reverse removes all hostnames that appear more than once
11927:         my %unique = reverse &all_library();
11928:         return reverse %unique;
11929:     }
11930: 
11931:     sub get_servers {
11932: 	&load_hosts_tab() if (!$loaded);
11933: 
11934: 	my ($domain,$type) = @_;
11935: 	my %possible_hosts = ($type eq 'library') ? %libserv
11936: 	                                          : %hostname;
11937: 	my %result;
11938: 	if (ref($domain) eq 'ARRAY') {
11939: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
11940: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
11941: 		    $result{$host} = $hostname;
11942: 		}
11943: 	    }
11944: 	} else {
11945: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
11946: 		if ($hostdom{$host} eq $domain) {
11947: 		    $result{$host} = $hostname;
11948: 		}
11949: 	    }
11950: 	}
11951: 	return %result;
11952:     }
11953: 
11954:     sub get_unique_servers {
11955:         my %unique = reverse &get_servers(@_);
11956: 	return reverse %unique;
11957:     }
11958: 
11959:     sub host_domain {
11960: 	&load_hosts_tab() if (!$loaded);
11961: 
11962: 	my ($lonid) = @_;
11963: 	return $hostdom{$lonid};
11964:     }
11965: 
11966:     sub all_domains {
11967: 	&load_hosts_tab() if (!$loaded);
11968: 
11969: 	my %seen;
11970: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
11971: 	return @uniq;
11972:     }
11973: 
11974:     sub internet_dom {
11975:         &load_hosts_tab() if (!$loaded);
11976: 
11977:         my ($lonid) = @_;
11978:         return $internetdom{$lonid};
11979:     }
11980: 
11981:     sub is_LC_dns {
11982:         &load_hosts_tab() if (!$loaded);
11983: 
11984:         my ($hostname) = @_;
11985:         return exists($LC_dns_serv{$hostname});
11986:     }
11987: 
11988: }
11989: 
11990: { 
11991:     my %iphost;
11992:     my %name_to_ip;
11993:     my %lonid_to_ip;
11994: 
11995:     sub get_hosts_from_ip {
11996: 	my ($ip) = @_;
11997: 	my %iphosts = &get_iphost();
11998: 	if (ref($iphosts{$ip})) {
11999: 	    return @{$iphosts{$ip}};
12000: 	}
12001: 	return;
12002:     }
12003:     
12004:     sub reset_hosts_ip_info {
12005: 	undef(%iphost);
12006: 	undef(%name_to_ip);
12007: 	undef(%lonid_to_ip);
12008:     }
12009: 
12010:     sub get_host_ip {
12011: 	my ($lonid) = @_;
12012: 	if (exists($lonid_to_ip{$lonid})) {
12013: 	    return $lonid_to_ip{$lonid};
12014: 	}
12015: 	my $name=&hostname($lonid);
12016:    	my $ip = gethostbyname($name);
12017: 	return if (!$ip || length($ip) ne 4);
12018: 	$ip=inet_ntoa($ip);
12019: 	$name_to_ip{$name}   = $ip;
12020: 	$lonid_to_ip{$lonid} = $ip;
12021: 	return $ip;
12022:     }
12023:     
12024:     sub get_iphost {
12025: 	my ($ignore_cache) = @_;
12026: 
12027: 	if (!$ignore_cache) {
12028: 	    if (%iphost) {
12029: 		return %iphost;
12030: 	    }
12031: 	    my ($ip_info,$cached)=
12032: 		&Apache::lonnet::is_cached_new('iphost','iphost');
12033: 	    if ($cached) {
12034: 		%iphost      = %{$ip_info->[0]};
12035: 		%name_to_ip  = %{$ip_info->[1]};
12036: 		%lonid_to_ip = %{$ip_info->[2]};
12037: 		return %iphost;
12038: 	    }
12039: 	}
12040: 
12041: 	# get yesterday's info for fallback
12042: 	my %old_name_to_ip;
12043: 	my ($ip_info,$cached)=
12044: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
12045: 	if ($cached) {
12046: 	    %old_name_to_ip = %{$ip_info->[1]};
12047: 	}
12048: 
12049: 	my %name_to_host = &all_names();
12050: 	foreach my $name (keys(%name_to_host)) {
12051: 	    my $ip;
12052: 	    if (!exists($name_to_ip{$name})) {
12053: 		$ip = gethostbyname($name);
12054: 		if (!$ip || length($ip) ne 4) {
12055: 		    if (defined($old_name_to_ip{$name})) {
12056: 			$ip = $old_name_to_ip{$name};
12057: 			&logthis("Can't find $name defaulting to old $ip");
12058: 		    } else {
12059: 			&logthis("Name $name no IP found");
12060: 			next;
12061: 		    }
12062: 		} else {
12063: 		    $ip=inet_ntoa($ip);
12064: 		}
12065: 		$name_to_ip{$name} = $ip;
12066: 	    } else {
12067: 		$ip = $name_to_ip{$name};
12068: 	    }
12069: 	    foreach my $id (@{ $name_to_host{$name} }) {
12070: 		$lonid_to_ip{$id} = $ip;
12071: 	    }
12072: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
12073: 	}
12074: 	&do_cache_new('iphost','iphost',
12075: 		      [\%iphost,\%name_to_ip,\%lonid_to_ip],
12076: 		      48*60*60);
12077: 
12078: 	return %iphost;
12079:     }
12080: 
12081:     #
12082:     #  Given a DNS returns the loncapa host name for that DNS 
12083:     # 
12084:     sub host_from_dns {
12085:         my ($dns) = @_;
12086:         my @hosts;
12087:         my $ip;
12088: 
12089:         if (exists($name_to_ip{$dns})) {
12090:             $ip = $name_to_ip{$dns};
12091:         }
12092:         if (!$ip) {
12093:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
12094:             if (length($ip) == 4) { 
12095: 	        $ip   = &IO::Socket::inet_ntoa($ip);
12096:             }
12097:         }
12098:         if ($ip) {
12099: 	    @hosts = get_hosts_from_ip($ip);
12100: 	    return $hosts[0];
12101:         }
12102:         return undef;
12103:     }
12104: 
12105:     sub get_internet_names {
12106:         my ($lonid) = @_;
12107:         return if ($lonid eq '');
12108:         my ($idnref,$cached)=
12109:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
12110:         if ($cached) {
12111:             return $idnref;
12112:         }
12113:         my $ip = &get_host_ip($lonid);
12114:         my @hosts = &get_hosts_from_ip($ip);
12115:         my %iphost = &get_iphost();
12116:         my (@idns,%seen);
12117:         foreach my $id (@hosts) {
12118:             my $dom = &host_domain($id);
12119:             my $prim_id = &domain($dom,'primary');
12120:             my $prim_ip = &get_host_ip($prim_id);
12121:             next if ($seen{$prim_ip});
12122:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
12123:                 foreach my $id (@{$iphost{$prim_ip}}) {
12124:                     my $intdom = &internet_dom($id);
12125:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
12126:                         push(@idns,$intdom);
12127:                     }
12128:                 }
12129:             }
12130:             $seen{$prim_ip} = 1;
12131:         }
12132:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
12133:     }
12134: 
12135: }
12136: 
12137: sub all_loncaparevs {
12138:     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);
12139: }
12140: 
12141: # ---------------------------------------------------------- Read loncaparev table
12142: {
12143:     sub load_loncaparevs { 
12144:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
12145:             if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
12146:                 while (my $configline=<$config>) {
12147:                     chomp($configline);
12148:                     my ($hostid,$loncaparev)=split(/:/,$configline);
12149:                     $loncaparevs{$hostid}=$loncaparev;
12150:                 }
12151:                 close($config);
12152:             }
12153:         }
12154:     }
12155: }
12156: 
12157: # ---------------------------------------------------------- Read serverhostID table
12158: {
12159:     sub load_serverhomeIDs {
12160:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
12161:             if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
12162:                 while (my $configline=<$config>) {
12163:                     chomp($configline);
12164:                     my ($name,$id)=split(/:/,$configline);
12165:                     $serverhomeIDs{$name}=$id;
12166:                 }
12167:                 close($config);
12168:             }
12169:         }
12170:     }
12171: }
12172: 
12173: 
12174: BEGIN {
12175: 
12176: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
12177:     unless ($readit) {
12178: {
12179:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
12180:     %perlvar = (%perlvar,%{$configvars});
12181: }
12182: 
12183: 
12184: # ------------------------------------------------------ Read spare server file
12185: {
12186:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
12187: 
12188:     while (my $configline=<$config>) {
12189:        chomp($configline);
12190:        if ($configline) {
12191: 	   my ($host,$type) = split(':',$configline,2);
12192: 	   if (!defined($type) || $type eq '') { $type = 'default' };
12193: 	   push(@{ $spareid{$type} }, $host);
12194:        }
12195:     }
12196:     close($config);
12197: }
12198: # ------------------------------------------------------------ Read permissions
12199: {
12200:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
12201: 
12202:     while (my $configline=<$config>) {
12203: 	chomp($configline);
12204: 	if ($configline) {
12205: 	    my ($role,$perm)=split(/ /,$configline);
12206: 	    if ($perm ne '') { $pr{$role}=$perm; }
12207: 	}
12208:     }
12209:     close($config);
12210: }
12211: 
12212: # -------------------------------------------- Read plain texts for permissions
12213: {
12214:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
12215: 
12216:     while (my $configline=<$config>) {
12217: 	chomp($configline);
12218: 	if ($configline) {
12219: 	    my ($short,@plain)=split(/:/,$configline);
12220:             %{$prp{$short}} = ();
12221: 	    if (@plain > 0) {
12222:                 $prp{$short}{'std'} = $plain[0];
12223:                 for (my $i=1; $i<@plain; $i++) {
12224:                     $prp{$short}{'alt'.$i} = $plain[$i];  
12225:                 }
12226:             }
12227: 	}
12228:     }
12229:     close($config);
12230: }
12231: 
12232: # ---------------------------------------------------------- Read package table
12233: {
12234:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
12235: 
12236:     while (my $configline=<$config>) {
12237: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
12238: 	chomp($configline);
12239: 	my ($short,$plain)=split(/:/,$configline);
12240: 	my ($pack,$name)=split(/\&/,$short);
12241: 	if ($plain ne '') {
12242: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
12243: 	    $packagetab{$short}=$plain; 
12244: 	}
12245:     }
12246:     close($config);
12247: }
12248: 
12249: # ---------------------------------------------------------- Read loncaparev table
12250: 
12251: &load_loncaparevs();
12252: 
12253: # ---------------------------------------------------------- Read serverhostID table
12254: 
12255: &load_serverhomeIDs();
12256: 
12257: # ---------------------------------------------------------- Read releaseslist XML
12258: {
12259:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
12260:     if (-e $file) {
12261:         my $parser = HTML::LCParser->new($file);
12262:         while (my $token = $parser->get_token()) {
12263:             if ($token->[0] eq 'S') {
12264:                 my $item = $token->[1];
12265:                 my $name = $token->[2]{'name'};
12266:                 my $value = $token->[2]{'value'};
12267:                 if ($item ne '' && $name ne '' && $value ne '') {
12268:                     my $release = $parser->get_text();
12269:                     $release =~ s/(^\s*|\s*$ )//gx;
12270:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
12271:                 }
12272:             }
12273:         }
12274:     }
12275: }
12276: 
12277: # ---------------------------------------------------------- Read managers table
12278: {
12279:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
12280:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
12281:             while (my $configline=<$config>) {
12282:                 chomp($configline);
12283:                 next if ($configline =~ /^\#/);
12284:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
12285:                     $managerstab{$configline} = 1;
12286:                 }
12287:             }
12288:             close($config);
12289:         }
12290:     }
12291: }
12292: 
12293: # ------------- set up temporary directory
12294: {
12295:     $tmpdir = LONCAPA::tempdir();
12296: 
12297: }
12298: 
12299: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
12300: 				'compress_threshold'=> 20_000,
12301:  			        });
12302: 
12303: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
12304: $dumpcount=0;
12305: $locknum=0;
12306: 
12307: &logtouch();
12308: &logthis('<font color="yellow">INFO: Read configuration</font>');
12309: $readit=1;
12310:     {
12311: 	use integer;
12312: 	my $test=(2**32)+1;
12313: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
12314: 	&logthis(" Detected 64bit platform ($_64bit)");
12315:     }
12316: }
12317: }
12318: 
12319: 1;
12320: __END__
12321: 
12322: =pod
12323: 
12324: =head1 NAME
12325: 
12326: Apache::lonnet - Subroutines to ask questions about things in the network.
12327: 
12328: =head1 SYNOPSIS
12329: 
12330: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
12331: 
12332:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
12333: 
12334: Common parameters:
12335: 
12336: =over 4
12337: 
12338: =item *
12339: 
12340: $uname : an internal username (if $cname expecting a course Id specifically)
12341: 
12342: =item *
12343: 
12344: $udom : a domain (if $cdom expecting a course's domain specifically)
12345: 
12346: =item *
12347: 
12348: $symb : a resource instance identifier
12349: 
12350: =item *
12351: 
12352: $namespace : the name of a .db file that contains the data needed or
12353: being set.
12354: 
12355: =back
12356: 
12357: =head1 OVERVIEW
12358: 
12359: lonnet provides subroutines which interact with the
12360: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
12361: about classes, users, and resources.
12362: 
12363: For many of these objects you can also use this to store data about
12364: them or modify them in various ways.
12365: 
12366: =head2 Symbs
12367: 
12368: To identify a specific instance of a resource, LON-CAPA uses symbols
12369: or "symbs"X<symb>. These identifiers are built from the URL of the
12370: map, the resource number of the resource in the map, and the URL of
12371: the resource itself. The latter is somewhat redundant, but might help
12372: if maps change.
12373: 
12374: An example is
12375: 
12376:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
12377: 
12378: The respective map entry is
12379: 
12380:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
12381:   title="Problem 2">
12382:  </resource>
12383: 
12384: Symbs are used by the random number generator, as well as to store and
12385: restore data specific to a certain instance of for example a problem.
12386: 
12387: =head2 Storing And Retrieving Data
12388: 
12389: X<store()>X<cstore()>X<restore()>Three of the most important functions
12390: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
12391: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
12392: is is the non-critical message twin of cstore. These functions are for
12393: handlers to store a perl hash to a user's permanent data space in an
12394: easy manner, and to retrieve it again on another call. It is expected
12395: that a handler would use this once at the beginning to retrieve data,
12396: and then again once at the end to send only the new data back.
12397: 
12398: The data is stored in the user's data directory on the user's
12399: homeserver under the ID of the course.
12400: 
12401: The hash that is returned by restore will have all of the previous
12402: value for all of the elements of the hash.
12403: 
12404: Example:
12405: 
12406:  #creating a hash
12407:  my %hash;
12408:  $hash{'foo'}='bar';
12409: 
12410:  #storing it
12411:  &Apache::lonnet::cstore(\%hash);
12412: 
12413:  #changing a value
12414:  $hash{'foo'}='notbar';
12415: 
12416:  #adding a new value
12417:  $hash{'bar'}='foo';
12418:  &Apache::lonnet::cstore(\%hash);
12419: 
12420:  #retrieving the hash
12421:  my %history=&Apache::lonnet::restore();
12422: 
12423:  #print the hash
12424:  foreach my $key (sort(keys(%history))) {
12425:    print("\%history{$key} = $history{$key}");
12426:  }
12427: 
12428: Will print out:
12429: 
12430:  %history{1:foo} = bar
12431:  %history{1:keys} = foo:timestamp
12432:  %history{1:timestamp} = 990455579
12433:  %history{2:bar} = foo
12434:  %history{2:foo} = notbar
12435:  %history{2:keys} = foo:bar:timestamp
12436:  %history{2:timestamp} = 990455580
12437:  %history{bar} = foo
12438:  %history{foo} = notbar
12439:  %history{timestamp} = 990455580
12440:  %history{version} = 2
12441: 
12442: Note that the special hash entries C<keys>, C<version> and
12443: C<timestamp> were added to the hash. C<version> will be equal to the
12444: total number of versions of the data that have been stored. The
12445: C<timestamp> attribute will be the UNIX time the hash was
12446: stored. C<keys> is available in every historical section to list which
12447: keys were added or changed at a specific historical revision of a
12448: hash.
12449: 
12450: B<Warning>: do not store the hash that restore returns directly. This
12451: will cause a mess since it will restore the historical keys as if the
12452: were new keys. I.E. 1:foo will become 1:1:foo etc.
12453: 
12454: Calling convention:
12455: 
12456:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
12457:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname);
12458: 
12459: For more detailed information, see lonnet specific documentation.
12460: 
12461: =head1 RETURN MESSAGES
12462: 
12463: =over 4
12464: 
12465: =item * B<con_lost>: unable to contact remote host
12466: 
12467: =item * B<con_delayed>: unable to contact remote host, message will be delivered
12468: when the connection is brought back up
12469: 
12470: =item * B<con_failed>: unable to contact remote host and unable to save message
12471: for later delivery
12472: 
12473: =item * B<error:>: an error a occurred, a description of the error follows the :
12474: 
12475: =item * B<no_such_host>: unable to fund a host associated with the user/domain
12476: that was requested
12477: 
12478: =back
12479: 
12480: =head1 PUBLIC SUBROUTINES
12481: 
12482: =head2 Session Environment Functions
12483: 
12484: =over 4
12485: 
12486: =item * 
12487: X<appenv()>
12488: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
12489: the user envirnoment file, and will be restored for each access this
12490: user makes during this session, also modifies the %env for the current
12491: process. Optional rolesarrayref - if defined contains a reference to an array
12492: of roles which are exempt from the restriction on modifying user.role entries 
12493: in the user's environment.db and in %env.    
12494: 
12495: =item *
12496: X<delenv()>
12497: B<delenv($delthis,$regexp)>: removes all items from the session
12498: environment file that begin with $delthis. If the 
12499: optional second arg - $regexp - is true, $delthis is treated as a 
12500: regular expression, otherwise \Q$delthis\E is used. 
12501: The values are also deleted from the current processes %env.
12502: 
12503: =item * get_env_multiple($name) 
12504: 
12505: gets $name from the %env hash, it seemlessly handles the cases where multiple
12506: values may be defined and end up as an array ref.
12507: 
12508: returns an array of values
12509: 
12510: =back
12511: 
12512: =head2 User Information
12513: 
12514: =over 4
12515: 
12516: =item *
12517: X<queryauthenticate()>
12518: B<queryauthenticate($uname,$udom)>: try to determine user's current 
12519: authentication scheme
12520: 
12521: =item *
12522: X<authenticate()>
12523: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
12524: authenticate user from domain's lib servers (first use the current
12525: one). C<$upass> should be the users password.
12526: $checkdefauth is optional (value is 1 if a check should be made to
12527:    authenticate user using default authentication method, and allow
12528:    account creation if username does not have account in the domain).
12529: $clientcancheckhost is optional (value is 1 if checking whether the
12530:    server can host will occur on the client side in lonauth.pm).   
12531: 
12532: =item *
12533: X<homeserver()>
12534: B<homeserver($uname,$udom)>: find the server which has
12535: the user's directory and files (there must be only one), this caches
12536: the answer, and also caches if there is a borken connection.
12537: 
12538: =item *
12539: X<idget()>
12540: B<idget($udom,@ids)>: find the usernames behind a list of IDs
12541: (IDs are a unique resource in a domain, there must be only 1 ID per
12542: username, and only 1 username per ID in a specific domain) (returns
12543: hash: id=>name,id=>name)
12544: 
12545: =item *
12546: X<idrget()>
12547: B<idrget($udom,@unames)>: find the IDs behind a list of
12548: usernames (returns hash: name=>id,name=>id)
12549: 
12550: =item *
12551: X<idput()>
12552: B<idput($udom,%ids)>: store away a list of names and associated IDs
12553: 
12554: =item *
12555: X<rolesinit()>
12556: B<rolesinit($udom,$username)>: get user privileges.
12557: returns user role, first access and timer interval hashes
12558: 
12559: =item *
12560: X<privileged()>
12561: B<privileged($username,$domain)>: returns a true if user has a
12562: privileged and active role (i.e. su or dc), false otherwise.
12563: 
12564: =item *
12565: X<getsection()>
12566: B<getsection($udom,$uname,$cname)>: finds the section of student in the
12567: course $cname, return section name/number or '' for "not in course"
12568: and '-1' for "no section"
12569: 
12570: =item *
12571: X<userenvironment()>
12572: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
12573: passed in @what from the requested user's environment, returns a hash
12574: 
12575: =item * 
12576: X<userlog_query()>
12577: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
12578: activity.log file. %filters defines filters applied when parsing the
12579: log file. These can be start or end timestamps, or the type of action
12580: - log to look for Login or Logout events, check for Checkin or
12581: Checkout, role for role selection. The response is in the form
12582: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
12583: escaped strings of the action recorded in the activity.log file.
12584: 
12585: =back
12586: 
12587: =head2 User Roles
12588: 
12589: =over 4
12590: 
12591: =item *
12592: 
12593: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
12594:  F: full access
12595:  U,I,K: authentication modes (cxx only)
12596:  '': forbidden
12597:  1: user needs to choose course
12598:  2: browse allowed
12599:  A: passphrase authentication needed
12600: 
12601: =item *
12602: 
12603: constructaccess($url,$setpriv) : check for access to construction space URL
12604: 
12605: See if the owner domain and name in the URL match those in the
12606: expected environment.  If so, return three element list
12607: ($ownername,$ownerdomain,$ownerhome).
12608: 
12609: Otherwise return the null string.
12610: 
12611: If second argument 'setpriv' is true, it assigns the privileges,
12612: and returns the same three element list, unless the owner has
12613: blocked "ad hoc" Domain Coordinator access to the Author Space,
12614: in which case the null string is returned.
12615: 
12616: =item *
12617: 
12618: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
12619: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
12620: and course level
12621: 
12622: =item *
12623: 
12624: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
12625: (rolesplain.tab); plain text explanation of a user role term.
12626: $type is Course (default) or Community.
12627: If $forcedefault evaluates to true, text returned will be default 
12628: text for $type. Otherwise, if this is a course, the text returned 
12629: will be a custom name for the role (if defined in the course's 
12630: environment).  If no custom name is defined the default is returned.
12631:    
12632: =item *
12633: 
12634: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
12635: All arguments are optional. Returns a hash of a roles, either for
12636: co-author/assistant author roles for a user's Construction Space
12637: (default), or if $context is 'userroles', roles for the user himself,
12638: In the hash, keys are set to colon-separated $uname,$udom,$role, and
12639: (optionally) if $withsec is true, a fourth colon-separated item - $section.
12640: For each key, value is set to colon-separated start and end times for
12641: the role.  If no username and domain are specified, will default to
12642: current user/domain. Types, roles, and roledoms are references to arrays
12643: of role statuses (active, future or previous), roles 
12644: (e.g., cc,in, st etc.) and domains of the roles which can be used
12645: to restrict the list of roles reported. If no array ref is 
12646: provided for types, will default to return only active roles.
12647: 
12648: =item *
12649: 
12650: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
12651: user: $uname:$udom has a role in the course: $cdom_$cnum. 
12652: 
12653: Additional optional arguments are: $type (if role checking is to be restricted 
12654: to certain user status types -- previous (expired roles), active (currently
12655: available roles) or future (roles available in the future), and
12656: $hideprivileged -- if true will not report course roles for users who
12657: have active Domain Coordinator role in course's domain or in additional
12658: domains (specified in 'Domains to check for privileged users' in course
12659: environment -- set via:  Course Settings -> Classlists and staff listing).
12660: 
12661: =item *
12662: 
12663: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
12664: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
12665: $possdomains and $possroles are optional array refs -- to domains to check and
12666: roles to check.  If $possdomains is not specified, a dump will be done of the
12667: users' roles.db to check for a dc or su role in any domain. This can be
12668: time consuming if &privileged is called repeatedly (e.g., when displaying a
12669: classlist), so in such cases, supplying a $possdomains array is preferred, as
12670: this then allows &privileged_by_domain() to be used, which caches the identity
12671: of privileged users, eliminating the need for repeated calls to &dump().
12672: 
12673: =item *
12674: 
12675: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
12676: where the outer hash keys are domains specified in the $possdomains array ref,
12677: next inner hash keys are privileged roles specified in the $roles array ref,
12678: and the innermost hash contains key = value pairs for username:domain = end:start
12679: for active or future "privileged" users with that role in that domain. To avoid
12680: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
12681: innerhash are cached using priv_$role and $dom as the identifiers.
12682: 
12683: =back
12684: 
12685: =head2 User Modification
12686: 
12687: =over 4
12688: 
12689: =item *
12690: 
12691: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
12692: user for the level given by URL.  Optional start and end dates (leave empty
12693: string or zero for "no date")
12694: 
12695: =item *
12696: 
12697: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
12698: change a users, password, possible return values are: ok,
12699: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
12700: refused
12701: 
12702: =item *
12703: 
12704: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
12705: 
12706: =item *
12707: 
12708: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
12709:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
12710: 
12711: will update user information (firstname,middlename,lastname,generation,
12712: permanentemail), and if forceid is true, student/employee ID also.
12713: A user's institutional affiliation(s) can also be updated.
12714: User information fields will not be overwritten with empty entries 
12715: unless the field is included in the $candelete array reference.
12716: This array is included when a single user is modified via "Manage Users",
12717: or when Autoupdate.pl is run by cron in a domain.
12718: 
12719: =item *
12720: 
12721: modifystudent
12722: 
12723: modify a student's enrollment and identification information.
12724: The course id is resolved based on the current user's environment.  
12725: This means the invoking user must be a course coordinator or otherwise
12726: associated with a course.
12727: 
12728: This call is essentially a wrapper for lonnet::modifyuser and
12729: lonnet::modify_student_enrollment
12730: 
12731: Inputs: 
12732: 
12733: =over 4
12734: 
12735: =item B<$udom> Student's loncapa domain
12736: 
12737: =item B<$uname> Student's loncapa login name
12738: 
12739: =item B<$uid> Student/Employee ID
12740: 
12741: =item B<$umode> Student's authentication mode
12742: 
12743: =item B<$upass> Student's password
12744: 
12745: =item B<$first> Student's first name
12746: 
12747: =item B<$middle> Student's middle name
12748: 
12749: =item B<$last> Student's last name
12750: 
12751: =item B<$gene> Student's generation
12752: 
12753: =item B<$usec> Student's section in course
12754: 
12755: =item B<$end> Unix time of the roles expiration
12756: 
12757: =item B<$start> Unix time of the roles start date
12758: 
12759: =item B<$forceid> If defined, allow $uid to be changed
12760: 
12761: =item B<$desiredhome> server to use as home server for student
12762: 
12763: =item B<$email> Student's permanent e-mail address
12764: 
12765: =item B<$type> Type of enrollment (auto or manual)
12766: 
12767: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
12768: 
12769: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
12770: 
12771: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
12772: 
12773: =item B<$context> role change context (shown in User Management Logs display in a course)
12774: 
12775: =item B<$inststatus> institutional status of user - : separated string of escaped status types
12776: 
12777: =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.
12778: 
12779: =back
12780: 
12781: =item *
12782: 
12783: modify_student_enrollment
12784: 
12785: Change a student's enrollment status in a class.  The environment variable
12786: 'role.request.course' must be defined for this function to proceed.
12787: 
12788: Inputs:
12789: 
12790: =over 4
12791: 
12792: =item $udom, student's domain
12793: 
12794: =item $uname, student's name
12795: 
12796: =item $uid, student's user id
12797: 
12798: =item $first, student's first name
12799: 
12800: =item $middle
12801: 
12802: =item $last
12803: 
12804: =item $gene
12805: 
12806: =item $usec
12807: 
12808: =item $end
12809: 
12810: =item $start
12811: 
12812: =item $type
12813: 
12814: =item $locktype
12815: 
12816: =item $cid
12817: 
12818: =item $selfenroll
12819: 
12820: =item $context
12821: 
12822: =item $credits, number of credits student will earn from this class
12823: 
12824: =back
12825: 
12826: 
12827: =item *
12828: 
12829: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
12830: custom role; give a custom role to a user for the level given by URL.  Specify
12831: name and domain of role author, and role name
12832: 
12833: =item *
12834: 
12835: revokerole($udom,$uname,$url,$role) : revoke a role for url
12836: 
12837: =item *
12838: 
12839: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
12840: 
12841: =back
12842: 
12843: =head2 Course Infomation
12844: 
12845: =over 4
12846: 
12847: =item *
12848: 
12849: coursedescription($courseid,$options) : returns a hash of information about the
12850: specified course id, including all environment settings for the
12851: course, the description of the course will be in the hash under the
12852: key 'description'
12853: 
12854: $options is an optional parameter that if supplied is a hash reference that controls
12855: what how this function works.  It has the following key/values:
12856: 
12857: =over 4
12858: 
12859: =item freshen_cache
12860: 
12861: If defined, and the environment cache for the course is valid, it is 
12862: returned in the returned hash.
12863: 
12864: =item one_time
12865: 
12866: If defined, the last cache time is set to _now_
12867: 
12868: =item user
12869: 
12870: If defined, the supplied username is used instead of the current user.
12871: 
12872: 
12873: =back
12874: 
12875: =item *
12876: 
12877: resdata($name,$domain,$type,@which) : request for current parameter
12878: setting for a specific $type, where $type is either 'course' or 'user',
12879: @what should be a list of parameters to ask about. This routine caches
12880: answers for 10 minutes.
12881: 
12882: =item *
12883: 
12884: get_courseresdata($courseid, $domain) : dump the entire course resource
12885: data base, returning a hash that is keyed by the resource name and has
12886: values that are the resource value.  I believe that the timestamps and
12887: versions are also returned.
12888: 
12889: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
12890: supplemental content area. This routine caches the number of files for 
12891: 10 minutes.
12892: 
12893: =back
12894: 
12895: =head2 Course Modification
12896: 
12897: =over 4
12898: 
12899: =item *
12900: 
12901: writecoursepref($courseid,%prefs) : write preferences (environment
12902: database) for a course
12903: 
12904: =item *
12905: 
12906: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
12907: 
12908: =item *
12909: 
12910: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
12911: 
12912: =item *
12913: 
12914: is_course($courseid), is_course($cdom, $cnum)
12915: 
12916: Accepts either a combined $courseid (in the form of domain_courseid) or the
12917: two component version $cdom, $cnum. It checks if the specified course exists.
12918: 
12919: Returns:
12920:     undef if the course doesn't exist, otherwise
12921:     in scalar context the combined courseid.
12922:     in list context the two components of the course identifier, domain and 
12923:     courseid.    
12924: 
12925: =back
12926: 
12927: =head2 Resource Subroutines
12928: 
12929: =over 4
12930: 
12931: =item *
12932: 
12933: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
12934: 
12935: =item *
12936: 
12937: repcopy($filename) : subscribes to the requested file, and attempts to
12938: replicate from the owning library server, Might return
12939: 'unavailable', 'not_found', 'forbidden', 'ok', or
12940: 'bad_request', also attempts to grab the metadata for the
12941: resource. Expects the local filesystem pathname
12942: (/home/httpd/html/res/....)
12943: 
12944: =back
12945: 
12946: =head2 Resource Information
12947: 
12948: =over 4
12949: 
12950: =item *
12951: 
12952: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
12953: and returns the value of a variety of different possible values,
12954: $varname should be a request string, and the other parameters can be
12955: used to specify who and what one is asking about. Ordinarily, $cid 
12956: does not need to be specified, as it is retrived from 
12957: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
12958: within lonuserstate::loadmap() when initializing a course, before
12959: $env{'request.course.id'} has been set, so it needs to be provided
12960: in that one case.
12961: 
12962: Possible values for $varname are environment.lastname (or other item
12963: from the envirnment hash), user.name (or someother aspect about the
12964: user), resource.0.maxtries (or some other part and parameter of a
12965: resource)
12966: 
12967: =item *
12968: 
12969: directcondval($number) : get current value of a condition; reads from a state
12970: string
12971: 
12972: =item *
12973: 
12974: condval($condidx) : value of condition index based on state
12975: 
12976: =item *
12977: 
12978: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
12979: resource's metadata, $what should be either a specific key, or either
12980: 'keys' (to get a list of possible keys) or 'packages' to get a list of
12981: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
12982: 
12983: this function automatically caches all requests
12984: 
12985: =item *
12986: 
12987: metadata_query($query,$custom,$customshow) : make a metadata query against the
12988: network of library servers; returns file handle of where SQL and regex results
12989: will be stored for query
12990: 
12991: =item *
12992: 
12993: symbread($filename) : return symbolic list entry (filename argument optional);
12994: returns the data handle
12995: 
12996: =item *
12997: 
12998: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
12999: and is a possible symb for the URL in $thisfn, and if is an encrypted
13000: resource that the user accessed using /enc/ returns a 1 on success, 0
13001: on failure, user must be in a course, as it assumes the existence of
13002: the course initial hash, and uses $env('request.course.id'}.  The third
13003: arg is an optional reference to a scalar.  If this arg is passed in the 
13004: call to symbverify, it will be set to 1 if the symb has been set to be 
13005: encrypted; otherwise it will be null.  
13006: 
13007: =item *
13008: 
13009: symbclean($symb) : removes versions numbers from a symb, returns the
13010: cleaned symb
13011: 
13012: =item *
13013: 
13014: is_on_map($uri) : checks if the $uri is somewhere on the current
13015: course map, user must be in a course for it to work.
13016: 
13017: =item *
13018: 
13019: numval($salt) : return random seed value (addend for rndseed)
13020: 
13021: =item *
13022: 
13023: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
13024: a random seed, all arguments are optional, if they aren't sent it uses the
13025: environment to derive them. Note: if symb isn't sent and it can't get one
13026: from &symbread it will use the current time as its return value
13027: 
13028: =item *
13029: 
13030: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
13031: unfakeable, receipt
13032: 
13033: =item *
13034: 
13035: receipt() : API to ireceipt working off of env values; given out to users
13036: 
13037: =item *
13038: 
13039: countacc($url) : count the number of accesses to a given URL
13040: 
13041: =item *
13042: 
13043: 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
13044: 
13045: =item *
13046: 
13047: 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)
13048: 
13049: =item *
13050: 
13051: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
13052: 
13053: =item *
13054: 
13055: devalidate($symb) : devalidate temporary spreadsheet calculations,
13056: forcing spreadsheet to reevaluate the resource scores next time.
13057: 
13058: =item * 
13059: 
13060: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
13061: when viewing in course context.
13062: 
13063:  input: six args -- filename (decluttered), course number, course domain,
13064:                     url, symb (if registered) and group (if this is a 
13065:                     group item -- e.g., bulletin board, group page etc.).
13066: 
13067:  output: array of five scalars --
13068:          $cfile -- url for file editing if editable on current server
13069:          $home -- homeserver of resource (i.e., for author if published,
13070:                                           or course if uploaded.).
13071:          $switchserver --  1 if server switch will be needed.
13072:          $forceedit -- 1 if icon/link should be to go to edit mode 
13073:          $forceview -- 1 if icon/link should be to go to view mode
13074: 
13075: =item *
13076: 
13077: is_course_upload($file,$cnum,$cdom)
13078: 
13079: Used in course context to determine if current file was uploaded to 
13080: the course (i.e., would be found in /userfiles/docs on the course's 
13081: homeserver.
13082: 
13083:   input: 3 args -- filename (decluttered), course number and course domain.
13084:   output: boolean -- 1 if file was uploaded.
13085: 
13086: =back
13087: 
13088: =head2 Storing/Retreiving Data
13089: 
13090: =over 4
13091: 
13092: =item *
13093: 
13094: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
13095: for this url; hashref needs to be given and should be a \%hashname; the
13096: remaining args aren't required and if they aren't passed or are '' they will
13097: be derived from the env
13098: 
13099: =item *
13100: 
13101: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
13102: uses critical subroutine
13103: 
13104: =item *
13105: 
13106: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
13107: all args are optional
13108: 
13109: =item *
13110: 
13111: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
13112: dumps the complete (or key matching regexp) namespace into a hash
13113: ($udom, $uname, $regexp, $range are optional) for a namespace that is
13114: normally &store()ed into
13115: 
13116: $range should be either an integer '100' (give me the first 100
13117:                                            matching records)
13118:               or be  two integers sperated by a - with no spaces
13119:                  '30-50' (give me the 30th through the 50th matching
13120:                           records)
13121: 
13122: 
13123: =item *
13124: 
13125: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
13126: replaces a &store() version of data with a replacement set of data
13127: for a particular resource in a namespace passed in the $storehash hash 
13128: reference
13129: 
13130: =item *
13131: 
13132: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
13133: works very similar to store/cstore, but all data is stored in a
13134: temporary location and can be reset using tmpreset, $storehash should
13135: be a hash reference, returns nothing on success
13136: 
13137: =item *
13138: 
13139: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
13140: similar to restore, but all data is stored in a temporary location and
13141: can be reset using tmpreset. Returns a hash of values on success,
13142: error string otherwise.
13143: 
13144: =item *
13145: 
13146: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
13147: deltes all keys for $symb form the temporary storage hash.
13148: 
13149: =item *
13150: 
13151: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13152: reference filled in from namesp ($udom and $uname are optional)
13153: 
13154: =item *
13155: 
13156: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
13157: namesp ($udom and $uname are optional)
13158: 
13159: =item *
13160: 
13161: dump($namespace,$udom,$uname,$regexp,$range) : 
13162: dumps the complete (or key matching regexp) namespace into a hash
13163: ($udom, $uname, $regexp, $range are optional)
13164: 
13165: $range should be either an integer '100' (give me the first 100
13166:                                            matching records)
13167:               or be  two integers sperated by a - with no spaces
13168:                  '30-50' (give me the 30th through the 50th matching
13169:                           records)
13170: =item *
13171: 
13172: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
13173: $store can be a scalar, an array reference, or if the amount to be 
13174: incremented is > 1, a hash reference.
13175: 
13176: ($udom and $uname are optional)
13177: 
13178: =item *
13179: 
13180: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
13181: ($udom and $uname are optional)
13182: 
13183: =item *
13184: 
13185: cput($namespace,$storehash,$udom,$uname) : critical put
13186: ($udom and $uname are optional)
13187: 
13188: =item *
13189: 
13190: newput($namespace,$storehash,$udom,$uname) :
13191: 
13192: Attempts to store the items in the $storehash, but only if they don't
13193: currently exist, if this succeeds you can be certain that you have 
13194: successfully created a new key value pair in the $namespace db.
13195: 
13196: 
13197: Args:
13198:  $namespace: name of database to store values to
13199:  $storehash: hashref to store to the db
13200:  $udom: (optional) domain of user containing the db
13201:  $uname: (optional) name of user caontaining the db
13202: 
13203: Returns:
13204:  'ok' -> succeeded in storing all keys of $storehash
13205:  'key_exists: <key>' -> failed to anything out of $storehash, as at
13206:                         least <key> already existed in the db (other
13207:                         requested keys may also already exist)
13208:  'error: <msg>' -> unable to tie the DB or other error occurred
13209:  'con_lost' -> unable to contact request server
13210:  'refused' -> action was not allowed by remote machine
13211: 
13212: 
13213: =item *
13214: 
13215: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13216: reference filled in from namesp (encrypts the return communication)
13217: ($udom and $uname are optional)
13218: 
13219: =item *
13220: 
13221: log($udom,$name,$home,$message) : write to permanent log for user; use
13222: critical subroutine
13223: 
13224: =item *
13225: 
13226: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
13227: array reference filled in from namespace found in domain level on either
13228: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
13229: 
13230: =item *
13231: 
13232: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
13233: domain level either on specified domain server ($uhome) or primary domain 
13234: server ($udom and $uhome are optional)
13235: 
13236: =item * 
13237: 
13238: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
13239: for: authentication, language, quotas, timezone, date locale, and portal URL in
13240: the target domain.
13241: 
13242: May also include additional key => value pairs for the following groups:
13243: 
13244: =over
13245: 
13246: =item
13247: disk quotas (MB allocated by default to portfolios and authoring spaces).
13248: 
13249: =over
13250: 
13251: =item defaultquota, authorquota
13252: 
13253: =back
13254: 
13255: =item
13256: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
13257: portfolio for users).
13258: 
13259: =over
13260: 
13261: =item
13262: aboutme, blog, webdav, portfolio
13263: 
13264: =back
13265: 
13266: =item
13267: requestcourses: ability to request courses, and how requests are processed.
13268: 
13269: =over
13270: 
13271: =item
13272: official, unofficial, community, textbook
13273: 
13274: =back
13275: 
13276: =item
13277: inststatus: types of institutional affiliation, and order in which they are displayed.
13278: 
13279: =over
13280: 
13281: =item
13282: inststatustypes, inststatusorder
13283: 
13284: =back
13285: 
13286: =item
13287: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
13288: for course's uploaded content.
13289: 
13290: =over
13291: 
13292: =item
13293: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
13294: communityquota, textbookquota
13295: 
13296: =back
13297: 
13298: =item
13299: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
13300: on your servers.
13301: 
13302: =over
13303: 
13304: =item 
13305: remotesessions, hostedsessions
13306: 
13307: =back
13308: 
13309: =back
13310: 
13311: In cases where a domain coordinator has never used the "Set Domain Configuration"
13312: utility to create a configuration.db file on a domain's primary library server 
13313: only the following domain defaults: auth_def, auth_arg_def, lang_def
13314: -- corresponding values are authentication type (internal, krb4, krb5,
13315: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
13316: will be available. Values are retrieved from cache (if current), unless the
13317: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
13318: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
13319: 
13320: Typical usage:
13321: 
13322: %domdefaults = &get_domain_defaults($target_domain);
13323: 
13324: =back
13325: 
13326: =head2 Network Status Functions
13327: 
13328: =over 4
13329: 
13330: =item *
13331: 
13332: dirlist() : return directory list based on URI (first arg).
13333: 
13334: Inputs: 1 required, 5 optional.
13335: 
13336: =over
13337: 
13338: =item 
13339: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
13340: 
13341: =item
13342: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
13343: 
13344: =item
13345: $username -  username of user/course to be listed. Extracted from $uri if absent. 
13346: 
13347: =item
13348: $getpropath - boolean: 1 if prepend path using &propath(). 
13349: 
13350: =item
13351: $getuserdir - boolean: 1 if prepend path for "userfiles".
13352: 
13353: =item 
13354: $alternateRoot - path to prepend in place of path from $uri.
13355: 
13356: =back
13357: 
13358: Returns: Array of up to two items.
13359: 
13360: =over
13361: 
13362: a reference to an array of files/subdirectories
13363: 
13364: =over
13365: 
13366: Each element in the array of files/subdirectories is a & separated list of
13367: item name and the result of running stat on the item.  If dirlist was requested
13368: for a file instead of a directory, the item name will be ''. For a directory 
13369: listing, if the item is a metadata file, the element will end &N&M 
13370: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
13371: default copyright set (1).  
13372: 
13373: =back
13374: 
13375: a scalar containing error condition (if encountered).
13376: 
13377: =over
13378: 
13379: =item 
13380: no_host (no homeserver identified for $username:$domain).
13381: 
13382: =item 
13383: no_such_host (server contacted for listing not identified as valid host).
13384: 
13385: =item 
13386: con_lost (connection to remote server failed).
13387: 
13388: =item 
13389: refused (invalid $username:$domain received on lond side).
13390: 
13391: =item 
13392: no_such_dir (directory at specified path on lond side does not exist). 
13393: 
13394: =item 
13395: empty (directory at specified path on lond side is empty).
13396: 
13397: =over
13398: 
13399: This is currently not encountered because the &ls3, &ls2, 
13400: &ls (_handler) routines on the lond side do not filter out
13401: . and .. from a directory listing. 
13402: 
13403: =back
13404: 
13405: =back
13406: 
13407: =back
13408: 
13409: =item *
13410: 
13411: spareserver() : find server with least workload from spare.tab
13412: 
13413: 
13414: =item *
13415: 
13416: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
13417: if there is no corresponding loncapa host.
13418: 
13419: =back
13420: 
13421: 
13422: =head2 Apache Request
13423: 
13424: =over 4
13425: 
13426: =item *
13427: 
13428: ssi($url,%hash) : server side include, does a complete request cycle on url to
13429: localhost, posts hash
13430: 
13431: =back
13432: 
13433: =head2 Data to String to Data
13434: 
13435: =over 4
13436: 
13437: =item *
13438: 
13439: hash2str(%hash) : convert a hash into a string complete with escaping and '='
13440: and '&' separators, supports elements that are arrayrefs and hashrefs
13441: 
13442: =item *
13443: 
13444: hashref2str($hashref) : convert a hashref into a string complete with
13445: escaping and '=' and '&' separators, supports elements that are
13446: arrayrefs and hashrefs
13447: 
13448: =item *
13449: 
13450: arrayref2str($arrayref) : convert an arrayref into a string complete
13451: with escaping and '&' separators, supports elements that are arrayrefs
13452: and hashrefs
13453: 
13454: =item *
13455: 
13456: str2hash($string) : convert string to hash using unescaping and
13457: splitting on '=' and '&', supports elements that are arrayrefs and
13458: hashrefs
13459: 
13460: =item *
13461: 
13462: str2array($string) : convert string to hash using unescaping and
13463: splitting on '&', supports elements that are arrayrefs and hashrefs
13464: 
13465: =back
13466: 
13467: =head2 Logging Routines
13468: 
13469: 
13470: These routines allow one to make log messages in the lonnet.log and
13471: lonnet.perm logfiles.
13472: 
13473: =over 4
13474: 
13475: =item *
13476: 
13477: logtouch() : make sure the logfile, lonnet.log, exists
13478: 
13479: =item *
13480: 
13481: logthis() : append message to the normal lonnet.log file, it gets
13482: preiodically rolled over and deleted.
13483: 
13484: =item *
13485: 
13486: logperm() : append a permanent message to lonnet.perm.log, this log
13487: file never gets deleted by any automated portion of the system, only
13488: messages of critical importance should go in here.
13489: 
13490: 
13491: =back
13492: 
13493: =head2 General File Helper Routines
13494: 
13495: =over 4
13496: 
13497: =item *
13498: 
13499: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
13500: (a) files in /uploaded
13501:   (i) If a local copy of the file exists - 
13502:       compares modification date of local copy with last-modified date for 
13503:       definitive version stored on home server for course. If local copy is 
13504:       stale, requests a new version from the home server and stores it. 
13505:       If the original has been removed from the home server, then local copy 
13506:       is unlinked.
13507:   (ii) If local copy does not exist -
13508:       requests the file from the home server and stores it. 
13509:   
13510:   If $caller is 'uploadrep':  
13511:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
13512:     for request for files originally uploaded via DOCS. 
13513:      - returns 'ok' if fresh local copy now available, -1 otherwise.
13514:   
13515:   Otherwise:
13516:      This indicates a call from the content generation phase of the request.
13517:      -  returns the entire contents of the file or -1.
13518:      
13519: (b) files in /res
13520:    - returns the entire contents of a file or -1; 
13521:    it properly subscribes to and replicates the file if neccessary.
13522: 
13523: 
13524: =item *
13525: 
13526: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
13527:                   reference
13528: 
13529: returns either a stat() list of data about the file or an empty list
13530: if the file doesn't exist or couldn't find out about it (connection
13531: problems or user unknown)
13532: 
13533: =item *
13534: 
13535: filelocation($dir,$file) : returns file system location of a file
13536: based on URI; meant to be "fairly clean" absolute reference, $dir is a
13537: directory that relative $file lookups are to looked in ($dir of /a/dir
13538: and a file of ../bob will become /a/bob)
13539: 
13540: =item *
13541: 
13542: hreflocation($dir,$file) : returns file system location or a URL; same as
13543: filelocation except for hrefs
13544: 
13545: =item *
13546: 
13547: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
13548: 
13549: =back
13550: 
13551: =head2 Usererfile file routines (/uploaded*)
13552: 
13553: =over 4
13554: 
13555: =item *
13556: 
13557: userfileupload(): main rotine for putting a file in a user or course's
13558:                   filespace, arguments are,
13559: 
13560:  formname - required - this is the name of the element in $env where the
13561:            filename, and the contents of the file to create/modifed exist
13562:            the filename is in $env{'form.'.$formname.'.filename'} and the
13563:            contents of the file is located in $env{'form.'.$formname}
13564:  context - if coursedoc, store the file in the course of the active role
13565:              of the current user; 
13566:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
13567:            if 'canceloverwrite': delete file in tmp/overwrites directory
13568:  subdir - required - subdirectory to put the file in under ../userfiles/
13569:          if undefined, it will be placed in "unknown"
13570: 
13571:  (This routine calls clean_filename() to remove any dangerous
13572:  characters from the filename, and then calls finuserfileupload() to
13573:  complete the transaction)
13574: 
13575:  returns either the url of the uploaded file (/uploaded/....) if successful
13576:  and /adm/notfound.html if unsuccessful
13577: 
13578: =item *
13579: 
13580: clean_filename(): routine for cleaing a filename up for storage in
13581:                  userfile space, argument is:
13582: 
13583:  filename - proposed filename
13584: 
13585: returns: the new clean filename
13586: 
13587: =item *
13588: 
13589: finishuserfileupload(): routine that creates and sends the file to
13590: userspace, probably shouldn't be called directly
13591: 
13592:   docuname: username or courseid of destination for the file
13593:   docudom: domain of user/course of destination for the file
13594:   formname: same as for userfileupload()
13595:   fname: filename (including subdirectories) for the file
13596:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
13597:   allfiles: reference to hash used to store objects found by parser
13598:   codebase: reference to hash used for codebases of java objects found by parser
13599:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
13600:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
13601:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
13602:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
13603:   context: if 'overwrite', will move the uploaded file from its temporary location to
13604:             userfiles to facilitate overwriting a previously uploaded file with same name.
13605:   mimetype: reference to scalar to accommodate mime type determined
13606:             from File::MMagic if $parser = parse.
13607: 
13608:  returns either the url of the uploaded file (/uploaded/....) if successful
13609:  and /adm/notfound.html if unsuccessful (or an error message if context 
13610:  was 'overwrite').
13611:  
13612: 
13613: =item *
13614: 
13615: renameuserfile(): renames an existing userfile to a new name
13616: 
13617:   Args:
13618:    docuname: username or courseid of destination for the file
13619:    docudom: domain of user/course of destination for the file
13620:    old: current file name (including any subdirs under userfiles)
13621:    new: desired file name (including any subdirs under userfiles)
13622: 
13623: =item *
13624: 
13625: mkdiruserfile(): creates a directory is a userfiles dir
13626: 
13627:   Args:
13628:    docuname: username or courseid of destination for the file
13629:    docudom: domain of user/course of destination for the file
13630:    dir: dir to create (including any subdirs under userfiles)
13631: 
13632: =item *
13633: 
13634: removeuserfile(): removes a file that exists in userfiles
13635: 
13636:   Args:
13637:    docuname: username or courseid of destination for the file
13638:    docudom: domain of user/course of destination for the file
13639:    fname: filname to delete (including any subdirs under userfiles)
13640: 
13641: =item *
13642: 
13643: removeuploadedurl(): convience function for removeuserfile()
13644: 
13645:   Args:
13646:    url:  a full /uploaded/... url to delete
13647: 
13648: =item * 
13649: 
13650: get_portfile_permissions():
13651:   Args:
13652:     domain: domain of user or course contain the portfolio files
13653:     user: name of user or num of course contain the portfolio files
13654:   Returns:
13655:     hashref of a dump of the proper file_permissions.db
13656:    
13657: 
13658: =item * 
13659: 
13660: get_access_controls():
13661: 
13662: Args:
13663:   current_permissions: the hash ref returned from get_portfile_permissions()
13664:   group: (optional) the group you want the files associated with
13665:   file: (optional) the file you want access info on
13666: 
13667: Returns:
13668:     a hash (keys are file names) of hashes containing
13669:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
13670:         values are XML containing access control settings (see below) 
13671: 
13672: Internal notes:
13673: 
13674:  access controls are stored in file_permissions.db as key=value pairs.
13675:     key -> path to file/file_name\0uniqueID:scope_end_start
13676:         where scope -> public,guest,course,group,domains or users.
13677:               end -> UNIX time for end of access (0 -> no end date)
13678:               start -> UNIX time for start of access
13679: 
13680:     value -> XML description of access control
13681:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
13682:             <start></start>
13683:             <end></end>
13684: 
13685:             <password></password>  for scope type = guest
13686: 
13687:             <domain></domain>     for scope type = course or group
13688:             <number></number>
13689:             <roles id="">
13690:              <role></role>
13691:              <access></access>
13692:              <section></section>
13693:              <group></group>
13694:             </roles>
13695: 
13696:             <dom></dom>         for scope type = domains
13697: 
13698:             <users>             for scope type = users
13699:              <user>
13700:               <uname></uname>
13701:               <udom></udom>
13702:              </user>
13703:             </users>
13704:            </scope> 
13705:               
13706:  Access data is also aggregated for each file in an additional key=value pair:
13707:  key -> path to file/file_name\0accesscontrol 
13708:  value -> reference to hash
13709:           hash contains key = value pairs
13710:           where key = uniqueID:scope_end_start
13711:                 value = UNIX time record was last updated
13712: 
13713:           Used to improve speed of look-ups of access controls for each file.  
13714:  
13715:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
13716: 
13717: =item *
13718: 
13719: modify_access_controls():
13720: 
13721: Modifies access controls for a portfolio file
13722: Args
13723: 1. file name
13724: 2. reference to hash of required changes,
13725: 3. domain
13726: 4. username
13727:   where domain,username are the domain of the portfolio owner 
13728:   (either a user or a course) 
13729: 
13730: Returns:
13731: 1. result of additions or updates ('ok' or 'error', with error message). 
13732: 2. result of deletions ('ok' or 'error', with error message).
13733: 3. reference to hash of any new or updated access controls.
13734: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
13735:    key = integer (inbound ID)
13736:    value = uniqueID
13737: 
13738: =item *
13739: 
13740: get_timebased_id():
13741: 
13742: Attempts to get a unique timestamp-based suffix for use with items added to a 
13743: course via the Course Editor (e.g., folders, composite pages, 
13744: group bulletin boards).
13745: 
13746: Args: (first three required; six others optional)
13747: 
13748: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
13749:    docssequence, or name of group
13750: 
13751: 2. keyid (alphanumeric): name of temporary locking key in hash,
13752:    e.g., num, boardids
13753: 
13754: 3. namespace: name of gdbm file used to store suffixes already assigned;  
13755:    file will be named nohist_namespace.db
13756: 
13757: 4. cdom: domain of course; default is current course domain from %env
13758: 
13759: 5. cnum: course number; default is current course number from %env
13760: 
13761: 6. idtype: set to concat if an additional digit is to be appended to the 
13762:    unix timestamp to form the suffix, if the plain timestamp is already
13763:    in use.  Default is to not do this, but simply increment the unix 
13764:    timestamp by 1 until a unique key is obtained.
13765: 
13766: 7. who: holder of locking key; defaults to user:domain for user.
13767: 
13768: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
13769:    retrying); default is 3.
13770: 
13771: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
13772: 
13773: Returns:
13774: 
13775: 1. suffix obtained (numeric)
13776: 
13777: 2. result of deleting locking key (ok if deleted, or lock never obtained)
13778: 
13779: 3. error: contains (localized) error message if an error occurred.
13780: 
13781: 
13782: =back
13783: 
13784: =head2 HTTP Helper Routines
13785: 
13786: =over 4
13787: 
13788: =item *
13789: 
13790: escape() : unpack non-word characters into CGI-compatible hex codes
13791: 
13792: =item *
13793: 
13794: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
13795: 
13796: =back
13797: 
13798: =head1 PRIVATE SUBROUTINES
13799: 
13800: =head2 Underlying communication routines (Shouldn't call)
13801: 
13802: =over 4
13803: 
13804: =item *
13805: 
13806: subreply() : tries to pass a message to lonc, returns con_lost if incapable
13807: 
13808: =item *
13809: 
13810: reply() : uses subreply to send a message to remote machine, logs all failures
13811: 
13812: =item *
13813: 
13814: critical() : passes a critical message to another server; if cannot
13815: get through then place message in connection buffer directory and
13816: returns con_delayed, if incapable of saving message, returns
13817: con_failed
13818: 
13819: =item *
13820: 
13821: reconlonc() : tries to reconnect lonc client processes.
13822: 
13823: =back
13824: 
13825: =head2 Resource Access Logging
13826: 
13827: =over 4
13828: 
13829: =item *
13830: 
13831: flushcourselogs() : flush (save) buffer logs and access logs
13832: 
13833: =item *
13834: 
13835: courselog($what) : save message for course in hash
13836: 
13837: =item *
13838: 
13839: courseacclog($what) : save message for course using &courselog().  Perform
13840: special processing for specific resource types (problems, exams, quizzes, etc).
13841: 
13842: =item *
13843: 
13844: goodbye() : flush course logs and log shutting down; it is called in srm.conf
13845: as a PerlChildExitHandler
13846: 
13847: =back
13848: 
13849: =head2 Other
13850: 
13851: =over 4
13852: 
13853: =item *
13854: 
13855: symblist($mapname,%newhash) : update symbolic storage links
13856: 
13857: =back
13858: 
13859: =cut
13860: 

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