File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1256: download - view: text, annotated - select for diffs
Wed Apr 23 10:11:34 2014 UTC (10 years, 2 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Institutional ststus types can now be defined via domain configuration
  web interface by Domain Coordinator -- will supercede use of customized
  localenroll::inst_usertypes().

- Self-creation of account with e-mail address as username:
  - Domain configuration to set which status types (faculty, staff , student
    etc.) can apply to "non-institutional" usernames.
  - Processing of username requests can be either automatic or queued for
    approval depending on status type (self-reported).

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1256 2014/04/23 10:11:34 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 =~ m{^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, $required) = @_;
  894: 
  895:     if ($required) {
  896:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
  897:         my $remoterev = &get_server_loncaparev(undef,$try_server);
  898:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
  899:         if (($major eq '' && $minor eq '') ||
  900:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
  901:             return ($spare_server,$lowest_load);
  902:         }
  903:     }
  904: 
  905:     my $loadans     = &reply('load',    $try_server);
  906:     my $userloadans = &reply('userload',$try_server);
  907: 
  908:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
  909: 	return ($spare_server, $lowest_load); #didn't get a number from the server
  910:     }
  911: 
  912:     my $load;
  913:     if ($loadans =~ /\d/) {
  914: 	if ($userloadans =~ /\d/) {
  915: 	    #both are numbers, pick the bigger one
  916: 	    $load = ($loadans > $userloadans) ? $loadans 
  917: 		                              : $userloadans;
  918: 	} else {
  919: 	    $load = $loadans;
  920: 	}
  921:     } else {
  922: 	$load = $userloadans;
  923:     }
  924: 
  925:     if (($load =~ /\d/) && ($load < $lowest_load)) {
  926: 	$spare_server = $try_server;
  927: 	$lowest_load  = $load;
  928:     }
  929:     return ($spare_server,$lowest_load);
  930: }
  931: 
  932: # --------------------------- ask offload servers if user already has a session
  933: sub find_existing_session {
  934:     my ($udom,$uname) = @_;
  935:     my $spareshash = &this_host_spares($udom);
  936:     if (ref($spareshash) eq 'HASH') {
  937:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
  938:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
  939:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
  940:             }
  941:         }
  942:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
  943:             foreach my $try_server (@{ $spareshash->{'default'} }) {
  944:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
  945:             }
  946:         }
  947:     }
  948:     return;
  949: }
  950: 
  951: # -------------------------------- ask if server already has a session for user
  952: sub has_user_session {
  953:     my ($lonid,$udom,$uname) = @_;
  954:     my $result = &reply(join(':','userhassession',
  955: 			     map {&escape($_)} ($udom,$uname)),$lonid);
  956:     return 1 if ($result eq 'ok');
  957: 
  958:     return 0;
  959: }
  960: 
  961: # --------- determine least loaded server in a user's domain which allows login
  962: 
  963: sub choose_server {
  964:     my ($udom,$checkloginvia,$required) = @_;
  965:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
  966:     my %servers = &get_servers($udom);
  967:     my $lowest_load = 30000;
  968:     my ($login_host,$hostname,$portal_path,$isredirect);
  969:     foreach my $lonhost (keys(%servers)) {
  970:         my $loginvia;
  971:         if ($checkloginvia) {
  972:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
  973:             if ($loginvia) {
  974:                 my ($server,$path) = split(/:/,$loginvia);
  975:                 ($login_host, $lowest_load) =
  976:                     &compare_server_load($server, $login_host, $lowest_load, $required);
  977:                 if ($login_host eq $server) {
  978:                     $portal_path = $path;
  979:                     $isredirect = 1;
  980:                 }
  981:             } else {
  982:                 ($login_host, $lowest_load) =
  983:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
  984:                 if ($login_host eq $lonhost) {
  985:                     $portal_path = '';
  986:                     $isredirect = ''; 
  987:                 }
  988:             }
  989:         } else {
  990:             ($login_host, $lowest_load) =
  991:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
  992:         }
  993:     }
  994:     if ($login_host ne '') {
  995:         $hostname = &hostname($login_host);
  996:     }
  997:     return ($login_host,$hostname,$portal_path,$isredirect);
  998: }
  999: 
 1000: # --------------------------------------------- Try to change a user's password
 1001: 
 1002: sub changepass {
 1003:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
 1004:     $currentpass = &escape($currentpass);
 1005:     $newpass     = &escape($newpass);
 1006:     my $lonhost = $perlvar{'lonHostID'};
 1007:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
 1008: 		       $server);
 1009:     if (! $answer) {
 1010: 	&logthis("No reply on password change request to $server ".
 1011: 		 "by $uname in domain $udom.");
 1012:     } elsif ($answer =~ "^ok") {
 1013:         &logthis("$uname in $udom successfully changed their password ".
 1014: 		 "on $server.");
 1015:     } elsif ($answer =~ "^pwchange_failure") {
 1016: 	&logthis("$uname in $udom was unable to change their password ".
 1017: 		 "on $server.  The action was blocked by either lcpasswd ".
 1018: 		 "or pwchange");
 1019:     } elsif ($answer =~ "^non_authorized") {
 1020:         &logthis("$uname in $udom did not get their password correct when ".
 1021: 		 "attempting to change it on $server.");
 1022:     } elsif ($answer =~ "^auth_mode_error") {
 1023:         &logthis("$uname in $udom attempted to change their password despite ".
 1024: 		 "not being locally or internally authenticated on $server.");
 1025:     } elsif ($answer =~ "^unknown_user") {
 1026:         &logthis("$uname in $udom attempted to change their password ".
 1027: 		 "on $server but were unable to because $server is not ".
 1028: 		 "their home server.");
 1029:     } elsif ($answer =~ "^refused") {
 1030: 	&logthis("$server refused to change $uname in $udom password because ".
 1031: 		 "it was sent an unencrypted request to change the password.");
 1032:     } elsif ($answer =~ "invalid_client") {
 1033:         &logthis("$server refused to change $uname in $udom password because ".
 1034:                  "it was a reset by e-mail originating from an invalid server.");
 1035:     }
 1036:     return $answer;
 1037: }
 1038: 
 1039: # ----------------------- Try to determine user's current authentication scheme
 1040: 
 1041: sub queryauthenticate {
 1042:     my ($uname,$udom)=@_;
 1043:     my $uhome=&homeserver($uname,$udom);
 1044:     if (!$uhome) {
 1045: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
 1046: 	return 'no_host';
 1047:     }
 1048:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
 1049:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
 1050: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1051:     }
 1052:     return $answer;
 1053: }
 1054: 
 1055: # --------- Try to authenticate user from domain's lib servers (first this one)
 1056: 
 1057: sub authenticate {
 1058:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
 1059:     $upass=&escape($upass);
 1060:     $uname= &LONCAPA::clean_username($uname);
 1061:     my $uhome=&homeserver($uname,$udom,1);
 1062:     my $newhome;
 1063:     if ((!$uhome) || ($uhome eq 'no_host')) {
 1064: # Maybe the machine was offline and only re-appeared again recently?
 1065:         &reconlonc();
 1066: # One more
 1067: 	$uhome=&homeserver($uname,$udom,1);
 1068:         if (($uhome eq 'no_host') && $checkdefauth) {
 1069:             if (defined(&domain($udom,'primary'))) {
 1070:                 $newhome=&domain($udom,'primary');
 1071:             }
 1072:             if ($newhome ne '') {
 1073:                 $uhome = $newhome;
 1074:             }
 1075:         }
 1076: 	if ((!$uhome) || ($uhome eq 'no_host')) {
 1077: 	    &logthis("User $uname at $udom is unknown in authenticate");
 1078: 	    return 'no_host';
 1079:         }
 1080:     }
 1081:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
 1082:     if ($answer eq 'authorized') {
 1083:         if ($newhome) {
 1084:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
 1085:             return 'no_account_on_host'; 
 1086:         } else {
 1087:             &logthis("User $uname at $udom authorized by $uhome");
 1088:             return $uhome;
 1089:         }
 1090:     }
 1091:     if ($answer eq 'non_authorized') {
 1092: 	&logthis("User $uname at $udom rejected by $uhome");
 1093: 	return 'no_host'; 
 1094:     }
 1095:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1096:     return 'no_host';
 1097: }
 1098: 
 1099: sub can_host_session {
 1100:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
 1101:     my $canhost = 1;
 1102:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
 1103:     if (ref($remotesessions) eq 'HASH') {
 1104:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
 1105:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
 1106:                 $canhost = 0;
 1107:             } else {
 1108:                 $canhost = 1;
 1109:             }
 1110:         }
 1111:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
 1112:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
 1113:                 $canhost = 1;
 1114:             } else {
 1115:                 $canhost = 0;
 1116:             }
 1117:         }
 1118:         if ($canhost) {
 1119:             if ($remotesessions->{'version'} ne '') {
 1120:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
 1121:                 if ($reqmajor ne '' && $reqminor ne '') {
 1122:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
 1123:                         my $major = $1;
 1124:                         my $minor = $2;
 1125:                         if (($major < $reqmajor ) ||
 1126:                             (($major == $reqmajor) && ($minor < $reqminor))) {
 1127:                             $canhost = 0;
 1128:                         }
 1129:                     } else {
 1130:                         $canhost = 0;
 1131:                     }
 1132:                 }
 1133:             }
 1134:         }
 1135:     }
 1136:     if ($canhost) {
 1137:         if (ref($hostedsessions) eq 'HASH') {
 1138:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1139:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
 1140:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
 1141:                 if (($uint_dom ne '') && 
 1142:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
 1143:                     $canhost = 0;
 1144:                 } else {
 1145:                     $canhost = 1;
 1146:                 }
 1147:             }
 1148:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
 1149:                 if (($uint_dom ne '') && 
 1150:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
 1151:                     $canhost = 1;
 1152:                 } else {
 1153:                     $canhost = 0;
 1154:                 }
 1155:             }
 1156:         }
 1157:     }
 1158:     return $canhost;
 1159: }
 1160: 
 1161: sub spare_can_host {
 1162:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
 1163:     my $canhost=1;
 1164:     my @intdoms;
 1165:     my $internet_names = &Apache::lonnet::get_internet_names($try_server);
 1166:     if (ref($internet_names) eq 'ARRAY') {
 1167:         @intdoms = @{$internet_names};
 1168:     }
 1169:     unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
 1170:         my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
 1171:         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
 1172:         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
 1173:         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
 1174:         $canhost = &can_host_session($udom,$try_server,$remoterev,
 1175:                                      $remotesessions,
 1176:                                      $defdomdefaults{'hostedsessions'});
 1177:     }
 1178:     return $canhost;
 1179: }
 1180: 
 1181: sub this_host_spares {
 1182:     my ($dom) = @_;
 1183:     my ($dom_in_use,$lonhost_in_use,$result);
 1184:     my @hosts = &current_machine_ids();
 1185:     foreach my $lonhost (@hosts) {
 1186:         if (&host_domain($lonhost) eq $dom) {
 1187:             $dom_in_use = $dom;
 1188:             $lonhost_in_use = $lonhost;
 1189:             last;
 1190:         }
 1191:     }
 1192:     if ($dom_in_use ne '') {
 1193:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1194:     }
 1195:     if (ref($result) ne 'HASH') {
 1196:         $lonhost_in_use = $perlvar{'lonHostID'};
 1197:         $dom_in_use = &host_domain($lonhost_in_use);
 1198:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1199:         if (ref($result) ne 'HASH') {
 1200:             $result = \%spareid;
 1201:         }
 1202:     }
 1203:     return $result;
 1204: }
 1205: 
 1206: sub spares_for_offload  {
 1207:     my ($dom_in_use,$lonhost_in_use) = @_;
 1208:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
 1209:     if (defined($cached)) {
 1210:         return $result;
 1211:     } else {
 1212:         my $cachetime = 60*60*24;
 1213:         my %domconfig =
 1214:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
 1215:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
 1216:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
 1217:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
 1218:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
 1219:                 }
 1220:             }
 1221:         }
 1222:     }
 1223:     return;
 1224: }
 1225: 
 1226: sub get_lonbalancer_config {
 1227:     my ($servers) = @_;
 1228:     my ($currbalancer,$currtargets);
 1229:     if (ref($servers) eq 'HASH') {
 1230:         foreach my $server (keys(%{$servers})) {
 1231:             my %what = (
 1232:                          spareid => 1,
 1233:                          perlvar => 1,
 1234:                        );
 1235:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
 1236:             if ($result eq 'ok') {
 1237:                 if (ref($returnhash) eq 'HASH') {
 1238:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
 1239:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
 1240:                             $currbalancer = $server;
 1241:                             $currtargets = {};
 1242:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
 1243:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
 1244:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
 1245:                                 }
 1246:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
 1247:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
 1248:                                 }
 1249:                             }
 1250:                             last;
 1251:                         }
 1252:                     }
 1253:                 }
 1254:             }
 1255:         }
 1256:     }
 1257:     return ($currbalancer,$currtargets);
 1258: }
 1259: 
 1260: sub check_loadbalancing {
 1261:     my ($uname,$udom) = @_;
 1262:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
 1263:         $rule_in_effect,$offloadto,$otherserver);
 1264:     my $lonhost = $perlvar{'lonHostID'};
 1265:     my @hosts = &current_machine_ids();
 1266:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1267:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
 1268:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
 1269:     my $serverhomedom = &host_domain($lonhost);
 1270: 
 1271:     my $cachetime = 60*60*24;
 1272: 
 1273:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1274:         $dom_in_use = $udom;
 1275:         $homeintdom = 1;
 1276:     } else {
 1277:         $dom_in_use = $serverhomedom;
 1278:     }
 1279:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
 1280:     unless (defined($cached)) {
 1281:         my %domconfig =
 1282:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
 1283:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1284:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1285:         }
 1286:     }
 1287:     if (ref($result) eq 'HASH') {
 1288:         ($is_balancer,$currtargets,$currrules) = 
 1289:             &check_balancer_result($result,@hosts);
 1290:         if ($is_balancer) {
 1291:             if (ref($currrules) eq 'HASH') {
 1292:                 if ($homeintdom) {
 1293:                     if ($uname ne '') {
 1294:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
 1295:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
 1296:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
 1297:                                 $rule_in_effect = $currrules->{'_LC_author'};
 1298:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
 1299:                                 $rule_in_effect = $currrules->{'_LC_adv'}
 1300:                             }
 1301:                         }
 1302:                         if ($rule_in_effect eq '') {
 1303:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
 1304:                             if ($userenv{'inststatus'} ne '') {
 1305:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
 1306:                                 my ($othertitle,$usertypes,$types) =
 1307:                                     &Apache::loncommon::sorted_inst_types($udom);
 1308:                                 if (ref($types) eq 'ARRAY') {
 1309:                                     foreach my $type (@{$types}) {
 1310:                                         if (grep(/^\Q$type\E$/,@statuses)) {
 1311:                                             if (exists($currrules->{$type})) {
 1312:                                                 $rule_in_effect = $currrules->{$type};
 1313:                                             }
 1314:                                         }
 1315:                                     }
 1316:                                 }
 1317:                             } else {
 1318:                                 if (exists($currrules->{'default'})) {
 1319:                                     $rule_in_effect = $currrules->{'default'};
 1320:                                 }
 1321:                             }
 1322:                         }
 1323:                     } else {
 1324:                         if (exists($currrules->{'default'})) {
 1325:                             $rule_in_effect = $currrules->{'default'};
 1326:                         }
 1327:                     }
 1328:                 } else {
 1329:                     if ($currrules->{'_LC_external'} ne '') {
 1330:                         $rule_in_effect = $currrules->{'_LC_external'};
 1331:                     }
 1332:                 }
 1333:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1334:                                                        $uname,$udom);
 1335:             }
 1336:         }
 1337:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
 1338:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
 1339:         unless (defined($cached)) {
 1340:             my %domconfig =
 1341:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
 1342:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1343:                 $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1344:             }
 1345:         }
 1346:         if (ref($result) eq 'HASH') {
 1347:             ($is_balancer,$currtargets,$currrules) = 
 1348:                 &check_balancer_result($result,@hosts);
 1349:             if ($is_balancer) {
 1350:                 if (ref($currrules) eq 'HASH') {
 1351:                     if ($currrules->{'_LC_internetdom'} ne '') {
 1352:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
 1353:                     }
 1354:                 }
 1355:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1356:                                                        $uname,$udom);
 1357:             }
 1358:         } else {
 1359:             if ($perlvar{'lonBalancer'} eq 'yes') {
 1360:                 $is_balancer = 1;
 1361:                 $offloadto = &this_host_spares($dom_in_use);
 1362:             }
 1363:         }
 1364:     } else {
 1365:         if ($perlvar{'lonBalancer'} eq 'yes') {
 1366:             $is_balancer = 1;
 1367:             $offloadto = &this_host_spares($dom_in_use);
 1368:         }
 1369:     }
 1370:     if ($is_balancer) {
 1371:         my $lowest_load = 30000;
 1372:         if (ref($offloadto) eq 'HASH') {
 1373:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
 1374:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
 1375:                     ($otherserver,$lowest_load) =
 1376:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1377:                 }
 1378:             }
 1379:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
 1380: 
 1381:             if (!$found_server) {
 1382:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
 1383:                     foreach my $try_server (@{$offloadto->{'default'}}) {
 1384:                         ($otherserver,$lowest_load) =
 1385:                             &compare_server_load($try_server,$otherserver,$lowest_load);
 1386:                     }
 1387:                 }
 1388:             }
 1389:         } elsif (ref($offloadto) eq 'ARRAY') {
 1390:             if (@{$offloadto} == 1) {
 1391:                 $otherserver = $offloadto->[0];
 1392:             } elsif (@{$offloadto} > 1) {
 1393:                 foreach my $try_server (@{$offloadto}) {
 1394:                     ($otherserver,$lowest_load) =
 1395:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1396:                 }
 1397:             }
 1398:         }
 1399:         if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
 1400:             $is_balancer = 0;
 1401:             if ($uname ne '' && $udom ne '') {
 1402:                 if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
 1403:                     
 1404:                     &appenv({'user.loadbalexempt'     => $lonhost,  
 1405:                              'user.loadbalcheck.time' => time});
 1406:                 }
 1407:             }
 1408:         }
 1409:     }
 1410:     return ($is_balancer,$otherserver);
 1411: }
 1412: 
 1413: sub check_balancer_result {
 1414:     my ($result,@hosts) = @_;
 1415:     my ($is_balancer,$currtargets,$currrules);
 1416:     if (ref($result) eq 'HASH') {
 1417:         if ($result->{'lonhost'} ne '') {
 1418:             my $currbalancer = $result->{'lonhost'};
 1419:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
 1420:                 $is_balancer = 1;
 1421:                 $currtargets = $result->{'targets'};
 1422:                 $currrules = $result->{'rules'};
 1423:             }
 1424:         } else {
 1425:             foreach my $key (keys(%{$result})) {
 1426:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
 1427:                     (ref($result->{$key}) eq 'HASH')) {
 1428:                     $is_balancer = 1;
 1429:                     $currrules = $result->{$key}{'rules'};
 1430:                     $currtargets = $result->{$key}{'targets'};
 1431:                     last;
 1432:                 }
 1433:             }
 1434:         }
 1435:     }
 1436:     return ($is_balancer,$currtargets,$currrules);
 1437: }
 1438: 
 1439: sub get_loadbalancer_targets {
 1440:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
 1441:     my $offloadto;
 1442:     if ($rule_in_effect eq 'none') {
 1443:         return [$perlvar{'lonHostID'}];
 1444:     } elsif ($rule_in_effect eq '') {
 1445:         $offloadto = $currtargets;
 1446:     } else {
 1447:         if ($rule_in_effect eq 'homeserver') {
 1448:             my $homeserver = &homeserver($uname,$udom);
 1449:             if ($homeserver ne 'no_host') {
 1450:                 $offloadto = [$homeserver];
 1451:             }
 1452:         } elsif ($rule_in_effect eq 'externalbalancer') {
 1453:             my %domconfig =
 1454:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
 1455:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1456:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
 1457:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
 1458:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
 1459:                     }
 1460:                 }
 1461:             } else {
 1462:                 my %servers = &internet_dom_servers($udom);
 1463:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
 1464:                 if (&hostname($remotebalancer) ne '') {
 1465:                     $offloadto = [$remotebalancer];
 1466:                 }
 1467:             }
 1468:         } elsif (&hostname($rule_in_effect) ne '') {
 1469:             $offloadto = [$rule_in_effect];
 1470:         }
 1471:     }
 1472:     return $offloadto;
 1473: }
 1474: 
 1475: sub internet_dom_servers {
 1476:     my ($dom) = @_;
 1477:     my (%uniqservers,%servers);
 1478:     my $primaryserver = &hostname(&domain($dom,'primary'));
 1479:     my @machinedoms = &machine_domains($primaryserver);
 1480:     foreach my $mdom (@machinedoms) {
 1481:         my %currservers = %servers;
 1482:         my %server = &get_servers($mdom);
 1483:         %servers = (%currservers,%server);
 1484:     }
 1485:     my %by_hostname;
 1486:     foreach my $id (keys(%servers)) {
 1487:         push(@{$by_hostname{$servers{$id}}},$id);
 1488:     }
 1489:     foreach my $hostname (sort(keys(%by_hostname))) {
 1490:         if (@{$by_hostname{$hostname}} > 1) {
 1491:             my $match = 0;
 1492:             foreach my $id (@{$by_hostname{$hostname}}) {
 1493:                 if (&host_domain($id) eq $dom) {
 1494:                     $uniqservers{$id} = $hostname;
 1495:                     $match = 1;
 1496:                 }
 1497:             }
 1498:             unless ($match) {
 1499:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1500:             }
 1501:         } else {
 1502:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1503:         }
 1504:     }
 1505:     return %uniqservers;
 1506: }
 1507: 
 1508: # ---------------------- Find the homebase for a user from domain's lib servers
 1509: 
 1510: my %homecache;
 1511: sub homeserver {
 1512:     my ($uname,$udom,$ignoreBadCache)=@_;
 1513:     my $index="$uname:$udom";
 1514: 
 1515:     if (exists($homecache{$index})) { return $homecache{$index}; }
 1516: 
 1517:     my %servers = &get_servers($udom,'library');
 1518:     foreach my $tryserver (keys(%servers)) {
 1519:         next if ($ignoreBadCache ne 'true' && 
 1520: 		 exists($badServerCache{$tryserver}));
 1521: 
 1522: 	my $answer=reply("home:$udom:$uname",$tryserver);
 1523: 	if ($answer eq 'found') {
 1524: 	    delete($badServerCache{$tryserver}); 
 1525: 	    return $homecache{$index}=$tryserver;
 1526: 	} elsif ($answer eq 'no_host') {
 1527: 	    $badServerCache{$tryserver}=1;
 1528: 	}
 1529:     }    
 1530:     return 'no_host';
 1531: }
 1532: 
 1533: # ------------------------------------- Find the usernames behind a list of IDs
 1534: 
 1535: sub idget {
 1536:     my ($udom,@ids)=@_;
 1537:     my %returnhash=();
 1538:     
 1539:     my %servers = &get_servers($udom,'library');
 1540:     foreach my $tryserver (keys(%servers)) {
 1541: 	my $idlist=join('&',@ids);
 1542: 	$idlist=~tr/A-Z/a-z/; 
 1543: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
 1544: 	my @answer=();
 1545: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
 1546: 	    @answer=split(/\&/,$reply);
 1547: 	}                    ;
 1548: 	my $i;
 1549: 	for ($i=0;$i<=$#ids;$i++) {
 1550: 	    if ($answer[$i]) {
 1551: 		$returnhash{$ids[$i]}=$answer[$i];
 1552: 	    } 
 1553: 	}
 1554:     } 
 1555:     return %returnhash;
 1556: }
 1557: 
 1558: # ------------------------------------- Find the IDs behind a list of usernames
 1559: 
 1560: sub idrget {
 1561:     my ($udom,@unames)=@_;
 1562:     my %returnhash=();
 1563:     foreach my $uname (@unames) {
 1564:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
 1565:     }
 1566:     return %returnhash;
 1567: }
 1568: 
 1569: # ------------------------------- Store away a list of names and associated IDs
 1570: 
 1571: sub idput {
 1572:     my ($udom,%ids)=@_;
 1573:     my %servers=();
 1574:     foreach my $uname (keys(%ids)) {
 1575: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
 1576:         my $uhom=&homeserver($uname,$udom);
 1577:         if ($uhom ne 'no_host') {
 1578:             my $id=&escape($ids{$uname});
 1579:             $id=~tr/A-Z/a-z/;
 1580:             my $esc_unam=&escape($uname);
 1581: 	    if ($servers{$uhom}) {
 1582: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
 1583:             } else {
 1584:                 $servers{$uhom}=$id.'='.$esc_unam;
 1585:             }
 1586:         }
 1587:     }
 1588:     foreach my $server (keys(%servers)) {
 1589:         &critical('idput:'.$udom.':'.$servers{$server},$server);
 1590:     }
 1591: }
 1592: 
 1593: # ---------------------------------------- Delete unwanted IDs from ids.db file 
 1594: 
 1595: sub iddel {
 1596:     my ($udom,$idshashref,$uhome)=@_;
 1597:     my %result=();
 1598:     unless (ref($idshashref) eq 'HASH') {
 1599:         return %result;
 1600:     }
 1601:     my %servers=();
 1602:     while (my ($id,$uname) = each(%{$idshashref})) {
 1603:         my $uhom;
 1604:         if ($uhome) {
 1605:             $uhom = $uhome;
 1606:         } else {
 1607:             $uhom=&homeserver($uname,$udom);
 1608:         }
 1609:         if ($uhom ne 'no_host') {
 1610:             if ($servers{$uhom}) {
 1611:                 $servers{$uhom}.='&'.&escape($id);
 1612:             } else {
 1613:                 $servers{$uhom}=&escape($id);
 1614:             }
 1615:         }
 1616:     }
 1617:     foreach my $server (keys(%servers)) {
 1618:         $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
 1619:     }
 1620:     return %result;
 1621: }
 1622: 
 1623: # ------------------------------dump from db file owned by domainconfig user
 1624: sub dump_dom {
 1625:     my ($namespace, $udom, $regexp) = @_;
 1626: 
 1627:     $udom ||= $env{'user.domain'};
 1628: 
 1629:     return () unless $udom;
 1630: 
 1631:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
 1632: }
 1633: 
 1634: # ------------------------------------------ get items from domain db files   
 1635: 
 1636: sub get_dom {
 1637:     my ($namespace,$storearr,$udom,$uhome)=@_;
 1638:     my $items='';
 1639:     foreach my $item (@$storearr) {
 1640:         $items.=&escape($item).'&';
 1641:     }
 1642:     $items=~s/\&$//;
 1643:     if (!$udom) {
 1644:         $udom=$env{'user.domain'};
 1645:         if (defined(&domain($udom,'primary'))) {
 1646:             $uhome=&domain($udom,'primary');
 1647:         } else {
 1648:             undef($uhome);
 1649:         }
 1650:     } else {
 1651:         if (!$uhome) {
 1652:             if (defined(&domain($udom,'primary'))) {
 1653:                 $uhome=&domain($udom,'primary');
 1654:             }
 1655:         }
 1656:     }
 1657:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1658:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
 1659:         my %returnhash;
 1660:         if ($rep eq '' || $rep =~ /^error: 2 /) {
 1661:             return %returnhash;
 1662:         }
 1663:         my @pairs=split(/\&/,$rep);
 1664:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 1665:             return @pairs;
 1666:         }
 1667:         my $i=0;
 1668:         foreach my $item (@$storearr) {
 1669:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
 1670:             $i++;
 1671:         }
 1672:         return %returnhash;
 1673:     } else {
 1674:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
 1675:     }
 1676: }
 1677: 
 1678: # -------------------------------------------- put items in domain db files 
 1679: 
 1680: sub put_dom {
 1681:     my ($namespace,$storehash,$udom,$uhome)=@_;
 1682:     if (!$udom) {
 1683:         $udom=$env{'user.domain'};
 1684:         if (defined(&domain($udom,'primary'))) {
 1685:             $uhome=&domain($udom,'primary');
 1686:         } else {
 1687:             undef($uhome);
 1688:         }
 1689:     } else {
 1690:         if (!$uhome) {
 1691:             if (defined(&domain($udom,'primary'))) {
 1692:                 $uhome=&domain($udom,'primary');
 1693:             }
 1694:         }
 1695:     } 
 1696:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1697:         my $items='';
 1698:         foreach my $item (keys(%$storehash)) {
 1699:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 1700:         }
 1701:         $items=~s/\&$//;
 1702:         return &reply("putdom:$udom:$namespace:$items",$uhome);
 1703:     } else {
 1704:         &logthis("put_dom failed - no homeserver and/or domain");
 1705:     }
 1706: }
 1707: 
 1708: # --------------------- newput for items in db file owned by domainconfig user
 1709: sub newput_dom {
 1710:     my ($namespace,$storehash,$udom) = @_;
 1711:     my $result;
 1712:     if (!$udom) {
 1713:         $udom=$env{'user.domain'};
 1714:     }
 1715:     if ($udom) {
 1716:         my $uname = &get_domainconfiguser($udom);
 1717:         $result = &newput($namespace,$storehash,$udom,$uname);
 1718:     }
 1719:     return $result;
 1720: }
 1721: 
 1722: # --------------------- delete for items in db file owned by domainconfig user
 1723: sub del_dom {
 1724:     my ($namespace,$storearr,$udom)=@_;
 1725:     if (ref($storearr) eq 'ARRAY') {
 1726:         if (!$udom) {
 1727:             $udom=$env{'user.domain'};
 1728:         }
 1729:         if ($udom) {
 1730:             my $uname = &get_domainconfiguser($udom); 
 1731:             return &del($namespace,$storearr,$udom,$uname);
 1732:         }
 1733:     }
 1734: }
 1735: 
 1736: # ----------------------------------construct domainconfig user for a domain 
 1737: sub get_domainconfiguser {
 1738:     my ($udom) = @_;
 1739:     return $udom.'-domainconfig';
 1740: }
 1741: 
 1742: sub retrieve_inst_usertypes {
 1743:     my ($udom) = @_;
 1744:     my (%returnhash,@order);
 1745:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 1746:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
 1747:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
 1748:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
 1749:     } else {
 1750:         if (defined(&domain($udom,'primary'))) {
 1751:             my $uhome=&domain($udom,'primary');
 1752:             my $rep=&reply("inst_usertypes:$udom",$uhome);
 1753:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
 1754:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
 1755:                 return (\%returnhash,\@order);
 1756:             }
 1757:             my ($hashitems,$orderitems) = split(/:/,$rep); 
 1758:             my @pairs=split(/\&/,$hashitems);
 1759:             foreach my $item (@pairs) {
 1760:                 my ($key,$value)=split(/=/,$item,2);
 1761:                 $key = &unescape($key);
 1762:                 next if ($key =~ /^error: 2 /);
 1763:                 $returnhash{$key}=&thaw_unescape($value);
 1764:             }
 1765:             my @esc_order = split(/\&/,$orderitems);
 1766:             foreach my $item (@esc_order) {
 1767:                 push(@order,&unescape($item));
 1768:             }
 1769:         } else {
 1770:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
 1771:         }
 1772:         return (\%returnhash,\@order);
 1773:     }
 1774: }
 1775: 
 1776: sub is_domainimage {
 1777:     my ($url) = @_;
 1778:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
 1779:         if (&domain($1) ne '') {
 1780:             return '1';
 1781:         }
 1782:     }
 1783:     return;
 1784: }
 1785: 
 1786: sub inst_directory_query {
 1787:     my ($srch) = @_;
 1788:     my $udom = $srch->{'srchdomain'};
 1789:     my %results;
 1790:     my $homeserver = &domain($udom,'primary');
 1791:     my $outcome;
 1792:     if ($homeserver ne '') {
 1793: 	my $queryid=&reply("querysend:instdirsearch:".
 1794: 			   &escape($srch->{'srchby'}).':'.
 1795: 			   &escape($srch->{'srchterm'}).':'.
 1796: 			   &escape($srch->{'srchtype'}),$homeserver);
 1797: 	my $host=&hostname($homeserver);
 1798: 	if ($queryid !~/^\Q$host\E\_/) {
 1799: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1800: 	    return;
 1801: 	}
 1802: 	my $response = &get_query_reply($queryid);
 1803: 	my $maxtries = 5;
 1804: 	my $tries = 1;
 1805: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1806: 	    $response = &get_query_reply($queryid);
 1807: 	    $tries ++;
 1808: 	}
 1809: 
 1810:         if (!&error($response) && $response ne 'refused') {
 1811:             if ($response eq 'unavailable') {
 1812:                 $outcome = $response;
 1813:             } else {
 1814:                 $outcome = 'ok';
 1815:                 my @matches = split(/\n/,$response);
 1816:                 foreach my $match (@matches) {
 1817:                     my ($key,$value) = split(/=/,$match);
 1818:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 1819:                 }
 1820:             }
 1821:         }
 1822:     }
 1823:     return ($outcome,%results);
 1824: }
 1825: 
 1826: sub usersearch {
 1827:     my ($srch) = @_;
 1828:     my $dom = $srch->{'srchdomain'};
 1829:     my %results;
 1830:     my %libserv = &all_library();
 1831:     my $query = 'usersearch';
 1832:     foreach my $tryserver (keys(%libserv)) {
 1833:         if (&host_domain($tryserver) eq $dom) {
 1834:             my $host=&hostname($tryserver);
 1835:             my $queryid=
 1836:                 &reply("querysend:".&escape($query).':'.
 1837:                        &escape($srch->{'srchby'}).':'.
 1838:                        &escape($srch->{'srchtype'}).':'.
 1839:                        &escape($srch->{'srchterm'}),$tryserver);
 1840:             if ($queryid !~/^\Q$host\E\_/) {
 1841:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 1842:                 next;
 1843:             }
 1844:             my $reply = &get_query_reply($queryid);
 1845:             my $maxtries = 1;
 1846:             my $tries = 1;
 1847:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 1848:                 $reply = &get_query_reply($queryid);
 1849:                 $tries ++;
 1850:             }
 1851:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 1852:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 1853:             } else {
 1854:                 my @matches;
 1855:                 if ($reply =~ /\n/) {
 1856:                     @matches = split(/\n/,$reply);
 1857:                 } else {
 1858:                     @matches = split(/\&/,$reply);
 1859:                 }
 1860:                 foreach my $match (@matches) {
 1861:                     my ($uname,$udom,%userhash);
 1862:                     foreach my $entry (split(/:/,$match)) {
 1863:                         my ($key,$value) =
 1864:                             map {&unescape($_);} split(/=/,$entry);
 1865:                         $userhash{$key} = $value;
 1866:                         if ($key eq 'username') {
 1867:                             $uname = $value;
 1868:                         } elsif ($key eq 'domain') {
 1869:                             $udom = $value;
 1870:                         }
 1871:                     }
 1872:                     $results{$uname.':'.$udom} = \%userhash;
 1873:                 }
 1874:             }
 1875:         }
 1876:     }
 1877:     return %results;
 1878: }
 1879: 
 1880: sub get_instuser {
 1881:     my ($udom,$uname,$id) = @_;
 1882:     my $homeserver = &domain($udom,'primary');
 1883:     my ($outcome,%results);
 1884:     if ($homeserver ne '') {
 1885:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 1886:                            &escape($id).':'.&escape($udom),$homeserver);
 1887:         my $host=&hostname($homeserver);
 1888:         if ($queryid !~/^\Q$host\E\_/) {
 1889:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1890:             return;
 1891:         }
 1892:         my $response = &get_query_reply($queryid);
 1893:         my $maxtries = 5;
 1894:         my $tries = 1;
 1895:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1896:             $response = &get_query_reply($queryid);
 1897:             $tries ++;
 1898:         }
 1899:         if (!&error($response) && $response ne 'refused') {
 1900:             if ($response eq 'unavailable') {
 1901:                 $outcome = $response;
 1902:             } else {
 1903:                 $outcome = 'ok';
 1904:                 my @matches = split(/\n/,$response);
 1905:                 foreach my $match (@matches) {
 1906:                     my ($key,$value) = split(/=/,$match);
 1907:                     $results{&unescape($key)} = &thaw_unescape($value);
 1908:                 }
 1909:             }
 1910:         }
 1911:     }
 1912:     my %userinfo;
 1913:     if (ref($results{$uname}) eq 'HASH') {
 1914:         %userinfo = %{$results{$uname}};
 1915:     } 
 1916:     return ($outcome,%userinfo);
 1917: }
 1918: 
 1919: sub inst_rulecheck {
 1920:     my ($udom,$uname,$id,$item,$rules) = @_;
 1921:     my %returnhash;
 1922:     if ($udom ne '') {
 1923:         if (ref($rules) eq 'ARRAY') {
 1924:             @{$rules} = map {&escape($_);} (@{$rules});
 1925:             my $rulestr = join(':',@{$rules});
 1926:             my $homeserver=&domain($udom,'primary');
 1927:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1928:                 my $response;
 1929:                 if ($item eq 'username') {                
 1930:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 1931:                                               ':'.&escape($uname).':'.$rulestr,
 1932:                                               $homeserver));
 1933:                 } elsif ($item eq 'id') {
 1934:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 1935:                                               ':'.&escape($id).':'.$rulestr,
 1936:                                               $homeserver));
 1937:                 } elsif ($item eq 'selfcreate') {
 1938:                     $response=&unescape(&reply('instselfcreatecheck:'.
 1939:                                                &escape($udom).':'.&escape($uname).
 1940:                                               ':'.$rulestr,$homeserver));
 1941:                 }
 1942:                 if ($response ne 'refused') {
 1943:                     my @pairs=split(/\&/,$response);
 1944:                     foreach my $item (@pairs) {
 1945:                         my ($key,$value)=split(/=/,$item,2);
 1946:                         $key = &unescape($key);
 1947:                         next if ($key =~ /^error: 2 /);
 1948:                         $returnhash{$key}=&thaw_unescape($value);
 1949:                     }
 1950:                 }
 1951:             }
 1952:         }
 1953:     }
 1954:     return %returnhash;
 1955: }
 1956: 
 1957: sub inst_userrules {
 1958:     my ($udom,$check) = @_;
 1959:     my (%ruleshash,@ruleorder);
 1960:     if ($udom ne '') {
 1961:         my $homeserver=&domain($udom,'primary');
 1962:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1963:             my $response;
 1964:             if ($check eq 'id') {
 1965:                 $response=&reply('instidrules:'.&escape($udom),
 1966:                                  $homeserver);
 1967:             } elsif ($check eq 'email') {
 1968:                 $response=&reply('instemailrules:'.&escape($udom),
 1969:                                  $homeserver);
 1970:             } else {
 1971:                 $response=&reply('instuserrules:'.&escape($udom),
 1972:                                  $homeserver);
 1973:             }
 1974:             if (($response ne 'refused') && ($response ne 'error') && 
 1975:                 ($response ne 'unknown_cmd') && 
 1976:                 ($response ne 'no_such_host')) {
 1977:                 my ($hashitems,$orderitems) = split(/:/,$response);
 1978:                 my @pairs=split(/\&/,$hashitems);
 1979:                 foreach my $item (@pairs) {
 1980:                     my ($key,$value)=split(/=/,$item,2);
 1981:                     $key = &unescape($key);
 1982:                     next if ($key =~ /^error: 2 /);
 1983:                     $ruleshash{$key}=&thaw_unescape($value);
 1984:                 }
 1985:                 my @esc_order = split(/\&/,$orderitems);
 1986:                 foreach my $item (@esc_order) {
 1987:                     push(@ruleorder,&unescape($item));
 1988:                 }
 1989:             }
 1990:         }
 1991:     }
 1992:     return (\%ruleshash,\@ruleorder);
 1993: }
 1994: 
 1995: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 1996: 
 1997: sub get_domain_defaults {
 1998:     my ($domain,$ignore_cache) = @_;
 1999:     return if (($domain eq '') || ($domain eq 'public'));
 2000:     my $cachetime = 60*60*24;
 2001:     unless ($ignore_cache) {
 2002:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 2003:         if (defined($cached)) {
 2004:             if (ref($result) eq 'HASH') {
 2005:                 return %{$result};
 2006:             }
 2007:         }
 2008:     }
 2009:     my %domdefaults;
 2010:     my %domconfig =
 2011:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
 2012:                                   'requestcourses','inststatus',
 2013:                                   'coursedefaults','usersessions',
 2014:                                   'requestauthor','selfenrollment'],$domain);
 2015:     my @coursetypes = ('official','unofficial','community','textbook');
 2016:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 2017:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 2018:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 2019:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 2020:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 2021:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
 2022:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
 2023:     } else {
 2024:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 2025:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 2026:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 2027:     }
 2028:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 2029:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 2030:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 2031:         } else {
 2032:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 2033:         }
 2034:         my @usertools = ('aboutme','blog','webdav','portfolio');
 2035:         foreach my $item (@usertools) {
 2036:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 2037:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 2038:             }
 2039:         }
 2040:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
 2041:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
 2042:         }
 2043:     }
 2044:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 2045:         foreach my $item ('official','unofficial','community','textbook') {
 2046:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
 2047:         }
 2048:     }
 2049:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
 2050:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
 2051:     }
 2052:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
 2053:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
 2054:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
 2055:         }
 2056:     }
 2057:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
 2058:         $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
 2059:         foreach my $type (@coursetypes) {
 2060:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
 2061:                 unless ($type eq 'community') {
 2062:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
 2063:                 }
 2064:             }
 2065:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
 2066:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
 2067:             }
 2068:         }
 2069:     }
 2070:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
 2071:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
 2072:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
 2073:         }
 2074:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
 2075:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
 2076:         }
 2077:     }
 2078:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
 2079:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
 2080:             my @settings = ('types','registered','enroll_dates','access_dates','section',
 2081:                             'approval','limit');
 2082:             foreach my $type (@coursetypes) {
 2083:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
 2084:                     my @mgrdc = ();
 2085:                     foreach my $item (@settings) {
 2086:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
 2087:                             push(@mgrdc,$item);
 2088:                         }
 2089:                     }
 2090:                     if (@mgrdc) {
 2091:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
 2092:                     }
 2093:                 }
 2094:             }
 2095:         }
 2096:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
 2097:             foreach my $type (@coursetypes) {
 2098:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
 2099:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
 2100:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
 2101:                     }
 2102:                 }
 2103:             }
 2104:         }
 2105:     }
 2106:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
 2107:     return %domdefaults;
 2108: }
 2109: 
 2110: # --------------------------------------------------- Assign a key to a student
 2111: 
 2112: sub assign_access_key {
 2113: #
 2114: # a valid key looks like uname:udom#comments
 2115: # comments are being appended
 2116: #
 2117:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 2118:     $kdom=
 2119:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 2120:     $knum=
 2121:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 2122:     $cdom=
 2123:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2124:     $cnum=
 2125:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2126:     $udom=$env{'user.name'} unless (defined($udom));
 2127:     $uname=$env{'user.domain'} unless (defined($uname));
 2128:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 2129:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 2130:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 2131:                                                   # assigned to this person
 2132:                                                   # - this should not happen,
 2133:                                                   # unless something went wrong
 2134:                                                   # the first time around
 2135: # ready to assign
 2136:         $logentry=$1.'; '.$logentry;
 2137:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 2138:                                                  $kdom,$knum) eq 'ok') {
 2139: # key now belongs to user
 2140: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 2141:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 2142:                 &appenv({'environment.'.$envkey => $ckey});
 2143:                 return 'ok';
 2144:             } else {
 2145:                 return 
 2146:   'error: Count not permanently assign key, will need to be re-entered later.';
 2147: 	    }
 2148:         } else {
 2149:             return 'error: Could not assign key, try again later.';
 2150:         }
 2151:     } elsif (!$existing{$ckey}) {
 2152: # the key does not exist
 2153: 	return 'error: The key does not exist';
 2154:     } else {
 2155: # the key is somebody else's
 2156: 	return 'error: The key is already in use';
 2157:     }
 2158: }
 2159: 
 2160: # ------------------------------------------ put an additional comment on a key
 2161: 
 2162: sub comment_access_key {
 2163: #
 2164: # a valid key looks like uname:udom#comments
 2165: # comments are being appended
 2166: #
 2167:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 2168:     $cdom=
 2169:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2170:     $cnum=
 2171:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2172:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2173:     if ($existing{$ckey}) {
 2174:         $existing{$ckey}.='; '.$logentry;
 2175: # ready to assign
 2176:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 2177:                                                  $cdom,$cnum) eq 'ok') {
 2178: 	    return 'ok';
 2179:         } else {
 2180: 	    return 'error: Count not store comment.';
 2181:         }
 2182:     } else {
 2183: # the key does not exist
 2184: 	return 'error: The key does not exist';
 2185:     }
 2186: }
 2187: 
 2188: # ------------------------------------------------------ Generate a set of keys
 2189: 
 2190: sub generate_access_keys {
 2191:     my ($number,$cdom,$cnum,$logentry)=@_;
 2192:     $cdom=
 2193:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2194:     $cnum=
 2195:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2196:     unless (&allowed('mky',$cdom)) { return 0; }
 2197:     unless (($cdom) && ($cnum)) { return 0; }
 2198:     if ($number>10000) { return 0; }
 2199:     sleep(2); # make sure don't get same seed twice
 2200:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 2201:     my $total=0;
 2202:     for (my $i=1;$i<=$number;$i++) {
 2203:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 2204:                   sprintf("%lx",int(100000*rand)).'-'.
 2205:                   sprintf("%lx",int(100000*rand));
 2206:        $newkey=~s/1/g/g; # folks mix up 1 and l
 2207:        $newkey=~s/0/h/g; # and also 0 and O
 2208:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 2209:        if ($existing{$newkey}) {
 2210:            $i--;
 2211:        } else {
 2212: 	  if (&put('accesskeys',
 2213:               { $newkey => '# generated '.localtime().
 2214:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 2215:                            '; '.$logentry },
 2216: 		   $cdom,$cnum) eq 'ok') {
 2217:               $total++;
 2218: 	  }
 2219:        }
 2220:     }
 2221:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 2222:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 2223:     return $total;
 2224: }
 2225: 
 2226: # ------------------------------------------------------- Validate an accesskey
 2227: 
 2228: sub validate_access_key {
 2229:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 2230:     $cdom=
 2231:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2232:     $cnum=
 2233:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2234:     $udom=$env{'user.domain'} unless (defined($udom));
 2235:     $uname=$env{'user.name'} unless (defined($uname));
 2236:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2237:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 2238: }
 2239: 
 2240: # ------------------------------------- Find the section of student in a course
 2241: sub devalidate_getsection_cache {
 2242:     my ($udom,$unam,$courseid)=@_;
 2243:     my $hashid="$udom:$unam:$courseid";
 2244:     &devalidate_cache_new('getsection',$hashid);
 2245: }
 2246: 
 2247: sub courseid_to_courseurl {
 2248:     my ($courseid) = @_;
 2249:     #already url style courseid
 2250:     return $courseid if ($courseid =~ m{^/});
 2251: 
 2252:     if (exists($env{'course.'.$courseid.'.num'})) {
 2253: 	my $cnum = $env{'course.'.$courseid.'.num'};
 2254: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 2255: 	return "/$cdom/$cnum";
 2256:     }
 2257: 
 2258:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 2259:     if (exists($courseinfo{'num'})) {
 2260: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 2261:     }
 2262: 
 2263:     return undef;
 2264: }
 2265: 
 2266: sub getsection {
 2267:     my ($udom,$unam,$courseid)=@_;
 2268:     my $cachetime=1800;
 2269: 
 2270:     my $hashid="$udom:$unam:$courseid";
 2271:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 2272:     if (defined($cached)) { return $result; }
 2273: 
 2274:     my %Pending; 
 2275:     my %Expired;
 2276:     #
 2277:     # Each role can either have not started yet (pending), be active, 
 2278:     #    or have expired.
 2279:     #
 2280:     # If there is an active role, we are done.
 2281:     #
 2282:     # If there is more than one role which has not started yet, 
 2283:     #     choose the one which will start sooner
 2284:     # If there is one role which has not started yet, return it.
 2285:     #
 2286:     # If there is more than one expired role, choose the one which ended last.
 2287:     # If there is a role which has expired, return it.
 2288:     #
 2289:     $courseid = &courseid_to_courseurl($courseid);
 2290:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 2291:     foreach my $key (keys(%roleshash)) {
 2292:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 2293:         my $section=$1;
 2294:         if ($key eq $courseid.'_st') { $section=''; }
 2295:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 2296:         my $now=time;
 2297:         if (defined($end) && $end && ($now > $end)) {
 2298:             $Expired{$end}=$section;
 2299:             next;
 2300:         }
 2301:         if (defined($start) && $start && ($now < $start)) {
 2302:             $Pending{$start}=$section;
 2303:             next;
 2304:         }
 2305:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 2306:     }
 2307:     #
 2308:     # Presumedly there will be few matching roles from the above
 2309:     # loop and the sorting time will be negligible.
 2310:     if (scalar(keys(%Pending))) {
 2311:         my ($time) = sort {$a <=> $b} keys(%Pending);
 2312:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 2313:     } 
 2314:     if (scalar(keys(%Expired))) {
 2315:         my @sorted = sort {$a <=> $b} keys(%Expired);
 2316:         my $time = pop(@sorted);
 2317:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 2318:     }
 2319:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 2320: }
 2321: 
 2322: sub save_cache {
 2323:     &purge_remembered();
 2324:     #&Apache::loncommon::validate_page();
 2325:     undef(%env);
 2326:     undef($env_loaded);
 2327: }
 2328: 
 2329: my $to_remember=-1;
 2330: my %remembered;
 2331: my %accessed;
 2332: my $kicks=0;
 2333: my $hits=0;
 2334: sub make_key {
 2335:     my ($name,$id) = @_;
 2336:     if (length($id) > 65 
 2337: 	&& length(&escape($id)) > 200) {
 2338: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 2339:     }
 2340:     return &escape($name.':'.$id);
 2341: }
 2342: 
 2343: sub devalidate_cache_new {
 2344:     my ($name,$id,$debug) = @_;
 2345:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 2346:     $id=&make_key($name,$id);
 2347:     $memcache->delete($id);
 2348:     delete($remembered{$id});
 2349:     delete($accessed{$id});
 2350: }
 2351: 
 2352: sub is_cached_new {
 2353:     my ($name,$id,$debug) = @_;
 2354:     $id=&make_key($name,$id);
 2355:     if (exists($remembered{$id})) {
 2356: 	if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
 2357: 	$accessed{$id}=[&gettimeofday()];
 2358: 	$hits++;
 2359: 	return ($remembered{$id},1);
 2360:     }
 2361:     my $value = $memcache->get($id);
 2362:     if (!(defined($value))) {
 2363: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 2364: 	return (undef,undef);
 2365:     }
 2366:     if ($value eq '__undef__') {
 2367: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 2368: 	$value=undef;
 2369:     }
 2370:     &make_room($id,$value,$debug);
 2371:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 2372:     return ($value,1);
 2373: }
 2374: 
 2375: sub do_cache_new {
 2376:     my ($name,$id,$value,$time,$debug) = @_;
 2377:     $id=&make_key($name,$id);
 2378:     my $setvalue=$value;
 2379:     if (!defined($setvalue)) {
 2380: 	$setvalue='__undef__';
 2381:     }
 2382:     if (!defined($time) ) {
 2383: 	$time=600;
 2384:     }
 2385:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 2386:     my $result = $memcache->set($id,$setvalue,$time);
 2387:     if (! $result) {
 2388: 	&logthis("caching of id -> $id  failed");
 2389: 	$memcache->disconnect_all();
 2390:     }
 2391:     # need to make a copy of $value
 2392:     &make_room($id,$value,$debug);
 2393:     return $value;
 2394: }
 2395: 
 2396: sub make_room {
 2397:     my ($id,$value,$debug)=@_;
 2398: 
 2399:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
 2400:                                     : $value;
 2401:     if ($to_remember<0) { return; }
 2402:     $accessed{$id}=[&gettimeofday()];
 2403:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 2404:     my $to_kick;
 2405:     my $max_time=0;
 2406:     foreach my $other (keys(%accessed)) {
 2407: 	if (&tv_interval($accessed{$other}) > $max_time) {
 2408: 	    $to_kick=$other;
 2409: 	    $max_time=&tv_interval($accessed{$other});
 2410: 	}
 2411:     }
 2412:     delete($remembered{$to_kick});
 2413:     delete($accessed{$to_kick});
 2414:     $kicks++;
 2415:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 2416:     return;
 2417: }
 2418: 
 2419: sub purge_remembered {
 2420:     #&logthis("Tossing ".scalar(keys(%remembered)));
 2421:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 2422:     undef(%remembered);
 2423:     undef(%accessed);
 2424: }
 2425: # ------------------------------------- Read an entry from a user's environment
 2426: 
 2427: sub userenvironment {
 2428:     my ($udom,$unam,@what)=@_;
 2429:     my $items;
 2430:     foreach my $item (@what) {
 2431:         $items.=&escape($item).'&';
 2432:     }
 2433:     $items=~s/\&$//;
 2434:     my %returnhash=();
 2435:     my $uhome = &homeserver($unam,$udom);
 2436:     unless ($uhome eq 'no_host') {
 2437:         my @answer=split(/\&/, 
 2438:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
 2439:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
 2440:             return %returnhash;
 2441:         }
 2442:         my $i;
 2443:         for ($i=0;$i<=$#what;$i++) {
 2444: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
 2445:         }
 2446:     }
 2447:     return %returnhash;
 2448: }
 2449: 
 2450: # ---------------------------------------------------------- Get a studentphoto
 2451: sub studentphoto {
 2452:     my ($udom,$unam,$ext) = @_;
 2453:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 2454:     if (defined($env{'request.course.id'})) {
 2455:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 2456:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 2457:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 2458:             } else {
 2459:                 my ($result,$perm_reqd)=
 2460: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 2461:                 if ($result eq 'ok') {
 2462:                     if (!($perm_reqd eq 'yes')) {
 2463:                         return(&retrievestudentphoto($udom,$unam,$ext));
 2464:                     }
 2465:                 }
 2466:             }
 2467:         }
 2468:     } else {
 2469:         my ($result,$perm_reqd) = 
 2470: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 2471:         if ($result eq 'ok') {
 2472:             if (!($perm_reqd eq 'yes')) {
 2473:                 return(&retrievestudentphoto($udom,$unam,$ext));
 2474:             }
 2475:         }
 2476:     }
 2477:     return '/adm/lonKaputt/lonlogo_broken.gif';
 2478: }
 2479: 
 2480: sub retrievestudentphoto {
 2481:     my ($udom,$unam,$ext,$type) = @_;
 2482:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 2483:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 2484:     if ($ret eq 'ok') {
 2485:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 2486:         if ($type eq 'thumbnail') {
 2487:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 2488:         }
 2489:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 2490:         return $tokenurl;
 2491:     } else {
 2492:         if ($type eq 'thumbnail') {
 2493:             return '/adm/lonKaputt/genericstudent_tn.gif';
 2494:         } else { 
 2495:             return '/adm/lonKaputt/lonlogo_broken.gif';
 2496:         }
 2497:     }
 2498: }
 2499: 
 2500: # -------------------------------------------------------------------- New chat
 2501: 
 2502: sub chatsend {
 2503:     my ($newentry,$anon,$group)=@_;
 2504:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 2505:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2506:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 2507:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 2508: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 2509: 		   &escape($newentry)).':'.$group,$chome);
 2510: }
 2511: 
 2512: # ------------------------------------------ Find current version of a resource
 2513: 
 2514: sub getversion {
 2515:     my $fname=&clutter(shift);
 2516:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
 2517:     return &currentversion(&filelocation('',$fname));
 2518: }
 2519: 
 2520: sub currentversion {
 2521:     my $fname=shift;
 2522:     my $author=$fname;
 2523:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2524:     my ($udom,$uname)=split(/\//,$author);
 2525:     my $home=&homeserver($uname,$udom);
 2526:     if ($home eq 'no_host') { 
 2527:         return -1; 
 2528:     }
 2529:     my $answer=&reply("currentversion:$fname",$home);
 2530:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 2531: 	return -1;
 2532:     }
 2533:     return $answer;
 2534: }
 2535: 
 2536: #
 2537: # Return special version number of resource if set by override, empty otherwise
 2538: #
 2539: sub usedversion {
 2540:     my $fname=shift;
 2541:     unless ($fname) { $fname=$env{'request.uri'}; }
 2542:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
 2543:     if ($urlversion) { return $urlversion; }
 2544:     return '';
 2545: }
 2546: 
 2547: # ----------------------------- Subscribe to a resource, return URL if possible
 2548: 
 2549: sub subscribe {
 2550:     my $fname=shift;
 2551:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 2552:     $fname=~s/[\n\r]//g;
 2553:     my $author=$fname;
 2554:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2555:     my ($udom,$uname)=split(/\//,$author);
 2556:     my $home=homeserver($uname,$udom);
 2557:     if ($home eq 'no_host') {
 2558:         return 'not_found';
 2559:     }
 2560:     my $answer=reply("sub:$fname",$home);
 2561:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 2562: 	$answer.=' by '.$home;
 2563:     }
 2564:     return $answer;
 2565: }
 2566:     
 2567: # -------------------------------------------------------------- Replicate file
 2568: 
 2569: sub repcopy {
 2570:     my $filename=shift;
 2571:     $filename=~s/\/+/\//g;
 2572:     my $londocroot = $perlvar{'lonDocRoot'};
 2573:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
 2574:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
 2575:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
 2576: 	$filename=~m{^/*(uploaded|editupload)/}) {
 2577: 	return &repcopy_userfile($filename);
 2578:     }
 2579:     $filename=~s/[\n\r]//g;
 2580:     my $transname="$filename.in.transfer";
 2581: # FIXME: this should flock
 2582:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 2583:     my $remoteurl=subscribe($filename);
 2584:     if ($remoteurl =~ /^con_lost by/) {
 2585: 	   &logthis("Subscribe returned $remoteurl: $filename");
 2586:            return 'unavailable';
 2587:     } elsif ($remoteurl eq 'not_found') {
 2588: 	   #&logthis("Subscribe returned not_found: $filename");
 2589: 	   return 'not_found';
 2590:     } elsif ($remoteurl =~ /^rejected by/) {
 2591: 	   &logthis("Subscribe returned $remoteurl: $filename");
 2592:            return 'forbidden';
 2593:     } elsif ($remoteurl eq 'directory') {
 2594:            return 'ok';
 2595:     } else {
 2596:         my $author=$filename;
 2597:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2598:         my ($udom,$uname)=split(/\//,$author);
 2599:         my $home=homeserver($uname,$udom);
 2600:         unless ($home eq $perlvar{'lonHostID'}) {
 2601:            my @parts=split(/\//,$filename);
 2602:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 2603:            if ($path ne "$londocroot/res") {
 2604:                &logthis("Malconfiguration for replication: $filename");
 2605: 	       return 'bad_request';
 2606:            }
 2607:            my $count;
 2608:            for ($count=5;$count<$#parts;$count++) {
 2609:                $path.="/$parts[$count]";
 2610:                if ((-e $path)!=1) {
 2611: 		   mkdir($path,0777);
 2612:                }
 2613:            }
 2614:            my $ua=new LWP::UserAgent;
 2615:            my $request=new HTTP::Request('GET',"$remoteurl");
 2616:            my $response=$ua->request($request,$transname);
 2617:            if ($response->is_error()) {
 2618: 	       unlink($transname);
 2619:                my $message=$response->status_line;
 2620:                &logthis("<font color=\"blue\">WARNING:"
 2621:                        ." LWP get: $message: $filename</font>");
 2622:                return 'unavailable';
 2623:            } else {
 2624: 	       if ($remoteurl!~/\.meta$/) {
 2625:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 2626:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
 2627:                   if ($mresponse->is_error()) {
 2628: 		      unlink($filename.'.meta');
 2629:                       &logthis(
 2630:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 2631:                   }
 2632: 	       }
 2633:                rename($transname,$filename);
 2634:                return 'ok';
 2635:            }
 2636:        }
 2637:     }
 2638: }
 2639: 
 2640: # ------------------------------------------------ Get server side include body
 2641: sub ssi_body {
 2642:     my ($filelink,%form)=@_;
 2643:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 2644:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 2645:     }
 2646:     my $output='';
 2647:     my $response;
 2648:     if ($filelink=~/^https?\:/) {
 2649:        ($output,$response)=&externalssi($filelink);
 2650:     } else {
 2651:        $filelink .= $filelink=~/\?/ ? '&' : '?';
 2652:        $filelink .= 'inhibitmenu=yes';
 2653:        ($output,$response)=&ssi($filelink,%form);
 2654:     }
 2655:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 2656:     $output=~s/^.*?\<body[^\>]*\>//si;
 2657:     $output=~s/\<\/body\s*\>.*?$//si;
 2658:     if (wantarray) {
 2659:         return ($output, $response);
 2660:     } else {
 2661:         return $output;
 2662:     }
 2663: }
 2664: 
 2665: # --------------------------------------------------------- Server Side Include
 2666: 
 2667: sub absolute_url {
 2668:     my ($host_name) = @_;
 2669:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 2670:     if ($host_name eq '') {
 2671: 	$host_name = $ENV{'SERVER_NAME'};
 2672:     }
 2673:     return $protocol.$host_name;
 2674: }
 2675: 
 2676: #
 2677: #   Server side include.
 2678: # Parameters:
 2679: #  fn     Possibly encrypted resource name/id.
 2680: #  form   Hash that describes how the rendering should be done
 2681: #         and other things.
 2682: # Returns:
 2683: #   Scalar context: The content of the response.
 2684: #   Array context:  2 element list of the content and the full response object.
 2685: #     
 2686: sub ssi {
 2687: 
 2688:     my ($fn,%form)=@_;
 2689:     my $ua=new LWP::UserAgent;
 2690:     my $request;
 2691: 
 2692:     $form{'no_update_last_known'}=1;
 2693:     &Apache::lonenc::check_encrypt(\$fn);
 2694:     if (%form) {
 2695:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 2696:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
 2697:     } else {
 2698:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 2699:     }
 2700: 
 2701:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 2702:     my $response= $ua->request($request);
 2703:     my $content = $response->content;
 2704: 
 2705: 
 2706:     if (wantarray) {
 2707: 	return ($content, $response);
 2708:     } else {
 2709: 	return $content;
 2710:     }
 2711: }
 2712: 
 2713: sub externalssi {
 2714:     my ($url)=@_;
 2715:     my $ua=new LWP::UserAgent;
 2716:     my $request=new HTTP::Request('GET',$url);
 2717:     my $response=$ua->request($request);
 2718:     if (wantarray) {
 2719:         return ($response->content, $response);
 2720:     } else {
 2721:         return $response->content;
 2722:     }
 2723: }
 2724: 
 2725: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 2726: 
 2727: sub allowuploaded {
 2728:     my ($srcurl,$url)=@_;
 2729:     $url=&clutter(&declutter($url));
 2730:     my $dir=$url;
 2731:     $dir=~s/\/[^\/]+$//;
 2732:     my %httpref=();
 2733:     my $httpurl=&hreflocation('',$url);
 2734:     $httpref{'httpref.'.$httpurl}=$srcurl;
 2735:     &Apache::lonnet::appenv(\%httpref);
 2736: }
 2737: 
 2738: #
 2739: # Determine if the current user should be able to edit a particular resource,
 2740: # when viewing in course context.
 2741: # (a) When viewing resource used to determine if "Edit" item is included in 
 2742: #     Functions.
 2743: # (b) When displaying folder contents in course editor, used to determine if
 2744: #     "Edit" link will be displayed alongside resource.
 2745: #
 2746: #  input: six args -- filename (decluttered), course number, course domain,
 2747: #                   url, symb (if registered) and group (if this is a group
 2748: #                   item -- e.g., bulletin board, group page etc.).
 2749: #  output: array of five scalars -- 
 2750: #          $cfile -- url for file editing if editable on current server
 2751: #          $home -- homeserver of resource (i.e., for author if published,
 2752: #                                           or course if uploaded.).
 2753: #          $switchserver --  1 if server switch will be needed.
 2754: #          $forceedit -- 1 if icon/link should be to go to edit mode 
 2755: #          $forceview -- 1 if icon/link should be to go to view mode
 2756: #
 2757: 
 2758: sub can_edit_resource {
 2759:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
 2760:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
 2761: #
 2762: # For aboutme pages user can only edit his/her own.
 2763: #
 2764:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
 2765:         my ($sdom,$sname) = ($1,$2);
 2766:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
 2767:             $home = $env{'user.home'};
 2768:             $cfile = $resurl;
 2769:             if ($env{'form.forceedit'}) {
 2770:                 $forceview = 1;
 2771:             } else {
 2772:                 $forceedit = 1;
 2773:             }
 2774:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
 2775:         } else {
 2776:             return;
 2777:         }
 2778:     }
 2779: 
 2780:     if ($env{'request.course.id'}) {
 2781:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
 2782:         if ($group ne '') {
 2783: # if this is a group homepage or group bulletin board, check group privs
 2784:             my $allowed = 0;
 2785:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
 2786:                 if ((&allowed('mdg',$env{'request.course.id'}.
 2787:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 2788:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 2789:                     $allowed = 1;
 2790:                 }
 2791:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
 2792:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 2793:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 2794:                     $allowed = 1;
 2795:                 }
 2796:             }
 2797:             if ($allowed) {
 2798:                 $home=&homeserver($cnum,$cdom);
 2799:                 if ($env{'form.forceedit'}) {
 2800:                     $forceview = 1;
 2801:                 } else {
 2802:                     $forceedit = 1;
 2803:                 }
 2804:                 $cfile = $resurl;
 2805:             } else {
 2806:                 return;
 2807:             }
 2808:         } else {
 2809:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
 2810:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
 2811:                     return;
 2812:                 }
 2813:             } elsif (!$crsedit) {
 2814: #
 2815: # No edit allowed where CC has switched to student role.
 2816: #
 2817:                 return;
 2818:             }
 2819:         }
 2820:     }
 2821: 
 2822:     if ($file ne '') {
 2823:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
 2824:             if (&is_course_upload($file,$cnum,$cdom)) {
 2825:                 $uploaded = 1;
 2826:                 $incourse = 1;
 2827:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
 2828:                     $cfile = &hreflocation('',$file);
 2829:                     if ($env{'form.forceedit'}) {
 2830:                         $forceview = 1;
 2831:                     } else {
 2832:                         $forceedit = 1;
 2833:                     }
 2834:                 }
 2835:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
 2836:                 $incourse = 1;
 2837:                 if ($env{'form.forceedit'}) {
 2838:                     $forceview = 1;
 2839:                 } else {
 2840:                     $forceedit = 1;
 2841:                 }
 2842:                 $cfile = $resurl;
 2843:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
 2844:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
 2845:                     $incourse = 1;
 2846:                     if ($env{'form.forceedit'}) {
 2847:                         $forceview = 1;
 2848:                     } else {
 2849:                         $forceedit = 1;
 2850:                     }
 2851:                     $cfile = $resurl;
 2852:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
 2853:                     $incourse = 1;
 2854:                     $cfile = $resurl.'/smpedit';
 2855:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
 2856:                     $incourse = 1;
 2857:                     if ($env{'form.forceedit'}) {
 2858:                         $forceview = 1;
 2859:                     } else {
 2860:                         $forceedit = 1;
 2861:                     }
 2862:                     $cfile = $resurl;
 2863:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 2864:                     $incourse = 1;
 2865:                     if ($env{'form.forceedit'}) {
 2866:                         $forceview = 1;
 2867:                     } else {
 2868:                         $forceedit = 1;
 2869:                     }
 2870:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 2871:                 }
 2872:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
 2873:                 my $template = '/res/lib/templates/simpleproblem.problem';
 2874:                 if (&is_on_map($template)) { 
 2875:                     $incourse = 1;
 2876:                     $forceview = 1;
 2877:                     $cfile = $template;
 2878:                 }
 2879:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 2880:                     $incourse = 1;
 2881:                     if ($env{'form.forceedit'}) {
 2882:                         $forceview = 1;
 2883:                     } else {
 2884:                         $forceedit = 1;
 2885:                     }
 2886:                     $cfile = $resurl;
 2887:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
 2888:                 $incourse = 1;
 2889:                 $forceview = 1;
 2890:                 if ($symb) {
 2891:                     my ($map,$id,$res)=&decode_symb($symb);
 2892:                     $env{'request.symb'} = $symb;
 2893:                     $cfile = &clutter($res);
 2894:                 } else {
 2895:                     $cfile = $env{'form.suppurl'};
 2896:                     $cfile =~ s{^http://}{};
 2897:                     $cfile = '/adm/wrapper/ext/'.$cfile;
 2898:                 }
 2899:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 2900:                 if ($env{'form.forceedit'}) {
 2901:                     $forceview = 1;
 2902:                 } else {
 2903:                     $forceedit = 1;
 2904:                 }
 2905:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 2906:             }
 2907:         }
 2908:         if ($uploaded || $incourse) {
 2909:             $home=&homeserver($cnum,$cdom);
 2910:         } elsif ($file !~ m{/$}) {
 2911:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
 2912:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
 2913:             # Check that the user has permission to edit this resource
 2914:             my $setpriv = 1;
 2915:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
 2916:             if (defined($cfudom)) {
 2917:                 $home=&homeserver($cfuname,$cfudom);
 2918:                 $cfile=$file;
 2919:             }
 2920:         }
 2921:         if (($cfile ne '') && (!$incourse || $uploaded) && 
 2922:             (($home ne '') && ($home ne 'no_host'))) {
 2923:             my @ids=&current_machine_ids();
 2924:             unless (grep(/^\Q$home\E$/,@ids)) {
 2925:                 $switchserver=1;
 2926:             }
 2927:         }
 2928:     }
 2929:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
 2930: }
 2931: 
 2932: sub is_course_upload {
 2933:     my ($file,$cnum,$cdom) = @_;
 2934:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
 2935:     $uploadpath =~ s{^\/}{};
 2936:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
 2937:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
 2938:         return 1;
 2939:     }
 2940:     return;
 2941: }
 2942: 
 2943: sub in_course {
 2944:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
 2945:     if ($hideprivileged) {
 2946:         my $skipuser;
 2947:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
 2948:         my @possdoms = ($cdom);  
 2949:         if ($coursehash{'checkforpriv'}) { 
 2950:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
 2951:         }
 2952:         if (&privileged($uname,$udom,\@possdoms)) {
 2953:             $skipuser = 1;
 2954:             if ($coursehash{'nothideprivileged'}) {
 2955:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 2956:                     my $user;
 2957:                     if ($item =~ /:/) {
 2958:                         $user = $item;
 2959:                     } else {
 2960:                         $user = join(':',split(/[\@]/,$item));
 2961:                     }
 2962:                     if ($user eq $uname.':'.$udom) {
 2963:                         undef($skipuser);
 2964:                         last;
 2965:                     }
 2966:                 }
 2967:             }
 2968:             if ($skipuser) {
 2969:                 return 0;
 2970:             }
 2971:         }
 2972:     }
 2973:     $type ||= 'any';
 2974:     if (!defined($cdom) || !defined($cnum)) {
 2975:         my $cid  = $env{'request.course.id'};
 2976:         $cdom = $env{'course.'.$cid.'.domain'};
 2977:         $cnum = $env{'course.'.$cid.'.num'};
 2978:     }
 2979:     my $typesref;
 2980:     if (($type eq 'any') || ($type eq 'all')) {
 2981:         $typesref = ['active','previous','future'];
 2982:     } elsif ($type eq 'previous' || $type eq 'future') {
 2983:         $typesref = [$type];
 2984:     }
 2985:     my %roles = &get_my_roles($uname,$udom,'userroles',
 2986:                               $typesref,undef,[$cdom]);
 2987:     my ($tmp) = keys(%roles);
 2988:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
 2989:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
 2990:     if (@course_roles > 0) {
 2991:         return 1;
 2992:     }
 2993:     return 0;
 2994: }
 2995: 
 2996: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 2997: # input: action, courseID, current domain, intended
 2998: #        path to file, source of file, instruction to parse file for objects,
 2999: #        ref to hash for embedded objects,
 3000: #        ref to hash for codebase of java objects.
 3001: #        reference to scalar to accommodate mime type determined
 3002: #          from File::MMagic if $parser = parse.
 3003: #
 3004: # output: url to file (if action was uploaddoc), 
 3005: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 3006: #
 3007: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 3008: # course.
 3009: #
 3010: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3011: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 3012: #          course's home server.
 3013: #
 3014: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 3015: #          be copied from $source (current location) to 
 3016: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3017: #         and will then be copied to
 3018: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 3019: #         course's home server.
 3020: #
 3021: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3022: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 3023: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3024: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 3025: #         in course's home server.
 3026: #
 3027: 
 3028: sub process_coursefile {
 3029:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
 3030:         $mimetype)=@_;
 3031:     my $fetchresult;
 3032:     my $home=&homeserver($docuname,$docudom);
 3033:     if ($action eq 'propagate') {
 3034:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3035: 			     $home);
 3036:     } else {
 3037:         my $fpath = '';
 3038:         my $fname = $file;
 3039:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3040:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3041:         my $filepath = &build_filepath($fpath);
 3042:         if ($action eq 'copy') {
 3043:             if ($source eq '') {
 3044:                 $fetchresult = 'no source file';
 3045:                 return $fetchresult;
 3046:             } else {
 3047:                 my $destination = $filepath.'/'.$fname;
 3048:                 rename($source,$destination);
 3049:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3050:                                  $home);
 3051:             }
 3052:         } elsif ($action eq 'uploaddoc') {
 3053:             open(my $fh,'>'.$filepath.'/'.$fname);
 3054:             print $fh $env{'form.'.$source};
 3055:             close($fh);
 3056:             if ($parser eq 'parse') {
 3057:                 my $mm = new File::MMagic;
 3058:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
 3059:                 if ($type eq 'text/html') {
 3060:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 3061:                     unless ($parse_result eq 'ok') {
 3062:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 3063:                     }
 3064:                 }
 3065:                 if (ref($mimetype)) {
 3066:                     $$mimetype = $type;
 3067:                 } 
 3068:             }
 3069:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3070:                                  $home);
 3071:             if ($fetchresult eq 'ok') {
 3072:                 return '/uploaded/'.$fpath.'/'.$fname;
 3073:             } else {
 3074:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3075:                         ' to host '.$home.': '.$fetchresult);
 3076:                 return '/adm/notfound.html';
 3077:             }
 3078:         }
 3079:     }
 3080:     unless ( $fetchresult eq 'ok') {
 3081:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3082:              ' to host '.$home.': '.$fetchresult);
 3083:     }
 3084:     return $fetchresult;
 3085: }
 3086: 
 3087: sub build_filepath {
 3088:     my ($fpath) = @_;
 3089:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 3090:     unless ($fpath eq '') {
 3091:         my @parts=split('/',$fpath);
 3092:         foreach my $part (@parts) {
 3093:             $filepath.= '/'.$part;
 3094:             if ((-e $filepath)!=1) {
 3095:                 mkdir($filepath,0777);
 3096:             }
 3097:         }
 3098:     }
 3099:     return $filepath;
 3100: }
 3101: 
 3102: sub store_edited_file {
 3103:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 3104:     my $file = $primary_url;
 3105:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 3106:     my $fpath = '';
 3107:     my $fname = $file;
 3108:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3109:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3110:     my $filepath = &build_filepath($fpath);
 3111:     open(my $fh,'>'.$filepath.'/'.$fname);
 3112:     print $fh $content;
 3113:     close($fh);
 3114:     my $home=&homeserver($docuname,$docudom);
 3115:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3116: 			  $home);
 3117:     if ($$fetchresult eq 'ok') {
 3118:         return '/uploaded/'.$fpath.'/'.$fname;
 3119:     } else {
 3120:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3121: 		 ' to host '.$home.': '.$$fetchresult);
 3122:         return '/adm/notfound.html';
 3123:     }
 3124: }
 3125: 
 3126: sub clean_filename {
 3127:     my ($fname,$args)=@_;
 3128: # Replace Windows backslashes by forward slashes
 3129:     $fname=~s/\\/\//g;
 3130:     if (!$args->{'keep_path'}) {
 3131:         # Get rid of everything but the actual filename
 3132: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 3133:     }
 3134: # Replace spaces by underscores
 3135:     $fname=~s/\s+/\_/g;
 3136: # Replace all other weird characters by nothing
 3137:     $fname=~s{[^/\w\.\-]}{}g;
 3138: # Replace all .\d. sequences with _\d. so they no longer look like version
 3139: # numbers
 3140:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 3141:     return $fname;
 3142: }
 3143: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
 3144: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
 3145: # image with the same aspect ratio as the original, but with dimensions which do 
 3146: # not exceed $resizewidth and $resizeheight.
 3147:  
 3148: sub resizeImage {
 3149:     my ($img_path,$resizewidth,$resizeheight) = @_;
 3150:     my $ima = Image::Magick->new;
 3151:     my $resized;
 3152:     if (-e $img_path) {
 3153:         $ima->Read($img_path);
 3154:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
 3155:             my $width = $ima->Get('width');
 3156:             my $height = $ima->Get('height');
 3157:             if ($width > $resizewidth) {
 3158: 	        my $factor = $width/$resizewidth;
 3159:                 my $newheight = $height/$factor;
 3160:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
 3161:                 $resized = 1;
 3162:             }
 3163:         }
 3164:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
 3165:             my $width = $ima->Get('width');
 3166:             my $height = $ima->Get('height');
 3167:             if ($height > $resizeheight) {
 3168:                 my $factor = $height/$resizeheight;
 3169:                 my $newwidth = $width/$factor;
 3170:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
 3171:                 $resized = 1;
 3172:             }
 3173:         }
 3174:         if ($resized) {
 3175:             $ima->Write($img_path);
 3176:         }
 3177:     }
 3178:     return;
 3179: }
 3180: 
 3181: # --------------- Take an uploaded file and put it into the userfiles directory
 3182: # input: $formname - the contents of the file are in $env{"form.$formname"}
 3183: #                    the desired filename is in $env{"form.$formname.filename"}
 3184: #        $context - possible values: coursedoc, existingfile, overwrite, 
 3185: #                                    canceloverwrite, or ''. 
 3186: #                   if 'coursedoc': upload to the current course
 3187: #                   if 'existingfile': write file to tmp/overwrites directory 
 3188: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
 3189: #                   $context is passed as argument to &finishuserfileupload
 3190: #        $subdir - directory in userfile to store the file into
 3191: #        $parser - instruction to parse file for objects ($parser = parse)    
 3192: #        $allfiles - reference to hash for embedded objects
 3193: #        $codebase - reference to hash for codebase of java objects
 3194: #        $desuname - username for permanent storage of uploaded file
 3195: #        $dsetudom - domain for permanaent storage of uploaded file
 3196: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 3197: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 3198: #        $resizewidth - width (pixels) to which to resize uploaded image
 3199: #        $resizeheight - height (pixels) to which to resize uploaded image
 3200: #        $mimetype - reference to scalar to accommodate mime type determined
 3201: #                    from File::MMagic.
 3202: # 
 3203: # output: url of file in userspace, or error: <message> 
 3204: #             or /adm/notfound.html if failure to upload occurse
 3205: 
 3206: sub userfileupload {
 3207:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
 3208:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
 3209:     if (!defined($subdir)) { $subdir='unknown'; }
 3210:     my $fname=$env{'form.'.$formname.'.filename'};
 3211:     $fname=&clean_filename($fname);
 3212:     # See if there is anything left
 3213:     unless ($fname) { return 'error: no uploaded file'; }
 3214:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
 3215:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
 3216:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
 3217:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3218:         my $now = time;
 3219:         my $filepath;
 3220:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
 3221:              $filepath = 'tmp/helprequests/'.$now;
 3222:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
 3223:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 3224:                          '_'.$env{'user.domain'}.'/pending';
 3225:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3226:             my ($docuname,$docudom);
 3227:             if ($destudom) {
 3228:                 $docudom = $destudom;
 3229:             } else {
 3230:                 $docudom = $env{'user.domain'};
 3231:             }
 3232:             if ($destuname) {
 3233:                 $docuname = $destuname;
 3234:             } else {
 3235:                 $docuname = $env{'user.name'};
 3236:             }
 3237:             if (exists($env{'form.group'})) {
 3238:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3239:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3240:             }
 3241:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
 3242:             if ($context eq 'canceloverwrite') {
 3243:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
 3244:                 if (-e  $tempfile) {
 3245:                     my @info = stat($tempfile);
 3246:                     if ($info[9] eq $env{'form.timestamp'}) {
 3247:                         unlink($tempfile);
 3248:                     }
 3249:                 }
 3250:                 return;
 3251:             }
 3252:         }
 3253:         # Create the directory if not present
 3254:         my @parts=split(/\//,$filepath);
 3255:         my $fullpath = $perlvar{'lonDaemons'};
 3256:         for (my $i=0;$i<@parts;$i++) {
 3257:             $fullpath .= '/'.$parts[$i];
 3258:             if ((-e $fullpath)!=1) {
 3259:                 mkdir($fullpath,0777);
 3260:             }
 3261:         }
 3262:         open(my $fh,'>'.$fullpath.'/'.$fname);
 3263:         print $fh $env{'form.'.$formname};
 3264:         close($fh);
 3265:         if ($context eq 'existingfile') {
 3266:             my @info = stat($fullpath.'/'.$fname);
 3267:             return ($fullpath.'/'.$fname,$info[9]);
 3268:         } else {
 3269:             return $fullpath.'/'.$fname;
 3270:         }
 3271:     }
 3272:     if ($subdir eq 'scantron') {
 3273:         $fname = 'scantron_orig_'.$fname;
 3274:     } else {
 3275:         $fname="$subdir/$fname";
 3276:     }
 3277:     if ($context eq 'coursedoc') {
 3278: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3279: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3280:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 3281:             return &finishuserfileupload($docuname,$docudom,
 3282: 					 $formname,$fname,$parser,$allfiles,
 3283: 					 $codebase,$thumbwidth,$thumbheight,
 3284:                                          $resizewidth,$resizeheight,$context,$mimetype);
 3285:         } else {
 3286:             if ($env{'form.folder'}) {
 3287:                 $fname=$env{'form.folder'}.'/'.$fname;
 3288:             }
 3289:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 3290: 				       $fname,$formname,$parser,
 3291: 				       $allfiles,$codebase,$mimetype);
 3292:         }
 3293:     } elsif (defined($destuname)) {
 3294:         my $docuname=$destuname;
 3295:         my $docudom=$destudom;
 3296: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 3297: 				     $parser,$allfiles,$codebase,
 3298:                                      $thumbwidth,$thumbheight,
 3299:                                      $resizewidth,$resizeheight,$context,$mimetype);
 3300:     } else {
 3301:         my $docuname=$env{'user.name'};
 3302:         my $docudom=$env{'user.domain'};
 3303:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
 3304:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3305:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3306:         }
 3307: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 3308: 				     $parser,$allfiles,$codebase,
 3309:                                      $thumbwidth,$thumbheight,
 3310:                                      $resizewidth,$resizeheight,$context,$mimetype);
 3311:     }
 3312: }
 3313: 
 3314: sub finishuserfileupload {
 3315:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 3316:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
 3317:     my $path=$docudom.'/'.$docuname.'/';
 3318:     my $filepath=$perlvar{'lonDocRoot'};
 3319:   
 3320:     my ($fnamepath,$file,$fetchthumb);
 3321:     $file=$fname;
 3322:     if ($fname=~m|/|) {
 3323:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 3324: 	$path.=$fnamepath.'/';
 3325:     }
 3326:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 3327:     my $count;
 3328:     for ($count=4;$count<=$#parts;$count++) {
 3329:         $filepath.="/$parts[$count]";
 3330:         if ((-e $filepath)!=1) {
 3331: 	    mkdir($filepath,0777);
 3332:         }
 3333:     }
 3334: 
 3335: # Save the file
 3336:     {
 3337: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
 3338: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 3339: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 3340: 	    return '/adm/notfound.html';
 3341: 	}
 3342:         if ($context eq 'overwrite') {
 3343:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
 3344:             my $target = $filepath.'/'.$file;
 3345:             if (-e $source) {
 3346:                 my @info = stat($source);
 3347:                 if ($info[9] eq $env{'form.timestamp'}) {   
 3348:                     unless (&File::Copy::move($source,$target)) {
 3349:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
 3350:                         return "Moving from $source failed";
 3351:                     }
 3352:                 } else {
 3353:                     return "Temporary file: $source had unexpected date/time for last modification";
 3354:                 }
 3355:             } else {
 3356:                 return "Temporary file: $source missing";
 3357:             }
 3358:         } elsif (!print FH ($env{'form.'.$formname})) {
 3359: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 3360: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 3361: 	    return '/adm/notfound.html';
 3362: 	}
 3363: 	close(FH);
 3364:         if ($resizewidth && $resizeheight) {
 3365:             my $mm = new File::MMagic;
 3366:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
 3367:             if ($mime_type =~ m{^image/}) {
 3368: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
 3369:             }  
 3370: 	}
 3371:     }
 3372:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
 3373:         if (ref($mimetype)) {
 3374:             if ($$mimetype eq '') {
 3375:                 my $mm = new File::MMagic;
 3376:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
 3377:                 $$mimetype = $type;
 3378:             }
 3379:         }
 3380:     }
 3381:     if ($parser eq 'parse') {
 3382:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
 3383:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
 3384:                                                        $allfiles,$codebase);
 3385:             unless ($parse_result eq 'ok') {
 3386:                 &logthis('Failed to parse '.$filepath.$file.
 3387: 	   	         ' for embedded media: '.$parse_result); 
 3388:             }
 3389:         }
 3390:     }
 3391:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 3392:         my $input = $filepath.'/'.$file;
 3393:         my $output = $filepath.'/'.'tn-'.$file;
 3394:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 3395:         system("convert -sample $thumbsize $input $output");
 3396:         if (-e $filepath.'/'.'tn-'.$file) {
 3397:             $fetchthumb  = 1; 
 3398:         }
 3399:     }
 3400:  
 3401: # Notify homeserver to grep it
 3402: #
 3403:     my $docuhome=&homeserver($docuname,$docudom);	
 3404:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 3405:     if ($fetchresult eq 'ok') {
 3406:         if ($fetchthumb) {
 3407:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 3408:             if ($thumbresult ne 'ok') {
 3409:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 3410:                          $docuhome.': '.$thumbresult);
 3411:             }
 3412:         }
 3413: #
 3414: # Return the URL to it
 3415:         return '/uploaded/'.$path.$file;
 3416:     } else {
 3417:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 3418: 		 ': '.$fetchresult);
 3419:         return '/adm/notfound.html';
 3420:     }
 3421: }
 3422: 
 3423: sub extract_embedded_items {
 3424:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 3425:     my @state = ();
 3426:     my (%lastids,%related,%shockwave,%flashvars);
 3427:     my %javafiles = (
 3428:                       codebase => '',
 3429:                       code => '',
 3430:                       archive => ''
 3431:                     );
 3432:     my %mediafiles = (
 3433:                       src => '',
 3434:                       movie => '',
 3435:                      );
 3436:     my $p;
 3437:     if ($content) {
 3438:         $p = HTML::LCParser->new($content);
 3439:     } else {
 3440:         $p = HTML::LCParser->new($fullpath);
 3441:     }
 3442:     while (my $t=$p->get_token()) {
 3443: 	if ($t->[0] eq 'S') {
 3444: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 3445: 	    push(@state, $tagname);
 3446:             if (lc($tagname) eq 'allow') {
 3447:                 &add_filetype($allfiles,$attr->{'src'},'src');
 3448:             }
 3449: 	    if (lc($tagname) eq 'img') {
 3450: 		&add_filetype($allfiles,$attr->{'src'},'src');
 3451: 	    }
 3452: 	    if (lc($tagname) eq 'a') {
 3453:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
 3454:                     &add_filetype($allfiles,$attr->{'href'},'href');
 3455:                 }
 3456: 	    }
 3457:             if (lc($tagname) eq 'script') {
 3458:                 my $src;
 3459:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 3460:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 3461:                 } else {
 3462:                     if ($attr->{'src'} ne '') {
 3463:                         $src = $attr->{'src'};
 3464:                         &add_filetype($allfiles,$src,'src');
 3465:                     }
 3466:                 }
 3467:                 my $text = $p->get_trimmed_text();
 3468:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
 3469:                     my @swfargs = split(/,/,$1);
 3470:                     foreach my $item (@swfargs) {
 3471:                         $item =~ s/["']//g;
 3472:                         $item =~ s/^\s+//;
 3473:                         $item =~ s/\s+$//;
 3474:                     }
 3475:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
 3476:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
 3477:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
 3478:                         } else {
 3479:                             $related{$swfargs[0]} = [$swfargs[2]];
 3480:                         }
 3481:                     }
 3482:                 }
 3483:             }
 3484:             if (lc($tagname) eq 'link') {
 3485:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 3486:                     &add_filetype($allfiles,$attr->{'href'},'href');
 3487:                 }
 3488:             }
 3489: 	    if (lc($tagname) eq 'object' ||
 3490: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 3491: 		foreach my $item (keys(%javafiles)) {
 3492: 		    $javafiles{$item} = '';
 3493: 		}
 3494:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
 3495:                     $lastids{lc($tagname)} = $attr->{'id'};
 3496:                 }
 3497: 	    }
 3498: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 3499: 		my $name = lc($attr->{'name'});
 3500: 		foreach my $item (keys(%javafiles)) {
 3501: 		    if ($name eq $item) {
 3502: 			$javafiles{$item} = $attr->{'value'};
 3503: 			last;
 3504: 		    }
 3505: 		}
 3506:                 my $pathfrom;
 3507: 		foreach my $item (keys(%mediafiles)) {
 3508: 		    if ($name eq $item) {
 3509:                         $pathfrom = $attr->{'value'};
 3510:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
 3511: 			&add_filetype($allfiles,$pathfrom,$name);
 3512: 			last;
 3513: 		    }
 3514: 		}
 3515:                 if ($name eq 'flashvars') {
 3516:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
 3517:                 }
 3518:                 if ($pathfrom ne '') {
 3519:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
 3520:                                          $pathfrom);
 3521:                 }
 3522: 	    }
 3523: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 3524: 		foreach my $item (keys(%javafiles)) {
 3525: 		    if ($attr->{$item}) {
 3526: 			$javafiles{$item} = $attr->{$item};
 3527: 			last;
 3528: 		    }
 3529: 		}
 3530: 		foreach my $item (keys(%mediafiles)) {
 3531: 		    if ($attr->{$item}) {
 3532: 			&add_filetype($allfiles,$attr->{$item},$item);
 3533: 			last;
 3534: 		    }
 3535: 		}
 3536:                 if (lc($tagname) eq 'embed') {
 3537:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
 3538:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
 3539:                                              $attr->{'src'});
 3540:                     }
 3541:                 }
 3542: 	    }
 3543:             if (lc($tagname) eq 'iframe') {
 3544:                 my $src = $attr->{'src'} ;
 3545:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
 3546:                     &add_filetype($allfiles,$src,'src');
 3547:                 } elsif ($src =~ m{^/}) {
 3548:                     if ($env{'request.course.id'}) {
 3549:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3550:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3551:                         my $url = &hreflocation('',$fullpath);
 3552:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
 3553:                             my $relpath = $1;
 3554:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
 3555:                                 &add_filetype($allfiles,$1,'src');
 3556:                             }
 3557:                         }
 3558:                     }
 3559:                 }
 3560:             }
 3561:             if ($t->[4] =~ m{/>$}) {
 3562:                 pop(@state);
 3563:             }
 3564: 	} elsif ($t->[0] eq 'E') {
 3565: 	    my ($tagname) = ($t->[1]);
 3566: 	    if ($javafiles{'codebase'} ne '') {
 3567: 		$javafiles{'codebase'} .= '/';
 3568: 	    }  
 3569: 	    if (lc($tagname) eq 'applet' ||
 3570: 		lc($tagname) eq 'object' ||
 3571: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 3572: 		) {
 3573: 		foreach my $item (keys(%javafiles)) {
 3574: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 3575: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 3576: 			&add_filetype($allfiles,$file,$item);
 3577: 		    }
 3578: 		}
 3579: 	    } 
 3580: 	    pop @state;
 3581: 	}
 3582:     }
 3583:     foreach my $id (sort(keys(%flashvars))) {
 3584:         if ($shockwave{$id} ne '') {
 3585:             my @pairs = split(/\&/,$flashvars{$id});
 3586:             foreach my $pair (@pairs) {
 3587:                 my ($key,$value) = split(/\=/,$pair);
 3588:                 if ($key eq 'thumb') {
 3589:                     &add_filetype($allfiles,$value,$key);
 3590:                 } elsif ($key eq 'content') {
 3591:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
 3592:                     my ($ext) = ($value =~ /\.([^.]+)$/);
 3593:                     if ($ext ne '') {
 3594:                         &add_filetype($allfiles,$path.$value,$ext);
 3595:                     }
 3596:                 }
 3597:             }
 3598:         }
 3599:     }
 3600:     return 'ok';
 3601: }
 3602: 
 3603: sub add_filetype {
 3604:     my ($allfiles,$file,$type)=@_;
 3605:     if (exists($allfiles->{$file})) {
 3606: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 3607: 	    push(@{$allfiles->{$file}}, &escape($type));
 3608: 	}
 3609:     } else {
 3610: 	@{$allfiles->{$file}} = (&escape($type));
 3611:     }
 3612: }
 3613: 
 3614: sub embedded_dependency {
 3615:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
 3616:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
 3617:         if (($identifier ne '') &&
 3618:             (ref($related->{$identifier}) eq 'ARRAY') &&
 3619:             ($pathfrom ne '')) {
 3620:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
 3621:             foreach my $dep (@{$related->{$identifier}}) {
 3622:                 &add_filetype($allfiles,$path.$dep,'object');
 3623:             }
 3624:         }
 3625:     }
 3626:     return;
 3627: }
 3628: 
 3629: sub removeuploadedurl {
 3630:     my ($url)=@_;	
 3631:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 3632:     return &removeuserfile($uname,$udom,$fname);
 3633: }
 3634: 
 3635: sub removeuserfile {
 3636:     my ($docuname,$docudom,$fname)=@_;
 3637:     my $home=&homeserver($docuname,$docudom);    
 3638:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 3639:     if ($result eq 'ok') {	
 3640:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 3641:             my $metafile = $fname.'.meta';
 3642:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 3643: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 3644:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 3645:             my $sqlresult = 
 3646:                 &update_portfolio_table($docuname,$docudom,$file,
 3647:                                         'portfolio_metadata',$group,
 3648:                                         'delete');
 3649:         }
 3650:     }
 3651:     return $result;
 3652: }
 3653: 
 3654: sub mkdiruserfile {
 3655:     my ($docuname,$docudom,$dir)=@_;
 3656:     my $home=&homeserver($docuname,$docudom);
 3657:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 3658: }
 3659: 
 3660: sub renameuserfile {
 3661:     my ($docuname,$docudom,$old,$new)=@_;
 3662:     my $home=&homeserver($docuname,$docudom);
 3663:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 3664:                         &escape("$old").':'.&escape("$new"),$home);
 3665:     if ($result eq 'ok') {
 3666:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 3667:             my $oldmeta = $old.'.meta';
 3668:             my $newmeta = $new.'.meta';
 3669:             my $metaresult = 
 3670:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 3671: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 3672:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 3673:             my $sqlresult = 
 3674:                 &update_portfolio_table($docuname,$docudom,$file,
 3675:                                         'portfolio_metadata',$group,
 3676:                                         'delete');
 3677:         }
 3678:     }
 3679:     return $result;
 3680: }
 3681: 
 3682: # ------------------------------------------------------------------------- Log
 3683: 
 3684: sub log {
 3685:     my ($dom,$nam,$hom,$what)=@_;
 3686:     return critical("log:$dom:$nam:$what",$hom);
 3687: }
 3688: 
 3689: # ------------------------------------------------------------------ Course Log
 3690: #
 3691: # This routine flushes several buffers of non-mission-critical nature
 3692: #
 3693: 
 3694: sub flushcourselogs {
 3695:     &logthis('Flushing log buffers');
 3696: #
 3697: # course logs
 3698: # This is a log of all transactions in a course, which can be used
 3699: # for data mining purposes
 3700: #
 3701: # It also collects the courseid database, which lists last transaction
 3702: # times and course titles for all courseids
 3703: #
 3704:     my %courseidbuffer=();
 3705:     foreach my $crsid (keys(%courselogs)) {
 3706:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 3707: 		          &escape($courselogs{$crsid}),
 3708: 		          $coursehombuf{$crsid}) eq 'ok') {
 3709: 	    delete $courselogs{$crsid};
 3710:         } else {
 3711:             &logthis('Failed to flush log buffer for '.$crsid);
 3712:             if (length($courselogs{$crsid})>40000) {
 3713:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 3714:                         " exceeded maximum size, deleting.</font>");
 3715:                delete $courselogs{$crsid};
 3716:             }
 3717:         }
 3718:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 3719:             'description' => $coursedescrbuf{$crsid},
 3720:             'inst_code'    => $courseinstcodebuf{$crsid},
 3721:             'type'        => $coursetypebuf{$crsid},
 3722:             'owner'       => $courseownerbuf{$crsid},
 3723:         };
 3724:     }
 3725: #
 3726: # Write course id database (reverse lookup) to homeserver of courses 
 3727: # Is used in pickcourse
 3728: #
 3729:     foreach my $crs_home (keys(%courseidbuffer)) {
 3730:         my $response = &courseidput(&host_domain($crs_home),
 3731:                                     $courseidbuffer{$crs_home},
 3732:                                     $crs_home,'timeonly');
 3733:     }
 3734: #
 3735: # File accesses
 3736: # Writes to the dynamic metadata of resources to get hit counts, etc.
 3737: #
 3738:     foreach my $entry (keys(%accesshash)) {
 3739:         if ($entry =~ /___count$/) {
 3740:             my ($dom,$name);
 3741:             ($dom,$name,undef)=
 3742: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 3743:             if (! defined($dom) || $dom eq '' || 
 3744:                 ! defined($name) || $name eq '') {
 3745:                 my $cid = $env{'request.course.id'};
 3746:                 $dom  = $env{'request.'.$cid.'.domain'};
 3747:                 $name = $env{'request.'.$cid.'.num'};
 3748:             }
 3749:             my $value = $accesshash{$entry};
 3750:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 3751:             my %temphash=($url => $value);
 3752:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 3753:             if ($result eq 'ok') {
 3754:                 delete $accesshash{$entry};
 3755:             }
 3756:         } else {
 3757:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 3758:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
 3759:             my %temphash=($entry => $accesshash{$entry});
 3760:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 3761:                 delete $accesshash{$entry};
 3762:             }
 3763:         }
 3764:     }
 3765: #
 3766: # Roles
 3767: # Reverse lookup of user roles for course faculty/staff and co-authorship
 3768: #
 3769:     foreach my $entry (keys(%userrolehash)) {
 3770:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 3771: 	    split(/\:/,$entry);
 3772:         if (&Apache::lonnet::put('nohist_userroles',
 3773:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 3774:                 $rudom,$runame) eq 'ok') {
 3775: 	    delete $userrolehash{$entry};
 3776:         }
 3777:     }
 3778: #
 3779: # Reverse lookup of domain roles (dc, ad, li, sc, au)
 3780: #
 3781:     my %domrolebuffer = ();
 3782:     foreach my $entry (keys(%domainrolehash)) {
 3783:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 3784:         if ($domrolebuffer{$rudom}) {
 3785:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 3786:                       '='.&escape($domainrolehash{$entry});
 3787:         } else {
 3788:             $domrolebuffer{$rudom}.=&escape($entry).
 3789:                       '='.&escape($domainrolehash{$entry});
 3790:         }
 3791:         delete $domainrolehash{$entry};
 3792:     }
 3793:     foreach my $dom (keys(%domrolebuffer)) {
 3794: 	my %servers = &get_servers($dom,'library');
 3795: 	foreach my $tryserver (keys(%servers)) {
 3796: 	    unless (&reply('domroleput:'.$dom.':'.
 3797: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
 3798: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 3799: 	    }
 3800:         }
 3801:     }
 3802:     $dumpcount++;
 3803: }
 3804: 
 3805: sub courselog {
 3806:     my $what=shift;
 3807:     $what=time.':'.$what;
 3808:     unless ($env{'request.course.id'}) { return ''; }
 3809:     $coursedombuf{$env{'request.course.id'}}=
 3810:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 3811:     $coursenumbuf{$env{'request.course.id'}}=
 3812:        $env{'course.'.$env{'request.course.id'}.'.num'};
 3813:     $coursehombuf{$env{'request.course.id'}}=
 3814:        $env{'course.'.$env{'request.course.id'}.'.home'};
 3815:     $coursedescrbuf{$env{'request.course.id'}}=
 3816:        $env{'course.'.$env{'request.course.id'}.'.description'};
 3817:     $courseinstcodebuf{$env{'request.course.id'}}=
 3818:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 3819:     $courseownerbuf{$env{'request.course.id'}}=
 3820:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 3821:     $coursetypebuf{$env{'request.course.id'}}=
 3822:        $env{'course.'.$env{'request.course.id'}.'.type'};
 3823:     if (defined $courselogs{$env{'request.course.id'}}) {
 3824: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 3825:     } else {
 3826: 	$courselogs{$env{'request.course.id'}}.=$what;
 3827:     }
 3828:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 3829: 	&flushcourselogs();
 3830:     }
 3831: }
 3832: 
 3833: sub courseacclog {
 3834:     my $fnsymb=shift;
 3835:     unless ($env{'request.course.id'}) { return ''; }
 3836:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 3837:     if ($fnsymb=~/$LONCAPA::assess_re/) {
 3838:         $what.=':POST';
 3839:         # FIXME: Probably ought to escape things....
 3840: 	foreach my $key (keys(%env)) {
 3841:             if ($key=~/^form\.(.*)/) {
 3842:                 my $formitem = $1;
 3843:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 3844:                     $what.=':'.$formitem.'='.$env{$key};
 3845:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 3846:                     $what.=':'.$formitem.'='.$env{$key};
 3847:                 }
 3848:             }
 3849:         }
 3850:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 3851:         # FIXME: We should not be depending on a form parameter that someone
 3852:         # editing lonsearchcat.pm might change in the future.
 3853:         if ($env{'form.phase'} eq 'course_search') {
 3854:             $what.= ':POST';
 3855:             # FIXME: Probably ought to escape things....
 3856:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 3857:                                  'crsdiscuss') {
 3858:                 $what.=':'.$element.'='.$env{'form.'.$element};
 3859:             }
 3860:         }
 3861:     }
 3862:     &courselog($what);
 3863: }
 3864: 
 3865: sub countacc {
 3866:     my $url=&declutter(shift);
 3867:     return if (! defined($url) || $url eq '');
 3868:     unless ($env{'request.course.id'}) { return ''; }
 3869: #
 3870: # Mark that this url was used in this course
 3871: #
 3872:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 3873: #
 3874: # Increase the access count for this resource in this child process
 3875: #
 3876:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 3877:     $accesshash{$key}++;
 3878: }
 3879: 
 3880: sub linklog {
 3881:     my ($from,$to)=@_;
 3882:     $from=&declutter($from);
 3883:     $to=&declutter($to);
 3884:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 3885:     $accesshash{$to.'___'.$from.'___goto'}=1;
 3886: }
 3887: 
 3888: sub statslog {
 3889:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
 3890:     if ($users<2) { return; }
 3891:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
 3892:             'course'       => $env{'request.course.id'},
 3893:             'sections'     => '"all"',
 3894:             'num_students' => $users,
 3895:             'part'         => $part,
 3896:             'symb'         => $symb,
 3897:             'mean_tries'   => $av_attempts,
 3898:             'deg_of_diff'  => $degdiff});
 3899:     foreach my $key (keys(%dynstore)) {
 3900:         $accesshash{$key}=$dynstore{$key};
 3901:     }
 3902: }
 3903:   
 3904: sub userrolelog {
 3905:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 3906:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
 3907:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 3908:        $userrolehash
 3909:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 3910:                     =$tend.':'.$tstart;
 3911:     }
 3912:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
 3913:        $userrolehash
 3914:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 3915:                     =$tend.':'.$tstart;
 3916:     }
 3917:     if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
 3918:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 3919:        $domainrolehash
 3920:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 3921:                     = $tend.':'.$tstart;
 3922:     }
 3923: }
 3924: 
 3925: sub courserolelog {
 3926:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 3927:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 3928:         my $cdom = $1;
 3929:         my $cnum = $2;
 3930:         my $sec = $3;
 3931:         my $namespace = 'rolelog';
 3932:         my %storehash = (
 3933:                            role    => $trole,
 3934:                            start   => $tstart,
 3935:                            end     => $tend,
 3936:                            selfenroll => $selfenroll,
 3937:                            context    => $context,
 3938:                         );
 3939:         if ($trole eq 'gr') {
 3940:             $namespace = 'groupslog';
 3941:             $storehash{'group'} = $sec;
 3942:         } else {
 3943:             $storehash{'section'} = $sec;
 3944:         }
 3945:         &write_log('course',$namespace,\%storehash,$delflag,$username,
 3946:                    $domain,$cnum,$cdom);
 3947:         if (($trole ne 'st') || ($sec ne '')) {
 3948:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 3949:         }
 3950:     }
 3951:     return;
 3952: }
 3953: 
 3954: sub domainrolelog {
 3955:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 3956:     if ($area =~ m{^/($match_domain)/$}) {
 3957:         my $cdom = $1;
 3958:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
 3959:         my $namespace = 'rolelog';
 3960:         my %storehash = (
 3961:                            role    => $trole,
 3962:                            start   => $tstart,
 3963:                            end     => $tend,
 3964:                            context => $context,
 3965:                         );
 3966:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
 3967:                    $domain,$domconfiguser,$cdom);
 3968:     }
 3969:     return;
 3970: 
 3971: }
 3972: 
 3973: sub coauthorrolelog {
 3974:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 3975:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
 3976:         my $audom = $1;
 3977:         my $auname = $2;
 3978:         my $namespace = 'rolelog';
 3979:         my %storehash = (
 3980:                            role    => $trole,
 3981:                            start   => $tstart,
 3982:                            end     => $tend,
 3983:                            context => $context,
 3984:                         );
 3985:         &write_log('author',$namespace,\%storehash,$delflag,$username,
 3986:                    $domain,$auname,$audom);
 3987:     }
 3988:     return;
 3989: }
 3990: 
 3991: sub get_course_adv_roles {
 3992:     my ($cid,$codes) = @_;
 3993:     $cid=$env{'request.course.id'} unless (defined($cid));
 3994:     my %coursehash=&coursedescription($cid);
 3995:     my $crstype = &Apache::loncommon::course_type($cid);
 3996:     my %nothide=();
 3997:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3998:         if ($user !~ /:/) {
 3999: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 4000:         } else {
 4001:             $nothide{$user}=1;
 4002:         }
 4003:     }
 4004:     my @possdoms = ($coursehash{'domain'});
 4005:     if ($coursehash{'checkforpriv'}) {
 4006:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
 4007:     }
 4008:     my %returnhash=();
 4009:     my %dumphash=
 4010:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 4011:     my $now=time;
 4012:     my %privileged;
 4013:     foreach my $entry (keys(%dumphash)) {
 4014: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 4015:         if (($tstart) && ($tstart<0)) { next; }
 4016:         if (($tend) && ($tend<$now)) { next; }
 4017:         if (($tstart) && ($now<$tstart)) { next; }
 4018:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 4019: 	if ($username eq '' || $domain eq '') { next; }
 4020:         if ((&privileged($username,$domain,\@possdoms)) &&
 4021:             (!$nothide{$username.':'.$domain})) { next; }
 4022: 	if ($role eq 'cr') { next; }
 4023:         if ($codes) {
 4024:             if ($section) { $role .= ':'.$section; }
 4025:             if ($returnhash{$role}) {
 4026:                 $returnhash{$role}.=','.$username.':'.$domain;
 4027:             } else {
 4028:                 $returnhash{$role}=$username.':'.$domain;
 4029:             }
 4030:         } else {
 4031:             my $key=&plaintext($role,$crstype);
 4032:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 4033:             if ($returnhash{$key}) {
 4034: 	        $returnhash{$key}.=','.$username.':'.$domain;
 4035:             } else {
 4036:                 $returnhash{$key}=$username.':'.$domain;
 4037:             }
 4038:         }
 4039:     }
 4040:     return %returnhash;
 4041: }
 4042: 
 4043: sub get_my_roles {
 4044:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 4045:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 4046:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 4047:     my (%dumphash,%nothide);
 4048:     if ($context eq 'userroles') {
 4049:         %dumphash = &dump('roles',$udom,$uname);
 4050:     } else {
 4051:         %dumphash = &dump('nohist_userroles',$udom,$uname);
 4052:         if ($hidepriv) {
 4053:             my %coursehash=&coursedescription($udom.'_'.$uname);
 4054:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 4055:                 if ($user !~ /:/) {
 4056:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 4057:                 } else {
 4058:                     $nothide{$user} = 1;
 4059:                 }
 4060:             }
 4061:         }
 4062:     }
 4063:     my %returnhash=();
 4064:     my $now=time;
 4065:     my %privileged;
 4066:     foreach my $entry (keys(%dumphash)) {
 4067:         my ($role,$tend,$tstart);
 4068:         if ($context eq 'userroles') {
 4069:             next if ($entry =~ /^rolesdef/);
 4070: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 4071:         } else {
 4072:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 4073:         }
 4074:         if (($tstart) && ($tstart<0)) { next; }
 4075:         my $status = 'active';
 4076:         if (($tend) && ($tend<=$now)) {
 4077:             $status = 'previous';
 4078:         } 
 4079:         if (($tstart) && ($now<$tstart)) {
 4080:             $status = 'future';
 4081:         }
 4082:         if (ref($types) eq 'ARRAY') {
 4083:             if (!grep(/^\Q$status\E$/,@{$types})) {
 4084:                 next;
 4085:             } 
 4086:         } else {
 4087:             if ($status ne 'active') {
 4088:                 next;
 4089:             }
 4090:         }
 4091:         my ($rolecode,$username,$domain,$section,$area);
 4092:         if ($context eq 'userroles') {
 4093:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
 4094:             (undef,$domain,$username,$section) = split(/\//,$area);
 4095:         } else {
 4096:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 4097:         }
 4098:         if (ref($roledoms) eq 'ARRAY') {
 4099:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 4100:                 next;
 4101:             }
 4102:         }
 4103:         if (ref($roles) eq 'ARRAY') {
 4104:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 4105:                 if ($role =~ /^cr\//) {
 4106:                     if (!grep(/^cr$/,@{$roles})) {
 4107:                         next;
 4108:                     }
 4109:                 } elsif ($role =~ /^gr\//) {
 4110:                     if (!grep(/^gr$/,@{$roles})) {
 4111:                         next;
 4112:                     }
 4113:                 } else {
 4114:                     next;
 4115:                 }
 4116:             }
 4117:         }
 4118:         if ($hidepriv) {
 4119:             my @privroles = ('dc','su');
 4120:             if ($context eq 'userroles') {
 4121:                 next if (grep(/^\Q$role\E$/,@privroles));
 4122:             } else {
 4123:                 my $possdoms = [$domain];
 4124:                 if (ref($roledoms) eq 'ARRAY') {
 4125:                    push(@{$possdoms},@{$roledoms}); 
 4126:                 }
 4127:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
 4128:                     if (!$nothide{$username.':'.$domain}) {
 4129:                         next;
 4130:                     }
 4131:                 }
 4132:             }
 4133:         }
 4134:         if ($withsec) {
 4135:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 4136:                 $tstart.':'.$tend;
 4137:         } else {
 4138:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 4139:         }
 4140:     }
 4141:     return %returnhash;
 4142: }
 4143: 
 4144: # ----------------------------------------------------- Frontpage Announcements
 4145: #
 4146: #
 4147: 
 4148: sub postannounce {
 4149:     my ($server,$text)=@_;
 4150:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 4151:     unless ($text=~/\w/) { $text=''; }
 4152:     return &reply('setannounce:'.&escape($text),$server);
 4153: }
 4154: 
 4155: sub getannounce {
 4156: 
 4157:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 4158: 	my $announcement='';
 4159: 	while (my $line = <$fh>) { $announcement .= $line; }
 4160: 	close($fh);
 4161: 	if ($announcement=~/\w/) { 
 4162: 	    return 
 4163:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 4164:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 4165: 	} else {
 4166: 	    return '';
 4167: 	}
 4168:     } else {
 4169: 	return '';
 4170:     }
 4171: }
 4172: 
 4173: # ---------------------------------------------------------- Course ID routines
 4174: # Deal with domain's nohist_courseid.db files
 4175: #
 4176: 
 4177: sub courseidput {
 4178:     my ($domain,$storehash,$coursehome,$caller) = @_;
 4179:     return unless (ref($storehash) eq 'HASH');
 4180:     my $outcome;
 4181:     if ($caller eq 'timeonly') {
 4182:         my $cids = '';
 4183:         foreach my $item (keys(%$storehash)) {
 4184:             $cids.=&escape($item).'&';
 4185:         }
 4186:         $cids=~s/\&$//;
 4187:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 4188:                           $coursehome);       
 4189:     } else {
 4190:         my $items = '';
 4191:         foreach my $item (keys(%$storehash)) {
 4192:             $items.= &escape($item).'='.
 4193:                      &freeze_escape($$storehash{$item}).'&';
 4194:         }
 4195:         $items=~s/\&$//;
 4196:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 4197:                           $coursehome);
 4198:     }
 4199:     if ($outcome eq 'unknown_cmd') {
 4200:         my $what;
 4201:         foreach my $cid (keys(%$storehash)) {
 4202:             $what .= &escape($cid).'=';
 4203:             foreach my $item ('description','inst_code','owner','type') {
 4204:                 $what .= &escape($storehash->{$cid}{$item}).':';
 4205:             }
 4206:             $what =~ s/\:$/&/;
 4207:         }
 4208:         $what =~ s/\&$//;  
 4209:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 4210:     } else {
 4211:         return $outcome;
 4212:     }
 4213: }
 4214: 
 4215: sub courseiddump {
 4216:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 4217:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 4218:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
 4219:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
 4220:         $hasuniquecode)=@_;
 4221:     my $as_hash = 1;
 4222:     my %returnhash;
 4223:     if (!$domfilter) { $domfilter=''; }
 4224:     my %libserv = &all_library();
 4225:     foreach my $tryserver (keys(%libserv)) {
 4226:         if ( (  $hostidflag == 1 
 4227: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 4228: 	     || (!defined($hostidflag)) ) {
 4229: 
 4230: 	    if (($domfilter eq '') ||
 4231: 		(&host_domain($tryserver) eq $domfilter)) {
 4232:                 my $rep;
 4233:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
 4234:                     $rep = LONCAPA::Lond::dump_course_id_handler(
 4235:                         join(":", (&host_domain($tryserver), $sincefilter, 
 4236:                                 &escape($descfilter), &escape($instcodefilter), 
 4237:                                 &escape($ownerfilter), &escape($coursefilter),
 4238:                                 &escape($typefilter), &escape($regexp_ok), 
 4239:                                 $as_hash, &escape($selfenrollonly), 
 4240:                                 &escape($catfilter), $showhidden, $caller, 
 4241:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
 4242:                                 &escape($createdbefore), &escape($createdafter), 
 4243:                                 &escape($creationcontext), $domcloner, $hasuniquecode)));
 4244:                 } else {
 4245:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
 4246:                              $sincefilter.':'.&escape($descfilter).':'.
 4247:                              &escape($instcodefilter).':'.&escape($ownerfilter).
 4248:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
 4249:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
 4250:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
 4251:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
 4252:                              &escape($cc_clone).':'.$cloneonly.':'.
 4253:                              &escape($createdbefore).':'.&escape($createdafter).':'.
 4254:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode,
 4255:                              $tryserver);
 4256:                 }
 4257:                      
 4258:                 my @pairs=split(/\&/,$rep);
 4259:                 foreach my $item (@pairs) {
 4260:                     my ($key,$value)=split(/\=/,$item,2);
 4261:                     $key = &unescape($key);
 4262:                     next if ($key =~ /^error: 2 /);
 4263:                     my $result = &thaw_unescape($value);
 4264:                     if (ref($result) eq 'HASH') {
 4265:                         $returnhash{$key}=$result;
 4266:                     } else {
 4267:                         my @responses = split(/:/,$value);
 4268:                         my @items = ('description','inst_code','owner','type');
 4269:                         for (my $i=0; $i<@responses; $i++) {
 4270:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 4271:                         }
 4272:                     }
 4273:                 }
 4274:             }
 4275:         }
 4276:     }
 4277:     return %returnhash;
 4278: }
 4279: 
 4280: sub courselastaccess {
 4281:     my ($cdom,$cnum,$hostidref) = @_;
 4282:     my %returnhash;
 4283:     if ($cdom && $cnum) {
 4284:         my $chome = &homeserver($cnum,$cdom);
 4285:         if ($chome ne 'no_host') {
 4286:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
 4287:             &extract_lastaccess(\%returnhash,$rep);
 4288:         }
 4289:     } else {
 4290:         if (!$cdom) { $cdom=''; }
 4291:         my %libserv = &all_library();
 4292:         foreach my $tryserver (keys(%libserv)) {
 4293:             if (ref($hostidref) eq 'ARRAY') {
 4294:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
 4295:             } 
 4296:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
 4297:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
 4298:                 &extract_lastaccess(\%returnhash,$rep);
 4299:             }
 4300:         }
 4301:     }
 4302:     return %returnhash;
 4303: }
 4304: 
 4305: sub extract_lastaccess {
 4306:     my ($returnhash,$rep) = @_;
 4307:     if (ref($returnhash) eq 'HASH') {
 4308:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
 4309:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
 4310:                  $rep eq '') {
 4311:             my @pairs=split(/\&/,$rep);
 4312:             foreach my $item (@pairs) {
 4313:                 my ($key,$value)=split(/\=/,$item,2);
 4314:                 $key = &unescape($key);
 4315:                 next if ($key =~ /^error: 2 /);
 4316:                 $returnhash->{$key} = &thaw_unescape($value);
 4317:             }
 4318:         }
 4319:     }
 4320:     return;
 4321: }
 4322: 
 4323: # ---------------------------------------------------------- DC e-mail
 4324: 
 4325: sub dcmailput {
 4326:     my ($domain,$msgid,$message,$server)=@_;
 4327:     my $status = &Apache::lonnet::critical(
 4328:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 4329:        &escape($message),$server);
 4330:     return $status;
 4331: }
 4332: 
 4333: sub dcmaildump {
 4334:     my ($dom,$startdate,$enddate,$senders) = @_;
 4335:     my %returnhash=();
 4336: 
 4337:     if (defined(&domain($dom,'primary'))) {
 4338:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 4339:                                                          &escape($enddate).':';
 4340: 	my @esc_senders=map { &escape($_)} @$senders;
 4341: 	$cmd.=&escape(join('&',@esc_senders));
 4342: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 4343:             my ($key,$value) = split(/\=/,$line,2);
 4344:             if (($key) && ($value)) {
 4345:                 $returnhash{&unescape($key)} = &unescape($value);
 4346:             }
 4347:         }
 4348:     }
 4349:     return %returnhash;
 4350: }
 4351: # ---------------------------------------------------------- Domain roles
 4352: 
 4353: sub get_domain_roles {
 4354:     my ($dom,$roles,$startdate,$enddate)=@_;
 4355:     if ((!defined($startdate)) || ($startdate eq '')) {
 4356:         $startdate = '.';
 4357:     }
 4358:     if ((!defined($enddate)) || ($enddate eq '')) {
 4359:         $enddate = '.';
 4360:     }
 4361:     my $rolelist;
 4362:     if (ref($roles) eq 'ARRAY') {
 4363:         $rolelist = join('&',@{$roles});
 4364:     }
 4365:     my %personnel = ();
 4366: 
 4367:     my %servers = &get_servers($dom,'library');
 4368:     foreach my $tryserver (keys(%servers)) {
 4369: 	%{$personnel{$tryserver}}=();
 4370: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 4371: 					    &escape($startdate).':'.
 4372: 					    &escape($enddate).':'.
 4373: 					    &escape($rolelist), $tryserver))) {
 4374: 	    my ($key,$value) = split(/\=/,$line,2);
 4375: 	    if (($key) && ($value)) {
 4376: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 4377: 	    }
 4378: 	}
 4379:     }
 4380:     return %personnel;
 4381: }
 4382: 
 4383: # ----------------------------------------------------------- Interval timing 
 4384: 
 4385: {
 4386: # Caches needed for speedup of navmaps
 4387: # We don't want to cache this for very long at all (5 seconds at most)
 4388: # 
 4389: # The user for whom we cache
 4390: my $cachedkey='';
 4391: # The cached times for this user
 4392: my %cachedtimes=();
 4393: # When this was last done
 4394: my $cachedtime=();
 4395: 
 4396: sub load_all_first_access {
 4397:     my ($uname,$udom)=@_;
 4398:     if (($cachedkey eq $uname.':'.$udom) &&
 4399:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
 4400:         return;
 4401:     }
 4402:     $cachedtime=time;
 4403:     $cachedkey=$uname.':'.$udom;
 4404:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
 4405: }
 4406: 
 4407: sub get_first_access {
 4408:     my ($type,$argsymb,$argmap)=@_;
 4409:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 4410:     if ($argsymb) { $symb=$argsymb; }
 4411:     my ($map,$id,$res)=&decode_symb($symb);
 4412:     if ($argmap) { $map = $argmap; }
 4413:     if ($type eq 'course') {
 4414: 	$res='course';
 4415:     } elsif ($type eq 'map') {
 4416: 	$res=&symbread($map);
 4417:     } else {
 4418: 	$res=$symb;
 4419:     }
 4420:     &load_all_first_access($uname,$udom);
 4421:     return $cachedtimes{"$courseid\0$res"};
 4422: }
 4423: 
 4424: sub set_first_access {
 4425:     my ($type,$interval)=@_;
 4426:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 4427:     my ($map,$id,$res)=&decode_symb($symb);
 4428:     if ($type eq 'course') {
 4429: 	$res='course';
 4430:     } elsif ($type eq 'map') {
 4431: 	$res=&symbread($map);
 4432:     } else {
 4433: 	$res=$symb;
 4434:     }
 4435:     $cachedkey='';
 4436:     my $firstaccess=&get_first_access($type,$symb,$map);
 4437:     if (!$firstaccess) {
 4438:         my $start = time;
 4439: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
 4440:                           $udom,$uname);
 4441:         if ($putres eq 'ok') {
 4442:             &put('timerinterval',{"$courseid\0$res"=>$interval},
 4443:                  $udom,$uname); 
 4444:             &appenv(
 4445:                      {
 4446:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
 4447:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
 4448:                      }
 4449:                   );
 4450:         }
 4451:         return $putres;
 4452:     }
 4453:     return 'already_set';
 4454: }
 4455: }
 4456: # --------------------------------------------- Set Expire Date for Spreadsheet
 4457: 
 4458: sub expirespread {
 4459:     my ($uname,$udom,$stype,$usymb)=@_;
 4460:     my $cid=$env{'request.course.id'}; 
 4461:     if ($cid) {
 4462:        my $now=time;
 4463:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 4464:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 4465:                             $env{'course.'.$cid.'.num'}.
 4466: 	        	    ':nohist_expirationdates:'.
 4467:                             &escape($key).'='.$now,
 4468:                             $env{'course.'.$cid.'.home'})
 4469:     }
 4470:     return 'ok';
 4471: }
 4472: 
 4473: # ----------------------------------------------------- Devalidate Spreadsheets
 4474: 
 4475: sub devalidate {
 4476:     my ($symb,$uname,$udom)=@_;
 4477:     my $cid=$env{'request.course.id'}; 
 4478:     if ($cid) {
 4479:         # delete the stored spreadsheets for
 4480:         # - the student level sheet of this user in course's homespace
 4481:         # - the assessment level sheet for this resource 
 4482:         #   for this user in user's homespace
 4483: 	# - current conditional state info
 4484: 	my $key=$uname.':'.$udom.':';
 4485:         my $status=
 4486: 	    &del('nohist_calculatedsheets',
 4487: 		 [$key.'studentcalc:'],
 4488: 		 $env{'course.'.$cid.'.domain'},
 4489: 		 $env{'course.'.$cid.'.num'})
 4490: 		.' '.
 4491: 	    &del('nohist_calculatedsheets_'.$cid,
 4492: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 4493:         unless ($status eq 'ok ok') {
 4494:            &logthis('Could not devalidate spreadsheet '.
 4495:                     $uname.' at '.$udom.' for '.
 4496: 		    $symb.': '.$status);
 4497:         }
 4498: 	&delenv('user.state.'.$cid);
 4499:     }
 4500: }
 4501: 
 4502: sub get_scalar {
 4503:     my ($string,$end) = @_;
 4504:     my $value;
 4505:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 4506: 	$value = $1;
 4507:     } elsif ($$string =~ s/^([^&]*?)&//) {
 4508: 	$value = $1;
 4509:     }
 4510:     return &unescape($value);
 4511: }
 4512: 
 4513: sub array2str {
 4514:   my (@array) = @_;
 4515:   my $result=&arrayref2str(\@array);
 4516:   $result=~s/^__ARRAY_REF__//;
 4517:   $result=~s/__END_ARRAY_REF__$//;
 4518:   return $result;
 4519: }
 4520: 
 4521: sub arrayref2str {
 4522:   my ($arrayref) = @_;
 4523:   my $result='__ARRAY_REF__';
 4524:   foreach my $elem (@$arrayref) {
 4525:     if(ref($elem) eq 'ARRAY') {
 4526:       $result.=&arrayref2str($elem).'&';
 4527:     } elsif(ref($elem) eq 'HASH') {
 4528:       $result.=&hashref2str($elem).'&';
 4529:     } elsif(ref($elem)) {
 4530:       #print("Got a ref of ".(ref($elem))." skipping.");
 4531:     } else {
 4532:       $result.=&escape($elem).'&';
 4533:     }
 4534:   }
 4535:   $result=~s/\&$//;
 4536:   $result .= '__END_ARRAY_REF__';
 4537:   return $result;
 4538: }
 4539: 
 4540: sub hash2str {
 4541:   my (%hash) = @_;
 4542:   my $result=&hashref2str(\%hash);
 4543:   $result=~s/^__HASH_REF__//;
 4544:   $result=~s/__END_HASH_REF__$//;
 4545:   return $result;
 4546: }
 4547: 
 4548: sub hashref2str {
 4549:   my ($hashref)=@_;
 4550:   my $result='__HASH_REF__';
 4551:   foreach my $key (sort(keys(%$hashref))) {
 4552:     if (ref($key) eq 'ARRAY') {
 4553:       $result.=&arrayref2str($key).'=';
 4554:     } elsif (ref($key) eq 'HASH') {
 4555:       $result.=&hashref2str($key).'=';
 4556:     } elsif (ref($key)) {
 4557:       $result.='=';
 4558:       #print("Got a ref of ".(ref($key))." skipping.");
 4559:     } else {
 4560: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
 4561:     }
 4562: 
 4563:     if(ref($hashref->{$key}) eq 'ARRAY') {
 4564:       $result.=&arrayref2str($hashref->{$key}).'&';
 4565:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 4566:       $result.=&hashref2str($hashref->{$key}).'&';
 4567:     } elsif(ref($hashref->{$key})) {
 4568:        $result.='&';
 4569:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 4570:     } else {
 4571:       $result.=&escape($hashref->{$key}).'&';
 4572:     }
 4573:   }
 4574:   $result=~s/\&$//;
 4575:   $result .= '__END_HASH_REF__';
 4576:   return $result;
 4577: }
 4578: 
 4579: sub str2hash {
 4580:     my ($string)=@_;
 4581:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 4582:     return %$hash;
 4583: }
 4584: 
 4585: sub str2hashref {
 4586:   my ($string) = @_;
 4587: 
 4588:   my %hash;
 4589: 
 4590:   if($string !~ /^__HASH_REF__/) {
 4591:       if (! ($string eq '' || !defined($string))) {
 4592: 	  $hash{'error'}='Not hash reference';
 4593:       }
 4594:       return (\%hash, $string);
 4595:   }
 4596: 
 4597:   $string =~ s/^__HASH_REF__//;
 4598: 
 4599:   while($string !~ /^__END_HASH_REF__/) {
 4600:       #key
 4601:       my $key='';
 4602:       if($string =~ /^__HASH_REF__/) {
 4603:           ($key, $string)=&str2hashref($string);
 4604:           if(defined($key->{'error'})) {
 4605:               $hash{'error'}='Bad data';
 4606:               return (\%hash, $string);
 4607:           }
 4608:       } elsif($string =~ /^__ARRAY_REF__/) {
 4609:           ($key, $string)=&str2arrayref($string);
 4610:           if($key->[0] eq 'Array reference error') {
 4611:               $hash{'error'}='Bad data';
 4612:               return (\%hash, $string);
 4613:           }
 4614:       } else {
 4615:           $string =~ s/^(.*?)=//;
 4616: 	  $key=&unescape($1);
 4617:       }
 4618:       $string =~ s/^=//;
 4619: 
 4620:       #value
 4621:       my $value='';
 4622:       if($string =~ /^__HASH_REF__/) {
 4623:           ($value, $string)=&str2hashref($string);
 4624:           if(defined($value->{'error'})) {
 4625:               $hash{'error'}='Bad data';
 4626:               return (\%hash, $string);
 4627:           }
 4628:       } elsif($string =~ /^__ARRAY_REF__/) {
 4629:           ($value, $string)=&str2arrayref($string);
 4630:           if($value->[0] eq 'Array reference error') {
 4631:               $hash{'error'}='Bad data';
 4632:               return (\%hash, $string);
 4633:           }
 4634:       } else {
 4635: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 4636:       }
 4637:       $string =~ s/^&//;
 4638: 
 4639:       $hash{$key}=$value;
 4640:   }
 4641: 
 4642:   $string =~ s/^__END_HASH_REF__//;
 4643: 
 4644:   return (\%hash, $string);
 4645: }
 4646: 
 4647: sub str2array {
 4648:     my ($string)=@_;
 4649:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 4650:     return @$array;
 4651: }
 4652: 
 4653: sub str2arrayref {
 4654:   my ($string) = @_;
 4655:   my @array;
 4656: 
 4657:   if($string !~ /^__ARRAY_REF__/) {
 4658:       if (! ($string eq '' || !defined($string))) {
 4659: 	  $array[0]='Array reference error';
 4660:       }
 4661:       return (\@array, $string);
 4662:   }
 4663: 
 4664:   $string =~ s/^__ARRAY_REF__//;
 4665: 
 4666:   while($string !~ /^__END_ARRAY_REF__/) {
 4667:       my $value='';
 4668:       if($string =~ /^__HASH_REF__/) {
 4669:           ($value, $string)=&str2hashref($string);
 4670:           if(defined($value->{'error'})) {
 4671:               $array[0] ='Array reference error';
 4672:               return (\@array, $string);
 4673:           }
 4674:       } elsif($string =~ /^__ARRAY_REF__/) {
 4675:           ($value, $string)=&str2arrayref($string);
 4676:           if($value->[0] eq 'Array reference error') {
 4677:               $array[0] ='Array reference error';
 4678:               return (\@array, $string);
 4679:           }
 4680:       } else {
 4681: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 4682:       }
 4683:       $string =~ s/^&//;
 4684: 
 4685:       push(@array, $value);
 4686:   }
 4687: 
 4688:   $string =~ s/^__END_ARRAY_REF__//;
 4689: 
 4690:   return (\@array, $string);
 4691: }
 4692: 
 4693: # -------------------------------------------------------------------Temp Store
 4694: 
 4695: sub tmpreset {
 4696:   my ($symb,$namespace,$domain,$stuname) = @_;
 4697:   if (!$symb) {
 4698:     $symb=&symbread();
 4699:     if (!$symb) { $symb= $env{'request.url'}; }
 4700:   }
 4701:   $symb=escape($symb);
 4702: 
 4703:   if (!$namespace) { $namespace=$env{'request.state'}; }
 4704:   $namespace=~s/\//\_/g;
 4705:   $namespace=~s/\W//g;
 4706: 
 4707:   if (!$domain) { $domain=$env{'user.domain'}; }
 4708:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4709:   if ($domain eq 'public' && $stuname eq 'public') {
 4710:       $stuname=$ENV{'REMOTE_ADDR'};
 4711:   }
 4712:   my $path=LONCAPA::tempdir();
 4713:   my %hash;
 4714:   if (tie(%hash,'GDBM_File',
 4715: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4716: 	  &GDBM_WRCREAT(),0640)) {
 4717:     foreach my $key (keys(%hash)) {
 4718:       if ($key=~ /:$symb/) {
 4719: 	delete($hash{$key});
 4720:       }
 4721:     }
 4722:   }
 4723: }
 4724: 
 4725: sub tmpstore {
 4726:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4727: 
 4728:   if (!$symb) {
 4729:     $symb=&symbread();
 4730:     if (!$symb) { $symb= $env{'request.url'}; }
 4731:   }
 4732:   $symb=escape($symb);
 4733: 
 4734:   if (!$namespace) {
 4735:     # I don't think we would ever want to store this for a course.
 4736:     # it seems this will only be used if we don't have a course.
 4737:     #$namespace=$env{'request.course.id'};
 4738:     #if (!$namespace) {
 4739:       $namespace=$env{'request.state'};
 4740:     #}
 4741:   }
 4742:   $namespace=~s/\//\_/g;
 4743:   $namespace=~s/\W//g;
 4744:   if (!$domain) { $domain=$env{'user.domain'}; }
 4745:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4746:   if ($domain eq 'public' && $stuname eq 'public') {
 4747:       $stuname=$ENV{'REMOTE_ADDR'};
 4748:   }
 4749:   my $now=time;
 4750:   my %hash;
 4751:   my $path=LONCAPA::tempdir();
 4752:   if (tie(%hash,'GDBM_File',
 4753: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4754: 	  &GDBM_WRCREAT(),0640)) {
 4755:     $hash{"version:$symb"}++;
 4756:     my $version=$hash{"version:$symb"};
 4757:     my $allkeys=''; 
 4758:     foreach my $key (keys(%$storehash)) {
 4759:       $allkeys.=$key.':';
 4760:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 4761:     }
 4762:     $hash{"$version:$symb:timestamp"}=$now;
 4763:     $allkeys.='timestamp';
 4764:     $hash{"$version:keys:$symb"}=$allkeys;
 4765:     if (untie(%hash)) {
 4766:       return 'ok';
 4767:     } else {
 4768:       return "error:$!";
 4769:     }
 4770:   } else {
 4771:     return "error:$!";
 4772:   }
 4773: }
 4774: 
 4775: # -----------------------------------------------------------------Temp Restore
 4776: 
 4777: sub tmprestore {
 4778:   my ($symb,$namespace,$domain,$stuname) = @_;
 4779: 
 4780:   if (!$symb) {
 4781:     $symb=&symbread();
 4782:     if (!$symb) { $symb= $env{'request.url'}; }
 4783:   }
 4784:   $symb=escape($symb);
 4785: 
 4786:   if (!$namespace) { $namespace=$env{'request.state'}; }
 4787: 
 4788:   if (!$domain) { $domain=$env{'user.domain'}; }
 4789:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4790:   if ($domain eq 'public' && $stuname eq 'public') {
 4791:       $stuname=$ENV{'REMOTE_ADDR'};
 4792:   }
 4793:   my %returnhash;
 4794:   $namespace=~s/\//\_/g;
 4795:   $namespace=~s/\W//g;
 4796:   my %hash;
 4797:   my $path=LONCAPA::tempdir();
 4798:   if (tie(%hash,'GDBM_File',
 4799: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4800: 	  &GDBM_READER(),0640)) {
 4801:     my $version=$hash{"version:$symb"};
 4802:     $returnhash{'version'}=$version;
 4803:     my $scope;
 4804:     for ($scope=1;$scope<=$version;$scope++) {
 4805:       my $vkeys=$hash{"$scope:keys:$symb"};
 4806:       my @keys=split(/:/,$vkeys);
 4807:       my $key;
 4808:       $returnhash{"$scope:keys"}=$vkeys;
 4809:       foreach $key (@keys) {
 4810: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 4811: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 4812:       }
 4813:     }
 4814:     if (!(untie(%hash))) {
 4815:       return "error:$!";
 4816:     }
 4817:   } else {
 4818:     return "error:$!";
 4819:   }
 4820:   return %returnhash;
 4821: }
 4822: 
 4823: # ----------------------------------------------------------------------- Store
 4824: 
 4825: sub store {
 4826:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4827:     my $home='';
 4828: 
 4829:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4830: 
 4831:     $symb=&symbclean($symb);
 4832:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 4833: 
 4834:     if (!$domain) { $domain=$env{'user.domain'}; }
 4835:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4836: 
 4837:     &devalidate($symb,$stuname,$domain);
 4838: 
 4839:     $symb=escape($symb);
 4840:     if (!$namespace) { 
 4841:        unless ($namespace=$env{'request.course.id'}) { 
 4842:           return ''; 
 4843:        } 
 4844:     }
 4845:     if (!$home) { $home=$env{'user.home'}; }
 4846: 
 4847:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 4848:     $$storehash{'host'}=$perlvar{'lonHostID'};
 4849: 
 4850:     my $namevalue='';
 4851:     foreach my $key (keys(%$storehash)) {
 4852:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4853:     }
 4854:     $namevalue=~s/\&$//;
 4855:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 4856:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 4857: }
 4858: 
 4859: # -------------------------------------------------------------- Critical Store
 4860: 
 4861: sub cstore {
 4862:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4863:     my $home='';
 4864: 
 4865:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4866: 
 4867:     $symb=&symbclean($symb);
 4868:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 4869: 
 4870:     if (!$domain) { $domain=$env{'user.domain'}; }
 4871:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4872: 
 4873:     &devalidate($symb,$stuname,$domain);
 4874: 
 4875:     $symb=escape($symb);
 4876:     if (!$namespace) { 
 4877:        unless ($namespace=$env{'request.course.id'}) { 
 4878:           return ''; 
 4879:        } 
 4880:     }
 4881:     if (!$home) { $home=$env{'user.home'}; }
 4882: 
 4883:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 4884:     $$storehash{'host'}=$perlvar{'lonHostID'};
 4885: 
 4886:     my $namevalue='';
 4887:     foreach my $key (keys(%$storehash)) {
 4888:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4889:     }
 4890:     $namevalue=~s/\&$//;
 4891:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 4892:     return critical
 4893:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 4894: }
 4895: 
 4896: # --------------------------------------------------------------------- Restore
 4897: 
 4898: sub restore {
 4899:     my ($symb,$namespace,$domain,$stuname) = @_;
 4900:     my $home='';
 4901: 
 4902:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4903: 
 4904:     if (!$symb) {
 4905:         return if ($namespace eq 'courserequests');
 4906:         unless ($symb=escape(&symbread())) { return ''; }
 4907:     } else {
 4908:         unless ($namespace eq 'courserequests') {
 4909:             $symb=&escape(&symbclean($symb));
 4910:         }
 4911:     }
 4912:     if (!$namespace) { 
 4913:        unless ($namespace=$env{'request.course.id'}) { 
 4914:           return ''; 
 4915:        } 
 4916:     }
 4917:     if (!$domain) { $domain=$env{'user.domain'}; }
 4918:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4919:     if (!$home) { $home=$env{'user.home'}; }
 4920:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 4921: 
 4922:     my %returnhash=();
 4923:     foreach my $line (split(/\&/,$answer)) {
 4924: 	my ($name,$value)=split(/\=/,$line);
 4925:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 4926:     }
 4927:     my $version;
 4928:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 4929:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 4930:           $returnhash{$item}=$returnhash{$version.':'.$item};
 4931:        }
 4932:     }
 4933:     return %returnhash;
 4934: }
 4935: 
 4936: # ---------------------------------------------------------- Course Description
 4937: #
 4938: #  
 4939: 
 4940: sub coursedescription {
 4941:     my ($courseid,$args)=@_;
 4942:     $courseid=~s/^\///;
 4943:     $courseid=~s/\_/\//g;
 4944:     my ($cdomain,$cnum)=split(/\//,$courseid);
 4945:     my $chome=&homeserver($cnum,$cdomain);
 4946:     my $normalid=$cdomain.'_'.$cnum;
 4947:     # need to always cache even if we get errors otherwise we keep 
 4948:     # trying and trying and trying to get the course description.
 4949:     my %envhash=();
 4950:     my %returnhash=();
 4951:     
 4952:     my $expiretime=600;
 4953:     if ($env{'request.course.id'} eq $normalid) {
 4954: 	$expiretime=120;
 4955:     }
 4956: 
 4957:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 4958:     if (!$args->{'freshen_cache'}
 4959: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 4960: 	foreach my $key (keys(%env)) {
 4961: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 4962: 	    my ($setting) = $1;
 4963: 	    $returnhash{$setting} = $env{$key};
 4964: 	}
 4965: 	return %returnhash;
 4966:     }
 4967: 
 4968:     # get the data again
 4969: 
 4970:     if (!$args->{'one_time'}) {
 4971: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 4972:     }
 4973: 
 4974:     if ($chome ne 'no_host') {
 4975:        %returnhash=&dump('environment',$cdomain,$cnum);
 4976:        if (!exists($returnhash{'con_lost'})) {
 4977: 	   my $username = $env{'user.name'}; # Defult username
 4978: 	   if(defined $args->{'user'}) {
 4979: 	       $username = $args->{'user'};
 4980: 	   }
 4981:            $returnhash{'home'}= $chome;
 4982: 	   $returnhash{'domain'} = $cdomain;
 4983: 	   $returnhash{'num'} = $cnum;
 4984:            if (!defined($returnhash{'type'})) {
 4985:                $returnhash{'type'} = 'Course';
 4986:            }
 4987:            while (my ($name,$value) = each %returnhash) {
 4988:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 4989:            }
 4990:            $returnhash{'url'}=&clutter($returnhash{'url'});
 4991:            $returnhash{'fn'}=LONCAPA::tempdir() .
 4992: 	       $username.'_'.$cdomain.'_'.$cnum;
 4993:            $envhash{'course.'.$normalid.'.home'}=$chome;
 4994:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 4995:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 4996:        }
 4997:     }
 4998:     if (!$args->{'one_time'}) {
 4999: 	&appenv(\%envhash);
 5000:     }
 5001:     return %returnhash;
 5002: }
 5003: 
 5004: sub update_released_required {
 5005:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
 5006:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
 5007:         $cid = $env{'request.course.id'};
 5008:         $cdom = $env{'course.'.$cid.'.domain'};
 5009:         $cnum = $env{'course.'.$cid.'.num'};
 5010:         $chome = $env{'course.'.$cid.'.home'};
 5011:     }
 5012:     if ($needsrelease) {
 5013:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
 5014:         my $needsupdate;
 5015:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
 5016:             $needsupdate = 1;
 5017:         } else {
 5018:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
 5019:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
 5020:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
 5021:                 $needsupdate = 1;
 5022:             }
 5023:         }
 5024:         if ($needsupdate) {
 5025:             my %needshash = (
 5026:                              'internal.releaserequired' => $needsrelease,
 5027:                             );
 5028:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
 5029:             if ($putresult eq 'ok') {
 5030:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
 5031:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 5032:                 if (ref($crsinfo{$cid}) eq 'HASH') {
 5033:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
 5034:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
 5035:                 }
 5036:             }
 5037:         }
 5038:     }
 5039:     return;
 5040: }
 5041: 
 5042: # -------------------------------------------------See if a user is privileged
 5043: 
 5044: sub privileged {
 5045:     my ($username,$domain,$possdomains,$possroles)=@_;
 5046:     my $now = time;
 5047:     my $roles;
 5048:     if (ref($possroles) eq 'ARRAY') {
 5049:         $roles = $possroles; 
 5050:     } else {
 5051:         $roles = ['dc','su'];
 5052:     }
 5053:     if (ref($possdomains) eq 'ARRAY') {
 5054:         my %privileged = &privileged_by_domain($possdomains,$roles);
 5055:         foreach my $dom (@{$possdomains}) {
 5056:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
 5057:                 (ref($privileged{$dom}) eq 'HASH')) {
 5058:                 foreach my $role (@{$roles}) {
 5059:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 5060:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
 5061:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
 5062:                             return 1 unless (($end && $end < $now) ||
 5063:                                              ($start && $start > $now));
 5064:                         }
 5065:                     }
 5066:                 }
 5067:             }
 5068:         }
 5069:     } else {
 5070:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
 5071:         my $now = time;
 5072: 
 5073:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys %rolesdump}) {
 5074:             my ($trole, $tend, $tstart) = split(/_/, $role);
 5075:             if (grep(/^\Q$trole\E$/,@{$roles})) {
 5076:                 return 1 unless ($tend && $tend < $now) 
 5077:                         or ($tstart && $tstart > $now);
 5078:             }
 5079:         }
 5080:     }
 5081:     return 0;
 5082: }
 5083: 
 5084: sub privileged_by_domain {
 5085:     my ($domains,$roles) = @_;
 5086:     my %privileged = ();
 5087:     my $cachetime = 60*60*24;
 5088:     my $now = time;
 5089:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
 5090:         return %privileged;
 5091:     }
 5092:     foreach my $dom (@{$domains}) {
 5093:         next if (ref($privileged{$dom}) eq 'HASH');
 5094:         my $needroles;
 5095:         foreach my $role (@{$roles}) {
 5096:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
 5097:             if (defined($cached)) {
 5098:                 if (ref($result) eq 'HASH') {
 5099:                     $privileged{$dom}{$role} = $result;
 5100:                 }
 5101:             } else {
 5102:                 $needroles = 1;
 5103:             }
 5104:         }
 5105:         if ($needroles) {
 5106:             my %dompersonnel = &get_domain_roles($dom,$roles);
 5107:             $privileged{$dom} = {};
 5108:             foreach my $server (keys(%dompersonnel)) {
 5109:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 5110:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
 5111:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
 5112:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
 5113:                         next if ($end && $end < $now);
 5114:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
 5115:                             $dompersonnel{$server}{$item};
 5116:                     }
 5117:                 }
 5118:             }
 5119:             if (ref($privileged{$dom}) eq 'HASH') {
 5120:                 foreach my $role (@{$roles}) {
 5121:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 5122:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
 5123:                     } else {
 5124:                         my %hash = ();
 5125:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
 5126:                     }
 5127:                 }
 5128:             }
 5129:         }
 5130:     }
 5131:     return %privileged;
 5132: }
 5133: 
 5134: # -------------------------------------------------------- Get user privileges
 5135: 
 5136: sub rolesinit {
 5137:     my ($domain, $username) = @_;
 5138:     my %userroles = ('user.login.time' => time);
 5139:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
 5140: 
 5141:     # firstaccess and timerinterval are related to timed maps/resources. 
 5142:     # also, blocking can be triggered by an activating timer
 5143:     # it's saved in the user's %env.
 5144:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
 5145:     my %timerinterval = &dump('timerinterval', $domain, $username);
 5146:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
 5147:         %timerintchk, %timerintenv);
 5148: 
 5149:     foreach my $key (keys(%firstaccess)) {
 5150:         my ($cid, $rest) = split(/\0/, $key);
 5151:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
 5152:     }
 5153: 
 5154:     foreach my $key (keys(%timerinterval)) {
 5155:         my ($cid,$rest) = split(/\0/,$key);
 5156:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
 5157:     }
 5158: 
 5159:     my %allroles=();
 5160:     my %allgroups=();
 5161: 
 5162:     for my $area (grep { ! /^rolesdef_/ } keys %rolesdump) {
 5163:         my $role = $rolesdump{$area};
 5164:         $area =~ s/\_\w\w$//;
 5165: 
 5166:         my ($trole, $tend, $tstart, $group_privs);
 5167: 
 5168:         if ($role =~ /^cr/) {
 5169:         # Custom role, defined by a user 
 5170:         # e.g., user.role.cr/msu/smith/mynewrole
 5171:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 5172:                 $trole = $1;
 5173:                 ($tend, $tstart) = split('_', $2);
 5174:             } else {
 5175:                 $trole = $role;
 5176:             }
 5177:         } elsif ($role =~ m|^gr/|) {
 5178:         # Role of member in a group, defined within a course/community
 5179:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
 5180:             ($trole, $tend, $tstart) = split(/_/, $role);
 5181:             next if $tstart eq '-1';
 5182:             ($trole, $group_privs) = split(/\//, $trole);
 5183:             $group_privs = &unescape($group_privs);
 5184:         } else {
 5185:         # Just a normal role, defined in roles.tab
 5186:             ($trole, $tend, $tstart) = split(/_/,$role);
 5187:         }
 5188: 
 5189:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 5190:                  $username);
 5191:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 5192: 
 5193:         # role expired or not available yet?
 5194:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
 5195:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
 5196: 
 5197:         next if $area eq '' or $trole eq '';
 5198: 
 5199:         my $spec = "$trole.$area";
 5200:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
 5201: 
 5202:         if ($trole =~ /^cr\//) {
 5203:         # Custom role, defined by a user
 5204:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 5205:         } elsif ($trole eq 'gr') {
 5206:         # Role of a member in a group, defined within a course/community
 5207:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 5208:             next;
 5209:         } else {
 5210:         # Normal role, defined in roles.tab
 5211:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 5212:         }
 5213: 
 5214:         my $cid = $tdomain.'_'.$trest;
 5215:         unless ($firstaccchk{$cid}) {
 5216:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
 5217:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
 5218:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
 5219:                         $coursetimerstarts{$cid}{$item}; 
 5220:                 }
 5221:             }
 5222:             $firstaccchk{$cid} = 1;
 5223:         }
 5224:         unless ($timerintchk{$cid}) {
 5225:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
 5226:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
 5227:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
 5228:                        $coursetimerintervals{$cid}{$item};
 5229:                 }
 5230:             }
 5231:             $timerintchk{$cid} = 1;
 5232:         }
 5233:     }
 5234: 
 5235:     @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
 5236:         \%allroles, \%allgroups);
 5237:     $env{'user.adv'} = $userroles{'user.adv'};
 5238: 
 5239:     return (\%userroles,\%firstaccenv,\%timerintenv);
 5240: }
 5241: 
 5242: sub set_arearole {
 5243:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
 5244:     unless ($nolog) {
 5245: # log the associated role with the area
 5246:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 5247:     }
 5248:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 5249: }
 5250: 
 5251: sub custom_roleprivs {
 5252:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 5253:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 5254:     my $homsvr = &homeserver($rauthor,$rdomain);
 5255:     if (&hostname($homsvr) ne '') {
 5256:         my ($rdummy,$roledef)=
 5257:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 5258:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 5259:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 5260:             if (defined($syspriv)) {
 5261:                 if ($trest =~ /^$match_community$/) {
 5262:                     $syspriv =~ s/bre\&S//; 
 5263:                 }
 5264:                 $$allroles{'cm./'}.=':'.$syspriv;
 5265:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 5266:             }
 5267:             if ($tdomain ne '') {
 5268:                 if (defined($dompriv)) {
 5269:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 5270:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 5271:                 }
 5272:                 if (($trest ne '') && (defined($coursepriv))) {
 5273:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 5274:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 5275:                 }
 5276:             }
 5277:         }
 5278:     }
 5279: }
 5280: 
 5281: sub group_roleprivs {
 5282:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 5283:     my $access = 1;
 5284:     my $now = time;
 5285:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 5286:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 5287:     if ($access) {
 5288:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 5289:         $$allgroups{$course}{$group} .=':'.$group_privs;
 5290:     }
 5291: }
 5292: 
 5293: sub standard_roleprivs {
 5294:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 5295:     if (defined($pr{$trole.':s'})) {
 5296:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 5297:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 5298:     }
 5299:     if ($tdomain ne '') {
 5300:         if (defined($pr{$trole.':d'})) {
 5301:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 5302:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 5303:         }
 5304:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 5305:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 5306:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 5307:         }
 5308:     }
 5309: }
 5310: 
 5311: sub set_userprivs {
 5312:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
 5313:     my $author=0;
 5314:     my $adv=0;
 5315:     my %grouproles = ();
 5316:     if (keys(%{$allgroups}) > 0) {
 5317:         my @groupkeys; 
 5318:         foreach my $role (keys(%{$allroles})) {
 5319:             push(@groupkeys,$role);
 5320:         }
 5321:         if (ref($groups_roles) eq 'HASH') {
 5322:             foreach my $key (keys(%{$groups_roles})) {
 5323:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
 5324:                     push(@groupkeys,$key);
 5325:                 }
 5326:             }
 5327:         }
 5328:         if (@groupkeys > 0) {
 5329:             foreach my $role (@groupkeys) {
 5330:                 my ($trole,$area,$sec,$extendedarea);
 5331:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 5332:                     $trole = $1;
 5333:                     $area = $2;
 5334:                     $sec = $3;
 5335:                     $extendedarea = $area.$sec;
 5336:                     if (exists($$allgroups{$area})) {
 5337:                         foreach my $group (keys(%{$$allgroups{$area}})) {
 5338:                             my $spec = $trole.'.'.$extendedarea;
 5339:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
 5340:                                                 $$allgroups{$area}{$group};
 5341:                         }
 5342:                     }
 5343:                 }
 5344:             }
 5345:         }
 5346:     }
 5347:     foreach my $group (keys(%grouproles)) {
 5348:         $$allroles{$group} = $grouproles{$group};
 5349:     }
 5350:     foreach my $role (keys(%{$allroles})) {
 5351:         my %thesepriv;
 5352:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 5353:         foreach my $item (split(/:/,$$allroles{$role})) {
 5354:             if ($item ne '') {
 5355:                 my ($privilege,$restrictions)=split(/&/,$item);
 5356:                 if ($restrictions eq '') {
 5357:                     $thesepriv{$privilege}='F';
 5358:                 } elsif ($thesepriv{$privilege} ne 'F') {
 5359:                     $thesepriv{$privilege}.=$restrictions;
 5360:                 }
 5361:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 5362:             }
 5363:         }
 5364:         my $thesestr='';
 5365:         foreach my $priv (sort(keys(%thesepriv))) {
 5366: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 5367: 	}
 5368:         $userroles->{'user.priv.'.$role} = $thesestr;
 5369:     }
 5370:     return ($author,$adv);
 5371: }
 5372: 
 5373: sub role_status {
 5374:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 5375:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 5376:         my ($one,$two) = split(m{\./},$rolekey,2);
 5377:         (undef,undef,$$role) = split(/\./,$one,3);
 5378:         unless (!defined($$role) || $$role eq '') {
 5379:             $$where = '/'.$two;
 5380:             $$trolecode=$$role.'.'.$$where;
 5381:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 5382:             $$tstatus='is';
 5383:             if ($$tstart && $$tstart>$update) {
 5384:                 $$tstatus='future';
 5385:                 if ($$tstart<$now) {
 5386:                     if ($$tstart && $$tstart>$refresh) {
 5387:                         if (($$where ne '') && ($$role ne '')) {
 5388:                             my (%allroles,%allgroups,$group_privs,
 5389:                                 %groups_roles,@rolecodes);
 5390:                             my %userroles = (
 5391:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 5392:                             );
 5393:                             @rolecodes = ('cm'); 
 5394:                             my $spec=$$role.'.'.$$where;
 5395:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 5396:                             if ($$role =~ /^cr\//) {
 5397:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 5398:                                 push(@rolecodes,'cr');
 5399:                             } elsif ($$role eq 'gr') {
 5400:                                 push(@rolecodes,$$role);
 5401:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 5402:                                                     $env{'user.name'});
 5403:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
 5404:                                 (undef,my $group_privs) = split(/\//,$trole);
 5405:                                 $group_privs = &unescape($group_privs);
 5406:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 5407:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
 5408:                                 &get_groups_roles($tdomain,$trest,
 5409:                                                   \%course_roles,\@rolecodes,
 5410:                                                   \%groups_roles);
 5411:                             } else {
 5412:                                 push(@rolecodes,$$role);
 5413:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 5414:                             }
 5415:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
 5416:                             &appenv(\%userroles,\@rolecodes);
 5417:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 5418:                         }
 5419:                     }
 5420:                     $$tstatus = 'is';
 5421:                 }
 5422:             }
 5423:             if ($$tend) {
 5424:                 if ($$tend<$update) {
 5425:                     $$tstatus='expired';
 5426:                 } elsif ($$tend<$now) {
 5427:                     $$tstatus='will_not';
 5428:                 }
 5429:             }
 5430:         }
 5431:     }
 5432: }
 5433: 
 5434: sub get_groups_roles {
 5435:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
 5436:     return unless((ref($cdom_courseroles) eq 'HASH') && 
 5437:                   (ref($rolecodes) eq 'ARRAY') && 
 5438:                   (ref($groups_roles) eq 'HASH')); 
 5439:     if (keys(%{$cdom_courseroles}) > 0) {
 5440:         my ($cnum) = ($rest =~ /^($match_courseid)/);
 5441:         if ($cdom ne '' && $cnum ne '') {
 5442:             foreach my $key (keys(%{$cdom_courseroles})) {
 5443:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
 5444:                     my $crsrole = $1;
 5445:                     my $crssec = $2;
 5446:                     if ($crsrole =~ /^cr/) {
 5447:                         unless (grep(/^cr$/,@{$rolecodes})) {
 5448:                             push(@{$rolecodes},'cr');
 5449:                         }
 5450:                     } else {
 5451:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
 5452:                             push(@{$rolecodes},$crsrole);
 5453:                         }
 5454:                     }
 5455:                     my $rolekey = "$crsrole./$cdom/$cnum";
 5456:                     if ($crssec ne '') {
 5457:                         $rolekey .= "/$crssec";
 5458:                     }
 5459:                     $rolekey .= './';
 5460:                     $groups_roles->{$rolekey} = $rolecodes;
 5461:                 }
 5462:             }
 5463:         }
 5464:     }
 5465:     return;
 5466: }
 5467: 
 5468: sub delete_env_groupprivs {
 5469:     my ($where,$courseroles,$possroles) = @_;
 5470:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
 5471:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
 5472:     unless (ref($courseroles->{$udom}) eq 'HASH') {
 5473:         %{$courseroles->{$udom}} =
 5474:             &get_my_roles('','','userroles',['active'],
 5475:                           $possroles,[$udom],1);
 5476:     }
 5477:     if (ref($courseroles->{$udom}) eq 'HASH') {
 5478:         foreach my $item (keys(%{$courseroles->{$udom}})) {
 5479:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
 5480:             my $area = '/'.$cdom.'/'.$cnum;
 5481:             my $privkey = "user.priv.$crsrole.$area";
 5482:             if ($crssec ne '') {
 5483:                 $privkey .= '/'.$crssec;
 5484:             }
 5485:             $privkey .= ".$area/$group";
 5486:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
 5487:         }
 5488:     }
 5489:     return;
 5490: }
 5491: 
 5492: sub check_adhoc_privs {
 5493:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
 5494:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 5495:     my $setprivs;
 5496:     if ($env{$cckey}) {
 5497:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 5498:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 5499:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 5500:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
 5501:             $setprivs = 1;
 5502:         }
 5503:     } else {
 5504:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
 5505:         $setprivs = 1;
 5506:     }
 5507:     return $setprivs;
 5508: }
 5509: 
 5510: sub set_adhoc_privileges {
 5511: # role can be cc or ca
 5512:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
 5513:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 5514:     my $spec = $role.'.'.$area;
 5515:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 5516:                                   $env{'user.name'},1);
 5517:     my %ccrole = ();
 5518:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
 5519:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
 5520:     &appenv(\%userroles,[$role,'cm']);
 5521:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 5522:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
 5523:         &appenv( {'request.role'        => $spec,
 5524:                   'request.role.domain' => $dcdom,
 5525:                   'request.course.sec'  => ''
 5526:                  }
 5527:                );
 5528:         my $tadv=0;
 5529:         if (&allowed('adv') eq 'F') { $tadv=1; }
 5530:         &appenv({'request.role.adv'    => $tadv});
 5531:     }
 5532: }
 5533: 
 5534: # --------------------------------------------------------------- get interface
 5535: 
 5536: sub get {
 5537:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5538:    my $items='';
 5539:    foreach my $item (@$storearr) {
 5540:        $items.=&escape($item).'&';
 5541:    }
 5542:    $items=~s/\&$//;
 5543:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5544:    if (!$uname) { $uname=$env{'user.name'}; }
 5545:    my $uhome=&homeserver($uname,$udomain);
 5546: 
 5547:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 5548:    my @pairs=split(/\&/,$rep);
 5549:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 5550:      return @pairs;
 5551:    }
 5552:    my %returnhash=();
 5553:    my $i=0;
 5554:    foreach my $item (@$storearr) {
 5555:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 5556:       $i++;
 5557:    }
 5558:    return %returnhash;
 5559: }
 5560: 
 5561: # --------------------------------------------------------------- del interface
 5562: 
 5563: sub del {
 5564:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5565:    my $items='';
 5566:    foreach my $item (@$storearr) {
 5567:        $items.=&escape($item).'&';
 5568:    }
 5569: 
 5570:    $items=~s/\&$//;
 5571:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5572:    if (!$uname) { $uname=$env{'user.name'}; }
 5573:    my $uhome=&homeserver($uname,$udomain);
 5574:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 5575: }
 5576: 
 5577: # -------------------------------------------------------------- dump interface
 5578: 
 5579: sub unserialize {
 5580:     my ($rep, $escapedkeys) = @_;
 5581: 
 5582:     return {} if $rep =~ /^error/;
 5583: 
 5584:     my %returnhash=();
 5585: 	foreach my $item (split(/\&/,$rep)) {
 5586: 	    my ($key, $value) = split(/=/, $item, 2);
 5587: 	    $key = unescape($key) unless $escapedkeys;
 5588: 	    next if $key =~ /^error: 2 /;
 5589: 	    $returnhash{$key} = &thaw_unescape($value);
 5590: 	}
 5591:     #return %returnhash;
 5592:     return \%returnhash;
 5593: }        
 5594: 
 5595: # see Lond::dump_with_regexp
 5596: # if $escapedkeys hash keys won't get unescaped.
 5597: sub dump {
 5598:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
 5599:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5600:     if (!$uname) { $uname=$env{'user.name'}; }
 5601:     my $uhome=&homeserver($uname,$udomain);
 5602: 
 5603:     my $reply;
 5604:     if (grep { $_ eq $uhome } current_machine_ids()) {
 5605:         # user is hosted on this machine
 5606:         $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
 5607:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
 5608:         return %{unserialize($reply, $escapedkeys)};
 5609:     }
 5610:     if ($regexp) {
 5611: 	$regexp=&escape($regexp);
 5612:     } else {
 5613: 	$regexp='.';
 5614:     }
 5615:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 5616:     my @pairs=split(/\&/,$rep);
 5617:     my %returnhash=();
 5618:     if (!($rep =~ /^error/ )) {
 5619: 	foreach my $item (@pairs) {
 5620: 	    my ($key,$value)=split(/=/,$item,2);
 5621:         $key = unescape($key) unless $escapedkeys;
 5622:         #$key = &unescape($key);
 5623: 	    next if ($key =~ /^error: 2 /);
 5624: 	    $returnhash{$key}=&thaw_unescape($value);
 5625: 	}
 5626:     }
 5627:     return %returnhash;
 5628: }
 5629: 
 5630: 
 5631: # --------------------------------------------------------- dumpstore interface
 5632: 
 5633: sub dumpstore {
 5634:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 5635:    # same as dump but keys must be escaped. They may contain colon separated
 5636:    # lists of values that may themself contain colons (e.g. symbs).
 5637:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
 5638: }
 5639: 
 5640: # -------------------------------------------------------------- keys interface
 5641: 
 5642: sub getkeys {
 5643:    my ($namespace,$udomain,$uname)=@_;
 5644:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5645:    if (!$uname) { $uname=$env{'user.name'}; }
 5646:    my $uhome=&homeserver($uname,$udomain);
 5647:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 5648:    my @keyarray=();
 5649:    foreach my $key (split(/\&/,$rep)) {
 5650:       next if ($key =~ /^error: 2 /);
 5651:       push(@keyarray,&unescape($key));
 5652:    }
 5653:    return @keyarray;
 5654: }
 5655: 
 5656: # --------------------------------------------------------------- currentdump
 5657: sub currentdump {
 5658:    my ($courseid,$sdom,$sname)=@_;
 5659:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 5660:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 5661:    $sname    = $env{'user.name'}         if (! defined($sname));
 5662:    my $uhome = &homeserver($sname,$sdom);
 5663:    my $rep;
 5664: 
 5665:    if (grep { $_ eq $uhome } current_machine_ids()) {
 5666:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
 5667:                    $courseid)));
 5668:    } else {
 5669:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 5670:    }
 5671: 
 5672:    return if ($rep =~ /^(error:|no_such_host)/);
 5673:    #
 5674:    my %returnhash=();
 5675:    #
 5676:    if ($rep eq "unknown_cmd") { 
 5677:        # an old lond will not know currentdump
 5678:        # Do a dump and make it look like a currentdump
 5679:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 5680:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 5681:        my %hash = @tmp;
 5682:        @tmp=();
 5683:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 5684:    } else {
 5685:        my @pairs=split(/\&/,$rep);
 5686:        foreach my $pair (@pairs) {
 5687:            my ($key,$value)=split(/=/,$pair,2);
 5688:            my ($symb,$param) = split(/:/,$key);
 5689:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 5690:                                                         &thaw_unescape($value);
 5691:        }
 5692:    }
 5693:    return %returnhash;
 5694: }
 5695: 
 5696: sub convert_dump_to_currentdump{
 5697:     my %hash = %{shift()};
 5698:     my %returnhash;
 5699:     # Code ripped from lond, essentially.  The only difference
 5700:     # here is the unescaping done by lonnet::dump().  Conceivably
 5701:     # we might run in to problems with parameter names =~ /^v\./
 5702:     while (my ($key,$value) = each(%hash)) {
 5703:         my ($v,$symb,$param) = split(/:/,$key);
 5704: 	$symb  = &unescape($symb);
 5705: 	$param = &unescape($param);
 5706:         next if ($v eq 'version' || $symb eq 'keys');
 5707:         next if (exists($returnhash{$symb}) &&
 5708:                  exists($returnhash{$symb}->{$param}) &&
 5709:                  $returnhash{$symb}->{'v.'.$param} > $v);
 5710:         $returnhash{$symb}->{$param}=$value;
 5711:         $returnhash{$symb}->{'v.'.$param}=$v;
 5712:     }
 5713:     #
 5714:     # Remove all of the keys in the hashes which keep track of
 5715:     # the version of the parameter.
 5716:     while (my ($symb,$param_hash) = each(%returnhash)) {
 5717:         # use a foreach because we are going to delete from the hash.
 5718:         foreach my $key (keys(%$param_hash)) {
 5719:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 5720:         }
 5721:     }
 5722:     return \%returnhash;
 5723: }
 5724: 
 5725: # ------------------------------------------------------ critical inc interface
 5726: 
 5727: sub cinc {
 5728:     return &inc(@_,'critical');
 5729: }
 5730: 
 5731: # --------------------------------------------------------------- inc interface
 5732: 
 5733: sub inc {
 5734:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 5735:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5736:     if (!$uname) { $uname=$env{'user.name'}; }
 5737:     my $uhome=&homeserver($uname,$udomain);
 5738:     my $items='';
 5739:     if (! ref($store)) {
 5740:         # got a single value, so use that instead
 5741:         $items = &escape($store).'=&';
 5742:     } elsif (ref($store) eq 'SCALAR') {
 5743:         $items = &escape($$store).'=&';        
 5744:     } elsif (ref($store) eq 'ARRAY') {
 5745:         $items = join('=&',map {&escape($_);} @{$store});
 5746:     } elsif (ref($store) eq 'HASH') {
 5747:         while (my($key,$value) = each(%{$store})) {
 5748:             $items.= &escape($key).'='.&escape($value).'&';
 5749:         }
 5750:     }
 5751:     $items=~s/\&$//;
 5752:     if ($critical) {
 5753: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 5754:     } else {
 5755: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 5756:     }
 5757: }
 5758: 
 5759: # --------------------------------------------------------------- put interface
 5760: 
 5761: sub put {
 5762:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5763:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5764:    if (!$uname) { $uname=$env{'user.name'}; }
 5765:    my $uhome=&homeserver($uname,$udomain);
 5766:    my $items='';
 5767:    foreach my $item (keys(%$storehash)) {
 5768:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5769:    }
 5770:    $items=~s/\&$//;
 5771:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 5772: }
 5773: 
 5774: # ------------------------------------------------------------ newput interface
 5775: 
 5776: sub newput {
 5777:    my ($namespace,$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 $items='';
 5782:    foreach my $key (keys(%$storehash)) {
 5783:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 5784:    }
 5785:    $items=~s/\&$//;
 5786:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 5787: }
 5788: 
 5789: # ---------------------------------------------------------  putstore interface
 5790: 
 5791: sub putstore {
 5792:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 5793:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5794:    if (!$uname) { $uname=$env{'user.name'}; }
 5795:    my $uhome=&homeserver($uname,$udomain);
 5796:    my $items='';
 5797:    foreach my $key (keys(%$storehash)) {
 5798:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 5799:    }
 5800:    $items=~s/\&$//;
 5801:    my $esc_symb=&escape($symb);
 5802:    my $esc_v=&escape($version);
 5803:    my $reply =
 5804:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 5805: 	      $uhome);
 5806:    if ($reply eq 'unknown_cmd') {
 5807:        # gfall back to way things use to be done
 5808:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 5809: 			    $uname);
 5810:    }
 5811:    return $reply;
 5812: }
 5813: 
 5814: sub old_putstore {
 5815:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 5816:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5817:     if (!$uname) { $uname=$env{'user.name'}; }
 5818:     my $uhome=&homeserver($uname,$udomain);
 5819:     my %newstorehash;
 5820:     foreach my $item (keys(%$storehash)) {
 5821: 	my $key = $version.':'.&escape($symb).':'.$item;
 5822: 	$newstorehash{$key} = $storehash->{$item};
 5823:     }
 5824:     my $items='';
 5825:     my %allitems = ();
 5826:     foreach my $item (keys(%newstorehash)) {
 5827: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 5828: 	    my $key = $1.':keys:'.$2;
 5829: 	    $allitems{$key} .= $3.':';
 5830: 	}
 5831: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 5832:     }
 5833:     foreach my $item (keys(%allitems)) {
 5834: 	$allitems{$item} =~ s/\:$//;
 5835: 	$items.= $item.'='.$allitems{$item}.'&';
 5836:     }
 5837:     $items=~s/\&$//;
 5838:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 5839: }
 5840: 
 5841: # ------------------------------------------------------ critical put interface
 5842: 
 5843: sub cput {
 5844:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5845:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5846:    if (!$uname) { $uname=$env{'user.name'}; }
 5847:    my $uhome=&homeserver($uname,$udomain);
 5848:    my $items='';
 5849:    foreach my $item (keys(%$storehash)) {
 5850:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5851:    }
 5852:    $items=~s/\&$//;
 5853:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 5854: }
 5855: 
 5856: # -------------------------------------------------------------- eget interface
 5857: 
 5858: sub eget {
 5859:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5860:    my $items='';
 5861:    foreach my $item (@$storearr) {
 5862:        $items.=&escape($item).'&';
 5863:    }
 5864:    $items=~s/\&$//;
 5865:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5866:    if (!$uname) { $uname=$env{'user.name'}; }
 5867:    my $uhome=&homeserver($uname,$udomain);
 5868:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 5869:    my @pairs=split(/\&/,$rep);
 5870:    my %returnhash=();
 5871:    my $i=0;
 5872:    foreach my $item (@$storearr) {
 5873:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 5874:       $i++;
 5875:    }
 5876:    return %returnhash;
 5877: }
 5878: 
 5879: # ------------------------------------------------------------ tmpput interface
 5880: sub tmpput {
 5881:     my ($storehash,$server,$context)=@_;
 5882:     my $items='';
 5883:     foreach my $item (keys(%$storehash)) {
 5884: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5885:     }
 5886:     $items=~s/\&$//;
 5887:     if (defined($context)) {
 5888:         $items .= ':'.&escape($context);
 5889:     }
 5890:     return &reply("tmpput:$items",$server);
 5891: }
 5892: 
 5893: # ------------------------------------------------------------ tmpget interface
 5894: sub tmpget {
 5895:     my ($token,$server)=@_;
 5896:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 5897:     my $rep=&reply("tmpget:$token",$server);
 5898:     my %returnhash;
 5899:     foreach my $item (split(/\&/,$rep)) {
 5900: 	my ($key,$value)=split(/=/,$item);
 5901:         next if ($key =~ /^error: 2 /);
 5902: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 5903:     }
 5904:     return %returnhash;
 5905: }
 5906: 
 5907: # ------------------------------------------------------------ tmpdel interface
 5908: sub tmpdel {
 5909:     my ($token,$server)=@_;
 5910:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 5911:     return &reply("tmpdel:$token",$server);
 5912: }
 5913: 
 5914: # ------------------------------------------------------------ get_timebased_id 
 5915: 
 5916: sub get_timebased_id {
 5917:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
 5918:         $maxtries) = @_;
 5919:     my ($newid,$error,$dellock);
 5920:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
 5921:         return ('','ok','invalid call to get suffix');
 5922:     }
 5923: 
 5924: # set defaults for any optional args for which values were not supplied
 5925:     if ($who eq '') {
 5926:         $who = $env{'user.name'}.':'.$env{'user.domain'};
 5927:     }
 5928:     if (!$locktries) {
 5929:         $locktries = 3;
 5930:     }
 5931:     if (!$maxtries) {
 5932:         $maxtries = 10;
 5933:     }
 5934:     
 5935:     if (($cdom eq '') || ($cnum eq '')) {
 5936:         if ($env{'request.course.id'}) {
 5937:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5938:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5939:         }
 5940:         if (($cdom eq '') || ($cnum eq '')) {
 5941:             return ('','ok','call to get suffix not in course context');
 5942:         }
 5943:     }
 5944: 
 5945: # construct locking item
 5946:     my $lockhash = {
 5947:                       $prefix."\0".'locked_'.$keyid => $who,
 5948:                    };
 5949:     my $tries = 0;
 5950: 
 5951: # attempt to get lock on nohist_$namespace file
 5952:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 5953:     while (($gotlock ne 'ok') && $tries <$locktries) {
 5954:         $tries ++;
 5955:         sleep 1;
 5956:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 5957:     }
 5958: 
 5959: # attempt to get unique identifier, based on current timestamp
 5960:     if ($gotlock eq 'ok') {
 5961:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
 5962:         my $id = time;
 5963:         $newid = $id;
 5964:         my $idtries = 0;
 5965:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
 5966:             if ($idtype eq 'concat') {
 5967:                 $newid = $id.$idtries;
 5968:             } else {
 5969:                 $newid ++;
 5970:             }
 5971:             $idtries ++;
 5972:         }
 5973:         if (!exists($inuse{$prefix."\0".$newid})) {
 5974:             my %new_item =  (
 5975:                               $prefix."\0".$newid => $who,
 5976:                             );
 5977:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
 5978:                                                  $cdom,$cnum);
 5979:             if ($putresult ne 'ok') {
 5980:                 undef($newid);
 5981:                 $error = 'error saving new item: '.$putresult;
 5982:             }
 5983:         } else {
 5984:              $error = ('error: no unique suffix available for the new item ');
 5985:         }
 5986: #  remove lock
 5987:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
 5988:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
 5989:     } else {
 5990:         $error = "error: could not obtain lockfile\n";
 5991:         $dellock = 'ok';
 5992:     }
 5993:     return ($newid,$dellock,$error);
 5994: }
 5995: 
 5996: # -------------------------------------------------- portfolio access checking
 5997: 
 5998: sub portfolio_access {
 5999:     my ($requrl) = @_;
 6000:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 6001:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
 6002:     if ($result) {
 6003:         my %setters;
 6004:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 6005:             my ($startblock,$endblock) =
 6006:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 6007:             if ($startblock && $endblock) {
 6008:                 return 'B';
 6009:             }
 6010:         } else {
 6011:             my ($startblock,$endblock) =
 6012:                 &Apache::loncommon::blockcheck(\%setters,'port');
 6013:             if ($startblock && $endblock) {
 6014:                 return 'B';
 6015:             }
 6016:         }
 6017:     }
 6018:     if ($result eq 'ok') {
 6019:        return 'F';
 6020:     } elsif ($result =~ /^[^:]+:guest_/) {
 6021:        return 'A';
 6022:     }
 6023:     return '';
 6024: }
 6025: 
 6026: sub get_portfolio_access {
 6027:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
 6028: 
 6029:     if (!ref($access_hash)) {
 6030: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 6031: 	my %access_controls = &get_access_controls($current_perms,$group,
 6032: 						   $file_name);
 6033: 	$access_hash = $access_controls{$file_name};
 6034:     }
 6035: 
 6036:     my ($public,$guest,@domains,@users,@courses,@groups);
 6037:     my $now = time;
 6038:     if (ref($access_hash) eq 'HASH') {
 6039:         foreach my $key (keys(%{$access_hash})) {
 6040:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 6041:             if ($start > $now) {
 6042:                 next;
 6043:             }
 6044:             if ($end && $end<$now) {
 6045:                 next;
 6046:             }
 6047:             if ($scope eq 'public') {
 6048:                 $public = $key;
 6049:                 last;
 6050:             } elsif ($scope eq 'guest') {
 6051:                 $guest = $key;
 6052:             } elsif ($scope eq 'domains') {
 6053:                 push(@domains,$key);
 6054:             } elsif ($scope eq 'users') {
 6055:                 push(@users,$key);
 6056:             } elsif ($scope eq 'course') {
 6057:                 push(@courses,$key);
 6058:             } elsif ($scope eq 'group') {
 6059:                 push(@groups,$key);
 6060:             }
 6061:         }
 6062:         if ($public) {
 6063:             return 'ok';
 6064:         }
 6065:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 6066:             if ($guest) {
 6067:                 return $guest;
 6068:             }
 6069:         } else {
 6070:             if (@domains > 0) {
 6071:                 foreach my $domkey (@domains) {
 6072:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 6073:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 6074:                             return 'ok';
 6075:                         }
 6076:                     }
 6077:                 }
 6078:             }
 6079:             if (@users > 0) {
 6080:                 foreach my $userkey (@users) {
 6081:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 6082:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 6083:                             if (ref($item) eq 'HASH') {
 6084:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 6085:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 6086:                                     return 'ok';
 6087:                                 }
 6088:                             }
 6089:                         }
 6090:                     } 
 6091:                 }
 6092:             }
 6093:             my %roleshash;
 6094:             my @courses_and_groups = @courses;
 6095:             push(@courses_and_groups,@groups); 
 6096:             if (@courses_and_groups > 0) {
 6097:                 my (%allgroups,%allroles); 
 6098:                 my ($start,$end,$role,$sec,$group);
 6099:                 foreach my $envkey (%env) {
 6100:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 6101:                         my $cid = $2.'_'.$3; 
 6102:                         if ($1 eq 'gr') {
 6103:                             $group = $4;
 6104:                             $allgroups{$cid}{$group} = $env{$envkey};
 6105:                         } else {
 6106:                             if ($4 eq '') {
 6107:                                 $sec = 'none';
 6108:                             } else {
 6109:                                 $sec = $4;
 6110:                             }
 6111:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 6112:                         }
 6113:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 6114:                         my $cid = $2.'_'.$3;
 6115:                         if ($4 eq '') {
 6116:                             $sec = 'none';
 6117:                         } else {
 6118:                             $sec = $4;
 6119:                         }
 6120:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 6121:                     }
 6122:                 }
 6123:                 if (keys(%allroles) == 0) {
 6124:                     return;
 6125:                 }
 6126:                 foreach my $key (@courses_and_groups) {
 6127:                     my %content = %{$$access_hash{$key}};
 6128:                     my $cnum = $content{'number'};
 6129:                     my $cdom = $content{'domain'};
 6130:                     my $cid = $cdom.'_'.$cnum;
 6131:                     if (!exists($allroles{$cid})) {
 6132:                         next;
 6133:                     }    
 6134:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 6135:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 6136:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 6137:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 6138:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 6139:                         foreach my $role (keys(%{$allroles{$cid}})) {
 6140:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 6141:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 6142:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 6143:                                         if (grep/^all$/,@sections) {
 6144:                                             return 'ok';
 6145:                                         } else {
 6146:                                             if (grep/^$sec$/,@sections) {
 6147:                                                 return 'ok';
 6148:                                             }
 6149:                                         }
 6150:                                     }
 6151:                                 }
 6152:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 6153:                                     if (grep/^none$/,@groups) {
 6154:                                         return 'ok';
 6155:                                     }
 6156:                                 } else {
 6157:                                     if (grep/^all$/,@groups) {
 6158:                                         return 'ok';
 6159:                                     } 
 6160:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 6161:                                         if (grep/^$group$/,@groups) {
 6162:                                             return 'ok';
 6163:                                         }
 6164:                                     }
 6165:                                 } 
 6166:                             }
 6167:                         }
 6168:                     }
 6169:                 }
 6170:             }
 6171:             if ($guest) {
 6172:                 return $guest;
 6173:             }
 6174:         }
 6175:     }
 6176:     return;
 6177: }
 6178: 
 6179: sub course_group_datechecker {
 6180:     my ($dates,$now,$status) = @_;
 6181:     my ($start,$end) = split(/\./,$dates);
 6182:     if (!$start && !$end) {
 6183:         return 'ok';
 6184:     }
 6185:     if (grep/^active$/,@{$status}) {
 6186:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 6187:             return 'ok';
 6188:         }
 6189:     }
 6190:     if (grep/^previous$/,@{$status}) {
 6191:         if ($end > $now ) {
 6192:             return 'ok';
 6193:         }
 6194:     }
 6195:     if (grep/^future$/,@{$status}) {
 6196:         if ($start > $now) {
 6197:             return 'ok';
 6198:         }
 6199:     }
 6200:     return; 
 6201: }
 6202: 
 6203: sub parse_portfolio_url {
 6204:     my ($url) = @_;
 6205: 
 6206:     my ($type,$udom,$unum,$group,$file_name);
 6207:     
 6208:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 6209: 	$type = 1;
 6210:         $udom = $1;
 6211:         $unum = $2;
 6212:         $file_name = $3;
 6213:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 6214: 	$type = 2;
 6215:         $udom = $1;
 6216:         $unum = $2;
 6217:         $group = $3;
 6218:         $file_name = $3.'/'.$4;
 6219:     }
 6220:     if (wantarray) {
 6221: 	return ($type,$udom,$unum,$file_name,$group);
 6222:     }
 6223:     return $type;
 6224: }
 6225: 
 6226: sub is_portfolio_url {
 6227:     my ($url) = @_;
 6228:     return scalar(&parse_portfolio_url($url));
 6229: }
 6230: 
 6231: sub is_portfolio_file {
 6232:     my ($file) = @_;
 6233:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 6234:         return 1;
 6235:     }
 6236:     return;
 6237: }
 6238: 
 6239: sub usertools_access {
 6240:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
 6241:     my ($access,%tools);
 6242:     if ($context eq '') {
 6243:         $context = 'tools';
 6244:     }
 6245:     if ($context eq 'requestcourses') {
 6246:         %tools = (
 6247:                       official   => 1,
 6248:                       unofficial => 1,
 6249:                       community  => 1,
 6250:                       textbook   => 1,
 6251:                  );
 6252:     } elsif ($context eq 'requestauthor') {
 6253:         %tools = (
 6254:                       requestauthor => 1,
 6255:                  );
 6256:     } else {
 6257:         %tools = (
 6258:                       aboutme   => 1,
 6259:                       blog      => 1,
 6260:                       webdav    => 1,
 6261:                       portfolio => 1,
 6262:                  );
 6263:     }
 6264:     return if (!defined($tools{$tool}));
 6265: 
 6266:     if (($udom eq '') || ($uname eq '')) {
 6267:         $udom = $env{'user.domain'};
 6268:         $uname = $env{'user.name'};
 6269:     }
 6270: 
 6271:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 6272:         if ($action ne 'reload') {
 6273:             if ($context eq 'requestcourses') {
 6274:                 return $env{'environment.canrequest.'.$tool};
 6275:             } elsif ($context eq 'requestauthor') {
 6276:                 return $env{'environment.canrequest.author'};
 6277:             } else {
 6278:                 return $env{'environment.availabletools.'.$tool};
 6279:             }
 6280:         }
 6281:     }
 6282: 
 6283:     my ($toolstatus,$inststatus,$envkey);
 6284:     if ($context eq 'requestauthor') {
 6285:         $envkey = $context; 
 6286:     } else {
 6287:         $envkey = $context.'.'.$tool;
 6288:     }
 6289: 
 6290:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 6291:          ($action ne 'reload')) {
 6292:         $toolstatus = $env{'environment.'.$envkey};
 6293:         $inststatus = $env{'environment.inststatus'};
 6294:     } else {
 6295:         if (ref($userenvref) eq 'HASH') {
 6296:             $toolstatus = $userenvref->{$envkey};
 6297:             $inststatus = $userenvref->{'inststatus'};
 6298:         } else {
 6299:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
 6300:             $toolstatus = $userenv{$envkey};
 6301:             $inststatus = $userenv{'inststatus'};
 6302:         }
 6303:     }
 6304: 
 6305:     if ($toolstatus ne '') {
 6306:         if ($toolstatus) {
 6307:             $access = 1;
 6308:         } else {
 6309:             $access = 0;
 6310:         }
 6311:         return $access;
 6312:     }
 6313: 
 6314:     my ($is_adv,%domdef);
 6315:     if (ref($is_advref) eq 'HASH') {
 6316:         $is_adv = $is_advref->{'is_adv'};
 6317:     } else {
 6318:         $is_adv = &is_advanced_user($udom,$uname);
 6319:     }
 6320:     if (ref($domdefref) eq 'HASH') {
 6321:         %domdef = %{$domdefref};
 6322:     } else {
 6323:         %domdef = &get_domain_defaults($udom);
 6324:     }
 6325:     if (ref($domdef{$tool}) eq 'HASH') {
 6326:         if ($is_adv) {
 6327:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 6328:                 if ($domdef{$tool}{'_LC_adv'}) { 
 6329:                     $access = 1;
 6330:                 } else {
 6331:                     $access = 0;
 6332:                 }
 6333:                 return $access;
 6334:             }
 6335:         }
 6336:         if ($inststatus ne '') {
 6337:             my ($hasaccess,$hasnoaccess);
 6338:             foreach my $affiliation (split(/:/,$inststatus)) {
 6339:                 if ($domdef{$tool}{$affiliation} ne '') { 
 6340:                     if ($domdef{$tool}{$affiliation}) {
 6341:                         $hasaccess = 1;
 6342:                     } else {
 6343:                         $hasnoaccess = 1;
 6344:                     }
 6345:                 }
 6346:             }
 6347:             if ($hasaccess || $hasnoaccess) {
 6348:                 if ($hasaccess) {
 6349:                     $access = 1;
 6350:                 } elsif ($hasnoaccess) {
 6351:                     $access = 0; 
 6352:                 }
 6353:                 return $access;
 6354:             }
 6355:         } else {
 6356:             if ($domdef{$tool}{'default'} ne '') {
 6357:                 if ($domdef{$tool}{'default'}) {
 6358:                     $access = 1;
 6359:                 } elsif ($domdef{$tool}{'default'} == 0) {
 6360:                     $access = 0;
 6361:                 }
 6362:                 return $access;
 6363:             }
 6364:         }
 6365:     } else {
 6366:         if (($context eq 'tools') && ($tool ne 'webdav')) {
 6367:             $access = 1;
 6368:         } else {
 6369:             $access = 0;
 6370:         }
 6371:         return $access;
 6372:     }
 6373: }
 6374: 
 6375: sub is_course_owner {
 6376:     my ($cdom,$cnum,$udom,$uname) = @_;
 6377:     if (($udom eq '') || ($uname eq '')) {
 6378:         $udom = $env{'user.domain'};
 6379:         $uname = $env{'user.name'};
 6380:     }
 6381:     unless (($udom eq '') || ($uname eq '')) {
 6382:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
 6383:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
 6384:                 return 1;
 6385:             } else {
 6386:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
 6387:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
 6388:                     return 1;
 6389:                 }
 6390:             }
 6391:         }
 6392:     }
 6393:     return;
 6394: }
 6395: 
 6396: sub is_advanced_user {
 6397:     my ($udom,$uname) = @_;
 6398:     if ($udom ne '' && $uname ne '') {
 6399:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 6400:             if (wantarray) {
 6401:                 return ($env{'user.adv'},$env{'user.author'});
 6402:             } else {
 6403:                 return $env{'user.adv'};
 6404:             }
 6405:         }
 6406:     }
 6407:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 6408:     my %allroles;
 6409:     my ($is_adv,$is_author);
 6410:     foreach my $role (keys(%roleshash)) {
 6411:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 6412:         my $area = '/'.$tdomain.'/'.$trest;
 6413:         if ($sec ne '') {
 6414:             $area .= '/'.$sec;
 6415:         }
 6416:         if (($area ne '') && ($trole ne '')) {
 6417:             my $spec=$trole.'.'.$area;
 6418:             if ($trole =~ /^cr\//) {
 6419:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 6420:             } elsif ($trole ne 'gr') {
 6421:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 6422:             }
 6423:             if ($trole eq 'au') {
 6424:                 $is_author = 1;
 6425:             }
 6426:         }
 6427:     }
 6428:     foreach my $role (keys(%allroles)) {
 6429:         last if ($is_adv);
 6430:         foreach my $item (split(/:/,$allroles{$role})) {
 6431:             if ($item ne '') {
 6432:                 my ($privilege,$restrictions)=split(/&/,$item);
 6433:                 if ($privilege eq 'adv') {
 6434:                     $is_adv = 1;
 6435:                     last;
 6436:                 }
 6437:             }
 6438:         }
 6439:     }
 6440:     if (wantarray) {
 6441:         return ($is_adv,$is_author);
 6442:     }
 6443:     return $is_adv;
 6444: }
 6445: 
 6446: sub check_can_request {
 6447:     my ($dom,$can_request,$request_domains) = @_;
 6448:     my $canreq = 0;
 6449:     my ($types,$typename) = &Apache::loncommon::course_types();
 6450:     my @options = ('approval','validate','autolimit');
 6451:     my $optregex = join('|',@options);
 6452:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
 6453:         foreach my $type (@{$types}) {
 6454:             if (&usertools_access($env{'user.name'},
 6455:                                   $env{'user.domain'},
 6456:                                   $type,undef,'requestcourses')) {
 6457:                 $canreq ++;
 6458:                 if (ref($request_domains) eq 'HASH') {
 6459:                     push(@{$request_domains->{$type}},$env{'user.domain'});
 6460:                 }
 6461:                 if ($dom eq $env{'user.domain'}) {
 6462:                     $can_request->{$type} = 1;
 6463:                 }
 6464:             }
 6465:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
 6466:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
 6467:                 if (@curr > 0) {
 6468:                     foreach my $item (@curr) {
 6469:                         if (ref($request_domains) eq 'HASH') {
 6470:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
 6471:                             if ($otherdom ne '') {
 6472:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
 6473:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
 6474:                                         push(@{$request_domains->{$type}},$otherdom);
 6475:                                     }
 6476:                                 } else {
 6477:                                     push(@{$request_domains->{$type}},$otherdom);
 6478:                                 }
 6479:                             }
 6480:                         }
 6481:                     }
 6482:                     unless($dom eq $env{'user.domain'}) {
 6483:                         $canreq ++;
 6484:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
 6485:                             $can_request->{$type} = 1;
 6486:                         }
 6487:                     }
 6488:                 }
 6489:             }
 6490:         }
 6491:     }
 6492:     return $canreq;
 6493: }
 6494: 
 6495: # ---------------------------------------------- Custom access rule evaluation
 6496: 
 6497: sub customaccess {
 6498:     my ($priv,$uri)=@_;
 6499:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 6500:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 6501:     $udom = &LONCAPA::clean_domain($udom);
 6502:     $ucrs = &LONCAPA::clean_username($ucrs);
 6503:     my $access=0;
 6504:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 6505: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 6506: 	if ($type eq 'user') {
 6507: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 6508: 		my ($tdom,$tuname)=split(m{/},$scope);
 6509: 		if ($tdom) {
 6510: 		    if ($tdom ne $env{'user.domain'}) { next; }
 6511: 		}
 6512: 		if ($tuname) {
 6513: 		    if ($tuname ne $env{'user.name'}) { next; }
 6514: 		}
 6515: 		$access=($effect eq 'allow');
 6516: 		last;
 6517: 	    }
 6518: 	} else {
 6519: 	    if ($role) {
 6520: 		if ($role ne $urole) { next; }
 6521: 	    }
 6522: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 6523: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 6524: 		if ($tdom) {
 6525: 		    if ($tdom ne $udom) { next; }
 6526: 		}
 6527: 		if ($tcrs) {
 6528: 		    if ($tcrs ne $ucrs) { next; }
 6529: 		}
 6530: 		if ($tsec) {
 6531: 		    if ($tsec ne $usec) { next; }
 6532: 		}
 6533: 		$access=($effect eq 'allow');
 6534: 		last;
 6535: 	    }
 6536: 	    if ($realm eq '' && $role eq '') {
 6537: 		$access=($effect eq 'allow');
 6538: 	    }
 6539: 	}
 6540:     }
 6541:     return $access;
 6542: }
 6543: 
 6544: # ------------------------------------------------- Check for a user privilege
 6545: 
 6546: sub allowed {
 6547:     my ($priv,$uri,$symb,$role)=@_;
 6548:     my $ver_orguri=$uri;
 6549:     $uri=&deversion($uri);
 6550:     my $orguri=$uri;
 6551:     $uri=&declutter($uri);
 6552: 
 6553:     if ($priv eq 'evb') {
 6554: # Evade communication block restrictions for specified role in a course
 6555:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 6556:             return $1;
 6557:         } else {
 6558:             return;
 6559:         }
 6560:     }
 6561: 
 6562:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 6563: # Free bre access to adm and meta resources
 6564:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
 6565: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 6566: 	&& ($priv eq 'bre')) {
 6567: 	return 'F';
 6568:     }
 6569: 
 6570: # Free bre access to user's own portfolio contents
 6571:     my ($space,$domain,$name,@dir)=split('/',$uri);
 6572:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 6573: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 6574:         my %setters;
 6575:         my ($startblock,$endblock) = 
 6576:             &Apache::loncommon::blockcheck(\%setters,'port');
 6577:         if ($startblock && $endblock) {
 6578:             return 'B';
 6579:         } else {
 6580:             return 'F';
 6581:         }
 6582:     }
 6583: 
 6584: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 6585:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 6586:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 6587:         if (exists($env{'request.course.id'})) {
 6588:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6589:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 6590:             if (($domain eq $cdom) && ($name eq $cnum)) {
 6591:                 my $courseprivid=$env{'request.course.id'};
 6592:                 $courseprivid=~s/\_/\//;
 6593:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 6594:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 6595:                     return $1; 
 6596:                 } else {
 6597:                     if ($env{'request.course.sec'}) {
 6598:                         $courseprivid.='/'.$env{'request.course.sec'};
 6599:                     }
 6600:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 6601:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 6602:                         return $2;
 6603:                     }
 6604:                 }
 6605:             }
 6606:         }
 6607:     }
 6608: 
 6609: # Free bre to public access
 6610: 
 6611:     if ($priv eq 'bre') {
 6612:         my $copyright=&metadata($uri,'copyright');
 6613: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 6614:            return 'F'; 
 6615:         }
 6616:         if ($copyright eq 'priv') {
 6617:             $uri=~/([^\/]+)\/([^\/]+)\//;
 6618: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 6619: 		return '';
 6620:             }
 6621:         }
 6622:         if ($copyright eq 'domain') {
 6623:             $uri=~/([^\/]+)\/([^\/]+)\//;
 6624: 	    unless (($env{'user.domain'} eq $1) ||
 6625:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 6626: 		return '';
 6627:             }
 6628:         }
 6629:         if ($env{'request.role'}=~ /li\.\//) {
 6630:             # Library role, so allow browsing of resources in this domain.
 6631:             return 'F';
 6632:         }
 6633:         if ($copyright eq 'custom') {
 6634: 	    unless (&customaccess($priv,$uri)) { return ''; }
 6635:         }
 6636:     }
 6637:     # Domain coordinator is trying to create a course
 6638:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 6639:         # uri is the requested domain in this case.
 6640:         # comparison to 'request.role.domain' shows if the user has selected
 6641:         # a role of dc for the domain in question.
 6642:         return 'F' if ($uri eq $env{'request.role.domain'});
 6643:     }
 6644: 
 6645:     my $thisallowed='';
 6646:     my $statecond=0;
 6647:     my $courseprivid='';
 6648: 
 6649:     my $ownaccess;
 6650:     # Community Coordinator or Assistant Co-author browsing resource space.
 6651:     if (($priv eq 'bro') && ($env{'user.author'})) {
 6652:         if ($uri eq '') {
 6653:             $ownaccess = 1;
 6654:         } else {
 6655:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
 6656:                 my $udom = $env{'user.domain'};
 6657:                 my $uname = $env{'user.name'};
 6658:                 if ($uri =~ m{^\Q$udom\E/?$}) {
 6659:                     $ownaccess = 1;
 6660:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
 6661:                     unless ($uri =~ m{\.\./}) {
 6662:                         $ownaccess = 1;
 6663:                     }
 6664:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
 6665:                     my $now = time;
 6666:                     if ($uri =~ m{^([^/]+)/?$}) {
 6667:                         my $adom = $1;
 6668:                         foreach my $key (keys(%env)) {
 6669:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
 6670:                                 my ($start,$end) = split('.',$env{$key});
 6671:                                 if (($now >= $start) && (!$end || $end < $now)) {
 6672:                                     $ownaccess = 1;
 6673:                                     last;
 6674:                                 }
 6675:                             }
 6676:                         }
 6677:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
 6678:                         my $adom = $1;
 6679:                         my $aname = $2;
 6680:                         foreach my $role ('ca','aa') { 
 6681:                             if ($env{"user.role.$role./$adom/$aname"}) {
 6682:                                 my ($start,$end) =
 6683:                                     split('.',$env{"user.role.$role./$adom/$aname"});
 6684:                                 if (($now >= $start) && (!$end || $end < $now)) {
 6685:                                     $ownaccess = 1;
 6686:                                     last;
 6687:                                 }
 6688:                             }
 6689:                         }
 6690:                     }
 6691:                 }
 6692:             }
 6693:         }
 6694:     }
 6695: 
 6696: # Course
 6697: 
 6698:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 6699:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6700:             $thisallowed.=$1;
 6701:         }
 6702:     }
 6703: 
 6704: # Domain
 6705: 
 6706:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 6707:        =~/\Q$priv\E\&([^\:]*)/) {
 6708:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6709:             $thisallowed.=$1;
 6710:         }
 6711:     }
 6712: 
 6713: # User who is not author or co-author might still be able to edit
 6714: # resource of an author in the domain (e.g., if Domain Coordinator).
 6715:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
 6716:         (&allowed('mdc',$env{'request.course.id'}))) {
 6717:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
 6718:             $thisallowed.=$1;
 6719:         }
 6720:     }
 6721: 
 6722: # Course: uri itself is a course
 6723:     my $courseuri=$uri;
 6724:     $courseuri=~s/\_(\d)/\/$1/;
 6725:     $courseuri=~s/^([^\/])/\/$1/;
 6726: 
 6727:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 6728:        =~/\Q$priv\E\&([^\:]*)/) {
 6729:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6730:             $thisallowed.=$1;
 6731:         }
 6732:     }
 6733: 
 6734: # URI is an uploaded document for this course, default permissions don't matter
 6735: # not allowing 'edit' access (editupload) to uploaded course docs
 6736:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 6737: 	$thisallowed='';
 6738:         my ($match)=&is_on_map($uri);
 6739:         if ($match) {
 6740:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 6741:                   =~/\Q$priv\E\&([^\:]*)/) {
 6742:                 my @blockers = &has_comm_blocking($priv,$symb,$uri);
 6743:                 if (@blockers > 0) {
 6744:                     $thisallowed = 'B';
 6745:                 } else {
 6746:                     $thisallowed.=$1;
 6747:                 }
 6748:             }
 6749:         } else {
 6750:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 6751:             if ($refuri) {
 6752:                 if ($refuri =~ m|^/adm/|) {
 6753:                     $thisallowed='F';
 6754:                 } else {
 6755:                     $refuri=&declutter($refuri);
 6756:                     my ($match) = &is_on_map($refuri);
 6757:                     if ($match) {
 6758:                         my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 6759:                         if (@blockers > 0) {
 6760:                             $thisallowed = 'B';
 6761:                         } else {
 6762:                             $thisallowed='F';
 6763:                         }
 6764:                     }
 6765:                 }
 6766:             }
 6767:         }
 6768:     }
 6769: 
 6770:     if ($priv eq 'bre'
 6771: 	&& $thisallowed ne 'F' 
 6772: 	&& $thisallowed ne '2'
 6773: 	&& &is_portfolio_url($uri)) {
 6774: 	$thisallowed = &portfolio_access($uri);
 6775:     }
 6776: 
 6777: # Full access at system, domain or course-wide level? Exit.
 6778:     if ($thisallowed=~/F/) {
 6779: 	return 'F';
 6780:     }
 6781: 
 6782: # If this is generating or modifying users, exit with special codes
 6783: 
 6784:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 6785: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 6786: 	    my ($audom,$auname)=split('/',$uri);
 6787: # no author name given, so this just checks on the general right to make a co-author in this domain
 6788: 	    unless ($auname) { return $thisallowed; }
 6789: # an author name is given, so we are about to actually make a co-author for a certain account
 6790: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 6791: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 6792: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 6793: 	}
 6794: 	return $thisallowed;
 6795:     }
 6796: #
 6797: # Gathered so far: system, domain and course wide privileges
 6798: #
 6799: # Course: See if uri or referer is an individual resource that is part of 
 6800: # the course
 6801: 
 6802:     if ($env{'request.course.id'}) {
 6803: 
 6804:        $courseprivid=$env{'request.course.id'};
 6805:        if ($env{'request.course.sec'}) {
 6806:           $courseprivid.='/'.$env{'request.course.sec'};
 6807:        }
 6808:        $courseprivid=~s/\_/\//;
 6809:        my $checkreferer=1;
 6810:        my ($match,$cond)=&is_on_map($uri);
 6811:        if ($match) {
 6812:            $statecond=$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,$uri);
 6818:                    if (@blockers > 0) {
 6819:                        $thisallowed = 'B';
 6820:                    } else {
 6821:                        $thisallowed.=$value;
 6822:                    }
 6823:                } else {
 6824:                    $thisallowed.=$value;
 6825:                }
 6826:                $checkreferer=0;
 6827:            }
 6828:        }
 6829:        
 6830:        if ($checkreferer) {
 6831: 	  my $refuri=$env{'httpref.'.$orguri};
 6832:             unless ($refuri) {
 6833:                 foreach my $key (keys(%env)) {
 6834: 		    if ($key=~/^httpref\..*\*/) {
 6835: 			my $pattern=$key;
 6836:                         $pattern=~s/^httpref\.\/res\///;
 6837:                         $pattern=~s/\*/\[\^\/\]\+/g;
 6838:                         $pattern=~s/\//\\\//g;
 6839:                         if ($orguri=~/$pattern/) {
 6840: 			    $refuri=$env{$key};
 6841:                         }
 6842:                     }
 6843:                 }
 6844:             }
 6845: 
 6846:          if ($refuri) { 
 6847: 	  $refuri=&declutter($refuri);
 6848:           my ($match,$cond)=&is_on_map($refuri);
 6849:             if ($match) {
 6850:               my $refstatecond=$cond;
 6851:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 6852:                   =~/\Q$priv\E\&([^\:]*)/) {
 6853:                   my $value = $1;
 6854:                   if ($priv eq 'bre') {
 6855:                       my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 6856:                       if (@blockers > 0) {
 6857:                           $thisallowed = 'B';
 6858:                       } else {
 6859:                           $thisallowed.=$value;
 6860:                       }
 6861:                   } else {
 6862:                       $thisallowed.=$value;
 6863:                   }
 6864:                   $uri=$refuri;
 6865:                   $statecond=$refstatecond;
 6866:               }
 6867:           }
 6868:         }
 6869:        }
 6870:    }
 6871: 
 6872: #
 6873: # Gathered now: all privileges that could apply, and condition number
 6874: # 
 6875: #
 6876: # Full or no access?
 6877: #
 6878: 
 6879:     if ($thisallowed=~/F/) {
 6880: 	return 'F';
 6881:     }
 6882: 
 6883:     unless ($thisallowed) {
 6884:         return '';
 6885:     }
 6886: 
 6887: # Restrictions exist, deal with them
 6888: #
 6889: #   C:according to course preferences
 6890: #   R:according to resource settings
 6891: #   L:unless locked
 6892: #   X:according to user session state
 6893: #
 6894: 
 6895: # Possibly locked functionality, check all courses
 6896: # Locks might take effect only after 10 minutes cache expiration for other
 6897: # courses, and 2 minutes for current course
 6898: 
 6899:     my $envkey;
 6900:     if ($thisallowed=~/L/) {
 6901:         foreach $envkey (keys(%env)) {
 6902:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 6903:                my $courseid=$2;
 6904:                my $roleid=$1.'.'.$2;
 6905:                $courseid=~s/^\///;
 6906:                my $expiretime=600;
 6907:                if ($env{'request.role'} eq $roleid) {
 6908: 		  $expiretime=120;
 6909:                }
 6910: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 6911:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 6912:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 6913: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 6914:                }
 6915:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 6916:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 6917: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 6918:                        &log($env{'user.domain'},$env{'user.name'},
 6919:                             $env{'user.home'},
 6920:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 6921:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 6922:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 6923: 		       return '';
 6924:                    }
 6925:                }
 6926:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 6927:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 6928: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 6929:                        &log($env{'user.domain'},$env{'user.name'},
 6930:                             $env{'user.home'},
 6931:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 6932:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 6933:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 6934: 		       return '';
 6935:                    }
 6936:                }
 6937: 	   }
 6938:        }
 6939:     }
 6940:    
 6941: #
 6942: # Rest of the restrictions depend on selected course
 6943: #
 6944: 
 6945:     unless ($env{'request.course.id'}) {
 6946: 	if ($thisallowed eq 'A') {
 6947: 	    return 'A';
 6948:         } elsif ($thisallowed eq 'B') {
 6949:             return 'B';
 6950: 	} else {
 6951: 	    return '1';
 6952: 	}
 6953:     }
 6954: 
 6955: #
 6956: # Now user is definitely in a course
 6957: #
 6958: 
 6959: 
 6960: # Course preferences
 6961: 
 6962:    if ($thisallowed=~/C/) {
 6963:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 6964:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 6965:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 6966: 	   =~/\Q$rolecode\E/) {
 6967: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 6968: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 6969: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 6970: 			$env{'request.course.id'});
 6971: 	   }
 6972:            return '';
 6973:        }
 6974: 
 6975:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 6976: 	   =~/\Q$unamedom\E/) {
 6977: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 6978: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 6979: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 6980: 			$env{'request.course.id'});
 6981: 	   }
 6982:            return '';
 6983:        }
 6984:    }
 6985: 
 6986: # Resource preferences
 6987: 
 6988:    if ($thisallowed=~/R/) {
 6989:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 6990:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 6991: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 6992: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 6993: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 6994: 	   }
 6995: 	   return '';
 6996:        }
 6997:    }
 6998: 
 6999: # Restricted by state or randomout?
 7000: 
 7001:    if ($thisallowed=~/X/) {
 7002:       if ($env{'acc.randomout'}) {
 7003: 	 if (!$symb) { $symb=&symbread($uri,1); }
 7004:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 7005:             return ''; 
 7006:          }
 7007:       }
 7008:       if (&condval($statecond)) {
 7009: 	 return '2';
 7010:       } else {
 7011:          return '';
 7012:       }
 7013:    }
 7014: 
 7015:     if ($thisallowed eq 'A') {
 7016: 	return 'A';
 7017:     } elsif ($thisallowed eq 'B') {
 7018:         return 'B';
 7019:     }
 7020:    return 'F';
 7021: }
 7022: 
 7023: # ------------------------------------------- Check construction space access
 7024: 
 7025: sub constructaccess {
 7026:     my ($url,$setpriv)=@_;
 7027: 
 7028: # We do not allow editing of previous versions of files
 7029:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
 7030: 
 7031: # Get username and domain from URL
 7032:     my ($ownername,$ownerdomain,$ownerhome);
 7033: 
 7034:     ($ownerdomain,$ownername) =
 7035:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)/});
 7036: 
 7037: # The URL does not really point to any authorspace, forget it
 7038:     unless (($ownername) && ($ownerdomain)) { return ''; }
 7039: 
 7040: # Now we need to see if the user has access to the authorspace of
 7041: # $ownername at $ownerdomain
 7042: 
 7043:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
 7044: # Real author for this?
 7045:        $ownerhome = $env{'user.home'};
 7046:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
 7047:           return ($ownername,$ownerdomain,$ownerhome);
 7048:        }
 7049:     } else {
 7050: # Co-author for this?
 7051:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
 7052:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
 7053:             $ownerhome = &homeserver($ownername,$ownerdomain);
 7054:             return ($ownername,$ownerdomain,$ownerhome);
 7055:         }
 7056:     }
 7057: 
 7058: # We don't have any access right now. If we are not possibly going to do anything about this,
 7059: # we might as well leave
 7060:    unless ($setpriv) { return ''; }
 7061: 
 7062: # Backdoor access?
 7063:     my $allowed=&allowed('eco',$ownerdomain);
 7064: # Nope
 7065:     unless ($allowed) { return ''; }
 7066: # Looks like we may have access, but could be locked by the owner of the construction space
 7067:     if ($allowed eq 'U') {
 7068:         my %blocked=&get('environment',['domcoord.author'],
 7069:                          $ownerdomain,$ownername);
 7070: # Is blocked by owner
 7071:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
 7072:     }
 7073:     if (($allowed eq 'F') || ($allowed eq 'U')) {
 7074: # Grant temporary access
 7075:         my $then=$env{'user.login.time'};
 7076:         my $update=$env{'user.update.time'};
 7077:         if (!$update) { $update = $then; }
 7078:         my $refresh=$env{'user.refresh.time'};
 7079:         if (!$refresh) { $refresh = $update; }
 7080:         my $now = time;
 7081:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
 7082:                            $now,'ca','constructaccess');
 7083:         $ownerhome = &homeserver($ownername,$ownerdomain);
 7084:         return($ownername,$ownerdomain,$ownerhome);
 7085:     }
 7086: # No business here
 7087:     return '';
 7088: }
 7089: 
 7090: sub get_comm_blocks {
 7091:     my ($cdom,$cnum) = @_;
 7092:     if ($cdom eq '' || $cnum eq '') {
 7093:         return unless ($env{'request.course.id'});
 7094:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7095:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7096:     }
 7097:     my %commblocks;
 7098:     my $hashid=$cdom.'_'.$cnum;
 7099:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
 7100:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
 7101:         %commblocks = %{$blocksref};
 7102:     } else {
 7103:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
 7104:         my $cachetime = 600;
 7105:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
 7106:     }
 7107:     return %commblocks;
 7108: }
 7109: 
 7110: sub has_comm_blocking {
 7111:     my ($priv,$symb,$uri,$blocks) = @_;
 7112:     return unless ($env{'request.course.id'});
 7113:     return unless ($priv eq 'bre');
 7114:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 7115:     my %commblocks;
 7116:     if (ref($blocks) eq 'HASH') {
 7117:         %commblocks = %{$blocks};
 7118:     } else {
 7119:         %commblocks = &get_comm_blocks();
 7120:     }
 7121:     return unless (keys(%commblocks) > 0);
 7122:     if (!$symb) { $symb=&symbread($uri,1); }
 7123:     my ($map,$resid,undef)=&decode_symb($symb);
 7124:     my %tocheck = (
 7125:                     maps      => $map,
 7126:                     resources => $symb,
 7127:                   );
 7128:     my @blockers;
 7129:     my $now = time;
 7130:     my $navmap = Apache::lonnavmaps::navmap->new();
 7131:     foreach my $block (keys(%commblocks)) {
 7132:         if ($block =~ /^(\d+)____(\d+)$/) {
 7133:             my ($start,$end) = ($1,$2);
 7134:             if ($start <= $now && $end >= $now) {
 7135:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 7136:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 7137:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 7138:                             if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
 7139:                                 unless (grep(/^\Q$block\E$/,@blockers)) {
 7140:                                     push(@blockers,$block);
 7141:                                 }
 7142:                             }
 7143:                         }
 7144:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 7145:                             if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
 7146:                                 unless (grep(/^\Q$block\E$/,@blockers)) {  
 7147:                                     push(@blockers,$block);
 7148:                                 }
 7149:                             }
 7150:                         }
 7151:                     }
 7152:                 }
 7153:             }
 7154:         } elsif ($block =~ /^firstaccess____(.+)$/) {
 7155:             my $item = $1;
 7156:             my @to_test;
 7157:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 7158:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 7159:                     my $check_interval;
 7160:                     if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
 7161:                         my @interval;
 7162:                         my $type = 'map';
 7163:                         if ($item eq 'course') {
 7164:                             $type = 'course';
 7165:                             @interval=&EXT("resource.0.interval");
 7166:                         } else {
 7167:                             if ($item =~ /___\d+___/) {
 7168:                                 $type = 'resource';
 7169:                                 @interval=&EXT("resource.0.interval",$item);
 7170:                                 if (ref($navmap)) {                        
 7171:                                     my $res = $navmap->getBySymb($item); 
 7172:                                     push(@to_test,$res);
 7173:                                 }
 7174:                             } else {
 7175:                                 my $mapsymb = &symbread($item,1);
 7176:                                 if ($mapsymb) {
 7177:                                     if (ref($navmap)) {
 7178:                                         my $mapres = $navmap->getBySymb($mapsymb);
 7179:                                         @to_test = $mapres->retrieveResources($mapres,undef,0,1);
 7180:                                         foreach my $res (@to_test) {
 7181:                                             my $symb = $res->symb();
 7182:                                             next if ($symb eq $mapsymb);
 7183:                                             if ($symb ne '') {
 7184:                                                 @interval=&EXT("resource.0.interval",$symb);
 7185:                                                 last;
 7186:                                             }
 7187:                                         }
 7188:                                     }
 7189:                                 }
 7190:                             }
 7191:                         }
 7192:                         if ($interval[0] =~ /\d+/) {
 7193:                             my $first_access;
 7194:                             if ($type eq 'resource') {
 7195:                                 $first_access=&get_first_access($interval[1],$item);
 7196:                             } elsif ($type eq 'map') {
 7197:                                 $first_access=&get_first_access($interval[1],undef,$item);
 7198:                             } else {
 7199:                                 $first_access=&get_first_access($interval[1]);
 7200:                             }
 7201:                             if ($first_access) {
 7202:                                 my $timesup = $first_access+$interval[0];
 7203:                                 if ($timesup > $now) {
 7204:                                     foreach my $res (@to_test) {
 7205:                                         if ($res->is_problem()) {
 7206:                                             if ($res->completable()) {
 7207:                                                 unless (grep(/^\Q$block\E$/,@blockers)) {
 7208:                                                     push(@blockers,$block);
 7209:                                                 }
 7210:                                                 last;
 7211:                                             }
 7212:                                         }
 7213:                                     }
 7214:                                 }
 7215:                             }
 7216:                         }
 7217:                     }
 7218:                 }
 7219:             }
 7220:         }
 7221:     }
 7222:     return @blockers;
 7223: }
 7224: 
 7225: sub check_docs_block {
 7226:     my ($docsblock,$tocheck) =@_;
 7227:     if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
 7228:         return;
 7229:     }
 7230:     if (ref($docsblock->{'maps'}) eq 'HASH') {
 7231:         if ($tocheck->{'maps'}) {
 7232:             if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
 7233:                 return 1;
 7234:             }
 7235:         }
 7236:     }
 7237:     if (ref($docsblock->{'resources'}) eq 'HASH') {
 7238:         if ($tocheck->{'resources'}) {
 7239:             if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
 7240:                 return 1;
 7241:             }
 7242:         }
 7243:     }
 7244:     return;
 7245: }
 7246: 
 7247: #
 7248: #   Removes the versino from a URI and
 7249: #   splits it in to its filename and path to the filename.
 7250: #   Seems like File::Basename could have done this more clearly.
 7251: #   Parameters:
 7252: #      $uri   - input URI
 7253: #   Returns:
 7254: #     Two element list consisting of 
 7255: #     $pathname  - the URI up to and excluding the trailing /
 7256: #     $filename  - The part of the URI following the last /
 7257: #  NOTE:
 7258: #    Another realization of this is simply:
 7259: #    use File::Basename;
 7260: #    ...
 7261: #    $uri = shift;
 7262: #    $filename = basename($uri);
 7263: #    $path     = dirname($uri);
 7264: #    return ($filename, $path);
 7265: #
 7266: #     The implementation below is probably faster however.
 7267: #
 7268: sub split_uri_for_cond {
 7269:     my $uri=&deversion(&declutter(shift));
 7270:     my @uriparts=split(/\//,$uri);
 7271:     my $filename=pop(@uriparts);
 7272:     my $pathname=join('/',@uriparts);
 7273:     return ($pathname,$filename);
 7274: }
 7275: # --------------------------------------------------- Is a resource on the map?
 7276: 
 7277: sub is_on_map {
 7278:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 7279:     #Trying to find the conditional for the file
 7280:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 7281: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 7282:     if ($match) {
 7283: 	return (1,$1);
 7284:     } else {
 7285: 	return (0,0);
 7286:     }
 7287: }
 7288: 
 7289: # --------------------------------------------------------- Get symb from alias
 7290: 
 7291: sub get_symb_from_alias {
 7292:     my $symb=shift;
 7293:     my ($map,$resid,$url)=&decode_symb($symb);
 7294: # Already is a symb
 7295:     if ($url) { return $symb; }
 7296: # Must be an alias
 7297:     my $aliassymb='';
 7298:     my %bighash;
 7299:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7300:                             &GDBM_READER(),0640)) {
 7301:         my $rid=$bighash{'mapalias_'.$symb};
 7302: 	if ($rid) {
 7303: 	    my ($mapid,$resid)=split(/\./,$rid);
 7304: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 7305: 				    $resid,$bighash{'src_'.$rid});
 7306: 	}
 7307:         untie %bighash;
 7308:     }
 7309:     return $aliassymb;
 7310: }
 7311: 
 7312: # ----------------------------------------------------------------- Define Role
 7313: 
 7314: sub definerole {
 7315:   if (allowed('mcr','/')) {
 7316:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 7317:     foreach my $role (split(':',$sysrole)) {
 7318: 	my ($crole,$cqual)=split(/\&/,$role);
 7319:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 7320:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 7321: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 7322:                return "refused:s:$crole&$cqual"; 
 7323:             }
 7324:         }
 7325:     }
 7326:     foreach my $role (split(':',$domrole)) {
 7327: 	my ($crole,$cqual)=split(/\&/,$role);
 7328:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 7329:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 7330: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 7331:                return "refused:d:$crole&$cqual"; 
 7332:             }
 7333:         }
 7334:     }
 7335:     foreach my $role (split(':',$courole)) {
 7336: 	my ($crole,$cqual)=split(/\&/,$role);
 7337:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 7338:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 7339: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 7340:                return "refused:c:$crole&$cqual"; 
 7341:             }
 7342:         }
 7343:     }
 7344:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 7345:                 "$env{'user.domain'}:$env{'user.name'}:".
 7346: 	        "rolesdef_$rolename=".
 7347:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 7348:     return reply($command,$env{'user.home'});
 7349:   } else {
 7350:     return 'refused';
 7351:   }
 7352: }
 7353: 
 7354: # ---------------- Make a metadata query against the network of library servers
 7355: 
 7356: sub metadata_query {
 7357:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
 7358:     my %rhash;
 7359:     my %libserv = &all_library();
 7360:     my @server_list = (defined($server_array) ? @$server_array
 7361:                                               : keys(%libserv) );
 7362:     for my $server (@server_list) {
 7363:         my $domains = ''; 
 7364:         if (ref($domains_hash) eq 'HASH') {
 7365:             $domains = $domains_hash->{$server}; 
 7366:         }
 7367: 	unless ($custom or $customshow) {
 7368: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
 7369: 	    $rhash{$server}=$reply;
 7370: 	}
 7371: 	else {
 7372: 	    my $reply=&reply("querysend:".&escape($query).':'.
 7373: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
 7374: 			     $server);
 7375: 	    $rhash{$server}=$reply;
 7376: 	}
 7377:     }
 7378:     return \%rhash;
 7379: }
 7380: 
 7381: # ----------------------------------------- Send log queries and wait for reply
 7382: 
 7383: sub log_query {
 7384:     my ($uname,$udom,$query,%filters)=@_;
 7385:     my $uhome=&homeserver($uname,$udom);
 7386:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 7387:     my $uhost=&hostname($uhome);
 7388:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 7389:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 7390:                        $uhome);
 7391:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 7392:     return get_query_reply($queryid);
 7393: }
 7394: 
 7395: # -------------------------- Update MySQL table for portfolio file
 7396: 
 7397: sub update_portfolio_table {
 7398:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 7399:     if ($group ne '') {
 7400:         $file_name =~s /^\Q$group\E//;
 7401:     }
 7402:     my $homeserver = &homeserver($uname,$udom);
 7403:     my $queryid=
 7404:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 7405:                ':'.&escape($file_name).':'.$action,$homeserver);
 7406:     my $reply = &get_query_reply($queryid);
 7407:     return $reply;
 7408: }
 7409: 
 7410: # -------------------------- Update MySQL allusers table
 7411: 
 7412: sub update_allusers_table {
 7413:     my ($uname,$udom,$names) = @_;
 7414:     my $homeserver = &homeserver($uname,$udom);
 7415:     my $queryid=
 7416:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 7417:                'lastname='.&escape($names->{'lastname'}).'%%'.
 7418:                'firstname='.&escape($names->{'firstname'}).'%%'.
 7419:                'middlename='.&escape($names->{'middlename'}).'%%'.
 7420:                'generation='.&escape($names->{'generation'}).'%%'.
 7421:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 7422:                'id='.&escape($names->{'id'}),$homeserver);
 7423:     return;
 7424: }
 7425: 
 7426: # ------- Request retrieval of institutional classlists for course(s)
 7427: 
 7428: sub fetch_enrollment_query {
 7429:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 7430:     my $homeserver;
 7431:     my $maxtries = 1;
 7432:     if ($context eq 'automated') {
 7433:         $homeserver = $perlvar{'lonHostID'};
 7434:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 7435:     } else {
 7436:         $homeserver = &homeserver($cnum,$dom);
 7437:     }
 7438:     my $host=&hostname($homeserver);
 7439:     my $cmd = '';
 7440:     foreach my $affiliate (keys(%{$affiliatesref})) {
 7441:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 7442:     }
 7443:     $cmd =~ s/%%$//;
 7444:     $cmd = &escape($cmd);
 7445:     my $query = 'fetchenrollment';
 7446:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 7447:     unless ($queryid=~/^\Q$host\E\_/) { 
 7448:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 7449:         return 'error: '.$queryid;
 7450:     }
 7451:     my $reply = &get_query_reply($queryid);
 7452:     my $tries = 1;
 7453:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 7454:         $reply = &get_query_reply($queryid);
 7455:         $tries ++;
 7456:     }
 7457:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 7458:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 7459:     } else {
 7460:         my @responses = split(/:/,$reply);
 7461:         if ($homeserver eq $perlvar{'lonHostID'}) {
 7462:             foreach my $line (@responses) {
 7463:                 my ($key,$value) = split(/=/,$line,2);
 7464:                 $$replyref{$key} = $value;
 7465:             }
 7466:         } else {
 7467:             my $pathname = LONCAPA::tempdir();
 7468:             foreach my $line (@responses) {
 7469:                 my ($key,$value) = split(/=/,$line);
 7470:                 $$replyref{$key} = $value;
 7471:                 if ($value > 0) {
 7472:                     foreach my $item (@{$$affiliatesref{$key}}) {
 7473:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 7474:                         my $destname = $pathname.'/'.$filename;
 7475:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 7476:                         if ($xml_classlist =~ /^error/) {
 7477:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 7478:                         } else {
 7479:                             if ( open(FILE,">$destname") ) {
 7480:                                 print FILE &unescape($xml_classlist);
 7481:                                 close(FILE);
 7482:                             } else {
 7483:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 7484:                             }
 7485:                         }
 7486:                     }
 7487:                 }
 7488:             }
 7489:         }
 7490:         return 'ok';
 7491:     }
 7492:     return 'error';
 7493: }
 7494: 
 7495: sub get_query_reply {
 7496:     my $queryid=shift;
 7497:     my $replyfile=LONCAPA::tempdir().$queryid;
 7498:     my $reply='';
 7499:     for (1..100) {
 7500: 	sleep 2;
 7501:         if (-e $replyfile.'.end') {
 7502: 	    if (open(my $fh,$replyfile)) {
 7503: 		$reply = join('',<$fh>);
 7504: 		close($fh);
 7505: 	   } else { return 'error: reply_file_error'; }
 7506:            return &unescape($reply);
 7507: 	}
 7508:     }
 7509:     return 'timeout:'.$queryid;
 7510: }
 7511: 
 7512: sub courselog_query {
 7513: #
 7514: # possible filters:
 7515: # url: url or symb
 7516: # username
 7517: # domain
 7518: # action: view, submit, grade
 7519: # start: timestamp
 7520: # end: timestamp
 7521: #
 7522:     my (%filters)=@_;
 7523:     unless ($env{'request.course.id'}) { return 'no_course'; }
 7524:     if ($filters{'url'}) {
 7525: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 7526:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 7527:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 7528:     }
 7529:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7530:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7531:     return &log_query($cname,$cdom,'courselog',%filters);
 7532: }
 7533: 
 7534: sub userlog_query {
 7535: #
 7536: # possible filters:
 7537: # action: log check role
 7538: # start: timestamp
 7539: # end: timestamp
 7540: #
 7541:     my ($uname,$udom,%filters)=@_;
 7542:     return &log_query($uname,$udom,'userlog',%filters);
 7543: }
 7544: 
 7545: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 7546: 
 7547: sub auto_run {
 7548:     my ($cnum,$cdom) = @_;
 7549:     my $response = 0;
 7550:     my $settings;
 7551:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 7552:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 7553:         $settings = $domconfig{'autoenroll'};
 7554:         if ($settings->{'run'} eq '1') {
 7555:             $response = 1;
 7556:         }
 7557:     } else {
 7558:         my $homeserver;
 7559:         if (&is_course($cdom,$cnum)) {
 7560:             $homeserver = &homeserver($cnum,$cdom);
 7561:         } else {
 7562:             $homeserver = &domain($cdom,'primary');
 7563:         }
 7564:         if ($homeserver ne 'no_host') {
 7565:             $response = &reply('autorun:'.$cdom,$homeserver);
 7566:         }
 7567:     }
 7568:     return $response;
 7569: }
 7570: 
 7571: sub auto_get_sections {
 7572:     my ($cnum,$cdom,$inst_coursecode) = @_;
 7573:     my $homeserver;
 7574:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
 7575:         $homeserver = &homeserver($cnum,$cdom);
 7576:     }
 7577:     if (!defined($homeserver)) { 
 7578:         if ($cdom =~ /^$match_domain$/) {
 7579:             $homeserver = &domain($cdom,'primary');
 7580:         }
 7581:     }
 7582:     my @secs;
 7583:     if (defined($homeserver)) {
 7584:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 7585:         unless ($response eq 'refused') {
 7586:             @secs = split(/:/,$response);
 7587:         }
 7588:     }
 7589:     return @secs;
 7590: }
 7591: 
 7592: sub auto_new_course {
 7593:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
 7594:     my $homeserver = &homeserver($cnum,$cdom);
 7595:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
 7596:     return $response;
 7597: }
 7598: 
 7599: sub auto_validate_courseID {
 7600:     my ($cnum,$cdom,$inst_course_id) = @_;
 7601:     my $homeserver = &homeserver($cnum,$cdom);
 7602:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 7603:     return $response;
 7604: }
 7605: 
 7606: sub auto_validate_instcode {
 7607:     my ($cnum,$cdom,$instcode,$owner) = @_;
 7608:     my ($homeserver,$response);
 7609:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 7610:         $homeserver = &homeserver($cnum,$cdom);
 7611:     }
 7612:     if (!defined($homeserver)) {
 7613:         if ($cdom =~ /^$match_domain$/) {
 7614:             $homeserver = &domain($cdom,'primary');
 7615:         }
 7616:     }
 7617:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
 7618:                         &escape($instcode).':'.&escape($owner),$homeserver));
 7619:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
 7620:     return ($outcome,$description,$defaultcredits);
 7621: }
 7622: 
 7623: sub auto_create_password {
 7624:     my ($cnum,$cdom,$authparam,$udom) = @_;
 7625:     my ($homeserver,$response);
 7626:     my $create_passwd = 0;
 7627:     my $authchk = '';
 7628:     if ($udom =~ /^$match_domain$/) {
 7629:         $homeserver = &domain($udom,'primary');
 7630:     }
 7631:     if ($homeserver eq '') {
 7632:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 7633:             $homeserver = &homeserver($cnum,$cdom);
 7634:         }
 7635:     }
 7636:     if ($homeserver eq '') {
 7637:         $authchk = 'nodomain';
 7638:     } else {
 7639:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 7640:         if ($response eq 'refused') {
 7641:             $authchk = 'refused';
 7642:         } else {
 7643:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 7644:         }
 7645:     }
 7646:     return ($authparam,$create_passwd,$authchk);
 7647: }
 7648: 
 7649: sub auto_photo_permission {
 7650:     my ($cnum,$cdom,$students) = @_;
 7651:     my $homeserver = &homeserver($cnum,$cdom);
 7652:     my ($outcome,$perm_reqd,$conditions) = 
 7653: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 7654:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 7655: 	return (undef,undef);
 7656:     }
 7657:     return ($outcome,$perm_reqd,$conditions);
 7658: }
 7659: 
 7660: sub auto_checkphotos {
 7661:     my ($uname,$udom,$pid) = @_;
 7662:     my $homeserver = &homeserver($uname,$udom);
 7663:     my ($result,$resulttype);
 7664:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 7665: 				   &escape($uname).':'.&escape($pid),
 7666: 				   $homeserver));
 7667:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 7668: 	return (undef,undef);
 7669:     }
 7670:     if ($outcome) {
 7671:         ($result,$resulttype) = split(/:/,$outcome);
 7672:     } 
 7673:     return ($result,$resulttype);
 7674: }
 7675: 
 7676: sub auto_photochoice {
 7677:     my ($cnum,$cdom) = @_;
 7678:     my $homeserver = &homeserver($cnum,$cdom);
 7679:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 7680: 						       &escape($cdom),
 7681: 						       $homeserver)));
 7682:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 7683: 	return (undef,undef);
 7684:     }
 7685:     return ($update,$comment);
 7686: }
 7687: 
 7688: sub auto_photoupdate {
 7689:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 7690:     my $homeserver = &homeserver($cnum,$dom);
 7691:     my $host=&hostname($homeserver);
 7692:     my $cmd = '';
 7693:     my $maxtries = 1;
 7694:     foreach my $affiliate (keys(%{$affiliatesref})) {
 7695:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 7696:     }
 7697:     $cmd =~ s/%%$//;
 7698:     $cmd = &escape($cmd);
 7699:     my $query = 'institutionalphotos';
 7700:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 7701:     unless ($queryid=~/^\Q$host\E\_/) {
 7702:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 7703:         return 'error: '.$queryid;
 7704:     }
 7705:     my $reply = &get_query_reply($queryid);
 7706:     my $tries = 1;
 7707:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 7708:         $reply = &get_query_reply($queryid);
 7709:         $tries ++;
 7710:     }
 7711:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 7712:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 7713:     } else {
 7714:         my @responses = split(/:/,$reply);
 7715:         my $outcome = shift(@responses); 
 7716:         foreach my $item (@responses) {
 7717:             my ($key,$value) = split(/=/,$item);
 7718:             $$photo{$key} = $value;
 7719:         }
 7720:         return $outcome;
 7721:     }
 7722:     return 'error';
 7723: }
 7724: 
 7725: sub auto_instcode_format {
 7726:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 7727: 	$cat_order) = @_;
 7728:     my $courses = '';
 7729:     my @homeservers;
 7730:     if ($caller eq 'global') {
 7731: 	my %servers = &get_servers($codedom,'library');
 7732: 	foreach my $tryserver (keys(%servers)) {
 7733: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7734: 		push(@homeservers,$tryserver);
 7735: 	    }
 7736:         }
 7737:     } elsif ($caller eq 'requests') {
 7738:         if ($codedom =~ /^$match_domain$/) {
 7739:             my $chome = &domain($codedom,'primary');
 7740:             unless ($chome eq 'no_host') {
 7741:                 push(@homeservers,$chome);
 7742:             }
 7743:         }
 7744:     } else {
 7745:         push(@homeservers,&homeserver($caller,$codedom));
 7746:     }
 7747:     foreach my $code (keys(%{$instcodes})) {
 7748:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 7749:     }
 7750:     chop($courses);
 7751:     my $ok_response = 0;
 7752:     my $response;
 7753:     while (@homeservers > 0 && $ok_response == 0) {
 7754:         my $server = shift(@homeservers); 
 7755:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 7756:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 7757:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 7758: 		split(/:/,$response);
 7759:             %{$codes} = (%{$codes},&str2hash($codes_str));
 7760:             push(@{$codetitles},&str2array($codetitles_str));
 7761:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 7762:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 7763:             $ok_response = 1;
 7764:         }
 7765:     }
 7766:     if ($ok_response) {
 7767:         return 'ok';
 7768:     } else {
 7769:         return $response;
 7770:     }
 7771: }
 7772: 
 7773: sub auto_instcode_defaults {
 7774:     my ($domain,$returnhash,$code_order) = @_;
 7775:     my @homeservers;
 7776: 
 7777:     my %servers = &get_servers($domain,'library');
 7778:     foreach my $tryserver (keys(%servers)) {
 7779: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7780: 	    push(@homeservers,$tryserver);
 7781: 	}
 7782:     }
 7783: 
 7784:     my $response;
 7785:     foreach my $server (@homeservers) {
 7786:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 7787:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 7788: 	
 7789: 	foreach my $pair (split(/\&/,$response)) {
 7790: 	    my ($name,$value)=split(/\=/,$pair);
 7791: 	    if ($name eq 'code_order') {
 7792: 		@{$code_order} = split(/\&/,&unescape($value));
 7793: 	    } else {
 7794: 		$returnhash->{&unescape($name)}=&unescape($value);
 7795: 	    }
 7796: 	}
 7797: 	return 'ok';
 7798:     }
 7799: 
 7800:     return $response;
 7801: }
 7802: 
 7803: sub auto_possible_instcodes {
 7804:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
 7805:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
 7806:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 7807:         return;
 7808:     }
 7809:     my (@homeservers,$uhome);
 7810:     if (defined(&domain($domain,'primary'))) {
 7811:         $uhome=&domain($domain,'primary');
 7812:         push(@homeservers,&domain($domain,'primary'));
 7813:     } else {
 7814:         my %servers = &get_servers($domain,'library');
 7815:         foreach my $tryserver (keys(%servers)) {
 7816:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7817:                 push(@homeservers,$tryserver);
 7818:             }
 7819:         }
 7820:     }
 7821:     my $response;
 7822:     foreach my $server (@homeservers) {
 7823:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
 7824:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 7825:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
 7826:             split(':',$response);
 7827:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
 7828:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
 7829:         foreach my $item (split('&',$cat_title)) {   
 7830:             my ($name,$value)=split('=',$item);
 7831:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
 7832:         }
 7833:         foreach my $item (split('&',$cat_order)) {
 7834:             my ($name,$value)=split('=',$item);
 7835:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
 7836:         }
 7837:         return 'ok';
 7838:     }
 7839:     return $response;
 7840: }
 7841: 
 7842: sub auto_courserequest_checks {
 7843:     my ($dom) = @_;
 7844:     my ($homeserver,%validations);
 7845:     if ($dom =~ /^$match_domain$/) {
 7846:         $homeserver = &domain($dom,'primary');
 7847:     }
 7848:     unless ($homeserver eq 'no_host') {
 7849:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
 7850:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 7851:             my @items = split(/&/,$response);
 7852:             foreach my $item (@items) {
 7853:                 my ($key,$value) = split('=',$item);
 7854:                 $validations{&unescape($key)} = &thaw_unescape($value);
 7855:             }
 7856:         }
 7857:     }
 7858:     return %validations; 
 7859: }
 7860: 
 7861: sub auto_courserequest_validation {
 7862:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
 7863:     my ($homeserver,$response);
 7864:     if ($dom =~ /^$match_domain$/) {
 7865:         $homeserver = &domain($dom,'primary');
 7866:     }
 7867:     unless ($homeserver eq 'no_host') {
 7868:         my $customdata;
 7869:         if (ref($custominfo) eq 'HASH') {
 7870:             $customdata = &freeze_escape($custominfo);
 7871:         }
 7872:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
 7873:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
 7874:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
 7875:                                     $customdata,$homeserver));
 7876:     }
 7877:     return $response;
 7878: }
 7879: 
 7880: sub auto_validate_class_sec {
 7881:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 7882:     my $homeserver = &homeserver($cnum,$cdom);
 7883:     my $ownerlist;
 7884:     if (ref($owners) eq 'ARRAY') {
 7885:         $ownerlist = join(',',@{$owners});
 7886:     } else {
 7887:         $ownerlist = $owners;
 7888:     }
 7889:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 7890:                         &escape($ownerlist).':'.$cdom,$homeserver);
 7891:     return $response;
 7892: }
 7893: 
 7894: sub auto_crsreq_update {
 7895:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
 7896:         $code,$inbound) = @_;
 7897:     my ($homeserver,%crsreqresponse);
 7898:     if ($cdom =~ /^$match_domain$/) {
 7899:         $homeserver = &domain($cdom,'primary');
 7900:     }
 7901:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
 7902:         my $info;
 7903:         if (ref($inbound) eq 'HASH') {
 7904:             $info = &freeze_escape($inbound);
 7905:         }
 7906:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
 7907:                             ':'.&escape($action).':'.&escape($ownername).':'.
 7908:                             &escape($ownerdomain).':'.&escape($fullname).':'.
 7909:                             &escape($title).':'.&escape($code).':'.$info,$homeserver);
 7910:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 7911:             my @items = split(/&/,$response);
 7912:             foreach my $item (@items) {
 7913:                 my ($key,$value) = split('=',$item);
 7914:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
 7915:             }
 7916:         }
 7917:     }
 7918:     return \%crsreqresponse;
 7919: }
 7920: 
 7921: # ------------------------------------------------------- Course Group routines
 7922: 
 7923: sub get_coursegroups {
 7924:     my ($cdom,$cnum,$group,$namespace) = @_;
 7925:     return(&dump($namespace,$cdom,$cnum,$group));
 7926: }
 7927: 
 7928: sub modify_coursegroup {
 7929:     my ($cdom,$cnum,$groupsettings) = @_;
 7930:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 7931: }
 7932: 
 7933: sub toggle_coursegroup_status {
 7934:     my ($cdom,$cnum,$group,$action) = @_;
 7935:     my ($from_namespace,$to_namespace);
 7936:     if ($action eq 'delete') {
 7937:         $from_namespace = 'coursegroups';
 7938:         $to_namespace = 'deleted_groups';
 7939:     } else {
 7940:         $from_namespace = 'deleted_groups';
 7941:         $to_namespace = 'coursegroups';
 7942:     }
 7943:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 7944:     if (my $tmp = &error(%curr_group)) {
 7945:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 7946:         return ('read error',$tmp);
 7947:     } else {
 7948:         my %savedsettings = %curr_group; 
 7949:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 7950:         my $deloutcome;
 7951:         if ($result eq 'ok') {
 7952:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 7953:         } else {
 7954:             return ('write error',$result);
 7955:         }
 7956:         if ($deloutcome eq 'ok') {
 7957:             return 'ok';
 7958:         } else {
 7959:             return ('delete error',$deloutcome);
 7960:         }
 7961:     }
 7962: }
 7963: 
 7964: sub modify_group_roles {
 7965:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 7966:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 7967:     my $role = 'gr/'.&escape($userprivs);
 7968:     my ($uname,$udom) = split(/:/,$user);
 7969:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 7970:     if ($result eq 'ok') {
 7971:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 7972:     }
 7973:     return $result;
 7974: }
 7975: 
 7976: sub modify_coursegroup_membership {
 7977:     my ($cdom,$cnum,$membership) = @_;
 7978:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 7979:     return $result;
 7980: }
 7981: 
 7982: sub get_active_groups {
 7983:     my ($udom,$uname,$cdom,$cnum) = @_;
 7984:     my $now = time;
 7985:     my %groups = ();
 7986:     foreach my $key (keys(%env)) {
 7987:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 7988:             my ($start,$end) = split(/\./,$env{$key});
 7989:             if (($end!=0) && ($end<$now)) { next; }
 7990:             if (($start!=0) && ($start>$now)) { next; }
 7991:             if ($1 eq $cdom && $2 eq $cnum) {
 7992:                 $groups{$3} = $env{$key} ;
 7993:             }
 7994:         }
 7995:     }
 7996:     return %groups;
 7997: }
 7998: 
 7999: sub get_group_membership {
 8000:     my ($cdom,$cnum,$group) = @_;
 8001:     return(&dump('groupmembership',$cdom,$cnum,$group));
 8002: }
 8003: 
 8004: sub get_users_groups {
 8005:     my ($udom,$uname,$courseid) = @_;
 8006:     my @usersgroups;
 8007:     my $cachetime=1800;
 8008: 
 8009:     my $hashid="$udom:$uname:$courseid";
 8010:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 8011:     if (defined($cached)) {
 8012:         @usersgroups = split(/:/,$grouplist);
 8013:     } else {  
 8014:         $grouplist = '';
 8015:         my $courseurl = &courseid_to_courseurl($courseid);
 8016:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 8017:         my $access_end = $env{'course.'.$courseid.
 8018:                               '.default_enrollment_end_date'};
 8019:         my $now = time;
 8020:         foreach my $key (keys(%roleshash)) {
 8021:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 8022:                 my $group = $1;
 8023:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 8024:                     my $start = $2;
 8025:                     my $end = $1;
 8026:                     if ($start == -1) { next; } # deleted from group
 8027:                     if (($start!=0) && ($start>$now)) { next; }
 8028:                     if (($end!=0) && ($end<$now)) {
 8029:                         if ($access_end && $access_end < $now) {
 8030:                             if ($access_end - $end < 86400) {
 8031:                                 push(@usersgroups,$group);
 8032:                             }
 8033:                         }
 8034:                         next;
 8035:                     }
 8036:                     push(@usersgroups,$group);
 8037:                 }
 8038:             }
 8039:         }
 8040:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 8041:         $grouplist = join(':',@usersgroups);
 8042:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 8043:     }
 8044:     return @usersgroups;
 8045: }
 8046: 
 8047: sub devalidate_getgroups_cache {
 8048:     my ($udom,$uname,$cdom,$cnum)=@_;
 8049:     my $courseid = $cdom.'_'.$cnum;
 8050: 
 8051:     my $hashid="$udom:$uname:$courseid";
 8052:     &devalidate_cache_new('getgroups',$hashid);
 8053: }
 8054: 
 8055: # ------------------------------------------------------------------ Plain Text
 8056: 
 8057: sub plaintext {
 8058:     my ($short,$type,$cid,$forcedefault) = @_;
 8059:     if ($short =~ m{^cr/}) {
 8060: 	return (split('/',$short))[-1];
 8061:     }
 8062:     if (!defined($cid)) {
 8063:         $cid = $env{'request.course.id'};
 8064:     }
 8065:     my %rolenames = (
 8066:                       Course    => 'std',
 8067:                       Community => 'alt1',
 8068:                     );
 8069:     if ($cid ne '') {
 8070:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
 8071:             unless ($forcedefault) {
 8072:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
 8073:                 &Apache::lonlocal::mt_escape(\$roletext);
 8074:                 return &Apache::lonlocal::mt($roletext);
 8075:             }
 8076:         }
 8077:     }
 8078:     if ((defined($type)) && (defined($rolenames{$type})) &&
 8079:         (defined($rolenames{$type})) && 
 8080:         (defined($prp{$short}{$rolenames{$type}}))) {
 8081:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 8082:     } elsif ($cid ne '') {
 8083:         my $crstype = $env{'course.'.$cid.'.type'};
 8084:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
 8085:             (defined($prp{$short}{$rolenames{$crstype}}))) {
 8086:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
 8087:         }
 8088:     }
 8089:     return &Apache::lonlocal::mt($prp{$short}{'std'});
 8090: }
 8091: 
 8092: # ----------------------------------------------------------------- Assign Role
 8093: 
 8094: sub assignrole {
 8095:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
 8096:         $context)=@_;
 8097:     my $mrole;
 8098:     if ($role =~ /^cr\//) {
 8099:         my $cwosec=$url;
 8100:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 8101: 	unless (&allowed('ccr',$cwosec)) {
 8102:            my $refused = 1;
 8103:            if ($context eq 'requestcourses') {
 8104:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 8105:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
 8106:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
 8107:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 8108:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 8109:                            if ($crsenv{'internal.courseowner'} eq
 8110:                                $env{'user.name'}.':'.$env{'user.domain'}) {
 8111:                                $refused = '';
 8112:                            }
 8113:                        }
 8114:                    }
 8115:                }
 8116:            }
 8117:            if ($refused) {
 8118:                &logthis('Refused custom assignrole: '.
 8119:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
 8120:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
 8121:                return 'refused';
 8122:            }
 8123:         }
 8124:         $mrole='cr';
 8125:     } elsif ($role =~ /^gr\//) {
 8126:         my $cwogrp=$url;
 8127:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 8128:         unless (&allowed('mdg',$cwogrp)) {
 8129:             &logthis('Refused group assignrole: '.
 8130:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 8131:                     $env{'user.name'}.' at '.$env{'user.domain'});
 8132:             return 'refused';
 8133:         }
 8134:         $mrole='gr';
 8135:     } else {
 8136:         my $cwosec=$url;
 8137:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 8138:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 8139:             my $refused;
 8140:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 8141:                 if (!(&allowed('c'.$role,$url))) {
 8142:                     $refused = 1;
 8143:                 }
 8144:             } else {
 8145:                 $refused = 1;
 8146:             }
 8147:             if ($refused) {
 8148:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 8149:                 if (!$selfenroll && $context eq 'course') {
 8150:                     my %crsenv;
 8151:                     if ($role eq 'cc' || $role eq 'co') {
 8152:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 8153:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
 8154:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
 8155:                                 if ($crsenv{'internal.courseowner'} eq 
 8156:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 8157:                                     $refused = '';
 8158:                                 }
 8159:                             }
 8160:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
 8161:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
 8162:                                 if ($crsenv{'internal.courseowner'} eq 
 8163:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 8164:                                     $refused = '';
 8165:                                 }
 8166:                             }
 8167:                         }
 8168:                     }
 8169:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 8170:                     $refused = '';
 8171:                 } elsif ($context eq 'requestcourses') {
 8172:                     my @possroles = ('st','ta','ep','in','cc','co');
 8173:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
 8174:                         my $wrongcc;
 8175:                         if ($cnum =~ /^$match_community$/) {
 8176:                             $wrongcc = 1 if ($role eq 'cc');
 8177:                         } else {
 8178:                             $wrongcc = 1 if ($role eq 'co');
 8179:                         }
 8180:                         unless ($wrongcc) {
 8181:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 8182:                             if ($crsenv{'internal.courseowner'} eq 
 8183:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
 8184:                                 $refused = '';
 8185:                             }
 8186:                         }
 8187:                     }
 8188:                 } elsif ($context eq 'requestauthor') {
 8189:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
 8190:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
 8191:                         if ($env{'environment.requestauthor'} eq 'automatic') {
 8192:                             $refused = '';
 8193:                         } else {
 8194:                             my %domdefaults = &get_domain_defaults($udom);
 8195:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
 8196:                                 my $checkbystatus;
 8197:                                 if ($env{'user.adv'}) { 
 8198:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
 8199:                                     if ($disposition eq 'automatic') {
 8200:                                         $refused = '';
 8201:                                     } elsif ($disposition eq '') {
 8202:                                         $checkbystatus = 1;
 8203:                                     } 
 8204:                                 } else {
 8205:                                     $checkbystatus = 1;
 8206:                                 }
 8207:                                 if ($checkbystatus) {
 8208:                                     if ($env{'environment.inststatus'}) {
 8209:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
 8210:                                         foreach my $type (@inststatuses) {
 8211:                                             if (($type ne '') &&
 8212:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
 8213:                                                 $refused = '';
 8214:                                             }
 8215:                                         }
 8216:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
 8217:                                         $refused = '';
 8218:                                     }
 8219:                                 }
 8220:                             }
 8221:                         }
 8222:                     }
 8223:                 }
 8224:                 if ($refused) {
 8225:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 8226:                              ' '.$role.' '.$end.' '.$start.' by '.
 8227: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
 8228:                     return 'refused';
 8229:                 }
 8230:             }
 8231:         } elsif ($role eq 'au') {
 8232:             if ($url ne '/'.$udom.'/') {
 8233:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
 8234:                          ' to assign author role for '.$uname.':'.$udom.
 8235:                          ' in domain: '.$url.' refused (wrong domain).');
 8236:                 return 'refused';
 8237:             }
 8238:         }
 8239:         $mrole=$role;
 8240:     }
 8241:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 8242:                 "$udom:$uname:$url".'_'."$mrole=$role";
 8243:     if ($end) { $command.='_'.$end; }
 8244:     if ($start) {
 8245: 	if ($end) { 
 8246:            $command.='_'.$start; 
 8247:         } else {
 8248:            $command.='_0_'.$start;
 8249:         }
 8250:     }
 8251:     my $origstart = $start;
 8252:     my $origend = $end;
 8253:     my $delflag;
 8254: # actually delete
 8255:     if ($deleteflag) {
 8256: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 8257: # modify command to delete the role
 8258:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 8259:                 "$udom:$uname:$url".'_'."$mrole";
 8260: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 8261: # set start and finish to negative values for userrolelog
 8262:            $start=-1;
 8263:            $end=-1;
 8264:            $delflag = 1;
 8265:         }
 8266:     }
 8267: # send command
 8268:     my $answer=&reply($command,&homeserver($uname,$udom));
 8269: # log new user role if status is ok
 8270:     if ($answer eq 'ok') {
 8271: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 8272:         if (($role eq 'cc') || ($role eq 'in') ||
 8273:             ($role eq 'ep') || ($role eq 'ad') ||
 8274:             ($role eq 'ta') || ($role eq 'st') ||
 8275:             ($role=~/^cr/) || ($role eq 'gr') ||
 8276:             ($role eq 'co')) {
 8277: # for course roles, perform group memberships changes triggered by role change.
 8278:             unless ($role =~ /^gr/) {
 8279:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 8280:                                                  $origstart,$selfenroll,$context);
 8281:             }
 8282:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 8283:                            $selfenroll,$context);
 8284:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
 8285:                  ($role eq 'au') || ($role eq 'dc')) {
 8286:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 8287:                            $context);
 8288:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
 8289:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 8290:                              $context); 
 8291:         }
 8292:         if ($role eq 'cc') {
 8293:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
 8294:         }
 8295:     }
 8296:     return $answer;
 8297: }
 8298: 
 8299: sub autoupdate_coowners {
 8300:     my ($url,$end,$start,$uname,$udom) = @_;
 8301:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
 8302:     if (($cdom ne '') && ($cnum ne '')) {
 8303:         my $now = time;
 8304:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
 8305:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
 8306:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
 8307:             my $instcode = $coursehash{'internal.coursecode'};
 8308:             if ($instcode ne '') {
 8309:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
 8310:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
 8311:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
 8312:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
 8313:                         if ($result eq 'valid') {
 8314:                             if ($coursehash{'internal.co-owners'}) {
 8315:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 8316:                                     push(@newcoowners,$coowner);
 8317:                                 }
 8318:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
 8319:                                     push(@newcoowners,$uname.':'.$udom);
 8320:                                 }
 8321:                                 @newcoowners = sort(@newcoowners);
 8322:                             } else {
 8323:                                 push(@newcoowners,$uname.':'.$udom);
 8324:                             }
 8325:                         } else {
 8326:                             if ($coursehash{'internal.co-owners'}) {
 8327:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 8328:                                     unless ($coowner eq $uname.':'.$udom) {
 8329:                                         push(@newcoowners,$coowner);
 8330:                                     }
 8331:                                 }
 8332:                                 unless (@newcoowners > 0) {
 8333:                                     $delcoowners = 1;
 8334:                                     $coowners = '';
 8335:                                 }
 8336:                             }
 8337:                         }
 8338:                         if (@newcoowners || $delcoowners) {
 8339:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
 8340:                                             $delcoowners,@newcoowners);
 8341:                         }
 8342:                     }
 8343:                 }
 8344:             }
 8345:         }
 8346:     }
 8347: }
 8348: 
 8349: sub store_coowners {
 8350:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
 8351:     my $cid = $cdom.'_'.$cnum;
 8352:     my ($coowners,$delresult,$putresult);
 8353:     if (@newcoowners) {
 8354:         $coowners = join(',',@newcoowners);
 8355:         my %coownershash = (
 8356:                             'internal.co-owners' => $coowners,
 8357:                            );
 8358:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
 8359:         if ($putresult eq 'ok') {
 8360:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
 8361:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
 8362:             }
 8363:         }
 8364:     }
 8365:     if ($delcoowners) {
 8366:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
 8367:         if ($delresult eq 'ok') {
 8368:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
 8369:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
 8370:             }
 8371:         }
 8372:     }
 8373:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
 8374:         my %crsinfo =
 8375:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 8376:         if (ref($crsinfo{$cid}) eq 'HASH') {
 8377:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
 8378:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
 8379:         }
 8380:     }
 8381: }
 8382: 
 8383: # -------------------------------------------------- Modify user authentication
 8384: # Overrides without validation
 8385: 
 8386: sub modifyuserauth {
 8387:     my ($udom,$uname,$umode,$upass)=@_;
 8388:     my $uhome=&homeserver($uname,$udom);
 8389:     unless (&allowed('mau',$udom)) { return 'refused'; }
 8390:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 8391:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 8392:              ' in domain '.$env{'request.role.domain'});  
 8393:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 8394: 		     &escape($upass),$uhome);
 8395:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 8396:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 8397:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 8398:     &log($udom,,$uname,$uhome,
 8399:         'Authentication changed by '.$env{'user.domain'}.', '.
 8400:                                      $env{'user.name'}.', '.$umode.
 8401:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 8402:     unless ($reply eq 'ok') {
 8403:         &logthis('Authentication mode error: '.$reply);
 8404: 	return 'error: '.$reply;
 8405:     }   
 8406:     return 'ok';
 8407: }
 8408: 
 8409: # --------------------------------------------------------------- Modify a user
 8410: 
 8411: sub modifyuser {
 8412:     my ($udom,    $uname, $uid,
 8413:         $umode,   $upass, $first,
 8414:         $middle,  $last,  $gene,
 8415:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
 8416:     $udom= &LONCAPA::clean_domain($udom);
 8417:     $uname=&LONCAPA::clean_username($uname);
 8418:     my $showcandelete = 'none';
 8419:     if (ref($candelete) eq 'ARRAY') {
 8420:         if (@{$candelete} > 0) {
 8421:             $showcandelete = join(', ',@{$candelete});
 8422:         }
 8423:     }
 8424:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 8425:              $umode.', '.$first.', '.$middle.', '.
 8426: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
 8427:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 8428:                                      ' desiredhome not specified'). 
 8429:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 8430:              ' in domain '.$env{'request.role.domain'});
 8431:     my $uhome=&homeserver($uname,$udom,'true');
 8432:     my $newuser;
 8433:     if ($uhome eq 'no_host') {
 8434:         $newuser = 1;
 8435:     }
 8436: # ----------------------------------------------------------------- Create User
 8437:     if (($uhome eq 'no_host') && 
 8438: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 8439:         my $unhome='';
 8440:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 8441:             $unhome = $desiredhome;
 8442: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 8443: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 8444:         } else { # load balancing routine for determining $unhome
 8445:             my $loadm=10000000;
 8446: 	    my %servers = &get_servers($udom,'library');
 8447: 	    foreach my $tryserver (keys(%servers)) {
 8448: 		my $answer=reply('load',$tryserver);
 8449: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 8450: 		    $loadm=$answer;
 8451: 		    $unhome=$tryserver;
 8452: 		}
 8453: 	    }
 8454:         }
 8455:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 8456: 	    return 'error: unable to find a home server for '.$uname.
 8457:                    ' in domain '.$udom;
 8458:         }
 8459:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 8460:                          &escape($upass),$unhome);
 8461: 	unless ($reply eq 'ok') {
 8462:             return 'error: '.$reply;
 8463:         }   
 8464:         $uhome=&homeserver($uname,$udom,'true');
 8465:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 8466: 	    return 'error: unable verify users home machine.';
 8467:         }
 8468:     }   # End of creation of new user
 8469: # ---------------------------------------------------------------------- Add ID
 8470:     if ($uid) {
 8471:        $uid=~tr/A-Z/a-z/;
 8472:        my %uidhash=&idrget($udom,$uname);
 8473:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 8474:          && (!$forceid)) {
 8475: 	  unless ($uid eq $uidhash{$uname}) {
 8476: 	      return 'error: user id "'.$uid.'" does not match '.
 8477:                   'current user id "'.$uidhash{$uname}.'".';
 8478:           }
 8479:        } else {
 8480: 	  &idput($udom,($uname => $uid));
 8481:        }
 8482:     }
 8483: # -------------------------------------------------------------- Add names, etc
 8484:     my @tmp=&get('environment',
 8485: 		   ['firstname','middlename','lastname','generation','id',
 8486:                     'permanentemail','inststatus'],
 8487: 		   $udom,$uname);
 8488:     my (%names,%oldnames);
 8489:     if ($tmp[0] =~ m/^error:.*/) { 
 8490:         %names=(); 
 8491:     } else {
 8492:         %names = @tmp;
 8493:         %oldnames = %names;
 8494:     }
 8495: #
 8496: # If name, email and/or uid are blank (e.g., because an uploaded file
 8497: # of users did not contain them), do not overwrite existing values
 8498: # unless field is in $candelete array ref.  
 8499: #
 8500: 
 8501:     my @fields = ('firstname','middlename','lastname','generation',
 8502:                   'permanentemail','id');
 8503:     my %newvalues;
 8504:     if (ref($candelete) eq 'ARRAY') {
 8505:         foreach my $field (@fields) {
 8506:             if (grep(/^\Q$field\E$/,@{$candelete})) {
 8507:                 if ($field eq 'firstname') {
 8508:                     $names{$field} = $first;
 8509:                 } elsif ($field eq 'middlename') {
 8510:                     $names{$field} = $middle;
 8511:                 } elsif ($field eq 'lastname') {
 8512:                     $names{$field} = $last;
 8513:                 } elsif ($field eq 'generation') { 
 8514:                     $names{$field} = $gene;
 8515:                 } elsif ($field eq 'permanentemail') {
 8516:                     $names{$field} = $email;
 8517:                 } elsif ($field eq 'id') {
 8518:                     $names{$field}  = $uid;
 8519:                 }
 8520:             }
 8521:         }
 8522:     }
 8523:     if ($first)  { $names{'firstname'}  = $first; }
 8524:     if (defined($middle)) { $names{'middlename'} = $middle; }
 8525:     if ($last)   { $names{'lastname'}   = $last; }
 8526:     if (defined($gene))   { $names{'generation'} = $gene; }
 8527:     if ($email) {
 8528:        $email=~s/[^\w\@\.\-\,]//gs;
 8529:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
 8530:     }
 8531:     if ($uid) { $names{'id'}  = $uid; }
 8532:     if (defined($inststatus)) {
 8533:         $names{'inststatus'} = '';
 8534:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
 8535:         if (ref($usertypes) eq 'HASH') {
 8536:             my @okstatuses; 
 8537:             foreach my $item (split(/:/,$inststatus)) {
 8538:                 if (defined($usertypes->{$item})) {
 8539:                     push(@okstatuses,$item);  
 8540:                 }
 8541:             }
 8542:             if (@okstatuses) {
 8543:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
 8544:             }
 8545:         }
 8546:     }
 8547:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
 8548:                  $umode.', '.$first.', '.$middle.', '.
 8549:                  $last.', '.$gene.', '.$email.', '.$inststatus;
 8550:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
 8551:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
 8552:     } else {
 8553:         $logmsg .= ' during self creation';
 8554:     }
 8555:     my $changed;
 8556:     if ($newuser) {
 8557:         $changed = 1;
 8558:     } else {
 8559:         foreach my $field (@fields) {
 8560:             if ($names{$field} ne $oldnames{$field}) {
 8561:                 $changed = 1;
 8562:                 last;
 8563:             }
 8564:         }
 8565:     }
 8566:     unless ($changed) {
 8567:         $logmsg = 'No changes in user information needed for: '.$logmsg;
 8568:         &logthis($logmsg);
 8569:         return 'ok';
 8570:     }
 8571:     my $reply = &put('environment', \%names, $udom,$uname);
 8572:     if ($reply ne 'ok') { 
 8573:         return 'error: '.$reply;
 8574:     }
 8575:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
 8576:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
 8577:     }
 8578:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
 8579:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 8580:     $logmsg = 'Success modifying user '.$logmsg;
 8581:     &logthis($logmsg);
 8582:     return 'ok';
 8583: }
 8584: 
 8585: # -------------------------------------------------------------- Modify student
 8586: 
 8587: sub modifystudent {
 8588:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 8589:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
 8590:         $selfenroll,$context,$inststatus,$credits)=@_;
 8591:     if (!$cid) {
 8592: 	unless ($cid=$env{'request.course.id'}) {
 8593: 	    return 'not_in_class';
 8594: 	}
 8595:     }
 8596: # --------------------------------------------------------------- Make the user
 8597:     my $reply=&modifyuser
 8598: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 8599:          $desiredhome,$email,$inststatus);
 8600:     unless ($reply eq 'ok') { return $reply; }
 8601:     # This will cause &modify_student_enrollment to get the uid from the
 8602:     # student's environment
 8603:     $uid = undef if (!$forceid);
 8604:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 8605:                                         $gene,$usec,$end,$start,$type,$locktype,
 8606:                                         $cid,$selfenroll,$context,$credits);
 8607:     return $reply;
 8608: }
 8609: 
 8610: sub modify_student_enrollment {
 8611:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
 8612:         $locktype,$cid,$selfenroll,$context,$credits) = @_;
 8613:     my ($cdom,$cnum,$chome);
 8614:     if (!$cid) {
 8615: 	unless ($cid=$env{'request.course.id'}) {
 8616: 	    return 'not_in_class';
 8617: 	}
 8618: 	$cdom=$env{'course.'.$cid.'.domain'};
 8619: 	$cnum=$env{'course.'.$cid.'.num'};
 8620:     } else {
 8621: 	($cdom,$cnum)=split(/_/,$cid);
 8622:     }
 8623:     $chome=$env{'course.'.$cid.'.home'};
 8624:     if (!$chome) {
 8625: 	$chome=&homeserver($cnum,$cdom);
 8626:     }
 8627:     if (!$chome) { return 'unknown_course'; }
 8628:     # Make sure the user exists
 8629:     my $uhome=&homeserver($uname,$udom);
 8630:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 8631: 	return 'error: no such user';
 8632:     }
 8633:     # Get student data if we were not given enough information
 8634:     if (!defined($first)  || $first  eq '' || 
 8635:         !defined($last)   || $last   eq '' || 
 8636:         !defined($uid)    || $uid    eq '' || 
 8637:         !defined($middle) || $middle eq '' || 
 8638:         !defined($gene)   || $gene   eq '') {
 8639:         # They did not supply us with enough data to enroll the student, so
 8640:         # we need to pick up more information.
 8641:         my %tmp = &get('environment',
 8642:                        ['firstname','middlename','lastname', 'generation','id']
 8643:                        ,$udom,$uname);
 8644: 
 8645:         #foreach my $key (keys(%tmp)) {
 8646:         #    &logthis("key $key = ".$tmp{$key});
 8647:         #}
 8648:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 8649:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 8650:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 8651:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 8652:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 8653:     }
 8654:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 8655:     my $user = "$uname:$udom";
 8656:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
 8657:     my $reply=cput('classlist',
 8658: 		   {$user => 
 8659: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits) },
 8660: 		   $cdom,$cnum);
 8661:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
 8662:         &devalidate_getsection_cache($udom,$uname,$cid);
 8663:     } else { 
 8664: 	return 'error: '.$reply;
 8665:     }
 8666:     # Add student role to user
 8667:     my $uurl='/'.$cid;
 8668:     $uurl=~s/\_/\//g;
 8669:     if ($usec) {
 8670: 	$uurl.='/'.$usec;
 8671:     }
 8672:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
 8673:                              $selfenroll,$context);
 8674:     if ($result ne 'ok') {
 8675:         if ($old_entry{$user} ne '') {
 8676:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
 8677:         } else {
 8678:             $reply = &del('classlist',[$user],$cdom,$cnum);
 8679:         }
 8680:     }
 8681:     return $result; 
 8682: }
 8683: 
 8684: sub format_name {
 8685:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 8686:     my $name;
 8687:     if ($first ne 'lastname') {
 8688: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 8689:     } else {
 8690: 	if ($lastname=~/\S/) {
 8691: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 8692: 	    $name=~s/\s+,/,/;
 8693: 	} else {
 8694: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 8695: 	}
 8696:     }
 8697:     $name=~s/^\s+//;
 8698:     $name=~s/\s+$//;
 8699:     $name=~s/\s+/ /g;
 8700:     return $name;
 8701: }
 8702: 
 8703: # ------------------------------------------------- Write to course preferences
 8704: 
 8705: sub writecoursepref {
 8706:     my ($courseid,%prefs)=@_;
 8707:     $courseid=~s/^\///;
 8708:     $courseid=~s/\_/\//g;
 8709:     my ($cdomain,$cnum)=split(/\//,$courseid);
 8710:     my $chome=homeserver($cnum,$cdomain);
 8711:     if (($chome eq '') || ($chome eq 'no_host')) { 
 8712: 	return 'error: no such course';
 8713:     }
 8714:     my $cstring='';
 8715:     foreach my $pref (keys(%prefs)) {
 8716: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 8717:     }
 8718:     $cstring=~s/\&$//;
 8719:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 8720: }
 8721: 
 8722: # ---------------------------------------------------------- Make/modify course
 8723: 
 8724: sub createcourse {
 8725:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 8726:         $course_owner,$crstype,$cnum,$context,$category)=@_;
 8727:     $url=&declutter($url);
 8728:     my $cid='';
 8729:     if ($context eq 'requestcourses') {
 8730:         my $can_create = 0;
 8731:         my ($ownername,$ownerdom) = split(':',$course_owner);
 8732:         if ($udom eq $ownerdom) {
 8733:             if (&usertools_access($ownername,$ownerdom,$category,undef,
 8734:                                   $context)) {
 8735:                 $can_create = 1;
 8736:             }
 8737:         } else {
 8738:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
 8739:                                            $category);
 8740:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
 8741:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
 8742:                 if (@curr > 0) {
 8743:                     my @options = qw(approval validate autolimit);
 8744:                     my $optregex = join('|',@options);
 8745:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
 8746:                         $can_create = 1;
 8747:                     }
 8748:                 }
 8749:             }
 8750:         }
 8751:         if ($can_create) {
 8752:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
 8753:                 unless (&allowed('ccc',$udom)) {
 8754:                     return 'refused'; 
 8755:                 }
 8756:             }
 8757:         } else {
 8758:             return 'refused';
 8759:         }
 8760:     } elsif (!&allowed('ccc',$udom)) {
 8761:         return 'refused';
 8762:     }
 8763: # --------------------------------------------------------------- Get Unique ID
 8764:     my $uname;
 8765:     if ($cnum =~ /^$match_courseid$/) {
 8766:         my $chome=&homeserver($cnum,$udom,'true');
 8767:         if (($chome eq '') || ($chome eq 'no_host')) {
 8768:             $uname = $cnum;
 8769:         } else {
 8770:             $uname = &generate_coursenum($udom,$crstype);
 8771:         }
 8772:     } else {
 8773:         $uname = &generate_coursenum($udom,$crstype);
 8774:     }
 8775:     return $uname if ($uname =~ /^error/);
 8776: # -------------------------------------------------- Check supplied server name
 8777:     if (!defined($course_server)) {
 8778:         if (defined(&domain($udom,'primary'))) {
 8779:             $course_server = &domain($udom,'primary');
 8780:         } else {
 8781:             $course_server = $env{'user.home'}; 
 8782:         }
 8783:     }
 8784:     my %host_servers =
 8785:         &Apache::lonnet::get_servers($udom,'library');
 8786:     unless ($host_servers{$course_server}) {
 8787:         return 'error: invalid home server for course: '.$course_server;
 8788:     }
 8789: # ------------------------------------------------------------- Make the course
 8790:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 8791:                       $course_server);
 8792:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 8793:     my $uhome=&homeserver($uname,$udom,'true');
 8794:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 8795: 	return 'error: no such course';
 8796:     }
 8797: # ----------------------------------------------------------------- Course made
 8798: # log existence
 8799:     my $now = time;
 8800:     my $newcourse = {
 8801:                     $udom.'_'.$uname => {
 8802:                                      description => $description,
 8803:                                      inst_code   => $inst_code,
 8804:                                      owner       => $course_owner,
 8805:                                      type        => $crstype,
 8806:                                      creator     => $env{'user.name'}.':'.
 8807:                                                     $env{'user.domain'},
 8808:                                      created     => $now,
 8809:                                      context     => $context,
 8810:                                                 },
 8811:                     };
 8812:     &courseidput($udom,$newcourse,$uhome,'notime');
 8813: # set toplevel url
 8814:     my $topurl=$url;
 8815:     unless ($nonstandard) {
 8816: # ------------------------------------------ For standard courses, make top url
 8817:         my $mapurl=&clutter($url);
 8818:         if ($mapurl eq '/res/') { $mapurl=''; }
 8819:         $env{'form.initmap'}=(<<ENDINITMAP);
 8820: <map>
 8821: <resource id="1" type="start"></resource>
 8822: <resource id="2" src="$mapurl"></resource>
 8823: <resource id="3" type="finish"></resource>
 8824: <link index="1" from="1" to="2"></link>
 8825: <link index="2" from="2" to="3"></link>
 8826: </map>
 8827: ENDINITMAP
 8828:         $topurl=&declutter(
 8829:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 8830:                           );
 8831:     }
 8832: # ----------------------------------------------------------- Write preferences
 8833:     &writecoursepref($udom.'_'.$uname,
 8834:                      ('description'              => $description,
 8835:                       'url'                      => $topurl,
 8836:                       'internal.creator'         => $env{'user.name'}.':'.
 8837:                                                     $env{'user.domain'},
 8838:                       'internal.created'         => $now,
 8839:                       'internal.creationcontext' => $context)
 8840:                     );
 8841:     return '/'.$udom.'/'.$uname;
 8842: }
 8843: 
 8844: # ------------------------------------------------------------------- Create ID
 8845: sub generate_coursenum {
 8846:     my ($udom,$crstype) = @_;
 8847:     my $domdesc = &domain($udom);
 8848:     return 'error: invalid domain' if ($domdesc eq '');
 8849:     my $first;
 8850:     if ($crstype eq 'Community') {
 8851:         $first = '0';
 8852:     } else {
 8853:         $first = int(1+rand(9)); 
 8854:     } 
 8855:     my $uname=$first.
 8856:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 8857:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
 8858:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 8859: # ----------------------------------------------- Make sure that does not exist
 8860:     my $uhome=&homeserver($uname,$udom,'true');
 8861:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
 8862:         if ($crstype eq 'Community') {
 8863:             $first = '0';
 8864:         } else {
 8865:             $first = int(1+rand(9));
 8866:         }
 8867:         $uname=$first.
 8868:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 8869:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
 8870:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 8871:         $uhome=&homeserver($uname,$udom,'true');
 8872:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
 8873:             return 'error: unable to generate unique course-ID';
 8874:         }
 8875:     }
 8876:     return $uname;
 8877: }
 8878: 
 8879: sub is_course {
 8880:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
 8881:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
 8882: 
 8883:     return unless $cdom and $cnum;
 8884: 
 8885:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
 8886:         '.');
 8887: 
 8888:     return unless(exists($courses{$cdom.'_'.$cnum}));
 8889:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
 8890: }
 8891: 
 8892: sub store_userdata {
 8893:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
 8894:     my $result;
 8895:     if ($datakey ne '') {
 8896:         if (ref($storehash) eq 'HASH') {
 8897:             if ($udom eq '' || $uname eq '') {
 8898:                 $udom = $env{'user.domain'};
 8899:                 $uname = $env{'user.name'};
 8900:             }
 8901:             my $uhome=&homeserver($uname,$udom);
 8902:             if (($uhome eq '') || ($uhome eq 'no_host')) {
 8903:                 $result = 'error: no_host';
 8904:             } else {
 8905:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
 8906:                 $storehash->{'host'} = $perlvar{'lonHostID'};
 8907: 
 8908:                 my $namevalue='';
 8909:                 foreach my $key (keys(%{$storehash})) {
 8910:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 8911:                 }
 8912:                 $namevalue=~s/\&$//;
 8913:                 unless ($namespace eq 'courserequests') {
 8914:                     $datakey = &escape($datakey);
 8915:                 }
 8916:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
 8917:                                   $namevalue,$uhome);
 8918:             }
 8919:         } else {
 8920:             $result = 'error: data to store was not a hash reference'; 
 8921:         }
 8922:     } else {
 8923:         $result= 'error: invalid requestkey'; 
 8924:     }
 8925:     return $result;
 8926: }
 8927: 
 8928: # ---------------------------------------------------------- Assign Custom Role
 8929: 
 8930: sub assigncustomrole {
 8931:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
 8932:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 8933:                        $end,$start,$deleteflag,$selfenroll,$context);
 8934: }
 8935: 
 8936: # ----------------------------------------------------------------- Revoke Role
 8937: 
 8938: sub revokerole {
 8939:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
 8940:     my $now=time;
 8941:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
 8942: }
 8943: 
 8944: # ---------------------------------------------------------- Revoke Custom Role
 8945: 
 8946: sub revokecustomrole {
 8947:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
 8948:     my $now=time;
 8949:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 8950:            $deleteflag,$selfenroll,$context);
 8951: }
 8952: 
 8953: # ------------------------------------------------------------ Disk usage
 8954: sub diskusage {
 8955:     my ($udom,$uname,$directorypath,$getpropath)=@_;
 8956:     $directorypath =~ s/\/$//;
 8957:     my $listing=&reply('du2:'.&escape($directorypath).':'
 8958:                        .&escape($getpropath).':'.&escape($uname).':'
 8959:                        .&escape($udom),homeserver($uname,$udom));
 8960:     if ($listing eq 'unknown_cmd') {
 8961:         if ($getpropath) {
 8962:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
 8963:         }
 8964:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
 8965:     }
 8966:     return $listing;
 8967: }
 8968: 
 8969: sub is_locked {
 8970:     my ($file_name, $domain, $user, $which) = @_;
 8971:     my @check;
 8972:     my $is_locked;
 8973:     push (@check,$file_name);
 8974:     my %locked = &get('file_permissions',\@check,
 8975: 		      $env{'user.domain'},$env{'user.name'});
 8976:     my ($tmp)=keys(%locked);
 8977:     if ($tmp=~/^error:/) { undef(%locked); }
 8978:     
 8979:     if (ref($locked{$file_name}) eq 'ARRAY') {
 8980:         $is_locked = 'false';
 8981:         foreach my $entry (@{$locked{$file_name}}) {
 8982:            if (ref($entry) eq 'ARRAY') {
 8983:                $is_locked = 'true';
 8984:                if (ref($which) eq 'ARRAY') {
 8985:                    push(@{$which},$entry);
 8986:                } else {
 8987:                    last;
 8988:                }
 8989:            }
 8990:        }
 8991:     } else {
 8992:         $is_locked = 'false';
 8993:     }
 8994:     return $is_locked;
 8995: }
 8996: 
 8997: sub declutter_portfile {
 8998:     my ($file) = @_;
 8999:     $file =~ s{^(/portfolio/|portfolio/)}{/};
 9000:     return $file;
 9001: }
 9002: 
 9003: # ------------------------------------------------------------- Mark as Read Only
 9004: 
 9005: sub mark_as_readonly {
 9006:     my ($domain,$user,$files,$what) = @_;
 9007:     my %current_permissions = &dump('file_permissions',$domain,$user);
 9008:     my ($tmp)=keys(%current_permissions);
 9009:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 9010:     foreach my $file (@{$files}) {
 9011: 	$file = &declutter_portfile($file);
 9012:         push(@{$current_permissions{$file}},$what);
 9013:     }
 9014:     &put('file_permissions',\%current_permissions,$domain,$user);
 9015:     return;
 9016: }
 9017: 
 9018: # ------------------------------------------------------------Save Selected Files
 9019: 
 9020: sub save_selected_files {
 9021:     my ($user, $path, @files) = @_;
 9022:     my $filename = $user."savedfiles";
 9023:     my @other_files = &files_not_in_path($user, $path);
 9024:     open (OUT, '>'.$tmpdir.$filename);
 9025:     foreach my $file (@files) {
 9026:         print (OUT $env{'form.currentpath'}.$file."\n");
 9027:     }
 9028:     foreach my $file (@other_files) {
 9029:         print (OUT $file."\n");
 9030:     }
 9031:     close (OUT);
 9032:     return 'ok';
 9033: }
 9034: 
 9035: sub clear_selected_files {
 9036:     my ($user) = @_;
 9037:     my $filename = $user."savedfiles";
 9038:     open (OUT, '>'.LONCAPA::tempdir().$filename);
 9039:     print (OUT undef);
 9040:     close (OUT);
 9041:     return ("ok");    
 9042: }
 9043: 
 9044: sub files_in_path {
 9045:     my ($user, $path) = @_;
 9046:     my $filename = $user."savedfiles";
 9047:     my %return_files;
 9048:     open (IN, '<'.LONCAPA::tempdir().$filename);
 9049:     while (my $line_in = <IN>) {
 9050:         chomp ($line_in);
 9051:         my @paths_and_file = split (m!/!, $line_in);
 9052:         my $file_part = pop (@paths_and_file);
 9053:         my $path_part = join ('/', @paths_and_file);
 9054:         $path_part.='/';
 9055:         my $path_and_file = $path_part.$file_part;
 9056:         if ($path_part eq $path) {
 9057:             $return_files{$file_part}= 'selected';
 9058:         }
 9059:     }
 9060:     close (IN);
 9061:     return (\%return_files);
 9062: }
 9063: 
 9064: # called in portfolio select mode, to show files selected NOT in current directory
 9065: sub files_not_in_path {
 9066:     my ($user, $path) = @_;
 9067:     my $filename = $user."savedfiles";
 9068:     my @return_files;
 9069:     my $path_part;
 9070:     open(IN, '<'.LONCAPA::.$filename);
 9071:     while (my $line = <IN>) {
 9072:         #ok, I know it's clunky, but I want it to work
 9073:         my @paths_and_file = split(m|/|, $line);
 9074:         my $file_part = pop(@paths_and_file);
 9075:         chomp($file_part);
 9076:         my $path_part = join('/', @paths_and_file);
 9077:         $path_part .= '/';
 9078:         my $path_and_file = $path_part.$file_part;
 9079:         if ($path_part ne $path) {
 9080:             push(@return_files, ($path_and_file));
 9081:         }
 9082:     }
 9083:     close(OUT);
 9084:     return (@return_files);
 9085: }
 9086: 
 9087: #----------------------------------------------Get portfolio file permissions
 9088: 
 9089: sub get_portfile_permissions {
 9090:     my ($domain,$user) = @_;
 9091:     my %current_permissions = &dump('file_permissions',$domain,$user);
 9092:     my ($tmp)=keys(%current_permissions);
 9093:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 9094:     return \%current_permissions;
 9095: }
 9096: 
 9097: #---------------------------------------------Get portfolio file access controls
 9098: 
 9099: sub get_access_controls {
 9100:     my ($current_permissions,$group,$file) = @_;
 9101:     my %access;
 9102:     my $real_file = $file;
 9103:     $file =~ s/\.meta$//;
 9104:     if (defined($file)) {
 9105:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
 9106:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
 9107:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
 9108:             }
 9109:         }
 9110:     } else {
 9111:         foreach my $key (keys(%{$current_permissions})) {
 9112:             if ($key =~ /\0accesscontrol$/) {
 9113:                 if (defined($group)) {
 9114:                     if ($key !~ m-^\Q$group\E/-) {
 9115:                         next;
 9116:                     }
 9117:                 }
 9118:                 my ($fullpath) = split(/\0/,$key);
 9119:                 if (ref($$current_permissions{$key}) eq 'HASH') {
 9120:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
 9121:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
 9122:                     }
 9123:                 }
 9124:             }
 9125:         }
 9126:     }
 9127:     return %access;
 9128: }
 9129: 
 9130: sub modify_access_controls {
 9131:     my ($file_name,$changes,$domain,$user)=@_;
 9132:     my ($outcome,$deloutcome);
 9133:     my %store_permissions;
 9134:     my %new_values;
 9135:     my %new_control;
 9136:     my %translation;
 9137:     my @deletions = ();
 9138:     my $now = time;
 9139:     if (exists($$changes{'activate'})) {
 9140:         if (ref($$changes{'activate'}) eq 'HASH') {
 9141:             my @newitems = sort(keys(%{$$changes{'activate'}}));
 9142:             my $numnew = scalar(@newitems);
 9143:             for (my $i=0; $i<$numnew; $i++) {
 9144:                 my $newkey = $newitems[$i];
 9145:                 my $newid = &Apache::loncommon::get_cgi_id();
 9146:                 if ($newkey =~ /^\d+:/) { 
 9147:                     $newkey =~ s/^(\d+)/$newid/;
 9148:                     $translation{$1} = $newid;
 9149:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
 9150:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
 9151:                     $translation{$1} = $newid;
 9152:                 }
 9153:                 $new_values{$file_name."\0".$newkey} = 
 9154:                                           $$changes{'activate'}{$newitems[$i]};
 9155:                 $new_control{$newkey} = $now;
 9156:             }
 9157:         }
 9158:     }
 9159:     my %todelete;
 9160:     my %changed_items;
 9161:     foreach my $action ('delete','update') {
 9162:         if (exists($$changes{$action})) {
 9163:             if (ref($$changes{$action}) eq 'HASH') {
 9164:                 foreach my $key (keys(%{$$changes{$action}})) {
 9165:                     my ($itemnum) = ($key =~ /^([^:]+):/);
 9166:                     if ($action eq 'delete') { 
 9167:                         $todelete{$itemnum} = 1;
 9168:                     } else {
 9169:                         $changed_items{$itemnum} = $key;
 9170:                     }
 9171:                 }
 9172:             }
 9173:         }
 9174:     }
 9175:     # get lock on access controls for file.
 9176:     my $lockhash = {
 9177:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
 9178:                                                        ':'.$env{'user.domain'},
 9179:                    }; 
 9180:     my $tries = 0;
 9181:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 9182:    
 9183:     while (($gotlock ne 'ok') && $tries <3) {
 9184:         $tries ++;
 9185:         sleep 1;
 9186:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 9187:     }
 9188:     if ($gotlock eq 'ok') {
 9189:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
 9190:         my ($tmp)=keys(%curr_permissions);
 9191:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
 9192:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
 9193:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
 9194:             if (ref($curr_controls) eq 'HASH') {
 9195:                 foreach my $control_item (keys(%{$curr_controls})) {
 9196:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
 9197:                     if (defined($todelete{$itemnum})) {
 9198:                         push(@deletions,$file_name."\0".$control_item);
 9199:                     } else {
 9200:                         if (defined($changed_items{$itemnum})) {
 9201:                             $new_control{$changed_items{$itemnum}} = $now;
 9202:                             push(@deletions,$file_name."\0".$control_item);
 9203:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
 9204:                         } else {
 9205:                             $new_control{$control_item} = $$curr_controls{$control_item};
 9206:                         }
 9207:                     }
 9208:                 }
 9209:             }
 9210:         }
 9211:         my ($group);
 9212:         if (&is_course($domain,$user)) {
 9213:             ($group,my $file) = split(/\//,$file_name,2);
 9214:         }
 9215:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
 9216:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
 9217:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
 9218:         #  remove lock
 9219:         my @del_lock = ($file_name."\0".'locked_access_records');
 9220:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
 9221:         my $sqlresult =
 9222:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
 9223:                                     $group);
 9224:     } else {
 9225:         $outcome = "error: could not obtain lockfile\n";  
 9226:     }
 9227:     return ($outcome,$deloutcome,\%new_values,\%translation);
 9228: }
 9229: 
 9230: sub make_public_indefinitely {
 9231:     my ($requrl) = @_;
 9232:     my $now = time;
 9233:     my $action = 'activate';
 9234:     my $aclnum = 0;
 9235:     if (&is_portfolio_url($requrl)) {
 9236:         my (undef,$udom,$unum,$file_name,$group) =
 9237:             &parse_portfolio_url($requrl);
 9238:         my $current_perms = &get_portfile_permissions($udom,$unum);
 9239:         my %access_controls = &get_access_controls($current_perms,
 9240:                                                    $group,$file_name);
 9241:         foreach my $key (keys(%{$access_controls{$file_name}})) {
 9242:             my ($num,$scope,$end,$start) = 
 9243:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 9244:             if ($scope eq 'public') {
 9245:                 if ($start <= $now && $end == 0) {
 9246:                     $action = 'none';
 9247:                 } else {
 9248:                     $action = 'update';
 9249:                     $aclnum = $num;
 9250:                 }
 9251:                 last;
 9252:             }
 9253:         }
 9254:         if ($action eq 'none') {
 9255:              return 'ok';
 9256:         } else {
 9257:             my %changes;
 9258:             my $newend = 0;
 9259:             my $newstart = $now;
 9260:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
 9261:             $changes{$action}{$newkey} = {
 9262:                 type => 'public',
 9263:                 time => {
 9264:                     start => $newstart,
 9265:                     end   => $newend,
 9266:                 },
 9267:             };
 9268:             my ($outcome,$deloutcome,$new_values,$translation) =
 9269:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
 9270:             return $outcome;
 9271:         }
 9272:     } else {
 9273:         return 'invalid';
 9274:     }
 9275: }
 9276: 
 9277: #------------------------------------------------------Get Marked as Read Only
 9278: 
 9279: sub get_marked_as_readonly {
 9280:     my ($domain,$user,$what,$group) = @_;
 9281:     my $current_permissions = &get_portfile_permissions($domain,$user);
 9282:     my @readonly_files;
 9283:     my $cmp1=$what;
 9284:     if (ref($what)) { $cmp1=join('',@{$what}) };
 9285:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 9286:         if (defined($group)) {
 9287:             if ($file_name !~ m-^\Q$group\E/-) {
 9288:                 next;
 9289:             }
 9290:         }
 9291:         if (ref($value) eq "ARRAY"){
 9292:             foreach my $stored_what (@{$value}) {
 9293:                 my $cmp2=$stored_what;
 9294:                 if (ref($stored_what) eq 'ARRAY') {
 9295:                     $cmp2=join('',@{$stored_what});
 9296:                 }
 9297:                 if ($cmp1 eq $cmp2) {
 9298:                     push(@readonly_files, $file_name);
 9299:                     last;
 9300:                 } elsif (!defined($what)) {
 9301:                     push(@readonly_files, $file_name);
 9302:                     last;
 9303:                 }
 9304:             }
 9305:         }
 9306:     }
 9307:     return @readonly_files;
 9308: }
 9309: #-----------------------------------------------------------Get Marked as Read Only Hash
 9310: 
 9311: sub get_marked_as_readonly_hash {
 9312:     my ($current_permissions,$group,$what) = @_;
 9313:     my %readonly_files;
 9314:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 9315:         if (defined($group)) {
 9316:             if ($file_name !~ m-^\Q$group\E/-) {
 9317:                 next;
 9318:             }
 9319:         }
 9320:         if (ref($value) eq "ARRAY"){
 9321:             foreach my $stored_what (@{$value}) {
 9322:                 if (ref($stored_what) eq 'ARRAY') {
 9323:                     foreach my $lock_descriptor(@{$stored_what}) {
 9324:                         if ($lock_descriptor eq 'graded') {
 9325:                             $readonly_files{$file_name} = 'graded';
 9326:                         } elsif ($lock_descriptor eq 'handback') {
 9327:                             $readonly_files{$file_name} = 'handback';
 9328:                         } else {
 9329:                             if (!exists($readonly_files{$file_name})) {
 9330:                                 $readonly_files{$file_name} = 'locked';
 9331:                             }
 9332:                         }
 9333:                     }
 9334:                 } 
 9335:             }
 9336:         } 
 9337:     }
 9338:     return %readonly_files;
 9339: }
 9340: # ------------------------------------------------------------ Unmark as Read Only
 9341: 
 9342: sub unmark_as_readonly {
 9343:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
 9344:     # for portfolio submissions, $what contains [$symb,$crsid] 
 9345:     my ($domain,$user,$what,$file_name,$group) = @_;
 9346:     $file_name = &declutter_portfile($file_name);
 9347:     my $symb_crs = $what;
 9348:     if (ref($what)) { $symb_crs=join('',@$what); }
 9349:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
 9350:     my ($tmp)=keys(%current_permissions);
 9351:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 9352:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
 9353:     foreach my $file (@readonly_files) {
 9354: 	my $clean_file = &declutter_portfile($file);
 9355: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
 9356: 	my $current_locks = $current_permissions{$file};
 9357:         my @new_locks;
 9358:         my @del_keys;
 9359:         if (ref($current_locks) eq "ARRAY"){
 9360:             foreach my $locker (@{$current_locks}) {
 9361:                 my $compare=$locker;
 9362:                 if (ref($locker) eq 'ARRAY') {
 9363:                     $compare=join('',@{$locker});
 9364:                     if ($compare ne $symb_crs) {
 9365:                         push(@new_locks, $locker);
 9366:                     }
 9367:                 }
 9368:             }
 9369:             if (scalar(@new_locks) > 0) {
 9370:                 $current_permissions{$file} = \@new_locks;
 9371:             } else {
 9372:                 push(@del_keys, $file);
 9373:                 &del('file_permissions',\@del_keys, $domain, $user);
 9374:                 delete($current_permissions{$file});
 9375:             }
 9376:         }
 9377:     }
 9378:     &put('file_permissions',\%current_permissions,$domain,$user);
 9379:     return;
 9380: }
 9381: 
 9382: # ------------------------------------------------------------ Directory lister
 9383: 
 9384: sub dirlist {
 9385:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
 9386:     $uri=~s/^\///;
 9387:     $uri=~s/\/$//;
 9388:     my ($udom, $uname);
 9389:     if ($getuserdir) {
 9390:         $udom = $userdomain;
 9391:         $uname = $username;
 9392:     } else {
 9393:         (undef,$udom,$uname)=split(/\//,$uri);
 9394:         if(defined($userdomain)) {
 9395:             $udom = $userdomain;
 9396:         }
 9397:         if(defined($username)) {
 9398:             $uname = $username;
 9399:         }
 9400:     }
 9401:     my ($dirRoot,$listing,@listing_results);
 9402: 
 9403:     $dirRoot = $perlvar{'lonDocRoot'};
 9404:     if (defined($getpropath)) {
 9405:         $dirRoot = &propath($udom,$uname);
 9406:         $dirRoot =~ s/\/$//;
 9407:     } elsif (defined($getuserdir)) {
 9408:         my $subdir=$uname.'__';
 9409:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 9410:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
 9411:                    ."/$udom/$subdir/$uname";
 9412:     } elsif (defined($alternateRoot)) {
 9413:         $dirRoot = $alternateRoot;
 9414:     }
 9415: 
 9416:     if($udom) {
 9417:         if($uname) {
 9418:             my $uhome = &homeserver($uname,$udom);
 9419:             if ($uhome eq 'no_host') {
 9420:                 return ([],'no_host');
 9421:             }
 9422:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
 9423:                               .$getuserdir.':'.&escape($dirRoot)
 9424:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
 9425:             if ($listing eq 'unknown_cmd') {
 9426:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
 9427:             } else {
 9428:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 9429:             }
 9430:             if ($listing eq 'unknown_cmd') {
 9431:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
 9432:                 @listing_results = split(/:/,$listing);
 9433:             } else {
 9434:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 9435:             }
 9436:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
 9437:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
 9438:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
 9439:                 return ([],$listing);
 9440:             } else {
 9441:                 return (\@listing_results);
 9442:             }
 9443:         } elsif(!$alternateRoot) {
 9444:             my (%allusers,%listerror);
 9445: 	    my %servers = &get_servers($udom,'library');
 9446:  	    foreach my $tryserver (keys(%servers)) {
 9447:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
 9448:                                   &escape($udom),$tryserver);
 9449:                 if ($listing eq 'unknown_cmd') {
 9450: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
 9451: 				      $udom, $tryserver);
 9452:                 } else {
 9453:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
 9454:                 }
 9455: 		if ($listing eq 'unknown_cmd') {
 9456: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 9457: 				      $udom, $tryserver);
 9458: 		    @listing_results = split(/:/,$listing);
 9459: 		} else {
 9460: 		    @listing_results =
 9461: 			map { &unescape($_); } split(/:/,$listing);
 9462: 		}
 9463:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
 9464:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
 9465:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
 9466:                     $listerror{$tryserver} = $listing;
 9467:                 } else {
 9468: 		    foreach my $line (@listing_results) {
 9469: 			my ($entry) = split(/&/,$line,2);
 9470: 			$allusers{$entry} = 1;
 9471: 		    }
 9472: 		}
 9473:             }
 9474:             my @alluserslist=();
 9475:             foreach my $user (sort(keys(%allusers))) {
 9476:                 push(@alluserslist,$user.'&user');
 9477:             }
 9478:             return (\@alluserslist);
 9479:         } else {
 9480:             return ([],'missing username');
 9481:         }
 9482:     } elsif(!defined($getpropath)) {
 9483:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
 9484:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
 9485:         return (\@all_domains);
 9486:     } else {
 9487:         return ([],'missing domain');
 9488:     }
 9489: }
 9490: 
 9491: # --------------------------------------------- GetFileTimestamp
 9492: # This function utilizes dirlist and returns the date stamp for
 9493: # when it was last modified.  It will also return an error of -1
 9494: # if an error occurs
 9495: 
 9496: sub GetFileTimestamp {
 9497:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
 9498:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
 9499:     $studentName   = &LONCAPA::clean_username($studentName);
 9500:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
 9501:                                     undef,$getuserdir);
 9502:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
 9503:         return -1;
 9504:     }
 9505:     if (ref($fileref) eq 'ARRAY') {
 9506:         my @stats = split('&',$fileref->[0]);
 9507:         # @stats contains first the filename, then the stat output
 9508:         return $stats[10]; # so this is 10 instead of 9.
 9509:     } else {
 9510:         return -1;
 9511:     }
 9512: }
 9513: 
 9514: sub stat_file {
 9515:     my ($uri) = @_;
 9516:     $uri = &clutter_with_no_wrapper($uri);
 9517: 
 9518:     my ($udom,$uname,$file);
 9519:     if ($uri =~ m-^/(uploaded|editupload)/-) {
 9520: 	($udom,$uname,$file) =
 9521: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
 9522: 	$file = 'userfiles/'.$file;
 9523:     }
 9524:     if ($uri =~ m-^/res/-) {
 9525: 	($udom,$uname) = 
 9526: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
 9527: 	$file = $uri;
 9528:     }
 9529: 
 9530:     if (!$udom || !$uname || !$file) {
 9531: 	# unable to handle the uri
 9532: 	return ();
 9533:     }
 9534:     my $getpropath;
 9535:     if ($file =~ /^userfiles\//) {
 9536:         $getpropath = 1;
 9537:     }
 9538:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
 9539:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
 9540:         return ();
 9541:     } else {
 9542:         if (ref($listref) eq 'ARRAY') {
 9543:             my @stats = split('&',$listref->[0]);
 9544: 	    shift(@stats); #filename is first
 9545: 	    return @stats;
 9546:         }
 9547:     }
 9548:     return ();
 9549: }
 9550: 
 9551: # -------------------------------------------------------- Value of a Condition
 9552: 
 9553: # gets the value of a specific preevaluated condition
 9554: #    stored in the string  $env{user.state.<cid>}
 9555: # or looks up a condition reference in the bighash and if if hasn't
 9556: # already been evaluated recurses into docondval to get the value of
 9557: # the condition, then memoizing it to 
 9558: #   $env{user.state.<cid>.<condition>}
 9559: sub directcondval {
 9560:     my $number=shift;
 9561:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
 9562: 	&Apache::lonuserstate::evalstate();
 9563:     }
 9564:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
 9565: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
 9566:     } elsif ($number =~ /^_/) {
 9567: 	my $sub_condition;
 9568: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 9569: 		&GDBM_READER(),0640)) {
 9570: 	    $sub_condition=$bighash{'conditions'.$number};
 9571: 	    untie(%bighash);
 9572: 	}
 9573: 	my $value = &docondval($sub_condition);
 9574: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
 9575: 	return $value;
 9576:     }
 9577:     if ($env{'user.state.'.$env{'request.course.id'}}) {
 9578:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
 9579:     } else {
 9580:        return 2;
 9581:     }
 9582: }
 9583: 
 9584: # get the collection of conditions for this resource
 9585: sub condval {
 9586:     my $condidx=shift;
 9587:     my $allpathcond='';
 9588:     foreach my $cond (split(/\|/,$condidx)) {
 9589: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
 9590: 	    $allpathcond.=
 9591: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
 9592: 	}
 9593:     }
 9594:     $allpathcond=~s/\|$//;
 9595:     return &docondval($allpathcond);
 9596: }
 9597: 
 9598: #evaluates an expression of conditions
 9599: sub docondval {
 9600:     my ($allpathcond) = @_;
 9601:     my $result=0;
 9602:     if ($env{'request.course.id'}
 9603: 	&& defined($allpathcond)) {
 9604: 	my $operand='|';
 9605: 	my @stack;
 9606: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
 9607: 	    if ($chunk eq '(') {
 9608: 		push @stack,($operand,$result);
 9609: 	    } elsif ($chunk eq ')') {
 9610: 		my $before=pop @stack;
 9611: 		if (pop @stack eq '&') {
 9612: 		    $result=$result>$before?$before:$result;
 9613: 		} else {
 9614: 		    $result=$result>$before?$result:$before;
 9615: 		}
 9616: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
 9617: 		$operand=$chunk;
 9618: 	    } else {
 9619: 		my $new=directcondval($chunk);
 9620: 		if ($operand eq '&') {
 9621: 		    $result=$result>$new?$new:$result;
 9622: 		} else {
 9623: 		    $result=$result>$new?$result:$new;
 9624: 		}
 9625: 	    }
 9626: 	}
 9627:     }
 9628:     return $result;
 9629: }
 9630: 
 9631: # ---------------------------------------------------- Devalidate courseresdata
 9632: 
 9633: sub devalidatecourseresdata {
 9634:     my ($coursenum,$coursedomain)=@_;
 9635:     my $hashid=$coursenum.':'.$coursedomain;
 9636:     &devalidate_cache_new('courseres',$hashid);
 9637: }
 9638: 
 9639: 
 9640: # --------------------------------------------------- Course Resourcedata Query
 9641: #
 9642: #  Parameters:
 9643: #      $coursenum    - Number of the course.
 9644: #      $coursedomain - Domain at which the course was created.
 9645: #  Returns:
 9646: #     A hash of the course parameters along (I think) with timestamps
 9647: #     and version info.
 9648: 
 9649: sub get_courseresdata {
 9650:     my ($coursenum,$coursedomain)=@_;
 9651:     my $coursehom=&homeserver($coursenum,$coursedomain);
 9652:     my $hashid=$coursenum.':'.$coursedomain;
 9653:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
 9654:     my %dumpreply;
 9655:     unless (defined($cached)) {
 9656: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 9657: 	$result=\%dumpreply;
 9658: 	my ($tmp) = keys(%dumpreply);
 9659: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 9660: 	    &do_cache_new('courseres',$hashid,$result,600);
 9661: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 9662: 	    return $tmp;
 9663: 	} elsif ($tmp =~ /^(error)/) {
 9664: 	    $result=undef;
 9665: 	    &do_cache_new('courseres',$hashid,$result,600);
 9666: 	}
 9667:     }
 9668:     return $result;
 9669: }
 9670: 
 9671: sub devalidateuserresdata {
 9672:     my ($uname,$udom)=@_;
 9673:     my $hashid="$udom:$uname";
 9674:     &devalidate_cache_new('userres',$hashid);
 9675: }
 9676: 
 9677: sub get_userresdata {
 9678:     my ($uname,$udom)=@_;
 9679:     #most student don\'t have any data set, check if there is some data
 9680:     if (&EXT_cache_status($udom,$uname)) { return undef; }
 9681: 
 9682:     my $hashid="$udom:$uname";
 9683:     my ($result,$cached)=&is_cached_new('userres',$hashid);
 9684:     if (!defined($cached)) {
 9685: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
 9686: 	$result=\%resourcedata;
 9687: 	&do_cache_new('userres',$hashid,$result,600);
 9688:     }
 9689:     my ($tmp)=keys(%$result);
 9690:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
 9691: 	return $result;
 9692:     }
 9693:     #error 2 occurs when the .db doesn't exist
 9694:     if ($tmp!~/error: 2 /) {
 9695: 	&logthis("<font color=\"blue\">WARNING:".
 9696: 		 " Trying to get resource data for ".
 9697: 		 $uname." at ".$udom.": ".
 9698: 		 $tmp."</font>");
 9699:     } elsif ($tmp=~/error: 2 /) {
 9700: 	#&EXT_cache_set($udom,$uname);
 9701: 	&do_cache_new('userres',$hashid,undef,600);
 9702: 	undef($tmp); # not really an error so don't send it back
 9703:     }
 9704:     return $tmp;
 9705: }
 9706: #----------------------------------------------- resdata - return resource data
 9707: #  Purpose:
 9708: #    Return resource data for either users or for a course.
 9709: #  Parameters:
 9710: #     $name      - Course/user name.
 9711: #     $domain    - Name of the domain the user/course is registered on.
 9712: #     $type      - Type of thing $name is (must be 'course' or 'user'
 9713: #     @which     - Array of names of resources desired.
 9714: #  Returns:
 9715: #     The value of the first reasource in @which that is found in the
 9716: #     resource hash.
 9717: #  Exceptional Conditions:
 9718: #     If the $type passed in is not valid (not the string 'course' or 
 9719: #     'user', an undefined  reference is returned.
 9720: #     If none of the resources are found, an undef is returned
 9721: sub resdata {
 9722:     my ($name,$domain,$type,@which)=@_;
 9723:     my $result;
 9724:     if ($type eq 'course') {
 9725: 	$result=&get_courseresdata($name,$domain);
 9726:     } elsif ($type eq 'user') {
 9727: 	$result=&get_userresdata($name,$domain);
 9728:     }
 9729:     if (!ref($result)) { return $result; }    
 9730:     foreach my $item (@which) {
 9731: 	if (defined($result->{$item->[0]})) {
 9732: 	    return [$result->{$item->[0]},$item->[1]];
 9733: 	}
 9734:     }
 9735:     return undef;
 9736: }
 9737: 
 9738: sub get_numsuppfiles {
 9739:     my ($cnum,$cdom,$ignorecache)=@_;
 9740:     my $hashid=$cnum.':'.$cdom;
 9741:     my ($suppcount,$cached);
 9742:     unless ($ignorecache) {
 9743:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
 9744:     }
 9745:     unless (defined($cached)) {
 9746:         my $chome=&homeserver($cnum,$cdom);
 9747:         unless ($chome eq 'no_host') {
 9748:             ($suppcount,my $errors) = (0,0);
 9749:             my $suppmap = 'supplemental.sequence';
 9750:             ($suppcount,$errors) = 
 9751:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
 9752:         }
 9753:         &do_cache_new('suppcount',$hashid,$suppcount,600);
 9754:     }
 9755:     return $suppcount;
 9756: }
 9757: 
 9758: #
 9759: # EXT resource caching routines
 9760: #
 9761: 
 9762: sub clear_EXT_cache_status {
 9763:     &delenv('cache.EXT.');
 9764: }
 9765: 
 9766: sub EXT_cache_status {
 9767:     my ($target_domain,$target_user) = @_;
 9768:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 9769:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
 9770:         # We know already the user has no data
 9771:         return 1;
 9772:     } else {
 9773:         return 0;
 9774:     }
 9775: }
 9776: 
 9777: sub EXT_cache_set {
 9778:     my ($target_domain,$target_user) = @_;
 9779:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 9780:     #&appenv({$cachename => time});
 9781: }
 9782: 
 9783: # --------------------------------------------------------- Value of a Variable
 9784: sub EXT {
 9785: 
 9786:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
 9787:     unless ($varname) { return ''; }
 9788:     #get real user name/domain, courseid and symb
 9789:     my $courseid;
 9790:     my $publicuser;
 9791:     if ($symbparm) {
 9792: 	$symbparm=&get_symb_from_alias($symbparm);
 9793:     }
 9794:     if (!($uname && $udom)) {
 9795:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
 9796:       if (!$symbparm) {	$symbparm=$cursymb; }
 9797:     } else {
 9798: 	$courseid=$env{'request.course.id'};
 9799:     }
 9800:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 9801:     my $rest;
 9802:     if (defined($therest[0])) {
 9803:        $rest=join('.',@therest);
 9804:     } else {
 9805:        $rest='';
 9806:     }
 9807: 
 9808:     my $qualifierrest=$qualifier;
 9809:     if ($rest) { $qualifierrest.='.'.$rest; }
 9810:     my $spacequalifierrest=$space;
 9811:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 9812:     if ($realm eq 'user') {
 9813: # --------------------------------------------------------------- user.resource
 9814: 	if ($space eq 'resource') {
 9815: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
 9816: 		  || defined($Apache::lonhomework::parsing_a_task))
 9817: 		 &&
 9818: 		 ($symbparm eq &symbread()) ) {	
 9819: 		# if we are in the middle of processing the resource the
 9820: 		# get the value we are planning on committing
 9821:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
 9822:                     return $Apache::lonhomework::results{$qualifierrest};
 9823:                 } else {
 9824:                     return $Apache::lonhomework::history{$qualifierrest};
 9825:                 }
 9826: 	    } else {
 9827: 		my %restored;
 9828: 		if ($publicuser || $env{'request.state'} eq 'construct') {
 9829: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
 9830: 		} else {
 9831: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
 9832: 		}
 9833: 		return $restored{$qualifierrest};
 9834: 	    }
 9835: # ----------------------------------------------------------------- user.access
 9836:         } elsif ($space eq 'access') {
 9837: 	    # FIXME - not supporting calls for a specific user
 9838:             return &allowed($qualifier,$rest);
 9839: # ------------------------------------------ user.preferences, user.environment
 9840:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 9841: 	    if (($uname eq $env{'user.name'}) &&
 9842: 		($udom eq $env{'user.domain'})) {
 9843: 		return $env{join('.',('environment',$qualifierrest))};
 9844: 	    } else {
 9845: 		my %returnhash;
 9846: 		if (!$publicuser) {
 9847: 		    %returnhash=&userenvironment($udom,$uname,
 9848: 						 $qualifierrest);
 9849: 		}
 9850: 		return $returnhash{$qualifierrest};
 9851: 	    }
 9852: # ----------------------------------------------------------------- user.course
 9853:         } elsif ($space eq 'course') {
 9854: 	    # FIXME - not supporting calls for a specific user
 9855:             return $env{join('.',('request.course',$qualifier))};
 9856: # ------------------------------------------------------------------- user.role
 9857:         } elsif ($space eq 'role') {
 9858: 	    # FIXME - not supporting calls for a specific user
 9859:             my ($role,$where)=split(/\./,$env{'request.role'});
 9860:             if ($qualifier eq 'value') {
 9861: 		return $role;
 9862:             } elsif ($qualifier eq 'extent') {
 9863:                 return $where;
 9864:             }
 9865: # ----------------------------------------------------------------- user.domain
 9866:         } elsif ($space eq 'domain') {
 9867:             return $udom;
 9868: # ------------------------------------------------------------------- user.name
 9869:         } elsif ($space eq 'name') {
 9870:             return $uname;
 9871: # ---------------------------------------------------- Any other user namespace
 9872:         } else {
 9873: 	    my %reply;
 9874: 	    if (!$publicuser) {
 9875: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
 9876: 	    }
 9877: 	    return $reply{$qualifierrest};
 9878:         }
 9879:     } elsif ($realm eq 'query') {
 9880: # ---------------------------------------------- pull stuff out of query string
 9881:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 9882: 						[$spacequalifierrest]);
 9883: 	return $env{'form.'.$spacequalifierrest}; 
 9884:    } elsif ($realm eq 'request') {
 9885: # ------------------------------------------------------------- request.browser
 9886:         if ($space eq 'browser') {
 9887:             return $env{'browser.'.$qualifier};
 9888: # ------------------------------------------------------------ request.filename
 9889:         } else {
 9890:             return $env{'request.'.$spacequalifierrest};
 9891:         }
 9892:     } elsif ($realm eq 'course') {
 9893: # ---------------------------------------------------------- course.description
 9894:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
 9895:     } elsif ($realm eq 'resource') {
 9896: 
 9897: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
 9898: 	    if (!$symbparm) { $symbparm=&symbread(); }
 9899: 	}
 9900: 
 9901:         if ($qualifier eq '') {
 9902: 	    if ($space eq 'title') {
 9903: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
 9904: 	        return &gettitle($symbparm);
 9905: 	    }
 9906: 	
 9907: 	    if ($space eq 'map') {
 9908: 	        my ($map) = &decode_symb($symbparm);
 9909: 	        return &symbread($map);
 9910: 	    }
 9911:             if ($space eq 'maptitle') {
 9912:                 my ($map) = &decode_symb($symbparm);
 9913:                 return &gettitle($map);
 9914:             }
 9915: 	    if ($space eq 'filename') {
 9916: 	        if ($symbparm) {
 9917: 		    return &clutter((&decode_symb($symbparm))[2]);
 9918: 	        }
 9919: 	        return &hreflocation('',$env{'request.filename'});
 9920: 	    }
 9921: 
 9922:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
 9923:                 if ($space eq 'visibleparts') {
 9924:                     my $navmap = Apache::lonnavmaps::navmap->new();
 9925:                     my $item;
 9926:                     if (ref($navmap)) {
 9927:                         my $res = $navmap->getBySymb($symbparm);
 9928:                         my $parts = $res->parts();
 9929:                         if (ref($parts) eq 'ARRAY') {
 9930:                             $item = join(',',@{$parts});
 9931:                         }
 9932:                         undef($navmap);
 9933:                     }
 9934:                     return $item;
 9935:                 }
 9936:             }
 9937:         }
 9938: 
 9939: 	my ($section, $group, @groups);
 9940: 	my ($courselevelm,$courselevel);
 9941:         if (($courseid eq '') && ($cid)) {
 9942:             $courseid = $cid;
 9943:         }
 9944: 	if (($symbparm && $courseid) && 
 9945: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
 9946: 
 9947: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
 9948: 
 9949: # ----------------------------------------------------- Cascading lookup scheme
 9950: 	    my $symbp=$symbparm;
 9951: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
 9952: 
 9953: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
 9954: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
 9955: 
 9956: 	    if (($env{'user.name'} eq $uname) &&
 9957: 		($env{'user.domain'} eq $udom)) {
 9958: 		$section=$env{'request.course.sec'};
 9959:                 @groups = split(/:/,$env{'request.course.groups'});  
 9960:                 @groups=&sort_course_groups($courseid,@groups); 
 9961: 	    } else {
 9962: 		if (! defined($usection)) {
 9963: 		    $section=&getsection($udom,$uname,$courseid);
 9964: 		} else {
 9965: 		    $section = $usection;
 9966: 		}
 9967:                 @groups = &get_users_groups($udom,$uname,$courseid);
 9968: 	    }
 9969: 
 9970: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
 9971: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
 9972: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
 9973: 
 9974: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
 9975: 	    my $courselevelr=$courseid.'.'.$symbparm;
 9976: 	    $courselevelm=$courseid.'.'.$mapparm;
 9977: 
 9978: # ----------------------------------------------------------- first, check user
 9979: 
 9980: 	    my $userreply=&resdata($uname,$udom,'user',
 9981: 				       ([$courselevelr,'resource'],
 9982: 					[$courselevelm,'map'     ],
 9983: 					[$courselevel, 'course'  ]));
 9984: 	    if (defined($userreply)) { return &get_reply($userreply); }
 9985: 
 9986: # ------------------------------------------------ second, check some of course
 9987:             my $coursereply;
 9988:             if (@groups > 0) {
 9989:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
 9990:                                        $mapparm,$spacequalifierrest);
 9991:                 if (defined($coursereply)) { return &get_reply($coursereply); }
 9992:             }
 9993: 
 9994: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 9995: 				  $env{'course.'.$courseid.'.domain'},
 9996: 				  'course',
 9997: 				  ([$seclevelr,   'resource'],
 9998: 				   [$seclevelm,   'map'     ],
 9999: 				   [$seclevel,    'course'  ],
10000: 				   [$courselevelr,'resource']));
10001: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
10002: 
10003: # ------------------------------------------------------ third, check map parms
10004: 	    my %parmhash=();
10005: 	    my $thisparm='';
10006: 	    if (tie(%parmhash,'GDBM_File',
10007: 		    $env{'request.course.fn'}.'_parms.db',
10008: 		    &GDBM_READER(),0640)) {
10009: 		$thisparm=$parmhash{$symbparm};
10010: 		untie(%parmhash);
10011: 	    }
10012: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
10013: 	}
10014: # ------------------------------------------ fourth, look in resource metadata
10015: 
10016: 	$spacequalifierrest=~s/\./\_/;
10017: 	my $filename;
10018: 	if (!$symbparm) { $symbparm=&symbread(); }
10019: 	if ($symbparm) {
10020: 	    $filename=(&decode_symb($symbparm))[2];
10021: 	} else {
10022: 	    $filename=$env{'request.filename'};
10023: 	}
10024: 	my $metadata=&metadata($filename,$spacequalifierrest);
10025: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
10026: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
10027: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
10028: 
10029: # ---------------------------------------------- fourth, look in rest of course
10030: 	if ($symbparm && defined($courseid) && 
10031: 	    $courseid eq $env{'request.course.id'}) {
10032: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
10033: 				     $env{'course.'.$courseid.'.domain'},
10034: 				     'course',
10035: 				     ([$courselevelm,'map'   ],
10036: 				      [$courselevel, 'course']));
10037: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
10038: 	}
10039: # ------------------------------------------------------------------ Cascade up
10040: 	unless ($space eq '0') {
10041: 	    my @parts=split(/_/,$space);
10042: 	    my $id=pop(@parts);
10043: 	    my $part=join('_',@parts);
10044: 	    if ($part eq '') { $part='0'; }
10045: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
10046: 				 $symbparm,$udom,$uname,$section,1);
10047: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
10048: 	}
10049: 	if ($recurse) { return undef; }
10050: 	my $pack_def=&packages_tab_default($filename,$varname);
10051: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
10052: # ---------------------------------------------------- Any other user namespace
10053:     } elsif ($realm eq 'environment') {
10054: # ----------------------------------------------------------------- environment
10055: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
10056: 	    return $env{'environment.'.$spacequalifierrest};
10057: 	} else {
10058: 	    if ($uname eq 'anonymous' && $udom eq '') {
10059: 		return '';
10060: 	    }
10061: 	    my %returnhash=&userenvironment($udom,$uname,
10062: 					    $spacequalifierrest);
10063: 	    return $returnhash{$spacequalifierrest};
10064: 	}
10065:     } elsif ($realm eq 'system') {
10066: # ----------------------------------------------------------------- system.time
10067: 	if ($space eq 'time') {
10068: 	    return time;
10069:         }
10070:     } elsif ($realm eq 'server') {
10071: # ----------------------------------------------------------------- system.time
10072: 	if ($space eq 'name') {
10073: 	    return $ENV{'SERVER_NAME'};
10074:         }
10075:     }
10076:     return '';
10077: }
10078: 
10079: sub get_reply {
10080:     my ($reply_value) = @_;
10081:     if (ref($reply_value) eq 'ARRAY') {
10082:         if (wantarray) {
10083: 	    return @$reply_value;
10084:         }
10085:         return $reply_value->[0];
10086:     } else {
10087:         return $reply_value;
10088:     }
10089: }
10090: 
10091: sub check_group_parms {
10092:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
10093:     my @groupitems = ();
10094:     my $resultitem;
10095:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
10096:     foreach my $group (@{$groups}) {
10097:         foreach my $level (@levels) {
10098:              my $item = $courseid.'.['.$group.'].'.$level->[0];
10099:              push(@groupitems,[$item,$level->[1]]);
10100:         }
10101:     }
10102:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
10103:                             $env{'course.'.$courseid.'.domain'},
10104:                                      'course',@groupitems);
10105:     return $coursereply;
10106: }
10107: 
10108: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
10109:     my ($courseid,@groups) = @_;
10110:     @groups = sort(@groups);
10111:     return @groups;
10112: }
10113: 
10114: sub packages_tab_default {
10115:     my ($uri,$varname)=@_;
10116:     my (undef,$part,$name)=split(/\./,$varname);
10117: 
10118:     my (@extension,@specifics,$do_default);
10119:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
10120: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
10121: 	if ($pack_type eq 'default') {
10122: 	    $do_default=1;
10123: 	} elsif ($pack_type eq 'extension') {
10124: 	    push(@extension,[$package,$pack_type,$pack_part]);
10125: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
10126: 	    # only look at packages defaults for packages that this id is
10127: 	    push(@specifics,[$package,$pack_type,$pack_part]);
10128: 	}
10129:     }
10130:     # first look for a package that matches the requested part id
10131:     foreach my $package (@specifics) {
10132: 	my (undef,$pack_type,$pack_part)=@{$package};
10133: 	next if ($pack_part ne $part);
10134: 	if (defined($packagetab{"$pack_type&$name&default"})) {
10135: 	    return $packagetab{"$pack_type&$name&default"};
10136: 	}
10137:     }
10138:     # look for any possible matching non extension_ package
10139:     foreach my $package (@specifics) {
10140: 	my (undef,$pack_type,$pack_part)=@{$package};
10141: 	if (defined($packagetab{"$pack_type&$name&default"})) {
10142: 	    return $packagetab{"$pack_type&$name&default"};
10143: 	}
10144: 	if ($pack_type eq 'part') { $pack_part='0'; }
10145: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
10146: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
10147: 	}
10148:     }
10149:     # look for any posible extension_ match
10150:     foreach my $package (@extension) {
10151: 	my ($package,$pack_type)=@{$package};
10152: 	if (defined($packagetab{"$pack_type&$name&default"})) {
10153: 	    return $packagetab{"$pack_type&$name&default"};
10154: 	}
10155: 	if (defined($packagetab{$package."&$name&default"})) {
10156: 	    return $packagetab{$package."&$name&default"};
10157: 	}
10158:     }
10159:     # look for a global default setting
10160:     if ($do_default && defined($packagetab{"default&$name&default"})) {
10161: 	return $packagetab{"default&$name&default"};
10162:     }
10163:     return undef;
10164: }
10165: 
10166: sub add_prefix_and_part {
10167:     my ($prefix,$part)=@_;
10168:     my $keyroot;
10169:     if (defined($prefix) && $prefix !~ /^__/) {
10170: 	# prefix that has a part already
10171: 	$keyroot=$prefix;
10172:     } elsif (defined($prefix)) {
10173: 	# prefix that is missing a part
10174: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
10175:     } else {
10176: 	# no prefix at all
10177: 	if (defined($part)) { $keyroot='_'.$part; }
10178:     }
10179:     return $keyroot;
10180: }
10181: 
10182: # ---------------------------------------------------------------- Get metadata
10183: 
10184: my %metaentry;
10185: my %importedpartids;
10186: sub metadata {
10187:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
10188:     $uri=&declutter($uri);
10189:     # if it is a non metadata possible uri return quickly
10190:     if (($uri eq '') || 
10191: 	(($uri =~ m|^/*adm/|) && 
10192: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
10193:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
10194: 	return undef;
10195:     }
10196:     if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) 
10197: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
10198: 	return undef;
10199:     }
10200:     my $filename=$uri;
10201:     $uri=~s/\.meta$//;
10202: #
10203: # Is the metadata already cached?
10204: # Look at timestamp of caching
10205: # Everything is cached by the main uri, libraries are never directly cached
10206: #
10207:     if (!defined($liburi)) {
10208: 	my ($result,$cached)=&is_cached_new('meta',$uri);
10209: 	if (defined($cached)) { return $result->{':'.$what}; }
10210:     }
10211:     {
10212: # Imported parts would go here
10213:         my %importedids=();
10214:         my @origfileimportpartids=();
10215:         my $importedparts=0;
10216: #
10217: # Is this a recursive call for a library?
10218: #
10219: #	if (! exists($metacache{$uri})) {
10220: #	    $metacache{$uri}={};
10221: #	}
10222: 	my $cachetime = 60*60;
10223:         if ($liburi) {
10224: 	    $liburi=&declutter($liburi);
10225:             $filename=$liburi;
10226:         } else {
10227: 	    &devalidate_cache_new('meta',$uri);
10228: 	    undef(%metaentry);
10229: 	}
10230:         my %metathesekeys=();
10231:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
10232: 	my $metastring;
10233: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
10234: 	    my $which = &hreflocation('','/'.($liburi || $uri));
10235: 	    $metastring = 
10236: 		&Apache::lonnet::ssi_body($which,
10237: 					  ('grade_target' => 'meta'));
10238: 	    $cachetime = 1; # only want this cached in the child not long term
10239: 	} elsif (($uri !~ m -^(editupload)/-) && 
10240:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
10241: 	    my $file=&filelocation('',&clutter($filename));
10242: 	    #push(@{$metaentry{$uri.'.file'}},$file);
10243: 	    $metastring=&getfile($file);
10244: 	}
10245:         my $parser=HTML::LCParser->new(\$metastring);
10246:         my $token;
10247:         undef %metathesekeys;
10248:         while ($token=$parser->get_token) {
10249: 	    if ($token->[0] eq 'S') {
10250: 		if (defined($token->[2]->{'package'})) {
10251: #
10252: # This is a package - get package info
10253: #
10254: 		    my $package=$token->[2]->{'package'};
10255: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10256: 		    if (defined($token->[2]->{'id'})) { 
10257: 			$keyroot.='_'.$token->[2]->{'id'}; 
10258: 		    }
10259: 		    if ($metaentry{':packages'}) {
10260: 			$metaentry{':packages'}.=','.$package.$keyroot;
10261: 		    } else {
10262: 			$metaentry{':packages'}=$package.$keyroot;
10263: 		    }
10264: 		    foreach my $pack_entry (keys(%packagetab)) {
10265: 			my $part=$keyroot;
10266: 			$part=~s/^\_//;
10267: 			if ($pack_entry=~/^\Q$package\E\&/ || 
10268: 			    $pack_entry=~/^\Q$package\E_0\&/) {
10269: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
10270: 			    # ignore package.tab specified default values
10271:                             # here &package_tab_default() will fetch those
10272: 			    if ($subp eq 'default') { next; }
10273: 			    my $value=$packagetab{$pack_entry};
10274: 			    my $unikey;
10275: 			    if ($pack =~ /_0$/) {
10276: 				$unikey='parameter_0_'.$name;
10277: 				$part=0;
10278: 			    } else {
10279: 				$unikey='parameter'.$keyroot.'_'.$name;
10280: 			    }
10281: 			    if ($subp eq 'display') {
10282: 				$value.=' [Part: '.$part.']';
10283: 			    }
10284: 			    $metaentry{':'.$unikey.'.part'}=$part;
10285: 			    $metathesekeys{$unikey}=1;
10286: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10287: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
10288: 			    }
10289: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
10290: 				$metaentry{':'.$unikey}=
10291: 				    $metaentry{':'.$unikey.'.default'};
10292: 			    }
10293: 			}
10294: 		    }
10295: 		} else {
10296: #
10297: # This is not a package - some other kind of start tag
10298: #
10299: 		    my $entry=$token->[1];
10300: 		    my $unikey='';
10301: 
10302: 		    if ($entry eq 'import') {
10303: #
10304: # Importing a library here
10305: #
10306:                         my $location=$parser->get_text('/import');
10307:                         my $dir=$filename;
10308:                         $dir=~s|[^/]*$||;
10309:                         $location=&filelocation($dir,$location);
10310:                        
10311:                         my $importmode=$token->[2]->{'importmode'};
10312:                         if ($importmode eq 'problem') {
10313: # Import as problem/response
10314:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10315:                         } elsif ($importmode eq 'part') {
10316: # Import as part(s)
10317:                            $importedparts=1;
10318: # We need to get the original file and the imported file to get the part order correct
10319: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
10320: # Load and inspect original file
10321:                            if ($#origfileimportpartids<0) {
10322:                               undef(%importedpartids);
10323:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
10324:                               my $origfile=&getfile($origfilelocation);
10325:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10326:                            }
10327: 
10328: # Load and inspect imported file
10329:                            my $impfile=&getfile($location);
10330:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10331:                            if ($#impfilepartids>=0) {
10332: # This problem had parts
10333:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
10334:                            } else {
10335: # Importing by turning a single problem into a problem part
10336: # It gets the import-tags ID as part-ID
10337:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
10338:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
10339:                            }
10340:                         } else {
10341: # Normal import
10342:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10343:                            if (defined($token->[2]->{'id'})) {
10344:                               $unikey.='_'.$token->[2]->{'id'};
10345:                            }
10346:                         }
10347: 
10348: 			if ($depthcount<20) {
10349: 			    my $metadata = 
10350: 				&metadata($uri,'keys', $location,$unikey,
10351: 					  $depthcount+1);
10352: 			    foreach my $meta (split(',',$metadata)) {
10353: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
10354: 				$metathesekeys{$meta}=1;
10355: 			    }
10356: 			
10357:                         }
10358: 		    } else {
10359: #
10360: # Not importing, some other kind of non-package, non-library start tag
10361: # 
10362:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
10363:                         if (defined($token->[2]->{'id'})) {
10364:                             $unikey.='_'.$token->[2]->{'id'};
10365:                         }
10366: 			if (defined($token->[2]->{'name'})) { 
10367: 			    $unikey.='_'.$token->[2]->{'name'}; 
10368: 			}
10369: 			$metathesekeys{$unikey}=1;
10370: 			foreach my $param (@{$token->[3]}) {
10371: 			    $metaentry{':'.$unikey.'.'.$param} =
10372: 				$token->[2]->{$param};
10373: 			}
10374: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
10375: 			my $default=$metaentry{':'.$unikey.'.default'};
10376: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
10377: 		 # only ws inside the tag, and not in default, so use default
10378: 		 # as value
10379: 			    $metaentry{':'.$unikey}=$default;
10380: 			} elsif ( $internaltext =~ /\S/ ) {
10381: 		  # something interesting inside the tag
10382: 			    $metaentry{':'.$unikey}=$internaltext;
10383: 			} else {
10384: 		  # no interesting values, don't set a default
10385: 			}
10386: # end of not-a-package not-a-library import
10387: 		    }
10388: # end of not-a-package start tag
10389: 		}
10390: # the next is the end of "start tag"
10391: 	    }
10392: 	}
10393: 	my ($extension) = ($uri =~ /\.(\w+)$/);
10394: 	$extension = lc($extension);
10395: 	if ($extension eq 'htm') { $extension='html'; }
10396: 
10397: 	foreach my $key (keys(%packagetab)) {
10398: 	    #no specific packages #how's our extension
10399: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
10400: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
10401: 					 \%metathesekeys);
10402: 	}
10403: 
10404: 	if (!exists($metaentry{':packages'})
10405: 	    || $packagetab{"import_defaults&extension_$extension"}) {
10406: 	    foreach my $key (keys(%packagetab)) {
10407: 		#no specific packages well let's get default then
10408: 		if ($key!~/^default&/) { next; }
10409: 		&metadata_create_package_def($uri,$key,'default',
10410: 					     \%metathesekeys);
10411: 	    }
10412: 	}
10413: # are there custom rights to evaluate
10414: 	if ($metaentry{':copyright'} eq 'custom') {
10415: 
10416:     #
10417:     # Importing a rights file here
10418:     #
10419: 	    unless ($depthcount) {
10420: 		my $location=$metaentry{':customdistributionfile'};
10421: 		my $dir=$filename;
10422: 		$dir=~s|[^/]*$||;
10423: 		$location=&filelocation($dir,$location);
10424: 		my $rights_metadata =
10425: 		    &metadata($uri,'keys',$location,'_rights',
10426: 			      $depthcount+1);
10427: 		foreach my $rights (split(',',$rights_metadata)) {
10428: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
10429: 		    $metathesekeys{$rights}=1;
10430: 		}
10431: 	    }
10432: 	}
10433: 	# uniqifiy package listing
10434: 	my %seen;
10435: 	my @uniq_packages =
10436: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
10437: 	$metaentry{':packages'} = join(',',@uniq_packages);
10438: 
10439:         if ($importedparts) {
10440: # We had imported parts and need to rebuild partorder
10441:            $metaentry{':partorder'}='';
10442:            $metathesekeys{'partorder'}=1;
10443:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
10444:                if ($origfileimportpartids[$index] eq 'part') {
10445: # original part, part of the problem
10446:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
10447:                } else {
10448: # we have imported parts at this position
10449:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
10450:                }
10451:            }
10452:            $metaentry{':partorder'}=~s/^\,//;
10453:         }
10454: 
10455: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
10456: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
10457: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
10458: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
10459: # this is the end of "was not already recently cached
10460:     }
10461:     return $metaentry{':'.$what};
10462: }
10463: 
10464: sub metadata_create_package_def {
10465:     my ($uri,$key,$package,$metathesekeys)=@_;
10466:     my ($pack,$name,$subp)=split(/\&/,$key);
10467:     if ($subp eq 'default') { next; }
10468:     
10469:     if (defined($metaentry{':packages'})) {
10470: 	$metaentry{':packages'}.=','.$package;
10471:     } else {
10472: 	$metaentry{':packages'}=$package;
10473:     }
10474:     my $value=$packagetab{$key};
10475:     my $unikey;
10476:     $unikey='parameter_0_'.$name;
10477:     $metaentry{':'.$unikey.'.part'}=0;
10478:     $$metathesekeys{$unikey}=1;
10479:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10480: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
10481:     }
10482:     if (defined($metaentry{':'.$unikey.'.default'})) {
10483: 	$metaentry{':'.$unikey}=
10484: 	    $metaentry{':'.$unikey.'.default'};
10485:     }
10486: }
10487: 
10488: sub metadata_generate_part0 {
10489:     my ($metadata,$metacache,$uri) = @_;
10490:     my %allnames;
10491:     foreach my $metakey (keys(%$metadata)) {
10492: 	if ($metakey=~/^parameter\_(.*)/) {
10493: 	  my $part=$$metacache{':'.$metakey.'.part'};
10494: 	  my $name=$$metacache{':'.$metakey.'.name'};
10495: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
10496: 	    $allnames{$name}=$part;
10497: 	  }
10498: 	}
10499:     }
10500:     foreach my $name (keys(%allnames)) {
10501:       $$metadata{"parameter_0_$name"}=1;
10502:       my $key=":parameter_0_$name";
10503:       $$metacache{"$key.part"}='0';
10504:       $$metacache{"$key.name"}=$name;
10505:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
10506: 					   $allnames{$name}.'_'.$name.
10507: 					   '.type'};
10508:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
10509: 			     '.display'};
10510:       my $expr='[Part: '.$allnames{$name}.']';
10511:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
10512:       $$metacache{"$key.display"}=$olddis;
10513:     }
10514: }
10515: 
10516: # ------------------------------------------------------ Devalidate title cache
10517: 
10518: sub devalidate_title_cache {
10519:     my ($url)=@_;
10520:     if (!$env{'request.course.id'}) { return; }
10521:     my $symb=&symbread($url);
10522:     if (!$symb) { return; }
10523:     my $key=$env{'request.course.id'}."\0".$symb;
10524:     &devalidate_cache_new('title',$key);
10525: }
10526: 
10527: # ------------------------------------------------- Get the title of a course
10528: 
10529: sub current_course_title {
10530:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
10531: }
10532: # ------------------------------------------------- Get the title of a resource
10533: 
10534: sub gettitle {
10535:     my $urlsymb=shift;
10536:     my $symb=&symbread($urlsymb);
10537:     if ($symb) {
10538: 	my $key=$env{'request.course.id'}."\0".$symb;
10539: 	my ($result,$cached)=&is_cached_new('title',$key);
10540: 	if (defined($cached)) { 
10541: 	    return $result;
10542: 	}
10543: 	my ($map,$resid,$url)=&decode_symb($symb);
10544: 	my $title='';
10545: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
10546: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
10547: 	} else {
10548: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10549: 		    &GDBM_READER(),0640)) {
10550: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
10551: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
10552: 		untie(%bighash);
10553: 	    }
10554: 	}
10555: 	$title=~s/\&colon\;/\:/gs;
10556: 	if ($title) {
10557: # Remember both $symb and $title for dynamic metadata
10558:             $accesshash{$symb.'___crstitle'}=$title;
10559:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
10560: # Cache this title and then return it
10561: 	    return &do_cache_new('title',$key,$title,600);
10562: 	}
10563: 	$urlsymb=$url;
10564:     }
10565:     my $title=&metadata($urlsymb,'title');
10566:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
10567:     return $title;
10568: }
10569: 
10570: sub get_slot {
10571:     my ($which,$cnum,$cdom)=@_;
10572:     if (!$cnum || !$cdom) {
10573: 	(undef,my $courseid)=&whichuser();
10574: 	$cdom=$env{'course.'.$courseid.'.domain'};
10575: 	$cnum=$env{'course.'.$courseid.'.num'};
10576:     }
10577:     my $key=join("\0",'slots',$cdom,$cnum,$which);
10578:     my %slotinfo;
10579:     if (exists($remembered{$key})) {
10580: 	$slotinfo{$which} = $remembered{$key};
10581:     } else {
10582: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
10583: 	&Apache::lonhomework::showhash(%slotinfo);
10584: 	my ($tmp)=keys(%slotinfo);
10585: 	if ($tmp=~/^error:/) { return (); }
10586: 	$remembered{$key} = $slotinfo{$which};
10587:     }
10588:     if (ref($slotinfo{$which}) eq 'HASH') {
10589: 	return %{$slotinfo{$which}};
10590:     }
10591:     return $slotinfo{$which};
10592: }
10593: 
10594: sub get_reservable_slots {
10595:     my ($cnum,$cdom,$uname,$udom) = @_;
10596:     my $now = time;
10597:     my $reservable_info;
10598:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
10599:     if (exists($remembered{$key})) {
10600:         $reservable_info = $remembered{$key};
10601:     } else {
10602:         my %resv;
10603:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
10604:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
10605:         $reservable_info = \%resv;
10606:         $remembered{$key} = $reservable_info;
10607:     }
10608:     return $reservable_info;
10609: }
10610: 
10611: sub get_course_slots {
10612:     my ($cnum,$cdom) = @_;
10613:     my $hashid=$cnum.':'.$cdom;
10614:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
10615:     if (defined($cached)) {
10616:         if (ref($result) eq 'HASH') {
10617:             return %{$result};
10618:         }
10619:     } else {
10620:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
10621:         my ($tmp) = keys(%slots);
10622:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
10623:             &do_cache_new('allslots',$hashid,\%slots,600);
10624:             return %slots;
10625:         }
10626:     }
10627:     return;
10628: }
10629: 
10630: sub devalidate_slots_cache {
10631:     my ($cnum,$cdom)=@_;
10632:     my $hashid=$cnum.':'.$cdom;
10633:     &devalidate_cache_new('allslots',$hashid);
10634: }
10635: 
10636: sub get_coursechange {
10637:     my ($cdom,$cnum) = @_;
10638:     if ($cdom eq '' || $cnum eq '') {
10639:         return unless ($env{'request.course.id'});
10640:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10641:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10642:     }
10643:     my $hashid=$cdom.'_'.$cnum;
10644:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
10645:     if ((defined($cached)) && ($change ne '')) {
10646:         return $change;
10647:     } else {
10648:         my %crshash;
10649:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
10650:         if ($crshash{'internal.contentchange'} eq '') {
10651:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
10652:             if ($change eq '') {
10653:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
10654:                 $change = $crshash{'internal.created'};
10655:             }
10656:         } else {
10657:             $change = $crshash{'internal.contentchange'};
10658:         }
10659:         my $cachetime = 600;
10660:         &do_cache_new('crschange',$hashid,$change,$cachetime);
10661:     }
10662:     return $change;
10663: }
10664: 
10665: sub devalidate_coursechange_cache {
10666:     my ($cnum,$cdom)=@_;
10667:     my $hashid=$cnum.':'.$cdom;
10668:     &devalidate_cache_new('crschange',$hashid);
10669: }
10670: 
10671: # ------------------------------------------------- Update symbolic store links
10672: 
10673: sub symblist {
10674:     my ($mapname,%newhash)=@_;
10675:     $mapname=&deversion(&declutter($mapname));
10676:     my %hash;
10677:     if (($env{'request.course.fn'}) && (%newhash)) {
10678:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
10679:                       &GDBM_WRCREAT(),0640)) {
10680: 	    foreach my $url (keys(%newhash)) {
10681: 		next if ($url eq 'last_known'
10682: 			 && $env{'form.no_update_last_known'});
10683: 		$hash{declutter($url)}=&encode_symb($mapname,
10684: 						    $newhash{$url}->[1],
10685: 						    $newhash{$url}->[0]);
10686:             }
10687:             if (untie(%hash)) {
10688: 		return 'ok';
10689:             }
10690:         }
10691:     }
10692:     return 'error';
10693: }
10694: 
10695: # --------------------------------------------------------------- Verify a symb
10696: 
10697: sub symbverify {
10698:     my ($symb,$thisurl,$encstate)=@_;
10699:     my $thisfn=$thisurl;
10700:     $thisfn=&declutter($thisfn);
10701: # direct jump to resource in page or to a sequence - will construct own symbs
10702:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
10703: # check URL part
10704:     my ($map,$resid,$url)=&decode_symb($symb);
10705: 
10706:     unless ($url eq $thisfn) { return 0; }
10707: 
10708:     $symb=&symbclean($symb);
10709:     $thisurl=&deversion($thisurl);
10710:     $thisfn=&deversion($thisfn);
10711: 
10712:     my %bighash;
10713:     my $okay=0;
10714: 
10715:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10716:                             &GDBM_READER(),0640)) {
10717:         my $noclutter;
10718:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
10719:             $thisurl =~ s/\?.+$//;
10720:             if ($map =~ m{^uploaded/.+\.page$}) {
10721:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
10722:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
10723:                 $noclutter = 1;
10724:             }
10725:         }
10726:         my $ids;
10727:         if ($noclutter) {
10728:             $ids=$bighash{'ids_'.$thisurl};
10729:         } else {
10730:             $ids=$bighash{'ids_'.&clutter($thisurl)};
10731:         }
10732:         unless ($ids) {
10733:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
10734:             $ids=$bighash{$idkey};
10735:         }
10736:         if ($ids) {
10737: # ------------------------------------------------------------------- Has ID(s)
10738:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
10739:                 $symb =~ s/\?.+$//;
10740:             }
10741: 	    foreach my $id (split(/\,/,$ids)) {
10742: 	       my ($mapid,$resid)=split(/\./,$id);
10743:                if (
10744:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
10745:    eq $symb) {
10746:                    if (ref($encstate)) {
10747:                        $$encstate = $bighash{'encrypted_'.$id};
10748:                    }
10749: 		   if (($env{'request.role.adv'}) ||
10750: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
10751:                        ($thisurl eq '/adm/navmaps')) {
10752: 		       $okay=1;
10753:                        last;
10754: 		   }
10755: 	       }
10756: 	   }
10757:         }
10758: 	untie(%bighash);
10759:     }
10760:     return $okay;
10761: }
10762: 
10763: # --------------------------------------------------------------- Clean-up symb
10764: 
10765: sub symbclean {
10766:     my $symb=shift;
10767:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
10768: # remove version from map
10769:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
10770: 
10771: # remove version from URL
10772:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
10773: 
10774: # remove wrapper
10775: 
10776:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
10777:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
10778:     return $symb;
10779: }
10780: 
10781: # ---------------------------------------------- Split symb to find map and url
10782: 
10783: sub encode_symb {
10784:     my ($map,$resid,$url)=@_;
10785:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
10786: }
10787: 
10788: sub decode_symb {
10789:     my $symb=shift;
10790:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
10791:     my ($map,$resid,$url)=split(/___/,$symb);
10792:     return (&fixversion($map),$resid,&fixversion($url));
10793: }
10794: 
10795: sub fixversion {
10796:     my $fn=shift;
10797:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
10798:     my %bighash;
10799:     my $uri=&clutter($fn);
10800:     my $key=$env{'request.course.id'}.'_'.$uri;
10801: # is this cached?
10802:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
10803:     if (defined($cached)) { return $result; }
10804: # unfortunately not cached, or expired
10805:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10806: 	    &GDBM_READER(),0640)) {
10807:  	if ($bighash{'version_'.$uri}) {
10808:  	    my $version=$bighash{'version_'.$uri};
10809:  	    unless (($version eq 'mostrecent') || 
10810: 		    ($version==&getversion($uri))) {
10811:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
10812:  	    }
10813:  	}
10814:  	untie %bighash;
10815:     }
10816:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
10817: }
10818: 
10819: sub deversion {
10820:     my $url=shift;
10821:     $url=~s/\.\d+\.(\w+)$/\.$1/;
10822:     return $url;
10823: }
10824: 
10825: # ------------------------------------------------------ Return symb list entry
10826: 
10827: sub symbread {
10828:     my ($thisfn,$donotrecurse)=@_;
10829:     my $cache_str;
10830:     if ($thisfn ne '') {
10831:         $cache_str='request.symbread.cached.'.$thisfn;
10832:         if ($env{$cache_str} ne '') {
10833:             return $env{$cache_str};
10834:         }
10835:     } else {
10836: # no filename provided? try from environment
10837:         if ($env{'request.symb'}) {
10838: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
10839: 	}
10840: 	$thisfn=$env{'request.filename'};
10841:     }
10842:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
10843: # is that filename actually a symb? Verify, clean, and return
10844:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
10845: 	if (&symbverify($thisfn,$1)) {
10846: 	    return $env{$cache_str}=&symbclean($thisfn);
10847: 	}
10848:     }
10849:     $thisfn=declutter($thisfn);
10850:     my %hash;
10851:     my %bighash;
10852:     my $syval='';
10853:     if (($env{'request.course.fn'}) && ($thisfn)) {
10854:         my $targetfn = $thisfn;
10855:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
10856:             $targetfn = 'adm/wrapper/'.$thisfn;
10857:         }
10858: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
10859: 	    $targetfn=$1;
10860: 	}
10861:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
10862:                       &GDBM_READER(),0640)) {
10863: 	    $syval=$hash{$targetfn};
10864:             untie(%hash);
10865:         }
10866: # ---------------------------------------------------------- There was an entry
10867:         if ($syval) {
10868: 	    #unless ($syval=~/\_\d+$/) {
10869: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
10870: 		    #&appenv({'request.ambiguous' => $thisfn});
10871: 		    #return $env{$cache_str}='';
10872: 		#}    
10873: 		#$syval.=$1;
10874: 	    #}
10875:         } else {
10876: # ------------------------------------------------------- Was not in symb table
10877:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10878:                             &GDBM_READER(),0640)) {
10879: # ---------------------------------------------- Get ID(s) for current resource
10880:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
10881:               unless ($ids) { 
10882:                  $ids=$bighash{'ids_/'.$thisfn};
10883:               }
10884:               unless ($ids) {
10885: # alias?
10886: 		  $ids=$bighash{'mapalias_'.$thisfn};
10887:               }
10888:               if ($ids) {
10889: # ------------------------------------------------------------------- Has ID(s)
10890:                  my @possibilities=split(/\,/,$ids);
10891:                  if ($#possibilities==0) {
10892: # ----------------------------------------------- There is only one possibility
10893: 		     my ($mapid,$resid)=split(/\./,$ids);
10894: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
10895: 						    $resid,$thisfn);
10896:                  } elsif (!$donotrecurse) {
10897: # ------------------------------------------ There is more than one possibility
10898:                      my $realpossible=0;
10899:                      foreach my $id (@possibilities) {
10900: 			 my $file=$bighash{'src_'.$id};
10901:                          if (&allowed('bre',$file)) {
10902:          		    my ($mapid,$resid)=split(/\./,$id);
10903:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
10904: 				$realpossible++;
10905:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
10906: 						    $resid,$thisfn);
10907:                             }
10908: 			 }
10909:                      }
10910: 		     if ($realpossible!=1) { $syval=''; }
10911:                  } else {
10912:                      $syval='';
10913:                  }
10914: 	      }
10915:               untie(%bighash)
10916:            }
10917:         }
10918:         if ($syval) {
10919: 	    return $env{$cache_str}=$syval;
10920:         }
10921:     }
10922:     &appenv({'request.ambiguous' => $thisfn});
10923:     return $env{$cache_str}='';
10924: }
10925: 
10926: # ---------------------------------------------------------- Return random seed
10927: 
10928: sub numval {
10929:     my $txt=shift;
10930:     $txt=~tr/A-J/0-9/;
10931:     $txt=~tr/a-j/0-9/;
10932:     $txt=~tr/K-T/0-9/;
10933:     $txt=~tr/k-t/0-9/;
10934:     $txt=~tr/U-Z/0-5/;
10935:     $txt=~tr/u-z/0-5/;
10936:     $txt=~s/\D//g;
10937:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
10938:     return int($txt);
10939: }
10940: 
10941: sub numval2 {
10942:     my $txt=shift;
10943:     $txt=~tr/A-J/0-9/;
10944:     $txt=~tr/a-j/0-9/;
10945:     $txt=~tr/K-T/0-9/;
10946:     $txt=~tr/k-t/0-9/;
10947:     $txt=~tr/U-Z/0-5/;
10948:     $txt=~tr/u-z/0-5/;
10949:     $txt=~s/\D//g;
10950:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10951:     my $total;
10952:     foreach my $val (@txts) { $total+=$val; }
10953:     if ($_64bit) { if ($total > 2**32) { return -1; } }
10954:     return int($total);
10955: }
10956: 
10957: sub numval3 {
10958:     use integer;
10959:     my $txt=shift;
10960:     $txt=~tr/A-J/0-9/;
10961:     $txt=~tr/a-j/0-9/;
10962:     $txt=~tr/K-T/0-9/;
10963:     $txt=~tr/k-t/0-9/;
10964:     $txt=~tr/U-Z/0-5/;
10965:     $txt=~tr/u-z/0-5/;
10966:     $txt=~s/\D//g;
10967:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10968:     my $total;
10969:     foreach my $val (@txts) { $total+=$val; }
10970:     if ($_64bit) { $total=(($total<<32)>>32); }
10971:     return $total;
10972: }
10973: 
10974: sub digest {
10975:     my ($data)=@_;
10976:     my $digest=&Digest::MD5::md5($data);
10977:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
10978:     my ($e,$f);
10979:     {
10980:         use integer;
10981:         $e=($a+$b);
10982:         $f=($c+$d);
10983:         if ($_64bit) {
10984:             $e=(($e<<32)>>32);
10985:             $f=(($f<<32)>>32);
10986:         }
10987:     }
10988:     if (wantarray) {
10989: 	return ($e,$f);
10990:     } else {
10991: 	my $g;
10992: 	{
10993: 	    use integer;
10994: 	    $g=($e+$f);
10995: 	    if ($_64bit) {
10996: 		$g=(($g<<32)>>32);
10997: 	    }
10998: 	}
10999: 	return $g;
11000:     }
11001: }
11002: 
11003: sub latest_rnd_algorithm_id {
11004:     return '64bit5';
11005: }
11006: 
11007: sub get_rand_alg {
11008:     my ($courseid)=@_;
11009:     if (!$courseid) { $courseid=(&whichuser())[1]; }
11010:     if ($courseid) {
11011: 	return $env{"course.$courseid.rndseed"};
11012:     }
11013:     return &latest_rnd_algorithm_id();
11014: }
11015: 
11016: sub validCODE {
11017:     my ($CODE)=@_;
11018:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
11019:     return 0;
11020: }
11021: 
11022: sub getCODE {
11023:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
11024:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
11025: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
11026: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
11027: 	return $Apache::lonhomework::history{'resource.CODE'};
11028:     }
11029:     return undef;
11030: }
11031: #
11032: #  Determines the random seed for a specific context:
11033: #
11034: # parameters:
11035: #   symb      - in course context the symb for the seed.
11036: #   course_id - The course id of the form domain_coursenum.
11037: #   domain    - Domain for the user.
11038: #   course    - Course for the user.
11039: #   cenv      - environment of the course.
11040: #
11041: # NOTE:
11042: #   All parameters are picked out of the environment if missing
11043: #   or not defined.
11044: #   If a symb cannot be determined the current time is used instead.
11045: #
11046: #  For a given well defined symb, courside, domain, username,
11047: #  and course environment, the seed is reproducible.
11048: #
11049: sub rndseed {
11050:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
11051:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
11052:     if (!defined($symb)) {
11053: 	unless ($symb=$wsymb) { return time; }
11054:     }
11055:     if (!defined $courseid) { 
11056: 	$courseid=$wcourseid; 
11057:     }
11058:     if (!defined $domain) { $domain=$wdomain; }
11059:     if (!defined $username) { $username=$wusername }
11060: 
11061:     my $which;
11062:     if (defined($cenv->{'rndseed'})) {
11063: 	$which = $cenv->{'rndseed'};
11064:     } else {
11065: 	$which =&get_rand_alg($courseid);
11066:     }
11067:     if (defined(&getCODE())) {
11068: 
11069: 	if ($which eq '64bit5') {
11070: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
11071: 	} elsif ($which eq '64bit4') {
11072: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
11073: 	} else {
11074: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
11075: 	}
11076:     } elsif ($which eq '64bit5') {
11077: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
11078:     } elsif ($which eq '64bit4') {
11079: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
11080:     } elsif ($which eq '64bit3') {
11081: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
11082:     } elsif ($which eq '64bit2') {
11083: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
11084:     } elsif ($which eq '64bit') {
11085: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
11086:     }
11087:     return &rndseed_32bit($symb,$courseid,$domain,$username);
11088: }
11089: 
11090: sub rndseed_32bit {
11091:     my ($symb,$courseid,$domain,$username)=@_;
11092:     {
11093: 	use integer;
11094: 	my $symbchck=unpack("%32C*",$symb) << 27;
11095: 	my $symbseed=numval($symb) << 22;
11096: 	my $namechck=unpack("%32C*",$username) << 17;
11097: 	my $nameseed=numval($username) << 12;
11098: 	my $domainseed=unpack("%32C*",$domain) << 7;
11099: 	my $courseseed=unpack("%32C*",$courseid);
11100: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
11101: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11102: 	#&logthis("rndseed :$num:$symb");
11103: 	if ($_64bit) { $num=(($num<<32)>>32); }
11104: 	return $num;
11105:     }
11106: }
11107: 
11108: sub rndseed_64bit {
11109:     my ($symb,$courseid,$domain,$username)=@_;
11110:     {
11111: 	use integer;
11112: 	my $symbchck=unpack("%32S*",$symb) << 21;
11113: 	my $symbseed=numval($symb) << 10;
11114: 	my $namechck=unpack("%32S*",$username);
11115: 	
11116: 	my $nameseed=numval($username) << 21;
11117: 	my $domainseed=unpack("%32S*",$domain) << 10;
11118: 	my $courseseed=unpack("%32S*",$courseid);
11119: 	
11120: 	my $num1=$symbchck+$symbseed+$namechck;
11121: 	my $num2=$nameseed+$domainseed+$courseseed;
11122: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11123: 	#&logthis("rndseed :$num:$symb");
11124: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11125: 	return "$num1,$num2";
11126:     }
11127: }
11128: 
11129: sub rndseed_64bit2 {
11130:     my ($symb,$courseid,$domain,$username)=@_;
11131:     {
11132: 	use integer;
11133: 	# strings need to be an even # of cahracters long, it it is odd the
11134:         # last characters gets thrown away
11135: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
11136: 	my $symbseed=numval($symb) << 10;
11137: 	my $namechck=unpack("%32S*",$username.' ');
11138: 	
11139: 	my $nameseed=numval($username) << 21;
11140: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
11141: 	my $courseseed=unpack("%32S*",$courseid.' ');
11142: 	
11143: 	my $num1=$symbchck+$symbseed+$namechck;
11144: 	my $num2=$nameseed+$domainseed+$courseseed;
11145: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11146: 	#&logthis("rndseed :$num:$symb");
11147: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11148: 	return "$num1,$num2";
11149:     }
11150: }
11151: 
11152: sub rndseed_64bit3 {
11153:     my ($symb,$courseid,$domain,$username)=@_;
11154:     {
11155: 	use integer;
11156: 	# strings need to be an even # of cahracters long, it it is odd the
11157:         # last characters gets thrown away
11158: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
11159: 	my $symbseed=numval2($symb) << 10;
11160: 	my $namechck=unpack("%32S*",$username.' ');
11161: 	
11162: 	my $nameseed=numval2($username) << 21;
11163: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
11164: 	my $courseseed=unpack("%32S*",$courseid.' ');
11165: 	
11166: 	my $num1=$symbchck+$symbseed+$namechck;
11167: 	my $num2=$nameseed+$domainseed+$courseseed;
11168: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11169: 	#&logthis("rndseed :$num1:$num2:$_64bit");
11170: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11171: 	
11172: 	return "$num1:$num2";
11173:     }
11174: }
11175: 
11176: sub rndseed_64bit4 {
11177:     my ($symb,$courseid,$domain,$username)=@_;
11178:     {
11179: 	use integer;
11180: 	# strings need to be an even # of cahracters long, it it is odd the
11181:         # last characters gets thrown away
11182: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
11183: 	my $symbseed=numval3($symb) << 10;
11184: 	my $namechck=unpack("%32S*",$username.' ');
11185: 	
11186: 	my $nameseed=numval3($username) << 21;
11187: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
11188: 	my $courseseed=unpack("%32S*",$courseid.' ');
11189: 	
11190: 	my $num1=$symbchck+$symbseed+$namechck;
11191: 	my $num2=$nameseed+$domainseed+$courseseed;
11192: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11193: 	#&logthis("rndseed :$num1:$num2:$_64bit");
11194: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11195: 	
11196: 	return "$num1:$num2";
11197:     }
11198: }
11199: 
11200: sub rndseed_64bit5 {
11201:     my ($symb,$courseid,$domain,$username)=@_;
11202:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
11203:     return "$num1:$num2";
11204: }
11205: 
11206: sub rndseed_CODE_64bit {
11207:     my ($symb,$courseid,$domain,$username)=@_;
11208:     {
11209: 	use integer;
11210: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
11211: 	my $symbseed=numval2($symb);
11212: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11213: 	my $CODEseed=numval(&getCODE());
11214: 	my $courseseed=unpack("%32S*",$courseid.' ');
11215: 	my $num1=$symbseed+$CODEchck;
11216: 	my $num2=$CODEseed+$courseseed+$symbchck;
11217: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11218: 	#&logthis("rndseed :$num1:$num2:$symb");
11219: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
11220: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
11221: 	return "$num1:$num2";
11222:     }
11223: }
11224: 
11225: sub rndseed_CODE_64bit4 {
11226:     my ($symb,$courseid,$domain,$username)=@_;
11227:     {
11228: 	use integer;
11229: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
11230: 	my $symbseed=numval3($symb);
11231: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11232: 	my $CODEseed=numval3(&getCODE());
11233: 	my $courseseed=unpack("%32S*",$courseid.' ');
11234: 	my $num1=$symbseed+$CODEchck;
11235: 	my $num2=$CODEseed+$courseseed+$symbchck;
11236: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11237: 	#&logthis("rndseed :$num1:$num2:$symb");
11238: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
11239: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
11240: 	return "$num1:$num2";
11241:     }
11242: }
11243: 
11244: sub rndseed_CODE_64bit5 {
11245:     my ($symb,$courseid,$domain,$username)=@_;
11246:     my $code = &getCODE();
11247:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
11248:     return "$num1:$num2";
11249: }
11250: 
11251: sub setup_random_from_rndseed {
11252:     my ($rndseed)=@_;
11253:     if ($rndseed =~/([,:])/) {
11254: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
11255: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
11256:     } else {
11257: 	&Math::Random::random_set_seed_from_phrase($rndseed);
11258:     }
11259: }
11260: 
11261: sub latest_receipt_algorithm_id {
11262:     return 'receipt3';
11263: }
11264: 
11265: sub recunique {
11266:     my $fucourseid=shift;
11267:     my $unique;
11268:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
11269: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
11270: 	$unique=$env{"course.$fucourseid.internal.encseed"};
11271:     } else {
11272: 	$unique=$perlvar{'lonReceipt'};
11273:     }
11274:     return unpack("%32C*",$unique);
11275: }
11276: 
11277: sub recprefix {
11278:     my $fucourseid=shift;
11279:     my $prefix;
11280:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
11281: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
11282: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
11283:     } else {
11284: 	$prefix=$perlvar{'lonHostID'};
11285:     }
11286:     return unpack("%32C*",$prefix);
11287: }
11288: 
11289: sub ireceipt {
11290:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
11291: 
11292:     my $return =&recprefix($fucourseid).'-';
11293: 
11294:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
11295: 	$env{'request.state'} eq 'construct') {
11296: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
11297: 	return $return;
11298:     }
11299: 
11300:     my $cuname=unpack("%32C*",$funame);
11301:     my $cudom=unpack("%32C*",$fudom);
11302:     my $cucourseid=unpack("%32C*",$fucourseid);
11303:     my $cusymb=unpack("%32C*",$fusymb);
11304:     my $cunique=&recunique($fucourseid);
11305:     my $cpart=unpack("%32S*",$part);
11306:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
11307: 
11308: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
11309: 			       
11310: 	$return.= ($cunique%$cuname+
11311: 		   $cunique%$cudom+
11312: 		   $cusymb%$cuname+
11313: 		   $cusymb%$cudom+
11314: 		   $cucourseid%$cuname+
11315: 		   $cucourseid%$cudom+
11316: 		   $cpart%$cuname+
11317: 		   $cpart%$cudom);
11318:     } else {
11319: 	$return.= ($cunique%$cuname+
11320: 		   $cunique%$cudom+
11321: 		   $cusymb%$cuname+
11322: 		   $cusymb%$cudom+
11323: 		   $cucourseid%$cuname+
11324: 		   $cucourseid%$cudom);
11325:     }
11326:     return $return;
11327: }
11328: 
11329: sub receipt {
11330:     my ($part)=@_;
11331:     my ($symb,$courseid,$domain,$name) = &whichuser();
11332:     return &ireceipt($name,$domain,$courseid,$symb,$part);
11333: }
11334: 
11335: sub whichuser {
11336:     my ($passedsymb)=@_;
11337:     my ($symb,$courseid,$domain,$name,$publicuser);
11338:     if (defined($env{'form.grade_symb'})) {
11339: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
11340: 	my $allowed=&allowed('vgr',$tmp_courseid);
11341: 	if (!$allowed &&
11342: 	    exists($env{'request.course.sec'}) &&
11343: 	    $env{'request.course.sec'} !~ /^\s*$/) {
11344: 	    $allowed=&allowed('vgr',$tmp_courseid.
11345: 			      '/'.$env{'request.course.sec'});
11346: 	}
11347: 	if ($allowed) {
11348: 	    ($symb)=&get_env_multiple('form.grade_symb');
11349: 	    $courseid=$tmp_courseid;
11350: 	    ($domain)=&get_env_multiple('form.grade_domain');
11351: 	    ($name)=&get_env_multiple('form.grade_username');
11352: 	    return ($symb,$courseid,$domain,$name,$publicuser);
11353: 	}
11354:     }
11355:     if (!$passedsymb) {
11356: 	$symb=&symbread();
11357:     } else {
11358: 	$symb=$passedsymb;
11359:     }
11360:     $courseid=$env{'request.course.id'};
11361:     $domain=$env{'user.domain'};
11362:     $name=$env{'user.name'};
11363:     if ($name eq 'public' && $domain eq 'public') {
11364: 	if (!defined($env{'form.username'})) {
11365: 	    $env{'form.username'}.=time.rand(10000000);
11366: 	}
11367: 	$name.=$env{'form.username'};
11368:     }
11369:     return ($symb,$courseid,$domain,$name,$publicuser);
11370: 
11371: }
11372: 
11373: # ------------------------------------------------------------ Serves up a file
11374: # returns either the contents of the file or 
11375: # -1 if the file doesn't exist
11376: #
11377: # if the target is a file that was uploaded via DOCS, 
11378: # a check will be made to see if a current copy exists on the local server,
11379: # if it does this will be served, otherwise a copy will be retrieved from
11380: # the home server for the course and stored in /home/httpd/html/userfiles on
11381: # the local server.   
11382: 
11383: sub getfile {
11384:     my ($file) = @_;
11385:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
11386:     &repcopy($file);
11387:     return &readfile($file);
11388: }
11389: 
11390: sub repcopy_userfile {
11391:     my ($file)=@_;
11392:     my $londocroot = $perlvar{'lonDocRoot'};
11393:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
11394:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
11395:     my ($cdom,$cnum,$filename) = 
11396: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
11397:     my $uri="/uploaded/$cdom/$cnum/$filename";
11398:     if (-e "$file") {
11399: # we already have a local copy, check it out
11400: 	my @fileinfo = stat($file);
11401: 	my $rtncode;
11402: 	my $info;
11403: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
11404: 	if ($lwpresp ne 'ok') {
11405: # there is no such file anymore, even though we had a local copy
11406: 	    if ($rtncode eq '404') {
11407: 		unlink($file);
11408: 	    }
11409: 	    return -1;
11410: 	}
11411: 	if ($info < $fileinfo[9]) {
11412: # nice, the file we have is up-to-date, just say okay
11413: 	    return 'ok';
11414: 	} else {
11415: # the file is outdated, get rid of it
11416: 	    unlink($file);
11417: 	}
11418:     }
11419: # one way or the other, at this point, we don't have the file
11420: # construct the correct path for the file
11421:     my @parts = ($cdom,$cnum); 
11422:     if ($filename =~ m|^(.+)/[^/]+$|) {
11423: 	push @parts, split(/\//,$1);
11424:     }
11425:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
11426:     foreach my $part (@parts) {
11427: 	$path .= '/'.$part;
11428: 	if (!-e $path) {
11429: 	    mkdir($path,0770);
11430: 	}
11431:     }
11432: # now the path exists for sure
11433: # get a user agent
11434:     my $ua=new LWP::UserAgent;
11435:     my $transferfile=$file.'.in.transfer';
11436: # FIXME: this should flock
11437:     if (-e $transferfile) { return 'ok'; }
11438:     my $request;
11439:     $uri=~s/^\///;
11440:     my $homeserver = &homeserver($cnum,$cdom);
11441:     my $protocol = $protocol{$homeserver};
11442:     $protocol = 'http' if ($protocol ne 'https');
11443:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
11444:     my $response=$ua->request($request,$transferfile);
11445: # did it work?
11446:     if ($response->is_error()) {
11447: 	unlink($transferfile);
11448: 	&logthis("Userfile repcopy failed for $uri");
11449: 	return -1;
11450:     }
11451: # worked, rename the transfer file
11452:     rename($transferfile,$file);
11453:     return 'ok';
11454: }
11455: 
11456: sub tokenwrapper {
11457:     my $uri=shift;
11458:     $uri=~s|^https?\://([^/]+)||;
11459:     $uri=~s|^/||;
11460:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
11461:     my $token=$1;
11462:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
11463:     if ($udom && $uname && $file) {
11464: 	$file=~s|(\?\.*)*$||;
11465:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
11466:         my $homeserver = &homeserver($uname,$udom);
11467:         my $protocol = $protocol{$homeserver};
11468:         $protocol = 'http' if ($protocol ne 'https');
11469:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
11470:                (($uri=~/\?/)?'&':'?').'token='.$token.
11471:                                '&tokenissued='.$perlvar{'lonHostID'};
11472:     } else {
11473:         return '/adm/notfound.html';
11474:     }
11475: }
11476: 
11477: # call with reqtype HEAD: get last modification time
11478: # call with reqtype GET: get the file contents
11479: # Do not call this with reqtype GET for large files! It loads everything into memory
11480: #
11481: sub getuploaded {
11482:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
11483:     $uri=~s/^\///;
11484:     my $homeserver = &homeserver($cnum,$cdom);
11485:     my $protocol = $protocol{$homeserver};
11486:     $protocol = 'http' if ($protocol ne 'https');
11487:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
11488:     my $ua=new LWP::UserAgent;
11489:     my $request=new HTTP::Request($reqtype,$uri);
11490:     my $response=$ua->request($request);
11491:     $$rtncode = $response->code;
11492:     if (! $response->is_success()) {
11493: 	return 'failed';
11494:     }      
11495:     if ($reqtype eq 'HEAD') {
11496: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
11497:     } elsif ($reqtype eq 'GET') {
11498: 	$$info = $response->content;
11499:     }
11500:     return 'ok';
11501: }
11502: 
11503: sub readfile {
11504:     my $file = shift;
11505:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
11506:     my $fh;
11507:     open($fh,"<$file");
11508:     my $a='';
11509:     while (my $line = <$fh>) { $a .= $line; }
11510:     return $a;
11511: }
11512: 
11513: sub filelocation {
11514:     my ($dir,$file) = @_;
11515:     my $location;
11516:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
11517: 
11518:     if ($file =~ m-^/adm/-) {
11519: 	$file=~s-^/adm/wrapper/-/-;
11520: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
11521:     }
11522: 
11523:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
11524:         $location = $file;
11525:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
11526:         my ($udom,$uname,$filename)=
11527:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
11528:         my $home=&homeserver($uname,$udom);
11529:         my $is_me=0;
11530:         my @ids=&current_machine_ids();
11531:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
11532:         if ($is_me) {
11533:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
11534:         } else {
11535:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
11536:   	      $udom.'/'.$uname.'/'.$filename;
11537:         }
11538:     } elsif ($file =~ m-^/adm/-) {
11539: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
11540:     } else {
11541:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
11542:         $file=~s:^/(res|priv)/:/:;
11543:         my $space=$1;
11544:         if ( !( $file =~ m:^/:) ) {
11545:             $location = $dir. '/'.$file;
11546:         } else {
11547:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
11548:         }
11549:     }
11550:     $location=~s://+:/:g; # remove duplicate /
11551:     while ($location=~m{/\.\./}) {
11552: 	if ($location =~ m{/[^/]+/\.\./}) {
11553: 	    $location=~ s{/[^/]+/\.\./}{/}g;
11554: 	} else {
11555: 	    $location=~ s{/\.\./}{/}g;
11556: 	}
11557:     } #remove dir/..
11558:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
11559:     return $location;
11560: }
11561: 
11562: sub hreflocation {
11563:     my ($dir,$file)=@_;
11564:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
11565: 	$file=filelocation($dir,$file);
11566:     } elsif ($file=~m-^/adm/-) {
11567: 	$file=~s-^/adm/wrapper/-/-;
11568: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
11569:     }
11570:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
11571: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
11572:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
11573: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
11574: 	        {/uploaded/$1/$2/}x;
11575:     }
11576:     if ($file=~ m{^/userfiles/}) {
11577: 	$file =~ s{^/userfiles/}{/uploaded/};
11578:     }
11579:     return $file;
11580: }
11581: 
11582: 
11583: 
11584: 
11585: 
11586: sub current_machine_domains {
11587:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
11588: }
11589: 
11590: sub machine_domains {
11591:     my ($hostname) = @_;
11592:     my @domains;
11593:     my %hostname = &all_hostnames();
11594:     while( my($id, $name) = each(%hostname)) {
11595: #	&logthis("-$id-$name-$hostname-");
11596: 	if ($hostname eq $name) {
11597: 	    push(@domains,&host_domain($id));
11598: 	}
11599:     }
11600:     return @domains;
11601: }
11602: 
11603: sub current_machine_ids {
11604:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
11605: }
11606: 
11607: sub machine_ids {
11608:     my ($hostname) = @_;
11609:     $hostname ||= &hostname($perlvar{'lonHostID'});
11610:     my @ids;
11611:     my %name_to_host = &all_names();
11612:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
11613: 	return @{ $name_to_host{$hostname} };
11614:     }
11615:     return;
11616: }
11617: 
11618: sub additional_machine_domains {
11619:     my @domains;
11620:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
11621:     while( my $line = <$fh>) {
11622:         $line =~ s/\s//g;
11623:         push(@domains,$line);
11624:     }
11625:     return @domains;
11626: }
11627: 
11628: sub default_login_domain {
11629:     my $domain = $perlvar{'lonDefDomain'};
11630:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
11631:     foreach my $posdom (&current_machine_domains(),
11632:                         &additional_machine_domains()) {
11633:         if (lc($posdom) eq lc($testdomain)) {
11634:             $domain=$posdom;
11635:             last;
11636:         }
11637:     }
11638:     return $domain;
11639: }
11640: 
11641: # ------------------------------------------------------------- Declutters URLs
11642: 
11643: sub declutter {
11644:     my $thisfn=shift;
11645:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
11646:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
11647:     $thisfn=~s/^\///;
11648:     $thisfn=~s|^adm/wrapper/||;
11649:     $thisfn=~s|^adm/coursedocs/showdoc/||;
11650:     $thisfn=~s/^res\///;
11651:     $thisfn=~s/^priv\///;
11652:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
11653:         $thisfn=~s/\?.+$//;
11654:     }
11655:     return $thisfn;
11656: }
11657: 
11658: # ------------------------------------------------------------- Clutter up URLs
11659: 
11660: sub clutter {
11661:     my $thisfn='/'.&declutter(shift);
11662:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
11663: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
11664:        $thisfn='/res'.$thisfn; 
11665:     }
11666:     if ($thisfn !~m|^/adm|) {
11667: 	if ($thisfn =~ m|^/ext/|) {
11668: 	    $thisfn='/adm/wrapper'.$thisfn;
11669: 	} else {
11670: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
11671: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
11672: 	    if ($embstyle eq 'ssi'
11673: 		|| ($embstyle eq 'hdn')
11674: 		|| ($embstyle eq 'rat')
11675: 		|| ($embstyle eq 'prv')
11676: 		|| ($embstyle eq 'ign')) {
11677: 		#do nothing with these
11678: 	    } elsif (($embstyle eq 'img') 
11679: 		|| ($embstyle eq 'emb')
11680: 		|| ($embstyle eq 'wrp')) {
11681: 		$thisfn='/adm/wrapper'.$thisfn;
11682: 	    } elsif ($embstyle eq 'unk'
11683: 		     && $thisfn!~/\.(sequence|page)$/) {
11684: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
11685: 	    } else {
11686: #		&logthis("Got a blank emb style");
11687: 	    }
11688: 	}
11689:     }
11690:     return $thisfn;
11691: }
11692: 
11693: sub clutter_with_no_wrapper {
11694:     my $uri = &clutter(shift);
11695:     if ($uri =~ m-^/adm/-) {
11696: 	$uri =~ s-^/adm/wrapper/-/-;
11697: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
11698:     }
11699:     return $uri;
11700: }
11701: 
11702: sub freeze_escape {
11703:     my ($value)=@_;
11704:     if (ref($value)) {
11705: 	$value=&nfreeze($value);
11706: 	return '__FROZEN__'.&escape($value);
11707:     }
11708:     return &escape($value);
11709: }
11710: 
11711: 
11712: sub thaw_unescape {
11713:     my ($value)=@_;
11714:     if ($value =~ /^__FROZEN__/) {
11715: 	substr($value,0,10,undef);
11716: 	$value=&unescape($value);
11717: 	return &thaw($value);
11718:     }
11719:     return &unescape($value);
11720: }
11721: 
11722: sub correct_line_ends {
11723:     my ($result)=@_;
11724:     $$result =~s/\r\n/\n/mg;
11725:     $$result =~s/\r/\n/mg;
11726: }
11727: # ================================================================ Main Program
11728: 
11729: sub goodbye {
11730:    &logthis("Starting Shut down");
11731: #not converted to using infrastruture and probably shouldn't be
11732:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
11733: #converted
11734: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
11735:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
11736: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
11737: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
11738: #1.1 only
11739: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
11740: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
11741: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
11742: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
11743:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
11744:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
11745:    &logthis(sprintf("%-20s is %s",'hits',$hits));
11746:    &flushcourselogs();
11747:    &logthis("Shutting down");
11748: }
11749: 
11750: sub get_dns {
11751:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
11752:     if (!$ignore_cache) {
11753: 	my ($content,$cached)=
11754: 	    &Apache::lonnet::is_cached_new('dns',$url);
11755: 	if ($cached) {
11756: 	    &$func($content,$hashref);
11757: 	    return;
11758: 	}
11759:     }
11760: 
11761:     my %alldns;
11762:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11763:     foreach my $dns (<$config>) {
11764: 	next if ($dns !~ /^\^(\S*)/x);
11765:         my $line = $1;
11766:         my ($host,$protocol) = split(/:/,$line);
11767:         if ($protocol ne 'https') {
11768:             $protocol = 'http';
11769:         }
11770: 	$alldns{$host} = $protocol;
11771:     }
11772:     while (%alldns) {
11773: 	my ($dns) = keys(%alldns);
11774: 	my $ua=new LWP::UserAgent;
11775:         $ua->timeout(30);
11776: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
11777: 	my $response=$ua->request($request);
11778:         delete($alldns{$dns});
11779: 	next if ($response->is_error());
11780: 	my @content = split("\n",$response->content);
11781: 	unless ($nocache) {
11782: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
11783: 	}
11784: 	&$func(\@content,$hashref);
11785: 	return;
11786:     }
11787:     close($config);
11788:     my $which = (split('/',$url))[3];
11789:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
11790:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
11791:     my @content = <$config>;
11792:     &$func(\@content,$hashref);
11793:     return;
11794: }
11795: 
11796: # ------------------------------------------------------Get DNS checksums file
11797: sub parse_dns_checksums_tab {
11798:     my ($lines,$hashref) = @_;
11799:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
11800:     my $loncaparev = &get_server_loncaparev($machine_dom);
11801:     my ($release,$timestamp) = split(/\-/,$loncaparev);
11802:     my (%chksum,%revnum);
11803:     if (ref($lines) eq 'ARRAY') {
11804:         chomp(@{$lines});
11805:         my $version = shift(@{$lines});
11806:         if ($version eq $release) {  
11807:             foreach my $line (@{$lines}) {
11808:                 my ($file,$version,$shasum) = split(/,/,$line);
11809:                 $chksum{$file} = $shasum;
11810:                 $revnum{$file} = $version;
11811:             }
11812:             if (ref($hashref) eq 'HASH') {
11813:                 %{$hashref} = (
11814:                                 sums     => \%chksum,
11815:                                 versions => \%revnum,
11816:                               );
11817:             }
11818:         }
11819:     }
11820:     return;
11821: }
11822: 
11823: sub fetch_dns_checksums {
11824:     my %checksums;
11825:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
11826:     my $loncaparev = &get_server_loncaparev($machine_dom);
11827:     my ($release,$timestamp) = split(/\-/,$loncaparev);
11828:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
11829:              \%checksums);
11830:     return \%checksums;
11831: }
11832: 
11833: # ------------------------------------------------------------ Read domain file
11834: {
11835:     my $loaded;
11836:     my %domain;
11837: 
11838:     sub parse_domain_tab {
11839: 	my ($lines) = @_;
11840: 	foreach my $line (@$lines) {
11841: 	    next if ($line =~ /^(\#|\s*$ )/x);
11842: 
11843: 	    chomp($line);
11844: 	    my ($name,@elements) = split(/:/,$line,9);
11845: 	    my %this_domain;
11846: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
11847: 			       'lang_def', 'city', 'longi', 'lati',
11848: 			       'primary') {
11849: 		$this_domain{$field} = shift(@elements);
11850: 	    }
11851: 	    $domain{$name} = \%this_domain;
11852: 	}
11853:     }
11854: 
11855:     sub reset_domain_info {
11856: 	undef($loaded);
11857: 	undef(%domain);
11858:     }
11859: 
11860:     sub load_domain_tab {
11861: 	my ($ignore_cache) = @_;
11862: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
11863: 	my $fh;
11864: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
11865: 	    my @lines = <$fh>;
11866: 	    &parse_domain_tab(\@lines);
11867: 	}
11868: 	close($fh);
11869: 	$loaded = 1;
11870:     }
11871: 
11872:     sub domain {
11873: 	&load_domain_tab() if (!$loaded);
11874: 
11875: 	my ($name,$what) = @_;
11876: 	return if ( !exists($domain{$name}) );
11877: 
11878: 	if (!$what) {
11879: 	    return $domain{$name}{'description'};
11880: 	}
11881: 	return $domain{$name}{$what};
11882:     }
11883: 
11884:     sub domain_info {
11885:         &load_domain_tab() if (!$loaded);
11886:         return %domain;
11887:     }
11888: 
11889: }
11890: 
11891: 
11892: # ------------------------------------------------------------- Read hosts file
11893: {
11894:     my %hostname;
11895:     my %hostdom;
11896:     my %libserv;
11897:     my $loaded;
11898:     my %name_to_host;
11899:     my %internetdom;
11900:     my %LC_dns_serv;
11901: 
11902:     sub parse_hosts_tab {
11903: 	my ($file) = @_;
11904: 	foreach my $configline (@$file) {
11905: 	    next if ($configline =~ /^(\#|\s*$ )/x);
11906:             chomp($configline);
11907: 	    if ($configline =~ /^\^/) {
11908:                 if ($configline =~ /^\^([\w.\-]+)/) {
11909:                     $LC_dns_serv{$1} = 1;
11910:                 }
11911:                 next;
11912:             }
11913: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
11914: 	    $name=~s/\s//g;
11915: 	    if ($id && $domain && $role && $name) {
11916: 		$hostname{$id}=$name;
11917: 		push(@{$name_to_host{$name}}, $id);
11918: 		$hostdom{$id}=$domain;
11919: 		if ($role eq 'library') { $libserv{$id}=$name; }
11920:                 if (defined($protocol)) {
11921:                     if ($protocol eq 'https') {
11922:                         $protocol{$id} = $protocol;
11923:                     } else {
11924:                         $protocol{$id} = 'http'; 
11925:                     }
11926:                 } else {
11927:                     $protocol{$id} = 'http';
11928:                 }
11929:                 if (defined($intdom)) {
11930:                     $internetdom{$id} = $intdom;
11931:                 }
11932: 	    }
11933: 	}
11934:     }
11935:     
11936:     sub reset_hosts_info {
11937: 	&purge_remembered();
11938: 	&reset_domain_info();
11939: 	&reset_hosts_ip_info();
11940: 	undef(%name_to_host);
11941: 	undef(%hostname);
11942: 	undef(%hostdom);
11943: 	undef(%libserv);
11944: 	undef($loaded);
11945:     }
11946: 
11947:     sub load_hosts_tab {
11948: 	my ($ignore_cache) = @_;
11949: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
11950: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11951: 	my @config = <$config>;
11952: 	&parse_hosts_tab(\@config);
11953: 	close($config);
11954: 	$loaded=1;
11955:     }
11956: 
11957:     sub hostname {
11958: 	&load_hosts_tab() if (!$loaded);
11959: 
11960: 	my ($lonid) = @_;
11961: 	return $hostname{$lonid};
11962:     }
11963: 
11964:     sub all_hostnames {
11965: 	&load_hosts_tab() if (!$loaded);
11966: 
11967: 	return %hostname;
11968:     }
11969: 
11970:     sub all_names {
11971: 	&load_hosts_tab() if (!$loaded);
11972: 
11973: 	return %name_to_host;
11974:     }
11975: 
11976:     sub all_host_domain {
11977:         &load_hosts_tab() if (!$loaded);
11978:         return %hostdom;
11979:     }
11980: 
11981:     sub is_library {
11982: 	&load_hosts_tab() if (!$loaded);
11983: 
11984: 	return exists($libserv{$_[0]});
11985:     }
11986: 
11987:     sub all_library {
11988: 	&load_hosts_tab() if (!$loaded);
11989: 
11990: 	return %libserv;
11991:     }
11992: 
11993:     sub unique_library {
11994: 	#2x reverse removes all hostnames that appear more than once
11995:         my %unique = reverse &all_library();
11996:         return reverse %unique;
11997:     }
11998: 
11999:     sub get_servers {
12000: 	&load_hosts_tab() if (!$loaded);
12001: 
12002: 	my ($domain,$type) = @_;
12003: 	my %possible_hosts = ($type eq 'library') ? %libserv
12004: 	                                          : %hostname;
12005: 	my %result;
12006: 	if (ref($domain) eq 'ARRAY') {
12007: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
12008: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
12009: 		    $result{$host} = $hostname;
12010: 		}
12011: 	    }
12012: 	} else {
12013: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
12014: 		if ($hostdom{$host} eq $domain) {
12015: 		    $result{$host} = $hostname;
12016: 		}
12017: 	    }
12018: 	}
12019: 	return %result;
12020:     }
12021: 
12022:     sub get_unique_servers {
12023:         my %unique = reverse &get_servers(@_);
12024: 	return reverse %unique;
12025:     }
12026: 
12027:     sub host_domain {
12028: 	&load_hosts_tab() if (!$loaded);
12029: 
12030: 	my ($lonid) = @_;
12031: 	return $hostdom{$lonid};
12032:     }
12033: 
12034:     sub all_domains {
12035: 	&load_hosts_tab() if (!$loaded);
12036: 
12037: 	my %seen;
12038: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
12039: 	return @uniq;
12040:     }
12041: 
12042:     sub internet_dom {
12043:         &load_hosts_tab() if (!$loaded);
12044: 
12045:         my ($lonid) = @_;
12046:         return $internetdom{$lonid};
12047:     }
12048: 
12049:     sub is_LC_dns {
12050:         &load_hosts_tab() if (!$loaded);
12051: 
12052:         my ($hostname) = @_;
12053:         return exists($LC_dns_serv{$hostname});
12054:     }
12055: 
12056: }
12057: 
12058: { 
12059:     my %iphost;
12060:     my %name_to_ip;
12061:     my %lonid_to_ip;
12062: 
12063:     sub get_hosts_from_ip {
12064: 	my ($ip) = @_;
12065: 	my %iphosts = &get_iphost();
12066: 	if (ref($iphosts{$ip})) {
12067: 	    return @{$iphosts{$ip}};
12068: 	}
12069: 	return;
12070:     }
12071:     
12072:     sub reset_hosts_ip_info {
12073: 	undef(%iphost);
12074: 	undef(%name_to_ip);
12075: 	undef(%lonid_to_ip);
12076:     }
12077: 
12078:     sub get_host_ip {
12079: 	my ($lonid) = @_;
12080: 	if (exists($lonid_to_ip{$lonid})) {
12081: 	    return $lonid_to_ip{$lonid};
12082: 	}
12083: 	my $name=&hostname($lonid);
12084:    	my $ip = gethostbyname($name);
12085: 	return if (!$ip || length($ip) ne 4);
12086: 	$ip=inet_ntoa($ip);
12087: 	$name_to_ip{$name}   = $ip;
12088: 	$lonid_to_ip{$lonid} = $ip;
12089: 	return $ip;
12090:     }
12091:     
12092:     sub get_iphost {
12093: 	my ($ignore_cache) = @_;
12094: 
12095: 	if (!$ignore_cache) {
12096: 	    if (%iphost) {
12097: 		return %iphost;
12098: 	    }
12099: 	    my ($ip_info,$cached)=
12100: 		&Apache::lonnet::is_cached_new('iphost','iphost');
12101: 	    if ($cached) {
12102: 		%iphost      = %{$ip_info->[0]};
12103: 		%name_to_ip  = %{$ip_info->[1]};
12104: 		%lonid_to_ip = %{$ip_info->[2]};
12105: 		return %iphost;
12106: 	    }
12107: 	}
12108: 
12109: 	# get yesterday's info for fallback
12110: 	my %old_name_to_ip;
12111: 	my ($ip_info,$cached)=
12112: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
12113: 	if ($cached) {
12114: 	    %old_name_to_ip = %{$ip_info->[1]};
12115: 	}
12116: 
12117: 	my %name_to_host = &all_names();
12118: 	foreach my $name (keys(%name_to_host)) {
12119: 	    my $ip;
12120: 	    if (!exists($name_to_ip{$name})) {
12121: 		$ip = gethostbyname($name);
12122: 		if (!$ip || length($ip) ne 4) {
12123: 		    if (defined($old_name_to_ip{$name})) {
12124: 			$ip = $old_name_to_ip{$name};
12125: 			&logthis("Can't find $name defaulting to old $ip");
12126: 		    } else {
12127: 			&logthis("Name $name no IP found");
12128: 			next;
12129: 		    }
12130: 		} else {
12131: 		    $ip=inet_ntoa($ip);
12132: 		}
12133: 		$name_to_ip{$name} = $ip;
12134: 	    } else {
12135: 		$ip = $name_to_ip{$name};
12136: 	    }
12137: 	    foreach my $id (@{ $name_to_host{$name} }) {
12138: 		$lonid_to_ip{$id} = $ip;
12139: 	    }
12140: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
12141: 	}
12142: 	&do_cache_new('iphost','iphost',
12143: 		      [\%iphost,\%name_to_ip,\%lonid_to_ip],
12144: 		      48*60*60);
12145: 
12146: 	return %iphost;
12147:     }
12148: 
12149:     #
12150:     #  Given a DNS returns the loncapa host name for that DNS 
12151:     # 
12152:     sub host_from_dns {
12153:         my ($dns) = @_;
12154:         my @hosts;
12155:         my $ip;
12156: 
12157:         if (exists($name_to_ip{$dns})) {
12158:             $ip = $name_to_ip{$dns};
12159:         }
12160:         if (!$ip) {
12161:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
12162:             if (length($ip) == 4) { 
12163: 	        $ip   = &IO::Socket::inet_ntoa($ip);
12164:             }
12165:         }
12166:         if ($ip) {
12167: 	    @hosts = get_hosts_from_ip($ip);
12168: 	    return $hosts[0];
12169:         }
12170:         return undef;
12171:     }
12172: 
12173:     sub get_internet_names {
12174:         my ($lonid) = @_;
12175:         return if ($lonid eq '');
12176:         my ($idnref,$cached)=
12177:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
12178:         if ($cached) {
12179:             return $idnref;
12180:         }
12181:         my $ip = &get_host_ip($lonid);
12182:         my @hosts = &get_hosts_from_ip($ip);
12183:         my %iphost = &get_iphost();
12184:         my (@idns,%seen);
12185:         foreach my $id (@hosts) {
12186:             my $dom = &host_domain($id);
12187:             my $prim_id = &domain($dom,'primary');
12188:             my $prim_ip = &get_host_ip($prim_id);
12189:             next if ($seen{$prim_ip});
12190:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
12191:                 foreach my $id (@{$iphost{$prim_ip}}) {
12192:                     my $intdom = &internet_dom($id);
12193:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
12194:                         push(@idns,$intdom);
12195:                     }
12196:                 }
12197:             }
12198:             $seen{$prim_ip} = 1;
12199:         }
12200:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
12201:     }
12202: 
12203: }
12204: 
12205: sub all_loncaparevs {
12206:     return qw(1.1 1.2 1.3 2.0 2.1 2.2 2.3 2.4 2.5 2.6 2.7 2.8 2.9 2.10 2.11);
12207: }
12208: 
12209: # ---------------------------------------------------------- Read loncaparev table
12210: {
12211:     sub load_loncaparevs { 
12212:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
12213:             if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
12214:                 while (my $configline=<$config>) {
12215:                     chomp($configline);
12216:                     my ($hostid,$loncaparev)=split(/:/,$configline);
12217:                     $loncaparevs{$hostid}=$loncaparev;
12218:                 }
12219:                 close($config);
12220:             }
12221:         }
12222:     }
12223: }
12224: 
12225: # ---------------------------------------------------------- Read serverhostID table
12226: {
12227:     sub load_serverhomeIDs {
12228:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
12229:             if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
12230:                 while (my $configline=<$config>) {
12231:                     chomp($configline);
12232:                     my ($name,$id)=split(/:/,$configline);
12233:                     $serverhomeIDs{$name}=$id;
12234:                 }
12235:                 close($config);
12236:             }
12237:         }
12238:     }
12239: }
12240: 
12241: 
12242: BEGIN {
12243: 
12244: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
12245:     unless ($readit) {
12246: {
12247:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
12248:     %perlvar = (%perlvar,%{$configvars});
12249: }
12250: 
12251: 
12252: # ------------------------------------------------------ Read spare server file
12253: {
12254:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
12255: 
12256:     while (my $configline=<$config>) {
12257:        chomp($configline);
12258:        if ($configline) {
12259: 	   my ($host,$type) = split(':',$configline,2);
12260: 	   if (!defined($type) || $type eq '') { $type = 'default' };
12261: 	   push(@{ $spareid{$type} }, $host);
12262:        }
12263:     }
12264:     close($config);
12265: }
12266: # ------------------------------------------------------------ Read permissions
12267: {
12268:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
12269: 
12270:     while (my $configline=<$config>) {
12271: 	chomp($configline);
12272: 	if ($configline) {
12273: 	    my ($role,$perm)=split(/ /,$configline);
12274: 	    if ($perm ne '') { $pr{$role}=$perm; }
12275: 	}
12276:     }
12277:     close($config);
12278: }
12279: 
12280: # -------------------------------------------- Read plain texts for permissions
12281: {
12282:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
12283: 
12284:     while (my $configline=<$config>) {
12285: 	chomp($configline);
12286: 	if ($configline) {
12287: 	    my ($short,@plain)=split(/:/,$configline);
12288:             %{$prp{$short}} = ();
12289: 	    if (@plain > 0) {
12290:                 $prp{$short}{'std'} = $plain[0];
12291:                 for (my $i=1; $i<@plain; $i++) {
12292:                     $prp{$short}{'alt'.$i} = $plain[$i];  
12293:                 }
12294:             }
12295: 	}
12296:     }
12297:     close($config);
12298: }
12299: 
12300: # ---------------------------------------------------------- Read package table
12301: {
12302:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
12303: 
12304:     while (my $configline=<$config>) {
12305: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
12306: 	chomp($configline);
12307: 	my ($short,$plain)=split(/:/,$configline);
12308: 	my ($pack,$name)=split(/\&/,$short);
12309: 	if ($plain ne '') {
12310: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
12311: 	    $packagetab{$short}=$plain; 
12312: 	}
12313:     }
12314:     close($config);
12315: }
12316: 
12317: # ---------------------------------------------------------- Read loncaparev table
12318: 
12319: &load_loncaparevs();
12320: 
12321: # ---------------------------------------------------------- Read serverhostID table
12322: 
12323: &load_serverhomeIDs();
12324: 
12325: # ---------------------------------------------------------- Read releaseslist XML
12326: {
12327:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
12328:     if (-e $file) {
12329:         my $parser = HTML::LCParser->new($file);
12330:         while (my $token = $parser->get_token()) {
12331:             if ($token->[0] eq 'S') {
12332:                 my $item = $token->[1];
12333:                 my $name = $token->[2]{'name'};
12334:                 my $value = $token->[2]{'value'};
12335:                 if ($item ne '' && $name ne '' && $value ne '') {
12336:                     my $release = $parser->get_text();
12337:                     $release =~ s/(^\s*|\s*$ )//gx;
12338:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
12339:                 }
12340:             }
12341:         }
12342:     }
12343: }
12344: 
12345: # ---------------------------------------------------------- Read managers table
12346: {
12347:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
12348:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
12349:             while (my $configline=<$config>) {
12350:                 chomp($configline);
12351:                 next if ($configline =~ /^\#/);
12352:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
12353:                     $managerstab{$configline} = 1;
12354:                 }
12355:             }
12356:             close($config);
12357:         }
12358:     }
12359: }
12360: 
12361: # ------------- set up temporary directory
12362: {
12363:     $tmpdir = LONCAPA::tempdir();
12364: 
12365: }
12366: 
12367: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
12368: 				'compress_threshold'=> 20_000,
12369:  			        });
12370: 
12371: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
12372: $dumpcount=0;
12373: $locknum=0;
12374: 
12375: &logtouch();
12376: &logthis('<font color="yellow">INFO: Read configuration</font>');
12377: $readit=1;
12378:     {
12379: 	use integer;
12380: 	my $test=(2**32)+1;
12381: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
12382: 	&logthis(" Detected 64bit platform ($_64bit)");
12383:     }
12384: }
12385: }
12386: 
12387: 1;
12388: __END__
12389: 
12390: =pod
12391: 
12392: =head1 NAME
12393: 
12394: Apache::lonnet - Subroutines to ask questions about things in the network.
12395: 
12396: =head1 SYNOPSIS
12397: 
12398: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
12399: 
12400:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
12401: 
12402: Common parameters:
12403: 
12404: =over 4
12405: 
12406: =item *
12407: 
12408: $uname : an internal username (if $cname expecting a course Id specifically)
12409: 
12410: =item *
12411: 
12412: $udom : a domain (if $cdom expecting a course's domain specifically)
12413: 
12414: =item *
12415: 
12416: $symb : a resource instance identifier
12417: 
12418: =item *
12419: 
12420: $namespace : the name of a .db file that contains the data needed or
12421: being set.
12422: 
12423: =back
12424: 
12425: =head1 OVERVIEW
12426: 
12427: lonnet provides subroutines which interact with the
12428: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
12429: about classes, users, and resources.
12430: 
12431: For many of these objects you can also use this to store data about
12432: them or modify them in various ways.
12433: 
12434: =head2 Symbs
12435: 
12436: To identify a specific instance of a resource, LON-CAPA uses symbols
12437: or "symbs"X<symb>. These identifiers are built from the URL of the
12438: map, the resource number of the resource in the map, and the URL of
12439: the resource itself. The latter is somewhat redundant, but might help
12440: if maps change.
12441: 
12442: An example is
12443: 
12444:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
12445: 
12446: The respective map entry is
12447: 
12448:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
12449:   title="Problem 2">
12450:  </resource>
12451: 
12452: Symbs are used by the random number generator, as well as to store and
12453: restore data specific to a certain instance of for example a problem.
12454: 
12455: =head2 Storing And Retrieving Data
12456: 
12457: X<store()>X<cstore()>X<restore()>Three of the most important functions
12458: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
12459: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
12460: is is the non-critical message twin of cstore. These functions are for
12461: handlers to store a perl hash to a user's permanent data space in an
12462: easy manner, and to retrieve it again on another call. It is expected
12463: that a handler would use this once at the beginning to retrieve data,
12464: and then again once at the end to send only the new data back.
12465: 
12466: The data is stored in the user's data directory on the user's
12467: homeserver under the ID of the course.
12468: 
12469: The hash that is returned by restore will have all of the previous
12470: value for all of the elements of the hash.
12471: 
12472: Example:
12473: 
12474:  #creating a hash
12475:  my %hash;
12476:  $hash{'foo'}='bar';
12477: 
12478:  #storing it
12479:  &Apache::lonnet::cstore(\%hash);
12480: 
12481:  #changing a value
12482:  $hash{'foo'}='notbar';
12483: 
12484:  #adding a new value
12485:  $hash{'bar'}='foo';
12486:  &Apache::lonnet::cstore(\%hash);
12487: 
12488:  #retrieving the hash
12489:  my %history=&Apache::lonnet::restore();
12490: 
12491:  #print the hash
12492:  foreach my $key (sort(keys(%history))) {
12493:    print("\%history{$key} = $history{$key}");
12494:  }
12495: 
12496: Will print out:
12497: 
12498:  %history{1:foo} = bar
12499:  %history{1:keys} = foo:timestamp
12500:  %history{1:timestamp} = 990455579
12501:  %history{2:bar} = foo
12502:  %history{2:foo} = notbar
12503:  %history{2:keys} = foo:bar:timestamp
12504:  %history{2:timestamp} = 990455580
12505:  %history{bar} = foo
12506:  %history{foo} = notbar
12507:  %history{timestamp} = 990455580
12508:  %history{version} = 2
12509: 
12510: Note that the special hash entries C<keys>, C<version> and
12511: C<timestamp> were added to the hash. C<version> will be equal to the
12512: total number of versions of the data that have been stored. The
12513: C<timestamp> attribute will be the UNIX time the hash was
12514: stored. C<keys> is available in every historical section to list which
12515: keys were added or changed at a specific historical revision of a
12516: hash.
12517: 
12518: B<Warning>: do not store the hash that restore returns directly. This
12519: will cause a mess since it will restore the historical keys as if the
12520: were new keys. I.E. 1:foo will become 1:1:foo etc.
12521: 
12522: Calling convention:
12523: 
12524:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
12525:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname);
12526: 
12527: For more detailed information, see lonnet specific documentation.
12528: 
12529: =head1 RETURN MESSAGES
12530: 
12531: =over 4
12532: 
12533: =item * B<con_lost>: unable to contact remote host
12534: 
12535: =item * B<con_delayed>: unable to contact remote host, message will be delivered
12536: when the connection is brought back up
12537: 
12538: =item * B<con_failed>: unable to contact remote host and unable to save message
12539: for later delivery
12540: 
12541: =item * B<error:>: an error a occurred, a description of the error follows the :
12542: 
12543: =item * B<no_such_host>: unable to fund a host associated with the user/domain
12544: that was requested
12545: 
12546: =back
12547: 
12548: =head1 PUBLIC SUBROUTINES
12549: 
12550: =head2 Session Environment Functions
12551: 
12552: =over 4
12553: 
12554: =item * 
12555: X<appenv()>
12556: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
12557: the user envirnoment file, and will be restored for each access this
12558: user makes during this session, also modifies the %env for the current
12559: process. Optional rolesarrayref - if defined contains a reference to an array
12560: of roles which are exempt from the restriction on modifying user.role entries 
12561: in the user's environment.db and in %env.    
12562: 
12563: =item *
12564: X<delenv()>
12565: B<delenv($delthis,$regexp)>: removes all items from the session
12566: environment file that begin with $delthis. If the 
12567: optional second arg - $regexp - is true, $delthis is treated as a 
12568: regular expression, otherwise \Q$delthis\E is used. 
12569: The values are also deleted from the current processes %env.
12570: 
12571: =item * get_env_multiple($name) 
12572: 
12573: gets $name from the %env hash, it seemlessly handles the cases where multiple
12574: values may be defined and end up as an array ref.
12575: 
12576: returns an array of values
12577: 
12578: =back
12579: 
12580: =head2 User Information
12581: 
12582: =over 4
12583: 
12584: =item *
12585: X<queryauthenticate()>
12586: B<queryauthenticate($uname,$udom)>: try to determine user's current 
12587: authentication scheme
12588: 
12589: =item *
12590: X<authenticate()>
12591: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
12592: authenticate user from domain's lib servers (first use the current
12593: one). C<$upass> should be the users password.
12594: $checkdefauth is optional (value is 1 if a check should be made to
12595:    authenticate user using default authentication method, and allow
12596:    account creation if username does not have account in the domain).
12597: $clientcancheckhost is optional (value is 1 if checking whether the
12598:    server can host will occur on the client side in lonauth.pm).   
12599: 
12600: =item *
12601: X<homeserver()>
12602: B<homeserver($uname,$udom)>: find the server which has
12603: the user's directory and files (there must be only one), this caches
12604: the answer, and also caches if there is a borken connection.
12605: 
12606: =item *
12607: X<idget()>
12608: B<idget($udom,@ids)>: find the usernames behind a list of IDs
12609: (IDs are a unique resource in a domain, there must be only 1 ID per
12610: username, and only 1 username per ID in a specific domain) (returns
12611: hash: id=>name,id=>name)
12612: 
12613: =item *
12614: X<idrget()>
12615: B<idrget($udom,@unames)>: find the IDs behind a list of
12616: usernames (returns hash: name=>id,name=>id)
12617: 
12618: =item *
12619: X<idput()>
12620: B<idput($udom,%ids)>: store away a list of names and associated IDs
12621: 
12622: =item *
12623: X<rolesinit()>
12624: B<rolesinit($udom,$username)>: get user privileges.
12625: returns user role, first access and timer interval hashes
12626: 
12627: =item *
12628: X<privileged()>
12629: B<privileged($username,$domain)>: returns a true if user has a
12630: privileged and active role (i.e. su or dc), false otherwise.
12631: 
12632: =item *
12633: X<getsection()>
12634: B<getsection($udom,$uname,$cname)>: finds the section of student in the
12635: course $cname, return section name/number or '' for "not in course"
12636: and '-1' for "no section"
12637: 
12638: =item *
12639: X<userenvironment()>
12640: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
12641: passed in @what from the requested user's environment, returns a hash
12642: 
12643: =item * 
12644: X<userlog_query()>
12645: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
12646: activity.log file. %filters defines filters applied when parsing the
12647: log file. These can be start or end timestamps, or the type of action
12648: - log to look for Login or Logout events, check for Checkin or
12649: Checkout, role for role selection. The response is in the form
12650: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
12651: escaped strings of the action recorded in the activity.log file.
12652: 
12653: =back
12654: 
12655: =head2 User Roles
12656: 
12657: =over 4
12658: 
12659: =item *
12660: 
12661: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
12662:  F: full access
12663:  U,I,K: authentication modes (cxx only)
12664:  '': forbidden
12665:  1: user needs to choose course
12666:  2: browse allowed
12667:  A: passphrase authentication needed
12668: 
12669: =item *
12670: 
12671: constructaccess($url,$setpriv) : check for access to construction space URL
12672: 
12673: See if the owner domain and name in the URL match those in the
12674: expected environment.  If so, return three element list
12675: ($ownername,$ownerdomain,$ownerhome).
12676: 
12677: Otherwise return the null string.
12678: 
12679: If second argument 'setpriv' is true, it assigns the privileges,
12680: and returns the same three element list, unless the owner has
12681: blocked "ad hoc" Domain Coordinator access to the Author Space,
12682: in which case the null string is returned.
12683: 
12684: =item *
12685: 
12686: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
12687: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
12688: and course level
12689: 
12690: =item *
12691: 
12692: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
12693: (rolesplain.tab); plain text explanation of a user role term.
12694: $type is Course (default) or Community.
12695: If $forcedefault evaluates to true, text returned will be default 
12696: text for $type. Otherwise, if this is a course, the text returned 
12697: will be a custom name for the role (if defined in the course's 
12698: environment).  If no custom name is defined the default is returned.
12699:    
12700: =item *
12701: 
12702: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
12703: All arguments are optional. Returns a hash of a roles, either for
12704: co-author/assistant author roles for a user's Construction Space
12705: (default), or if $context is 'userroles', roles for the user himself,
12706: In the hash, keys are set to colon-separated $uname,$udom,$role, and
12707: (optionally) if $withsec is true, a fourth colon-separated item - $section.
12708: For each key, value is set to colon-separated start and end times for
12709: the role.  If no username and domain are specified, will default to
12710: current user/domain. Types, roles, and roledoms are references to arrays
12711: of role statuses (active, future or previous), roles 
12712: (e.g., cc,in, st etc.) and domains of the roles which can be used
12713: to restrict the list of roles reported. If no array ref is 
12714: provided for types, will default to return only active roles.
12715: 
12716: =item *
12717: 
12718: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
12719: user: $uname:$udom has a role in the course: $cdom_$cnum. 
12720: 
12721: Additional optional arguments are: $type (if role checking is to be restricted 
12722: to certain user status types -- previous (expired roles), active (currently
12723: available roles) or future (roles available in the future), and
12724: $hideprivileged -- if true will not report course roles for users who
12725: have active Domain Coordinator role in course's domain or in additional
12726: domains (specified in 'Domains to check for privileged users' in course
12727: environment -- set via:  Course Settings -> Classlists and staff listing).
12728: 
12729: =item *
12730: 
12731: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
12732: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
12733: $possdomains and $possroles are optional array refs -- to domains to check and
12734: roles to check.  If $possdomains is not specified, a dump will be done of the
12735: users' roles.db to check for a dc or su role in any domain. This can be
12736: time consuming if &privileged is called repeatedly (e.g., when displaying a
12737: classlist), so in such cases, supplying a $possdomains array is preferred, as
12738: this then allows &privileged_by_domain() to be used, which caches the identity
12739: of privileged users, eliminating the need for repeated calls to &dump().
12740: 
12741: =item *
12742: 
12743: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
12744: where the outer hash keys are domains specified in the $possdomains array ref,
12745: next inner hash keys are privileged roles specified in the $roles array ref,
12746: and the innermost hash contains key = value pairs for username:domain = end:start
12747: for active or future "privileged" users with that role in that domain. To avoid
12748: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
12749: innerhash are cached using priv_$role and $dom as the identifiers.
12750: 
12751: =back
12752: 
12753: =head2 User Modification
12754: 
12755: =over 4
12756: 
12757: =item *
12758: 
12759: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
12760: user for the level given by URL.  Optional start and end dates (leave empty
12761: string or zero for "no date")
12762: 
12763: =item *
12764: 
12765: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
12766: change a users, password, possible return values are: ok,
12767: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
12768: refused
12769: 
12770: =item *
12771: 
12772: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
12773: 
12774: =item *
12775: 
12776: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
12777:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
12778: 
12779: will update user information (firstname,middlename,lastname,generation,
12780: permanentemail), and if forceid is true, student/employee ID also.
12781: A user's institutional affiliation(s) can also be updated.
12782: User information fields will not be overwritten with empty entries 
12783: unless the field is included in the $candelete array reference.
12784: This array is included when a single user is modified via "Manage Users",
12785: or when Autoupdate.pl is run by cron in a domain.
12786: 
12787: =item *
12788: 
12789: modifystudent
12790: 
12791: modify a student's enrollment and identification information.
12792: The course id is resolved based on the current user's environment.  
12793: This means the invoking user must be a course coordinator or otherwise
12794: associated with a course.
12795: 
12796: This call is essentially a wrapper for lonnet::modifyuser and
12797: lonnet::modify_student_enrollment
12798: 
12799: Inputs: 
12800: 
12801: =over 4
12802: 
12803: =item B<$udom> Student's loncapa domain
12804: 
12805: =item B<$uname> Student's loncapa login name
12806: 
12807: =item B<$uid> Student/Employee ID
12808: 
12809: =item B<$umode> Student's authentication mode
12810: 
12811: =item B<$upass> Student's password
12812: 
12813: =item B<$first> Student's first name
12814: 
12815: =item B<$middle> Student's middle name
12816: 
12817: =item B<$last> Student's last name
12818: 
12819: =item B<$gene> Student's generation
12820: 
12821: =item B<$usec> Student's section in course
12822: 
12823: =item B<$end> Unix time of the roles expiration
12824: 
12825: =item B<$start> Unix time of the roles start date
12826: 
12827: =item B<$forceid> If defined, allow $uid to be changed
12828: 
12829: =item B<$desiredhome> server to use as home server for student
12830: 
12831: =item B<$email> Student's permanent e-mail address
12832: 
12833: =item B<$type> Type of enrollment (auto or manual)
12834: 
12835: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
12836: 
12837: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
12838: 
12839: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
12840: 
12841: =item B<$context> role change context (shown in User Management Logs display in a course)
12842: 
12843: =item B<$inststatus> institutional status of user - : separated string of escaped status types
12844: 
12845: =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.
12846: 
12847: =back
12848: 
12849: =item *
12850: 
12851: modify_student_enrollment
12852: 
12853: Change a student's enrollment status in a class.  The environment variable
12854: 'role.request.course' must be defined for this function to proceed.
12855: 
12856: Inputs:
12857: 
12858: =over 4
12859: 
12860: =item $udom, student's domain
12861: 
12862: =item $uname, student's name
12863: 
12864: =item $uid, student's user id
12865: 
12866: =item $first, student's first name
12867: 
12868: =item $middle
12869: 
12870: =item $last
12871: 
12872: =item $gene
12873: 
12874: =item $usec
12875: 
12876: =item $end
12877: 
12878: =item $start
12879: 
12880: =item $type
12881: 
12882: =item $locktype
12883: 
12884: =item $cid
12885: 
12886: =item $selfenroll
12887: 
12888: =item $context
12889: 
12890: =item $credits, number of credits student will earn from this class
12891: 
12892: =back
12893: 
12894: 
12895: =item *
12896: 
12897: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
12898: custom role; give a custom role to a user for the level given by URL.  Specify
12899: name and domain of role author, and role name
12900: 
12901: =item *
12902: 
12903: revokerole($udom,$uname,$url,$role) : revoke a role for url
12904: 
12905: =item *
12906: 
12907: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
12908: 
12909: =back
12910: 
12911: =head2 Course Infomation
12912: 
12913: =over 4
12914: 
12915: =item *
12916: 
12917: coursedescription($courseid,$options) : returns a hash of information about the
12918: specified course id, including all environment settings for the
12919: course, the description of the course will be in the hash under the
12920: key 'description'
12921: 
12922: $options is an optional parameter that if supplied is a hash reference that controls
12923: what how this function works.  It has the following key/values:
12924: 
12925: =over 4
12926: 
12927: =item freshen_cache
12928: 
12929: If defined, and the environment cache for the course is valid, it is 
12930: returned in the returned hash.
12931: 
12932: =item one_time
12933: 
12934: If defined, the last cache time is set to _now_
12935: 
12936: =item user
12937: 
12938: If defined, the supplied username is used instead of the current user.
12939: 
12940: 
12941: =back
12942: 
12943: =item *
12944: 
12945: resdata($name,$domain,$type,@which) : request for current parameter
12946: setting for a specific $type, where $type is either 'course' or 'user',
12947: @what should be a list of parameters to ask about. This routine caches
12948: answers for 10 minutes.
12949: 
12950: =item *
12951: 
12952: get_courseresdata($courseid, $domain) : dump the entire course resource
12953: data base, returning a hash that is keyed by the resource name and has
12954: values that are the resource value.  I believe that the timestamps and
12955: versions are also returned.
12956: 
12957: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
12958: supplemental content area. This routine caches the number of files for 
12959: 10 minutes.
12960: 
12961: =back
12962: 
12963: =head2 Course Modification
12964: 
12965: =over 4
12966: 
12967: =item *
12968: 
12969: writecoursepref($courseid,%prefs) : write preferences (environment
12970: database) for a course
12971: 
12972: =item *
12973: 
12974: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
12975: 
12976: =item *
12977: 
12978: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
12979: 
12980: =item *
12981: 
12982: is_course($courseid), is_course($cdom, $cnum)
12983: 
12984: Accepts either a combined $courseid (in the form of domain_courseid) or the
12985: two component version $cdom, $cnum. It checks if the specified course exists.
12986: 
12987: Returns:
12988:     undef if the course doesn't exist, otherwise
12989:     in scalar context the combined courseid.
12990:     in list context the two components of the course identifier, domain and 
12991:     courseid.    
12992: 
12993: =back
12994: 
12995: =head2 Resource Subroutines
12996: 
12997: =over 4
12998: 
12999: =item *
13000: 
13001: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
13002: 
13003: =item *
13004: 
13005: repcopy($filename) : subscribes to the requested file, and attempts to
13006: replicate from the owning library server, Might return
13007: 'unavailable', 'not_found', 'forbidden', 'ok', or
13008: 'bad_request', also attempts to grab the metadata for the
13009: resource. Expects the local filesystem pathname
13010: (/home/httpd/html/res/....)
13011: 
13012: =back
13013: 
13014: =head2 Resource Information
13015: 
13016: =over 4
13017: 
13018: =item *
13019: 
13020: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
13021: and returns the value of a variety of different possible values,
13022: $varname should be a request string, and the other parameters can be
13023: used to specify who and what one is asking about. Ordinarily, $cid 
13024: does not need to be specified, as it is retrived from 
13025: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
13026: within lonuserstate::loadmap() when initializing a course, before
13027: $env{'request.course.id'} has been set, so it needs to be provided
13028: in that one case.
13029: 
13030: Possible values for $varname are environment.lastname (or other item
13031: from the envirnment hash), user.name (or someother aspect about the
13032: user), resource.0.maxtries (or some other part and parameter of a
13033: resource)
13034: 
13035: =item *
13036: 
13037: directcondval($number) : get current value of a condition; reads from a state
13038: string
13039: 
13040: =item *
13041: 
13042: condval($condidx) : value of condition index based on state
13043: 
13044: =item *
13045: 
13046: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
13047: resource's metadata, $what should be either a specific key, or either
13048: 'keys' (to get a list of possible keys) or 'packages' to get a list of
13049: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
13050: 
13051: this function automatically caches all requests
13052: 
13053: =item *
13054: 
13055: metadata_query($query,$custom,$customshow) : make a metadata query against the
13056: network of library servers; returns file handle of where SQL and regex results
13057: will be stored for query
13058: 
13059: =item *
13060: 
13061: symbread($filename) : return symbolic list entry (filename argument optional);
13062: returns the data handle
13063: 
13064: =item *
13065: 
13066: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
13067: and is a possible symb for the URL in $thisfn, and if is an encrypted
13068: resource that the user accessed using /enc/ returns a 1 on success, 0
13069: on failure, user must be in a course, as it assumes the existence of
13070: the course initial hash, and uses $env('request.course.id'}.  The third
13071: arg is an optional reference to a scalar.  If this arg is passed in the 
13072: call to symbverify, it will be set to 1 if the symb has been set to be 
13073: encrypted; otherwise it will be null.  
13074: 
13075: =item *
13076: 
13077: symbclean($symb) : removes versions numbers from a symb, returns the
13078: cleaned symb
13079: 
13080: =item *
13081: 
13082: is_on_map($uri) : checks if the $uri is somewhere on the current
13083: course map, user must be in a course for it to work.
13084: 
13085: =item *
13086: 
13087: numval($salt) : return random seed value (addend for rndseed)
13088: 
13089: =item *
13090: 
13091: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
13092: a random seed, all arguments are optional, if they aren't sent it uses the
13093: environment to derive them. Note: if symb isn't sent and it can't get one
13094: from &symbread it will use the current time as its return value
13095: 
13096: =item *
13097: 
13098: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
13099: unfakeable, receipt
13100: 
13101: =item *
13102: 
13103: receipt() : API to ireceipt working off of env values; given out to users
13104: 
13105: =item *
13106: 
13107: countacc($url) : count the number of accesses to a given URL
13108: 
13109: =item *
13110: 
13111: 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
13112: 
13113: =item *
13114: 
13115: 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)
13116: 
13117: =item *
13118: 
13119: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
13120: 
13121: =item *
13122: 
13123: devalidate($symb) : devalidate temporary spreadsheet calculations,
13124: forcing spreadsheet to reevaluate the resource scores next time.
13125: 
13126: =item * 
13127: 
13128: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
13129: when viewing in course context.
13130: 
13131:  input: six args -- filename (decluttered), course number, course domain,
13132:                     url, symb (if registered) and group (if this is a 
13133:                     group item -- e.g., bulletin board, group page etc.).
13134: 
13135:  output: array of five scalars --
13136:          $cfile -- url for file editing if editable on current server
13137:          $home -- homeserver of resource (i.e., for author if published,
13138:                                           or course if uploaded.).
13139:          $switchserver --  1 if server switch will be needed.
13140:          $forceedit -- 1 if icon/link should be to go to edit mode 
13141:          $forceview -- 1 if icon/link should be to go to view mode
13142: 
13143: =item *
13144: 
13145: is_course_upload($file,$cnum,$cdom)
13146: 
13147: Used in course context to determine if current file was uploaded to 
13148: the course (i.e., would be found in /userfiles/docs on the course's 
13149: homeserver.
13150: 
13151:   input: 3 args -- filename (decluttered), course number and course domain.
13152:   output: boolean -- 1 if file was uploaded.
13153: 
13154: =back
13155: 
13156: =head2 Storing/Retreiving Data
13157: 
13158: =over 4
13159: 
13160: =item *
13161: 
13162: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
13163: for this url; hashref needs to be given and should be a \%hashname; the
13164: remaining args aren't required and if they aren't passed or are '' they will
13165: be derived from the env
13166: 
13167: =item *
13168: 
13169: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
13170: uses critical subroutine
13171: 
13172: =item *
13173: 
13174: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
13175: all args are optional
13176: 
13177: =item *
13178: 
13179: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
13180: dumps the complete (or key matching regexp) namespace into a hash
13181: ($udom, $uname, $regexp, $range are optional) for a namespace that is
13182: normally &store()ed into
13183: 
13184: $range should be either an integer '100' (give me the first 100
13185:                                            matching records)
13186:               or be  two integers sperated by a - with no spaces
13187:                  '30-50' (give me the 30th through the 50th matching
13188:                           records)
13189: 
13190: 
13191: =item *
13192: 
13193: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
13194: replaces a &store() version of data with a replacement set of data
13195: for a particular resource in a namespace passed in the $storehash hash 
13196: reference
13197: 
13198: =item *
13199: 
13200: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
13201: works very similar to store/cstore, but all data is stored in a
13202: temporary location and can be reset using tmpreset, $storehash should
13203: be a hash reference, returns nothing on success
13204: 
13205: =item *
13206: 
13207: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
13208: similar to restore, but all data is stored in a temporary location and
13209: can be reset using tmpreset. Returns a hash of values on success,
13210: error string otherwise.
13211: 
13212: =item *
13213: 
13214: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
13215: deltes all keys for $symb form the temporary storage hash.
13216: 
13217: =item *
13218: 
13219: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13220: reference filled in from namesp ($udom and $uname are optional)
13221: 
13222: =item *
13223: 
13224: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
13225: namesp ($udom and $uname are optional)
13226: 
13227: =item *
13228: 
13229: dump($namespace,$udom,$uname,$regexp,$range) : 
13230: dumps the complete (or key matching regexp) namespace into a hash
13231: ($udom, $uname, $regexp, $range are optional)
13232: 
13233: $range should be either an integer '100' (give me the first 100
13234:                                            matching records)
13235:               or be  two integers sperated by a - with no spaces
13236:                  '30-50' (give me the 30th through the 50th matching
13237:                           records)
13238: =item *
13239: 
13240: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
13241: $store can be a scalar, an array reference, or if the amount to be 
13242: incremented is > 1, a hash reference.
13243: 
13244: ($udom and $uname are optional)
13245: 
13246: =item *
13247: 
13248: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
13249: ($udom and $uname are optional)
13250: 
13251: =item *
13252: 
13253: cput($namespace,$storehash,$udom,$uname) : critical put
13254: ($udom and $uname are optional)
13255: 
13256: =item *
13257: 
13258: newput($namespace,$storehash,$udom,$uname) :
13259: 
13260: Attempts to store the items in the $storehash, but only if they don't
13261: currently exist, if this succeeds you can be certain that you have 
13262: successfully created a new key value pair in the $namespace db.
13263: 
13264: 
13265: Args:
13266:  $namespace: name of database to store values to
13267:  $storehash: hashref to store to the db
13268:  $udom: (optional) domain of user containing the db
13269:  $uname: (optional) name of user caontaining the db
13270: 
13271: Returns:
13272:  'ok' -> succeeded in storing all keys of $storehash
13273:  'key_exists: <key>' -> failed to anything out of $storehash, as at
13274:                         least <key> already existed in the db (other
13275:                         requested keys may also already exist)
13276:  'error: <msg>' -> unable to tie the DB or other error occurred
13277:  'con_lost' -> unable to contact request server
13278:  'refused' -> action was not allowed by remote machine
13279: 
13280: 
13281: =item *
13282: 
13283: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13284: reference filled in from namesp (encrypts the return communication)
13285: ($udom and $uname are optional)
13286: 
13287: =item *
13288: 
13289: log($udom,$name,$home,$message) : write to permanent log for user; use
13290: critical subroutine
13291: 
13292: =item *
13293: 
13294: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
13295: array reference filled in from namespace found in domain level on either
13296: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
13297: 
13298: =item *
13299: 
13300: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
13301: domain level either on specified domain server ($uhome) or primary domain 
13302: server ($udom and $uhome are optional)
13303: 
13304: =item * 
13305: 
13306: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
13307: for: authentication, language, quotas, timezone, date locale, and portal URL in
13308: the target domain.
13309: 
13310: May also include additional key => value pairs for the following groups:
13311: 
13312: =over
13313: 
13314: =item
13315: disk quotas (MB allocated by default to portfolios and authoring spaces).
13316: 
13317: =over
13318: 
13319: =item defaultquota, authorquota
13320: 
13321: =back
13322: 
13323: =item
13324: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
13325: portfolio for users).
13326: 
13327: =over
13328: 
13329: =item
13330: aboutme, blog, webdav, portfolio
13331: 
13332: =back
13333: 
13334: =item
13335: requestcourses: ability to request courses, and how requests are processed.
13336: 
13337: =over
13338: 
13339: =item
13340: official, unofficial, community, textbook
13341: 
13342: =back
13343: 
13344: =item
13345: inststatus: types of institutional affiliation, and order in which they are displayed.
13346: 
13347: =over
13348: 
13349: =item
13350: inststatustypes, inststatusorder, inststatusguest
13351: 
13352: =back
13353: 
13354: =item
13355: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
13356: for course's uploaded content.
13357: 
13358: =over
13359: 
13360: =item
13361: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
13362: communityquota, textbookquota
13363: 
13364: =back
13365: 
13366: =item
13367: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
13368: on your servers.
13369: 
13370: =over
13371: 
13372: =item 
13373: remotesessions, hostedsessions
13374: 
13375: =back
13376: 
13377: =back
13378: 
13379: In cases where a domain coordinator has never used the "Set Domain Configuration"
13380: utility to create a configuration.db file on a domain's primary library server 
13381: only the following domain defaults: auth_def, auth_arg_def, lang_def
13382: -- corresponding values are authentication type (internal, krb4, krb5,
13383: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
13384: will be available. Values are retrieved from cache (if current), unless the
13385: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
13386: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
13387: 
13388: Typical usage:
13389: 
13390: %domdefaults = &get_domain_defaults($target_domain);
13391: 
13392: =back
13393: 
13394: =head2 Network Status Functions
13395: 
13396: =over 4
13397: 
13398: =item *
13399: 
13400: dirlist() : return directory list based on URI (first arg).
13401: 
13402: Inputs: 1 required, 5 optional.
13403: 
13404: =over
13405: 
13406: =item 
13407: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
13408: 
13409: =item
13410: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
13411: 
13412: =item
13413: $username -  username of user/course to be listed. Extracted from $uri if absent. 
13414: 
13415: =item
13416: $getpropath - boolean: 1 if prepend path using &propath(). 
13417: 
13418: =item
13419: $getuserdir - boolean: 1 if prepend path for "userfiles".
13420: 
13421: =item 
13422: $alternateRoot - path to prepend in place of path from $uri.
13423: 
13424: =back
13425: 
13426: Returns: Array of up to two items.
13427: 
13428: =over
13429: 
13430: a reference to an array of files/subdirectories
13431: 
13432: =over
13433: 
13434: Each element in the array of files/subdirectories is a & separated list of
13435: item name and the result of running stat on the item.  If dirlist was requested
13436: for a file instead of a directory, the item name will be ''. For a directory 
13437: listing, if the item is a metadata file, the element will end &N&M 
13438: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
13439: default copyright set (1).  
13440: 
13441: =back
13442: 
13443: a scalar containing error condition (if encountered).
13444: 
13445: =over
13446: 
13447: =item 
13448: no_host (no homeserver identified for $username:$domain).
13449: 
13450: =item 
13451: no_such_host (server contacted for listing not identified as valid host).
13452: 
13453: =item 
13454: con_lost (connection to remote server failed).
13455: 
13456: =item 
13457: refused (invalid $username:$domain received on lond side).
13458: 
13459: =item 
13460: no_such_dir (directory at specified path on lond side does not exist). 
13461: 
13462: =item 
13463: empty (directory at specified path on lond side is empty).
13464: 
13465: =over
13466: 
13467: This is currently not encountered because the &ls3, &ls2, 
13468: &ls (_handler) routines on the lond side do not filter out
13469: . and .. from a directory listing. 
13470: 
13471: =back
13472: 
13473: =back
13474: 
13475: =back
13476: 
13477: =item *
13478: 
13479: spareserver() : find server with least workload from spare.tab
13480: 
13481: 
13482: =item *
13483: 
13484: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
13485: if there is no corresponding loncapa host.
13486: 
13487: =back
13488: 
13489: 
13490: =head2 Apache Request
13491: 
13492: =over 4
13493: 
13494: =item *
13495: 
13496: ssi($url,%hash) : server side include, does a complete request cycle on url to
13497: localhost, posts hash
13498: 
13499: =back
13500: 
13501: =head2 Data to String to Data
13502: 
13503: =over 4
13504: 
13505: =item *
13506: 
13507: hash2str(%hash) : convert a hash into a string complete with escaping and '='
13508: and '&' separators, supports elements that are arrayrefs and hashrefs
13509: 
13510: =item *
13511: 
13512: hashref2str($hashref) : convert a hashref into a string complete with
13513: escaping and '=' and '&' separators, supports elements that are
13514: arrayrefs and hashrefs
13515: 
13516: =item *
13517: 
13518: arrayref2str($arrayref) : convert an arrayref into a string complete
13519: with escaping and '&' separators, supports elements that are arrayrefs
13520: and hashrefs
13521: 
13522: =item *
13523: 
13524: str2hash($string) : convert string to hash using unescaping and
13525: splitting on '=' and '&', supports elements that are arrayrefs and
13526: hashrefs
13527: 
13528: =item *
13529: 
13530: str2array($string) : convert string to hash using unescaping and
13531: splitting on '&', supports elements that are arrayrefs and hashrefs
13532: 
13533: =back
13534: 
13535: =head2 Logging Routines
13536: 
13537: 
13538: These routines allow one to make log messages in the lonnet.log and
13539: lonnet.perm logfiles.
13540: 
13541: =over 4
13542: 
13543: =item *
13544: 
13545: logtouch() : make sure the logfile, lonnet.log, exists
13546: 
13547: =item *
13548: 
13549: logthis() : append message to the normal lonnet.log file, it gets
13550: preiodically rolled over and deleted.
13551: 
13552: =item *
13553: 
13554: logperm() : append a permanent message to lonnet.perm.log, this log
13555: file never gets deleted by any automated portion of the system, only
13556: messages of critical importance should go in here.
13557: 
13558: 
13559: =back
13560: 
13561: =head2 General File Helper Routines
13562: 
13563: =over 4
13564: 
13565: =item *
13566: 
13567: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
13568: (a) files in /uploaded
13569:   (i) If a local copy of the file exists - 
13570:       compares modification date of local copy with last-modified date for 
13571:       definitive version stored on home server for course. If local copy is 
13572:       stale, requests a new version from the home server and stores it. 
13573:       If the original has been removed from the home server, then local copy 
13574:       is unlinked.
13575:   (ii) If local copy does not exist -
13576:       requests the file from the home server and stores it. 
13577:   
13578:   If $caller is 'uploadrep':  
13579:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
13580:     for request for files originally uploaded via DOCS. 
13581:      - returns 'ok' if fresh local copy now available, -1 otherwise.
13582:   
13583:   Otherwise:
13584:      This indicates a call from the content generation phase of the request.
13585:      -  returns the entire contents of the file or -1.
13586:      
13587: (b) files in /res
13588:    - returns the entire contents of a file or -1; 
13589:    it properly subscribes to and replicates the file if neccessary.
13590: 
13591: 
13592: =item *
13593: 
13594: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
13595:                   reference
13596: 
13597: returns either a stat() list of data about the file or an empty list
13598: if the file doesn't exist or couldn't find out about it (connection
13599: problems or user unknown)
13600: 
13601: =item *
13602: 
13603: filelocation($dir,$file) : returns file system location of a file
13604: based on URI; meant to be "fairly clean" absolute reference, $dir is a
13605: directory that relative $file lookups are to looked in ($dir of /a/dir
13606: and a file of ../bob will become /a/bob)
13607: 
13608: =item *
13609: 
13610: hreflocation($dir,$file) : returns file system location or a URL; same as
13611: filelocation except for hrefs
13612: 
13613: =item *
13614: 
13615: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
13616: 
13617: =back
13618: 
13619: =head2 Usererfile file routines (/uploaded*)
13620: 
13621: =over 4
13622: 
13623: =item *
13624: 
13625: userfileupload(): main rotine for putting a file in a user or course's
13626:                   filespace, arguments are,
13627: 
13628:  formname - required - this is the name of the element in $env where the
13629:            filename, and the contents of the file to create/modifed exist
13630:            the filename is in $env{'form.'.$formname.'.filename'} and the
13631:            contents of the file is located in $env{'form.'.$formname}
13632:  context - if coursedoc, store the file in the course of the active role
13633:              of the current user; 
13634:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
13635:            if 'canceloverwrite': delete file in tmp/overwrites directory
13636:  subdir - required - subdirectory to put the file in under ../userfiles/
13637:          if undefined, it will be placed in "unknown"
13638: 
13639:  (This routine calls clean_filename() to remove any dangerous
13640:  characters from the filename, and then calls finuserfileupload() to
13641:  complete the transaction)
13642: 
13643:  returns either the url of the uploaded file (/uploaded/....) if successful
13644:  and /adm/notfound.html if unsuccessful
13645: 
13646: =item *
13647: 
13648: clean_filename(): routine for cleaing a filename up for storage in
13649:                  userfile space, argument is:
13650: 
13651:  filename - proposed filename
13652: 
13653: returns: the new clean filename
13654: 
13655: =item *
13656: 
13657: finishuserfileupload(): routine that creates and sends the file to
13658: userspace, probably shouldn't be called directly
13659: 
13660:   docuname: username or courseid of destination for the file
13661:   docudom: domain of user/course of destination for the file
13662:   formname: same as for userfileupload()
13663:   fname: filename (including subdirectories) for the file
13664:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
13665:   allfiles: reference to hash used to store objects found by parser
13666:   codebase: reference to hash used for codebases of java objects found by parser
13667:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
13668:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
13669:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
13670:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
13671:   context: if 'overwrite', will move the uploaded file from its temporary location to
13672:             userfiles to facilitate overwriting a previously uploaded file with same name.
13673:   mimetype: reference to scalar to accommodate mime type determined
13674:             from File::MMagic if $parser = parse.
13675: 
13676:  returns either the url of the uploaded file (/uploaded/....) if successful
13677:  and /adm/notfound.html if unsuccessful (or an error message if context 
13678:  was 'overwrite').
13679:  
13680: 
13681: =item *
13682: 
13683: renameuserfile(): renames an existing userfile to a new name
13684: 
13685:   Args:
13686:    docuname: username or courseid of destination for the file
13687:    docudom: domain of user/course of destination for the file
13688:    old: current file name (including any subdirs under userfiles)
13689:    new: desired file name (including any subdirs under userfiles)
13690: 
13691: =item *
13692: 
13693: mkdiruserfile(): creates a directory is a userfiles dir
13694: 
13695:   Args:
13696:    docuname: username or courseid of destination for the file
13697:    docudom: domain of user/course of destination for the file
13698:    dir: dir to create (including any subdirs under userfiles)
13699: 
13700: =item *
13701: 
13702: removeuserfile(): removes a file that exists in userfiles
13703: 
13704:   Args:
13705:    docuname: username or courseid of destination for the file
13706:    docudom: domain of user/course of destination for the file
13707:    fname: filname to delete (including any subdirs under userfiles)
13708: 
13709: =item *
13710: 
13711: removeuploadedurl(): convience function for removeuserfile()
13712: 
13713:   Args:
13714:    url:  a full /uploaded/... url to delete
13715: 
13716: =item * 
13717: 
13718: get_portfile_permissions():
13719:   Args:
13720:     domain: domain of user or course contain the portfolio files
13721:     user: name of user or num of course contain the portfolio files
13722:   Returns:
13723:     hashref of a dump of the proper file_permissions.db
13724:    
13725: 
13726: =item * 
13727: 
13728: get_access_controls():
13729: 
13730: Args:
13731:   current_permissions: the hash ref returned from get_portfile_permissions()
13732:   group: (optional) the group you want the files associated with
13733:   file: (optional) the file you want access info on
13734: 
13735: Returns:
13736:     a hash (keys are file names) of hashes containing
13737:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
13738:         values are XML containing access control settings (see below) 
13739: 
13740: Internal notes:
13741: 
13742:  access controls are stored in file_permissions.db as key=value pairs.
13743:     key -> path to file/file_name\0uniqueID:scope_end_start
13744:         where scope -> public,guest,course,group,domains or users.
13745:               end -> UNIX time for end of access (0 -> no end date)
13746:               start -> UNIX time for start of access
13747: 
13748:     value -> XML description of access control
13749:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
13750:             <start></start>
13751:             <end></end>
13752: 
13753:             <password></password>  for scope type = guest
13754: 
13755:             <domain></domain>     for scope type = course or group
13756:             <number></number>
13757:             <roles id="">
13758:              <role></role>
13759:              <access></access>
13760:              <section></section>
13761:              <group></group>
13762:             </roles>
13763: 
13764:             <dom></dom>         for scope type = domains
13765: 
13766:             <users>             for scope type = users
13767:              <user>
13768:               <uname></uname>
13769:               <udom></udom>
13770:              </user>
13771:             </users>
13772:            </scope> 
13773:               
13774:  Access data is also aggregated for each file in an additional key=value pair:
13775:  key -> path to file/file_name\0accesscontrol 
13776:  value -> reference to hash
13777:           hash contains key = value pairs
13778:           where key = uniqueID:scope_end_start
13779:                 value = UNIX time record was last updated
13780: 
13781:           Used to improve speed of look-ups of access controls for each file.  
13782:  
13783:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
13784: 
13785: =item *
13786: 
13787: modify_access_controls():
13788: 
13789: Modifies access controls for a portfolio file
13790: Args
13791: 1. file name
13792: 2. reference to hash of required changes,
13793: 3. domain
13794: 4. username
13795:   where domain,username are the domain of the portfolio owner 
13796:   (either a user or a course) 
13797: 
13798: Returns:
13799: 1. result of additions or updates ('ok' or 'error', with error message). 
13800: 2. result of deletions ('ok' or 'error', with error message).
13801: 3. reference to hash of any new or updated access controls.
13802: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
13803:    key = integer (inbound ID)
13804:    value = uniqueID
13805: 
13806: =item *
13807: 
13808: get_timebased_id():
13809: 
13810: Attempts to get a unique timestamp-based suffix for use with items added to a 
13811: course via the Course Editor (e.g., folders, composite pages, 
13812: group bulletin boards).
13813: 
13814: Args: (first three required; six others optional)
13815: 
13816: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
13817:    docssequence, or name of group
13818: 
13819: 2. keyid (alphanumeric): name of temporary locking key in hash,
13820:    e.g., num, boardids
13821: 
13822: 3. namespace: name of gdbm file used to store suffixes already assigned;  
13823:    file will be named nohist_namespace.db
13824: 
13825: 4. cdom: domain of course; default is current course domain from %env
13826: 
13827: 5. cnum: course number; default is current course number from %env
13828: 
13829: 6. idtype: set to concat if an additional digit is to be appended to the 
13830:    unix timestamp to form the suffix, if the plain timestamp is already
13831:    in use.  Default is to not do this, but simply increment the unix 
13832:    timestamp by 1 until a unique key is obtained.
13833: 
13834: 7. who: holder of locking key; defaults to user:domain for user.
13835: 
13836: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
13837:    retrying); default is 3.
13838: 
13839: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
13840: 
13841: Returns:
13842: 
13843: 1. suffix obtained (numeric)
13844: 
13845: 2. result of deleting locking key (ok if deleted, or lock never obtained)
13846: 
13847: 3. error: contains (localized) error message if an error occurred.
13848: 
13849: 
13850: =back
13851: 
13852: =head2 HTTP Helper Routines
13853: 
13854: =over 4
13855: 
13856: =item *
13857: 
13858: escape() : unpack non-word characters into CGI-compatible hex codes
13859: 
13860: =item *
13861: 
13862: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
13863: 
13864: =back
13865: 
13866: =head1 PRIVATE SUBROUTINES
13867: 
13868: =head2 Underlying communication routines (Shouldn't call)
13869: 
13870: =over 4
13871: 
13872: =item *
13873: 
13874: subreply() : tries to pass a message to lonc, returns con_lost if incapable
13875: 
13876: =item *
13877: 
13878: reply() : uses subreply to send a message to remote machine, logs all failures
13879: 
13880: =item *
13881: 
13882: critical() : passes a critical message to another server; if cannot
13883: get through then place message in connection buffer directory and
13884: returns con_delayed, if incapable of saving message, returns
13885: con_failed
13886: 
13887: =item *
13888: 
13889: reconlonc() : tries to reconnect lonc client processes.
13890: 
13891: =back
13892: 
13893: =head2 Resource Access Logging
13894: 
13895: =over 4
13896: 
13897: =item *
13898: 
13899: flushcourselogs() : flush (save) buffer logs and access logs
13900: 
13901: =item *
13902: 
13903: courselog($what) : save message for course in hash
13904: 
13905: =item *
13906: 
13907: courseacclog($what) : save message for course using &courselog().  Perform
13908: special processing for specific resource types (problems, exams, quizzes, etc).
13909: 
13910: =item *
13911: 
13912: goodbye() : flush course logs and log shutting down; it is called in srm.conf
13913: as a PerlChildExitHandler
13914: 
13915: =back
13916: 
13917: =head2 Other
13918: 
13919: =over 4
13920: 
13921: =item *
13922: 
13923: symblist($mapname,%newhash) : update symbolic storage links
13924: 
13925: =back
13926: 
13927: =cut
13928: 

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